text
stringlengths
478
483k
<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 __qdisc_run(struct net_device *dev) { do { if (!qdisc_restart(dev)) break; } while (!netif_queue_stopped(dev)); clear_bit(__LINK_STATE_QDISC_RUNNING, &dev->state); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': '[NET]: Add preemption point in qdisc_run The qdisc_run loop is currently unbounded and runs entirely in a softirq. This is bad as it may create an unbounded softirq run. This patch fixes this by calling need_resched and breaking out if necessary. It also adds a break out if the jiffies value changes since that would indicate we've been transmitting for too long which starves other softirqs. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> 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: sctp_disposition_t sctp_sf_eat_fwd_tsn(const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_fwdtsn_hdr *fwdtsn_hdr; __u16 len; __u32 tsn; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(ep, asoc, type, arg, commands); } /* Make sure that the FORWARD_TSN chunk has valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk))) return sctp_sf_violation_chunklen(ep, asoc, type, arg, commands); fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data; chunk->subh.fwdtsn_hdr = fwdtsn_hdr; len = ntohs(chunk->chunk_hdr->length); len -= sizeof(struct sctp_chunkhdr); skb_pull(chunk->skb, len); tsn = ntohl(fwdtsn_hdr->new_cum_tsn); SCTP_DEBUG_PRINTK("%s: TSN 0x%x.\n", __func__, tsn); /* The TSN is too high--silently discard the chunk and count on it * getting retransmitted later. */ if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0) goto discard_noforce; sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn)); if (len > sizeof(struct sctp_fwdtsn_hdr)) sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN, SCTP_CHUNK(chunk)); /* Count this as receiving DATA. */ if (asoc->autoclose) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); } /* FIXME: For now send a SACK, but DATA processing may * send another. */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE()); return SCTP_DISPOSITION_CONSUME; discard_noforce: return SCTP_DISPOSITION_DISCARD; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'sctp: Avoid memory overflow while FWD-TSN chunk is received with bad stream ID If FWD-TSN chunk is received with bad stream ID, the sctp will not do the validity check, this may cause memory overflow when overwrite the TSN of the stream ID. The FORWARD-TSN chunk is like this: FORWARD-TSN chunk Type = 192 Flags = 0 Length = 172 NewTSN = 99 Stream = 10000 StreamSequence = 0xFFFF This patch fix this problem by discard the chunk if stream ID is not less than MIS. Signed-off-by: Wei Yongjun <yjwei@cn.fujitsu.com> Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.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: _AFmoduleinst _af_ms_adpcm_init_decompress (_Track *track, AFvirtualfile *fh, bool seekok, bool headerless, AFframecount *chunkframes) { _AFmoduleinst ret = _AFnewmodinst(&ms_adpcm_decompress); ms_adpcm_data *d; AUpvlist pv; long l; void *v; assert(af_ftell(fh) == track->fpos_first_frame); d = (ms_adpcm_data *) _af_malloc(sizeof (ms_adpcm_data)); d->track = track; d->fh = fh; d->track->frames2ignore = 0; d->track->fpos_next_frame = d->track->fpos_first_frame; pv = d->track->f.compressionParams; if (_af_pv_getlong(pv, _AF_MS_ADPCM_NUM_COEFFICIENTS, &l)) d->numCoefficients = l; else _af_error(AF_BAD_CODEC_CONFIG, "number of coefficients not set"); if (_af_pv_getptr(pv, _AF_MS_ADPCM_COEFFICIENTS, &v)) memcpy(d->coefficients, v, sizeof (int16_t) * 256 * 2); else _af_error(AF_BAD_CODEC_CONFIG, "coefficient array not set"); if (_af_pv_getlong(pv, _AF_SAMPLES_PER_BLOCK, &l)) d->samplesPerBlock = l; else _af_error(AF_BAD_CODEC_CONFIG, "samples per block not set"); if (_af_pv_getlong(pv, _AF_BLOCK_SIZE, &l)) d->blockAlign = l; else _af_error(AF_BAD_CODEC_CONFIG, "block size not set"); *chunkframes = d->samplesPerBlock / d->track->f.channelCount; ret.modspec = d; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 ms_adpcm_reset2 (_AFmoduleinst *i) { ms_adpcm_data *d = (ms_adpcm_data *) i->modspec; int framesPerBlock; framesPerBlock = d->samplesPerBlock / d->track->f.channelCount; d->track->fpos_next_frame = d->track->fpos_first_frame + d->blockAlign * (d->track->nextfframe / framesPerBlock); d->track->frames2ignore += d->framesToIgnore; assert(d->track->nextfframe % framesPerBlock == 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 _af_adpcm_decoder (uint8_t *indata, int16_t *outdata, int len, struct adpcm_state *state) { uint8_t *inp; /* Input buffer pointer */ int16_t *outp; /* output buffer pointer */ int sign; /* Current adpcm sign bit */ int delta; /* Current adpcm output value */ int step; /* Stepsize */ int valpred; /* Predicted value */ int vpdiff; /* Current change to valpred */ int index; /* Current step change index */ int inputbuffer; /* place to keep next 4-bit value */ int bufferstep; /* toggle between inputbuffer/input */ outp = outdata; inp = indata; valpred = state->valprev; index = state->index; step = stepsizeTable[index]; bufferstep = 0; for ( ; len > 0 ; len-- ) { /* Step 1 - get the delta value */ if ( bufferstep ) { delta = (inputbuffer >> 4) & 0xf; } else { inputbuffer = *inp++; delta = inputbuffer & 0xf; } bufferstep = !bufferstep; /* Step 2 - Find new index value (for later) */ index += indexTable[delta]; if ( index < 0 ) index = 0; if ( index > 88 ) index = 88; /* Step 3 - Separate sign and magnitude */ sign = delta & 8; delta = delta & 7; /* Step 4 - Compute difference and new predicted value */ /* ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment ** in adpcm_coder. */ vpdiff = step >> 3; if ( delta & 4 ) vpdiff += step; if ( delta & 2 ) vpdiff += step>>1; if ( delta & 1 ) vpdiff += step>>2; if ( sign ) valpred -= vpdiff; else valpred += vpdiff; /* Step 5 - clamp output value */ if ( valpred > 32767 ) valpred = 32767; else if ( valpred < -32768 ) valpred = -32768; /* Step 6 - Update step value */ step = stepsizeTable[index]; /* Step 7 - Output value */ *outp++ = valpred; } state->valprev = valpred; state->index = index; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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: _AFmoduleinst _af_ima_adpcm_init_decompress (_Track *track, AFvirtualfile *fh, bool seekok, bool headerless, AFframecount *chunkframes) { _AFmoduleinst ret = _AFnewmodinst(&ima_adpcm_decompress); ima_adpcm_data *d; AUpvlist pv; long l; assert(af_ftell(fh) == track->fpos_first_frame); d = (ima_adpcm_data *) _af_malloc(sizeof (ima_adpcm_data)); d->track = track; d->fh = fh; d->track->frames2ignore = 0; d->track->fpos_next_frame = d->track->fpos_first_frame; pv = d->track->f.compressionParams; if (_af_pv_getlong(pv, _AF_SAMPLES_PER_BLOCK, &l)) d->samplesPerBlock = l; else _af_error(AF_BAD_CODEC_CONFIG, "samples per block not set"); if (_af_pv_getlong(pv, _AF_BLOCK_SIZE, &l)) d->blockAlign = l; else _af_error(AF_BAD_CODEC_CONFIG, "block size not set"); *chunkframes = d->samplesPerBlock / d->track->f.channelCount; ret.modspec = d; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 _af_adpcm_coder (int16_t *indata, uint8_t *outdata, int len, struct adpcm_state *state) { int16_t *inp; /* Input buffer pointer */ uint8_t *outp; /* Output buffer pointer */ int val; /* Current input sample value */ int sign; /* Current adpcm sign bit */ int delta; /* Current adpcm output value */ int diff; /* Difference between val and valprev */ int step; /* Stepsize */ int valpred; /* Predicted output value */ int vpdiff; /* Current change to valpred */ int index; /* Current step change index */ int outputbuffer; /* place to keep previous 4-bit value */ int bufferstep; /* toggle between outputbuffer/output */ outp = outdata; inp = indata; valpred = state->valprev; index = state->index; step = stepsizeTable[index]; bufferstep = 1; for ( ; len > 0 ; len-- ) { val = *inp++; /* Step 1 - compute difference with previous value */ diff = val - valpred; sign = (diff < 0) ? 8 : 0; if ( sign ) diff = (-diff); /* Step 2 - Divide and clamp */ /* Note: ** This code *approximately* computes: ** delta = diff*4/step; ** vpdiff = (delta+0.5)*step/4; ** but in shift step bits are dropped. The net result of this is ** that even if you have fast mul/div hardware you cannot put it to ** good use since the fixup would be too expensive. */ delta = 0; vpdiff = (step >> 3); if ( diff >= step ) { delta = 4; diff -= step; vpdiff += step; } step >>= 1; if ( diff >= step ) { delta |= 2; diff -= step; vpdiff += step; } step >>= 1; if ( diff >= step ) { delta |= 1; vpdiff += step; } /* Step 3 - Update previous value */ if ( sign ) valpred -= vpdiff; else valpred += vpdiff; /* Step 4 - Clamp previous value to 16 bits */ if ( valpred > 32767 ) valpred = 32767; else if ( valpred < -32768 ) valpred = -32768; /* Step 5 - Assemble value, update index and step values */ delta |= sign; index += indexTable[delta]; if ( index < 0 ) index = 0; if ( index > 88 ) index = 88; step = stepsizeTable[index]; /* Step 6 - Output value */ if ( bufferstep ) { outputbuffer = delta & 0x0f; } else { *outp++ = ((delta << 4) & 0xf0) | outputbuffer; } bufferstep = !bufferstep; } /* Output last step, if needed */ if ( !bufferstep ) *outp++ = outputbuffer; state->valprev = valpred; state->index = index; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 ms_adpcm_decode_block (ms_adpcm_data *msadpcm, uint8_t *encoded, int16_t *decoded) { int i, outputLength, samplesRemaining; int channelCount; int16_t *coefficient[2]; ms_adpcm_state decoderState[2]; ms_adpcm_state *state[2]; /* Calculate the number of bytes needed for decoded data. */ outputLength = msadpcm->samplesPerBlock * sizeof (int16_t) * msadpcm->track->f.channelCount; channelCount = msadpcm->track->f.channelCount; state[0] = &decoderState[0]; if (channelCount == 2) state[1] = &decoderState[1]; else state[1] = &decoderState[0]; /* Initialize predictor. */ for (i=0; i<channelCount; i++) { state[i]->predictor = *encoded++; assert(state[i]->predictor < msadpcm->numCoefficients); } /* Initialize delta. */ for (i=0; i<channelCount; i++) { state[i]->delta = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } /* Initialize first two samples. */ for (i=0; i<channelCount; i++) { state[i]->sample1 = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } for (i=0; i<channelCount; i++) { state[i]->sample2 = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } coefficient[0] = msadpcm->coefficients[state[0]->predictor]; coefficient[1] = msadpcm->coefficients[state[1]->predictor]; for (i=0; i<channelCount; i++) *decoded++ = state[i]->sample2; for (i=0; i<channelCount; i++) *decoded++ = state[i]->sample1; /* The first two samples have already been 'decoded' in the block header. */ samplesRemaining = (msadpcm->samplesPerBlock - 2) * msadpcm->track->f.channelCount; while (samplesRemaining > 0) { uint8_t code; int16_t newSample; code = *encoded >> 4; newSample = ms_adpcm_decode_sample(state[0], code, coefficient[0]); *decoded++ = newSample; code = *encoded & 0x0f; newSample = ms_adpcm_decode_sample(state[1], code, coefficient[1]); *decoded++ = newSample; encoded++; samplesRemaining -= 2; } return outputLength; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 status ParseFormat (AFfilehandle filehandle, AFvirtualfile *fp, uint32_t id, size_t size) { _Track *track; uint16_t formatTag, channelCount; uint32_t sampleRate, averageBytesPerSecond; uint16_t blockAlign; _WAVEInfo *wave; assert(filehandle != NULL); assert(fp != NULL); assert(!memcmp(&id, "fmt ", 4)); track = _af_filehandle_get_track(filehandle, AF_DEFAULT_TRACK); assert(filehandle->formatSpecific != NULL); wave = (_WAVEInfo *) filehandle->formatSpecific; af_read_uint16_le(&formatTag, fp); af_read_uint16_le(&channelCount, fp); af_read_uint32_le(&sampleRate, fp); af_read_uint32_le(&averageBytesPerSecond, fp); af_read_uint16_le(&blockAlign, fp); track->f.channelCount = channelCount; track->f.sampleRate = sampleRate; track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN; /* Default to uncompressed audio data. */ track->f.compressionType = AF_COMPRESSION_NONE; switch (formatTag) { case WAVE_FORMAT_PCM: { uint16_t bitsPerSample; af_read_uint16_le(&bitsPerSample, fp); track->f.sampleWidth = bitsPerSample; if (bitsPerSample == 0 || bitsPerSample > 32) { _af_error(AF_BAD_WIDTH, "bad sample width of %d bits", bitsPerSample); return AF_FAIL; } if (bitsPerSample <= 8) track->f.sampleFormat = AF_SAMPFMT_UNSIGNED; else track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; } break; case WAVE_FORMAT_MULAW: case IBM_FORMAT_MULAW: track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_G711_ULAW; break; case WAVE_FORMAT_ALAW: case IBM_FORMAT_ALAW: track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_G711_ALAW; break; case WAVE_FORMAT_IEEE_FLOAT: { uint16_t bitsPerSample; af_read_uint16_le(&bitsPerSample, fp); if (bitsPerSample == 64) { track->f.sampleWidth = 64; track->f.sampleFormat = AF_SAMPFMT_DOUBLE; } else { track->f.sampleWidth = 32; track->f.sampleFormat = AF_SAMPFMT_FLOAT; } } break; case WAVE_FORMAT_ADPCM: { uint16_t bitsPerSample, extraByteCount, samplesPerBlock, numCoefficients; int i; AUpvlist pv; long l; void *v; if (track->f.channelCount != 1 && track->f.channelCount != 2) { _af_error(AF_BAD_CHANNELS, "WAVE file with MS ADPCM compression " "must have 1 or 2 channels"); } af_read_uint16_le(&bitsPerSample, fp); af_read_uint16_le(&extraByteCount, fp); af_read_uint16_le(&samplesPerBlock, fp); af_read_uint16_le(&numCoefficients, fp); /* numCoefficients should be at least 7. */ assert(numCoefficients >= 7 && numCoefficients <= 255); for (i=0; i<numCoefficients; i++) { int16_t a0, a1; af_fread(&a0, 1, 2, fp); af_fread(&a1, 1, 2, fp); a0 = LENDIAN_TO_HOST_INT16(a0); a1 = LENDIAN_TO_HOST_INT16(a1); wave->msadpcmCoefficients[i][0] = a0; wave->msadpcmCoefficients[i][1] = a1; } track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_MS_ADPCM; track->f.byteOrder = _AF_BYTEORDER_NATIVE; /* Create the parameter list. */ pv = AUpvnew(4); AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS); AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG); l = numCoefficients; AUpvsetval(pv, 0, &l); AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS); AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR); v = wave->msadpcmCoefficients; AUpvsetval(pv, 1, &v); AUpvsetparam(pv, 2, _AF_SAMPLES_PER_BLOCK); AUpvsetvaltype(pv, 2, AU_PVTYPE_LONG); l = samplesPerBlock; AUpvsetval(pv, 2, &l); AUpvsetparam(pv, 3, _AF_BLOCK_SIZE); AUpvsetvaltype(pv, 3, AU_PVTYPE_LONG); l = blockAlign; AUpvsetval(pv, 3, &l); track->f.compressionParams = pv; } break; case WAVE_FORMAT_DVI_ADPCM: { AUpvlist pv; long l; uint16_t bitsPerSample, extraByteCount, samplesPerBlock; af_read_uint16_le(&bitsPerSample, fp); af_read_uint16_le(&extraByteCount, fp); af_read_uint16_le(&samplesPerBlock, fp); track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_IMA; track->f.byteOrder = _AF_BYTEORDER_NATIVE; /* Create the parameter list. */ pv = AUpvnew(2); AUpvsetparam(pv, 0, _AF_SAMPLES_PER_BLOCK); AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG); l = samplesPerBlock; AUpvsetval(pv, 0, &l); AUpvsetparam(pv, 1, _AF_BLOCK_SIZE); AUpvsetvaltype(pv, 1, AU_PVTYPE_LONG); l = blockAlign; AUpvsetval(pv, 1, &l); track->f.compressionParams = pv; } break; case WAVE_FORMAT_YAMAHA_ADPCM: case WAVE_FORMAT_OKI_ADPCM: case WAVE_FORMAT_CREATIVE_ADPCM: case IBM_FORMAT_ADPCM: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE ADPCM data format 0x%x is not currently supported", formatTag); return AF_FAIL; break; case WAVE_FORMAT_MPEG: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG data format is not supported"); return AF_FAIL; break; case WAVE_FORMAT_MPEGLAYER3: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG layer 3 data format is not supported"); return AF_FAIL; break; default: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE file data format 0x%x not currently supported", formatTag); return AF_FAIL; break; } _af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth); return AF_SUCCEED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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 sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; unsigned int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; switch(optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = !!sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_KEEPALIVE: v.val = !!sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val==0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = !!sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = !!sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_RCVTIMEO: lv=sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv=sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val=1; break; case SO_PASSCRED: v.val = test_bit(SOCK_PASSCRED, &sock->flags) ? 1 : 0; break; case SO_PEERCRED: if (len > sizeof(sk->sk_peercred)) len = sizeof(sk->sk_peercred); if (copy_to_user(optval, &sk->sk_peercred, len)) return -EFAULT; goto lenout; case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = test_bit(SOCK_PASSSEC, &sock->flags) ? 1 : 0; break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; default: return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'net: 4 bytes kernel memory disclosure in SO_BSDCOMPAT gsopt try #2 In function sock_getsockopt() located in net/core/sock.c, optval v.val is not correctly initialized and directly returned in userland in case we have SO_BSDCOMPAT option set. This dummy code should trigger the bug: int main(void) { unsigned char buf[4] = { 0, 0, 0, 0 }; int len; int sock; sock = socket(33, 2, 2); getsockopt(sock, 1, SO_BSDCOMPAT, &buf, &len); printf("%x%x%x%x\n", buf[0], buf[1], buf[2], buf[3]); close(sock); } Here is a patch that fix this bug by initalizing v.val just after its declaration. Signed-off-by: Clément Lecigne <clement.lecigne@netasq.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: static int skfp_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *lp = &smc->os; struct s_skfp_ioctl ioc; int status = 0; if (copy_from_user(&ioc, rq->ifr_data, sizeof(struct s_skfp_ioctl))) return -EFAULT; switch (ioc.cmd) { case SKFP_GET_STATS: /* Get the driver statistics */ ioc.len = sizeof(lp->MacStat); status = copy_to_user(ioc.data, skfp_ctl_get_stats(dev), ioc.len) ? -EFAULT : 0; break; case SKFP_CLR_STATS: /* Zero out the driver statistics */ if (!capable(CAP_NET_ADMIN)) { memset(&lp->MacStat, 0, sizeof(lp->MacStat)); } else { status = -EPERM; } break; default: printk("ioctl for %s: unknow cmd: %04x\n", dev->name, ioc.cmd); status = -EOPNOTSUPP; } // switch return status; } // skfp_ioctl ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'drivers/net/skfp: if !capable(CAP_NET_ADMIN): inverted logic Fix inverted logic Signed-off-by: Roel Kluin <roel.kluin@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: static int make_indexed_dir(handle_t *handle, struct dentry *dentry, struct inode *inode, struct buffer_head *bh) { struct inode *dir = dentry->d_parent->d_inode; const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; struct buffer_head *bh2; struct dx_root *root; struct dx_frame frames[2], *frame; struct dx_entry *entries; struct ext4_dir_entry_2 *de, *de2; char *data1, *top; unsigned len; int retval; unsigned blocksize; struct dx_hash_info hinfo; ext4_lblk_t block; struct fake_dirent *fde; blocksize = dir->i_sb->s_blocksize; dxtrace(printk(KERN_DEBUG "Creating index\n")); retval = ext4_journal_get_write_access(handle, bh); if (retval) { ext4_std_error(dir->i_sb, retval); brelse(bh); return retval; } root = (struct dx_root *) bh->b_data; bh2 = ext4_append(handle, dir, &block, &retval); if (!(bh2)) { brelse(bh); return retval; } EXT4_I(dir)->i_flags |= EXT4_INDEX_FL; data1 = bh2->b_data; /* The 0th block becomes the root, move the dirents out */ fde = &root->dotdot; de = (struct ext4_dir_entry_2 *)((char *)fde + ext4_rec_len_from_disk(fde->rec_len)); len = ((char *) root) + blocksize - (char *) de; memcpy (data1, de, len); de = (struct ext4_dir_entry_2 *) data1; top = data1 + len; while ((char *)(de2 = ext4_next_entry(de)) < top) de = de2; de->rec_len = ext4_rec_len_to_disk(data1 + blocksize - (char *) de); /* Initialize the root; the dot dirents already exist */ de = (struct ext4_dir_entry_2 *) (&root->dotdot); de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2)); memset (&root->info, 0, sizeof(root->info)); root->info.info_length = sizeof(root->info); root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version; entries = root->entries; dx_set_block(entries, 1); dx_set_count(entries, 1); dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info))); /* Initialize as for dx_probe */ hinfo.hash_version = root->info.hash_version; if (hinfo.hash_version <= DX_HASH_TEA) hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned; hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed; ext4fs_dirhash(name, namelen, &hinfo); frame = frames; frame->entries = entries; frame->at = entries; frame->bh = bh; bh = bh2; de = do_split(handle,dir, &bh, frame, &hinfo, &retval); dx_release (frames); if (!(de)) return retval; return add_dirent_to_buf(handle, dentry, inode, de, bh); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'ext4: Add sanity check to make_indexed_dir Make sure the rec_len field in the '..' entry is sane, lest we overrun the directory block and cause a kernel oops on a purposefully corrupted filesystem. Thanks to Sami Liedes for reporting this bug. http://bugzilla.kernel.org/show_bug.cgi?id=12430 Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@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 inline loff_t ext4_isize(struct ext4_inode *raw_inode) { return ((loff_t)le32_to_cpu(raw_inode->i_size_high) << 32) | le32_to_cpu(raw_inode->i_size_lo); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ext4: only use i_size_high for regular files Directories are not allowed to be bigger than 2GB, so don't use i_size_high for anything other than regular files. E2fsck should complain about these inodes, but the simplest thing to do for the kernel is to only use i_size_high for regular files. This prevents an intentially corrupted filesystem from causing the kernel to burn a huge amount of CPU and issuing error messages such as: EXT4-fs warning (device loop0): ext4_block_to_path: block 135090028 > max Thanks to David Maciejak from Fortinet's FortiGuard Global Security Research Team for reporting this issue. http://bugzilla.kernel.org/show_bug.cgi?id=12375 Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@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 ssize_t inotify_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { size_t event_size = sizeof (struct inotify_event); struct inotify_device *dev; char __user *start; int ret; DEFINE_WAIT(wait); start = buf; dev = file->private_data; while (1) { prepare_to_wait(&dev->wq, &wait, TASK_INTERRUPTIBLE); mutex_lock(&dev->ev_mutex); if (!list_empty(&dev->events)) { ret = 0; break; } mutex_unlock(&dev->ev_mutex); if (file->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -EINTR; break; } schedule(); } finish_wait(&dev->wq, &wait); if (ret) return ret; while (1) { struct inotify_kernel_event *kevent; ret = buf - start; if (list_empty(&dev->events)) break; kevent = inotify_dev_get_event(dev); if (event_size + kevent->event.len > count) { if (ret == 0 && count > 0) { /* * could not get a single event because we * didn't have enough buffer space. */ ret = -EINVAL; } break; } remove_kevent(dev, kevent); /* * Must perform the copy_to_user outside the mutex in order * to avoid a lock order reversal with mmap_sem. */ mutex_unlock(&dev->ev_mutex); if (copy_to_user(buf, &kevent->event, event_size)) { ret = -EFAULT; break; } buf += event_size; count -= event_size; if (kevent->name) { if (copy_to_user(buf, kevent->name, kevent->event.len)){ ret = -EFAULT; break; } buf += kevent->event.len; count -= kevent->event.len; } free_kevent(kevent); mutex_lock(&dev->ev_mutex); } mutex_unlock(&dev->ev_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'inotify: clean up inotify_read and fix locking problems If userspace supplies an invalid pointer to a read() of an inotify instance, the inotify device's event list mutex is unlocked twice. This causes an unbalance which effectively leaves the data structure unprotected, and we can trigger oopses by accessing the inotify instance from different tasks concurrently. The best fix (contributed largely by Linus) is a total rewrite of the function in question: On Thu, Jan 22, 2009 at 7:05 AM, Linus Torvalds wrote: > The thing to notice is that: > > - locking is done in just one place, and there is no question about it > not having an unlock. > > - that whole double-while(1)-loop thing is gone. > > - use multiple functions to make nesting and error handling sane > > - do error testing after doing the things you always need to do, ie do > this: > > mutex_lock(..) > ret = function_call(); > mutex_unlock(..) > > .. test ret here .. > > instead of doing conditional exits with unlocking or freeing. > > So if the code is written in this way, it may still be buggy, but at least > it's not buggy because of subtle "forgot to unlock" or "forgot to free" > issues. > > This _always_ unlocks if it locked, and it always frees if it got a > non-error kevent. Cc: John McCutchan <ttb@tentacle.dhs.org> Cc: Robert Love <rlove@google.com> Cc: <stable@kernel.org> Signed-off-by: Vegard Nossum <vegard.nossum@gmail.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: ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry, struct ecryptfs_crypt_stat *crypt_stat, char *page_virt, size_t size) { int rc; rc = ecryptfs_setxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME, page_virt, size, 0); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'eCryptfs: Allocate a variable number of pages for file headers When allocating the memory used to store the eCryptfs header contents, a single, zeroed page was being allocated with get_zeroed_page(). However, the size of an eCryptfs header is either PAGE_CACHE_SIZE or ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE (8192), whichever is larger, and is stored in the file's private_data->crypt_stat->num_header_bytes_at_front field. ecryptfs_write_metadata_to_contents() was using num_header_bytes_at_front to decide how many bytes should be written to the lower filesystem for the file header. Unfortunately, at least 8K was being written from the page, despite the chance of the single, zeroed page being smaller than 8K. This resulted in random areas of kernel memory being written between the 0x1000 and 0x1FFF bytes offsets in the eCryptfs file headers if PAGE_SIZE was 4K. This patch allocates a variable number of pages, calculated with num_header_bytes_at_front, and passes the number of allocated pages along to ecryptfs_write_metadata_to_contents(). Thanks to Florian Streibelt for reporting the data leak and working with me to find the problem. 2.6.28 is the only kernel release with this vulnerability. Corresponds to CVE-2009-0787 Signed-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com> Acked-by: Dustin Kirkland <kirkland@canonical.com> Reviewed-by: Eric Sandeen <sandeen@redhat.com> Reviewed-by: Eugene Teo <eugeneteo@kernel.sg> Cc: Greg KH <greg@kroah.com> Cc: dann frazier <dannf@dannf.org> Cc: Serge E. Hallyn <serue@us.ibm.com> Cc: Florian Streibelt <florian@f-streibelt.de> Cc: stable@kernel.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: int set_selection(const struct tiocl_selection __user *sel, struct tty_struct *tty) { struct vc_data *vc = vc_cons[fg_console].d; int sel_mode, new_sel_start, new_sel_end, spc; char *bp, *obp; int i, ps, pe, multiplier; u16 c; struct kbd_struct *kbd = kbd_table + fg_console; poke_blanked_console(); { unsigned short xs, ys, xe, ye; if (!access_ok(VERIFY_READ, sel, sizeof(*sel))) return -EFAULT; __get_user(xs, &sel->xs); __get_user(ys, &sel->ys); __get_user(xe, &sel->xe); __get_user(ye, &sel->ye); __get_user(sel_mode, &sel->sel_mode); xs--; ys--; xe--; ye--; xs = limit(xs, vc->vc_cols - 1); ys = limit(ys, vc->vc_rows - 1); xe = limit(xe, vc->vc_cols - 1); ye = limit(ye, vc->vc_rows - 1); ps = ys * vc->vc_size_row + (xs << 1); pe = ye * vc->vc_size_row + (xe << 1); if (sel_mode == TIOCL_SELCLEAR) { /* useful for screendump without selection highlights */ clear_selection(); return 0; } if (mouse_reporting() && (sel_mode & TIOCL_SELMOUSEREPORT)) { mouse_report(tty, sel_mode & TIOCL_SELBUTTONMASK, xs, ys); return 0; } } if (ps > pe) /* make sel_start <= sel_end */ { int tmp = ps; ps = pe; pe = tmp; } if (sel_cons != vc_cons[fg_console].d) { clear_selection(); sel_cons = vc_cons[fg_console].d; } use_unicode = kbd && kbd->kbdmode == VC_UNICODE; switch (sel_mode) { case TIOCL_SELCHAR: /* character-by-character selection */ new_sel_start = ps; new_sel_end = pe; break; case TIOCL_SELWORD: /* word-by-word selection */ spc = isspace(sel_pos(ps)); for (new_sel_start = ps; ; ps -= 2) { if ((spc && !isspace(sel_pos(ps))) || (!spc && !inword(sel_pos(ps)))) break; new_sel_start = ps; if (!(ps % vc->vc_size_row)) break; } spc = isspace(sel_pos(pe)); for (new_sel_end = pe; ; pe += 2) { if ((spc && !isspace(sel_pos(pe))) || (!spc && !inword(sel_pos(pe)))) break; new_sel_end = pe; if (!((pe + 2) % vc->vc_size_row)) break; } break; case TIOCL_SELLINE: /* line-by-line selection */ new_sel_start = ps - ps % vc->vc_size_row; new_sel_end = pe + vc->vc_size_row - pe % vc->vc_size_row - 2; break; case TIOCL_SELPOINTER: highlight_pointer(pe); return 0; default: return -EINVAL; } /* remove the pointer */ highlight_pointer(-1); /* select to end of line if on trailing space */ if (new_sel_end > new_sel_start && !atedge(new_sel_end, vc->vc_size_row) && isspace(sel_pos(new_sel_end))) { for (pe = new_sel_end + 2; ; pe += 2) if (!isspace(sel_pos(pe)) || atedge(pe, vc->vc_size_row)) break; if (isspace(sel_pos(pe))) new_sel_end = pe; } if (sel_start == -1) /* no current selection */ highlight(new_sel_start, new_sel_end); else if (new_sel_start == sel_start) { if (new_sel_end == sel_end) /* no action required */ return 0; else if (new_sel_end > sel_end) /* extend to right */ highlight(sel_end + 2, new_sel_end); else /* contract from right */ highlight(new_sel_end + 2, sel_end); } else if (new_sel_end == sel_end) { if (new_sel_start < sel_start) /* extend to left */ highlight(new_sel_start, sel_start - 2); else /* contract from left */ highlight(sel_start, new_sel_start - 2); } else /* some other case; start selection from scratch */ { clear_selection(); highlight(new_sel_start, new_sel_end); } sel_start = new_sel_start; sel_end = new_sel_end; /* Allocate a new buffer before freeing the old one ... */ multiplier = use_unicode ? 3 : 1; /* chars can take up to 3 bytes */ bp = kmalloc((sel_end-sel_start)/2*multiplier+1, GFP_KERNEL); if (!bp) { printk(KERN_WARNING "selection: kmalloc() failed\n"); clear_selection(); return -ENOMEM; } kfree(sel_buffer); sel_buffer = bp; obp = bp; for (i = sel_start; i <= sel_end; i += 2) { c = sel_pos(i); if (use_unicode) bp += store_utf8(c, bp); else *bp++ = c; if (!isspace(c)) obp = bp; if (! ((i + 2) % vc->vc_size_row)) { /* strip trailing blanks from line and add newline, unless non-space at end of line. */ if (obp != bp) { bp = obp; *bp++ = '\r'; } obp = bp; } } sel_buffer_lth = bp - sel_buffer; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fix memory corruption in console selection Fix an off-by-two memory error in console selection. The loop below goes from sel_start to sel_end (inclusive), so it writes one more character. This one more character was added to the allocated size (+1), but it was not multiplied by an UTF-8 multiplier. This patch fixes a memory corruption when UTF-8 console is used and the user selects a few characters, all of them 3-byte in UTF-8 (for example a frame line). When memory redzones are enabled, a redzone corruption is reported. When they are not enabled, trashing of random memory occurs. Signed-off-by: Mikulas Patocka <mpatocka@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: static struct dentry *nfs_readdir_lookup(nfs_readdir_descriptor_t *desc) { struct dentry *parent = desc->file->f_path.dentry; struct inode *dir = parent->d_inode; struct nfs_entry *entry = desc->entry; struct dentry *dentry, *alias; struct qstr name = { .name = entry->name, .len = entry->len, }; struct inode *inode; switch (name.len) { case 2: if (name.name[0] == '.' && name.name[1] == '.') return dget_parent(parent); break; case 1: if (name.name[0] == '.') return dget(parent); } name.hash = full_name_hash(name.name, name.len); dentry = d_lookup(parent, &name); if (dentry != NULL) { /* Is this a positive dentry that matches the readdir info? */ if (dentry->d_inode != NULL && (NFS_FILEID(dentry->d_inode) == entry->ino || d_mountpoint(dentry))) { if (!desc->plus || entry->fh->size == 0) return dentry; if (nfs_compare_fh(NFS_FH(dentry->d_inode), entry->fh) == 0) goto out_renew; } /* No, so d_drop to allow one to be created */ d_drop(dentry); dput(dentry); } if (!desc->plus || !(entry->fattr->valid & NFS_ATTR_FATTR)) return NULL; /* Note: caller is already holding the dir->i_mutex! */ dentry = d_alloc(parent, &name); if (dentry == NULL) return NULL; dentry->d_op = NFS_PROTO(dir)->dentry_ops; inode = nfs_fhget(dentry->d_sb, entry->fh, entry->fattr); if (IS_ERR(inode)) { dput(dentry); return NULL; } alias = d_materialise_unique(dentry, inode); if (alias != NULL) { dput(dentry); if (IS_ERR(alias)) return NULL; dentry = alias; } nfs_renew_times(dentry); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); return dentry; out_renew: nfs_renew_times(dentry); nfs_refresh_verifier(dentry, nfs_save_change_attribute(dir)); return dentry; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup() It doesn't look as if the NFS file name limit is being initialised correctly in the struct nfs_server. Make sure that we limit whatever is being set in nfs_probe_fsinfo() and nfs_init_server(). Also ensure that readdirplus and nfs4_path_walk respect our file name limits. Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.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: struct nfs_server *nfs4_create_referral_server(struct nfs_clone_mount *data, struct nfs_fh *mntfh) { struct nfs_client *parent_client; struct nfs_server *server, *parent_server; struct nfs_fattr fattr; int error; dprintk("--> nfs4_create_referral_server()\n"); server = nfs_alloc_server(); if (!server) return ERR_PTR(-ENOMEM); parent_server = NFS_SB(data->sb); parent_client = parent_server->nfs_client; /* Get a client representation. * Note: NFSv4 always uses TCP, */ error = nfs4_set_client(server, data->hostname, data->addr, parent_client->cl_ipaddr, data->authflavor, parent_server->client->cl_xprt->prot, parent_client->retrans_timeo, parent_client->retrans_count); if (error < 0) goto error; /* Initialise the client representation from the parent server */ nfs_server_copy_userdata(server, parent_server); server->caps |= NFS_CAP_ATOMIC_OPEN; error = nfs_init_server_rpcclient(server, data->authflavor); if (error < 0) goto error; BUG_ON(!server->nfs_client); BUG_ON(!server->nfs_client->rpc_ops); BUG_ON(!server->nfs_client->rpc_ops->file_inode_ops); /* Probe the root fh to retrieve its FSID and filehandle */ error = nfs4_path_walk(server, mntfh, data->mnt_path); if (error < 0) goto error; /* probe the filesystem info for this server filesystem */ error = nfs_probe_fsinfo(server, mntfh, &fattr); if (error < 0) goto error; dprintk("Referral FSID: %llx:%llx\n", (unsigned long long) server->fsid.major, (unsigned long long) server->fsid.minor); spin_lock(&nfs_client_lock); list_add_tail(&server->client_link, &server->nfs_client->cl_superblocks); list_add_tail(&server->master_link, &nfs_volume_list); spin_unlock(&nfs_client_lock); server->mount_time = jiffies; dprintk("<-- nfs_create_referral_server() = %p\n", server); return server; error: nfs_free_server(server); dprintk("<-- nfs4_create_referral_server() = error %d\n", error); return ERR_PTR(error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup() It doesn't look as if the NFS file name limit is being initialised correctly in the struct nfs_server. Make sure that we limit whatever is being set in nfs_probe_fsinfo() and nfs_init_server(). Also ensure that readdirplus and nfs4_path_walk respect our file name limits. Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.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: struct nfs_server *nfs_create_server(const struct nfs_mount_data *data, struct nfs_fh *mntfh) { struct nfs_server *server; struct nfs_fattr fattr; int error; server = nfs_alloc_server(); if (!server) return ERR_PTR(-ENOMEM); /* Get a client representation */ error = nfs_init_server(server, data); if (error < 0) goto error; BUG_ON(!server->nfs_client); BUG_ON(!server->nfs_client->rpc_ops); BUG_ON(!server->nfs_client->rpc_ops->file_inode_ops); /* Probe the root fh to retrieve its FSID */ error = nfs_probe_fsinfo(server, mntfh, &fattr); if (error < 0) goto error; if (!(fattr.valid & NFS_ATTR_FATTR)) { error = server->nfs_client->rpc_ops->getattr(server, mntfh, &fattr); if (error < 0) { dprintk("nfs_create_server: getattr error = %d\n", -error); goto error; } } memcpy(&server->fsid, &fattr.fsid, sizeof(server->fsid)); dprintk("Server FSID: %llx:%llx\n", (unsigned long long) server->fsid.major, (unsigned long long) server->fsid.minor); BUG_ON(!server->nfs_client); BUG_ON(!server->nfs_client->rpc_ops); BUG_ON(!server->nfs_client->rpc_ops->file_inode_ops); spin_lock(&nfs_client_lock); list_add_tail(&server->client_link, &server->nfs_client->cl_superblocks); list_add_tail(&server->master_link, &nfs_volume_list); spin_unlock(&nfs_client_lock); server->mount_time = jiffies; return server; error: nfs_free_server(server); return ERR_PTR(error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup() It doesn't look as if the NFS file name limit is being initialised correctly in the struct nfs_server. Make sure that we limit whatever is being set in nfs_probe_fsinfo() and nfs_init_server(). Also ensure that readdirplus and nfs4_path_walk respect our file name limits. Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.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: int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor) { int err; const int on = 1; if (udev_monitor->snl.nl_family != 0) { err = bind(udev_monitor->sock, (struct sockaddr *)&udev_monitor->snl, sizeof(struct sockaddr_nl)); if (err < 0) { err(udev_monitor->udev, "bind failed: %m\n"); return err; } dbg(udev_monitor->udev, "monitor %p listening on netlink\n", udev_monitor); } else if (udev_monitor->sun.sun_family != 0) { err = bind(udev_monitor->sock, (struct sockaddr *)&udev_monitor->sun, udev_monitor->addrlen); if (err < 0) { err(udev_monitor->udev, "bind failed: %m\n"); return err; } /* enable receiving of the sender credentials */ setsockopt(udev_monitor->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)); dbg(udev_monitor->udev, "monitor %p listening on socket\n", udev_monitor); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-346'], 'message': 'libudev: monitor - unify socket message handling'</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 udev_monitor_send_device(struct udev_monitor *udev_monitor, struct udev_device *udev_device) { const char *buf; ssize_t len; ssize_t count; len = udev_device_get_properties_monitor_buf(udev_device, &buf); if (len < 32) return -1; if (udev_monitor->sun.sun_family != 0) { count = sendto(udev_monitor->sock, buf, len, 0, (struct sockaddr *)&udev_monitor->sun, udev_monitor->addrlen); } else { /* no destination besides the muticast group, we will always get -1 ECONNREFUSED */ count = sendto(udev_monitor->sock, buf, len, 0, (struct sockaddr *)&udev_monitor->snl_peer, sizeof(struct sockaddr_nl)); } info(udev_monitor->udev, "passed %zi bytes to monitor %p, \n", count, udev_monitor); return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-346'], 'message': 'libudev: monitor - unify socket message handling'</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 udev_monitor_send_device(struct udev_monitor *udev_monitor, struct udev_device *udev_device) { const char *buf; ssize_t len; ssize_t count; len = udev_device_get_properties_monitor_buf(udev_device, &buf); if (len < 32) return -1; if (udev_monitor->sun.sun_family != 0) count = sendto(udev_monitor->sock, buf, len, 0, (struct sockaddr *)&udev_monitor->sun, udev_monitor->addrlen); else if (udev_monitor->snl.nl_family != 0) /* no destination besides the muticast group, we will always get ECONNREFUSED */ count = sendto(udev_monitor->sock, buf, len, 0, (struct sockaddr *)&udev_monitor->snl_peer, sizeof(struct sockaddr_nl)); else return -1; info(udev_monitor->udev, "passed %zi bytes to monitor %p, \n", count, udev_monitor); return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-346'], 'message': 'libudev: monitor - ignore messages from unusual sources For added protection, ignore any unicast message received on the netlink socket or any multicast message on the kernel group not received from the kernel. Signed-off-by: Scott James Remnant <scott@ubuntu.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 vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_msr_entry *msr; u64 host_tsc; int ret = 0; switch (msr_index) { #ifdef CONFIG_X86_64 case MSR_EFER: vmx_load_host_state(vmx); ret = kvm_set_msr_common(vcpu, msr_index, data); break; case MSR_FS_BASE: vmcs_writel(GUEST_FS_BASE, data); break; case MSR_GS_BASE: vmcs_writel(GUEST_GS_BASE, data); break; #endif case MSR_IA32_SYSENTER_CS: vmcs_write32(GUEST_SYSENTER_CS, data); break; case MSR_IA32_SYSENTER_EIP: vmcs_writel(GUEST_SYSENTER_EIP, data); break; case MSR_IA32_SYSENTER_ESP: vmcs_writel(GUEST_SYSENTER_ESP, data); break; case MSR_IA32_TIME_STAMP_COUNTER: rdtscll(host_tsc); guest_write_tsc(data, host_tsc); break; case MSR_P6_PERFCTR0: case MSR_P6_PERFCTR1: case MSR_P6_EVNTSEL0: case MSR_P6_EVNTSEL1: /* * Just discard all writes to the performance counters; this * should keep both older linux and windows 64-bit guests * happy */ pr_unimpl(vcpu, "unimplemented perfctr wrmsr: 0x%x data 0x%llx\n", msr_index, data); break; case MSR_IA32_CR_PAT: if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) { vmcs_write64(GUEST_IA32_PAT, data); vcpu->arch.pat = data; break; } /* Otherwise falls through to kvm_set_msr_common */ default: vmx_load_host_state(vmx); msr = find_msr_entry(vmx, msr_index); if (msr) { msr->data = data; break; } ret = kvm_set_msr_common(vcpu, msr_index, data); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: VMX: Don't allow uninhibited access to EFER on i386 vmx_set_msr() does not allow i386 guests to touch EFER, but they can still do so through the default: label in the switch. If they set EFER_LME, they can oops the host. Fix by having EFER access through the normal channel (which will check for EFER_LME) even on i386. Reported-and-tested-by: Benjamin Gilbert <bgilbert@cs.cmu.edu> Cc: stable@kernel.org Signed-off-by: Avi Kivity <avi@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 bool set_canon_ace_list(files_struct *fsp, canon_ace *the_ace, bool default_ace, gid_t prim_gid, bool *pacl_set_support) { connection_struct *conn = fsp->conn; bool ret = False; SMB_ACL_T the_acl = SMB_VFS_SYS_ACL_INIT(conn, (int)count_canon_ace_list(the_ace) + 1); canon_ace *p_ace; int i; SMB_ACL_ENTRY_T mask_entry; bool got_mask_entry = False; SMB_ACL_PERMSET_T mask_permset; SMB_ACL_TYPE_T the_acl_type = (default_ace ? SMB_ACL_TYPE_DEFAULT : SMB_ACL_TYPE_ACCESS); bool needs_mask = False; mode_t mask_perms = 0; #if defined(POSIX_ACL_NEEDS_MASK) /* HP-UX always wants to have a mask (called "class" there). */ needs_mask = True; #endif if (the_acl == NULL) { if (!no_acl_syscall_error(errno)) { /* * Only print this error message if we have some kind of ACL * support that's not working. Otherwise we would always get this. */ DEBUG(0,("set_canon_ace_list: Unable to init %s ACL. (%s)\n", default_ace ? "default" : "file", strerror(errno) )); } *pacl_set_support = False; return False; } if( DEBUGLVL( 10 )) { dbgtext("set_canon_ace_list: setting ACL:\n"); for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) { print_canon_ace( p_ace, i); } } for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) { SMB_ACL_ENTRY_T the_entry; SMB_ACL_PERMSET_T the_permset; /* * ACLs only "need" an ACL_MASK entry if there are any named user or * named group entries. But if there is an ACL_MASK entry, it applies * to ACL_USER, ACL_GROUP, and ACL_GROUP_OBJ entries. Set the mask * so that it doesn't deny (i.e., mask off) any permissions. */ if (p_ace->type == SMB_ACL_USER || p_ace->type == SMB_ACL_GROUP) { needs_mask = True; mask_perms |= p_ace->perms; } else if (p_ace->type == SMB_ACL_GROUP_OBJ) { mask_perms |= p_ace->perms; } /* * Get the entry for this ACE. */ if (SMB_VFS_SYS_ACL_CREATE_ENTRY(conn, &the_acl, &the_entry) == -1) { DEBUG(0,("set_canon_ace_list: Failed to create entry %d. (%s)\n", i, strerror(errno) )); goto fail; } if (p_ace->type == SMB_ACL_MASK) { mask_entry = the_entry; got_mask_entry = True; } /* * Ok - we now know the ACL calls should be working, don't * allow fallback to chmod. */ *pacl_set_support = True; /* * Initialise the entry from the canon_ace. */ /* * First tell the entry what type of ACE this is. */ if (SMB_VFS_SYS_ACL_SET_TAG_TYPE(conn, the_entry, p_ace->type) == -1) { DEBUG(0,("set_canon_ace_list: Failed to set tag type on entry %d. (%s)\n", i, strerror(errno) )); goto fail; } /* * Only set the qualifier (user or group id) if the entry is a user * or group id ACE. */ if ((p_ace->type == SMB_ACL_USER) || (p_ace->type == SMB_ACL_GROUP)) { if (SMB_VFS_SYS_ACL_SET_QUALIFIER(conn, the_entry,(void *)&p_ace->unix_ug.uid) == -1) { DEBUG(0,("set_canon_ace_list: Failed to set qualifier on entry %d. (%s)\n", i, strerror(errno) )); goto fail; } } /* * Convert the mode_t perms in the canon_ace to a POSIX permset. */ if (SMB_VFS_SYS_ACL_GET_PERMSET(conn, the_entry, &the_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to get permset on entry %d. (%s)\n", i, strerror(errno) )); goto fail; } if (map_acl_perms_to_permset(conn, p_ace->perms, &the_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to create permset for mode (%u) on entry %d. (%s)\n", (unsigned int)p_ace->perms, i, strerror(errno) )); goto fail; } /* * ..and apply them to the entry. */ if (SMB_VFS_SYS_ACL_SET_PERMSET(conn, the_entry, the_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to add permset on entry %d. (%s)\n", i, strerror(errno) )); goto fail; } if( DEBUGLVL( 10 )) print_canon_ace( p_ace, i); } if (needs_mask && !got_mask_entry) { if (SMB_VFS_SYS_ACL_CREATE_ENTRY(conn, &the_acl, &mask_entry) == -1) { DEBUG(0,("set_canon_ace_list: Failed to create mask entry. (%s)\n", strerror(errno) )); goto fail; } if (SMB_VFS_SYS_ACL_SET_TAG_TYPE(conn, mask_entry, SMB_ACL_MASK) == -1) { DEBUG(0,("set_canon_ace_list: Failed to set tag type on mask entry. (%s)\n",strerror(errno) )); goto fail; } if (SMB_VFS_SYS_ACL_GET_PERMSET(conn, mask_entry, &mask_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to get mask permset. (%s)\n", strerror(errno) )); goto fail; } if (map_acl_perms_to_permset(conn, S_IRUSR|S_IWUSR|S_IXUSR, &mask_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to create mask permset. (%s)\n", strerror(errno) )); goto fail; } if (SMB_VFS_SYS_ACL_SET_PERMSET(conn, mask_entry, mask_permset) == -1) { DEBUG(0,("set_canon_ace_list: Failed to add mask permset. (%s)\n", strerror(errno) )); goto fail; } } /* * Finally apply it to the file or directory. */ if(default_ace || fsp->is_directory || fsp->fh->fd == -1) { if (SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name, the_acl_type, the_acl) == -1) { /* * Some systems allow all the above calls and only fail with no ACL support * when attempting to apply the acl. HPUX with HFS is an example of this. JRA. */ if (no_acl_syscall_error(errno)) { *pacl_set_support = False; } if (acl_group_override(conn, prim_gid, fsp->fsp_name)) { int sret; DEBUG(5,("set_canon_ace_list: acl group control on and current user in file %s primary group.\n", fsp->fsp_name )); become_root(); sret = SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name, the_acl_type, the_acl); unbecome_root(); if (sret == 0) { ret = True; } } if (ret == False) { DEBUG(2,("set_canon_ace_list: sys_acl_set_file type %s failed for file %s (%s).\n", the_acl_type == SMB_ACL_TYPE_DEFAULT ? "directory default" : "file", fsp->fsp_name, strerror(errno) )); goto fail; } } } else { if (SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl) == -1) { /* * Some systems allow all the above calls and only fail with no ACL support * when attempting to apply the acl. HPUX with HFS is an example of this. JRA. */ if (no_acl_syscall_error(errno)) { *pacl_set_support = False; } if (acl_group_override(conn, prim_gid, fsp->fsp_name)) { int sret; DEBUG(5,("set_canon_ace_list: acl group control on and current user in file %s primary group.\n", fsp->fsp_name )); become_root(); sret = SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl); unbecome_root(); if (sret == 0) { ret = True; } } if (ret == False) { DEBUG(2,("set_canon_ace_list: sys_acl_set_file failed for file %s (%s).\n", fsp->fsp_name, strerror(errno) )); goto fail; } } } ret = True; fail: if (the_acl != NULL) { SMB_VFS_SYS_ACL_FREE_ACL(conn, the_acl); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Bug 6488: acl_group_override() call in posix acls references an uninitialized variable. (cherry picked from commit f92195e3a1baaddda47a5d496f9488c8445b41ad)'</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 unsigned int tun_chr_poll(struct file *file, poll_table * wait) { struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); struct sock *sk = tun->sk; unsigned int mask = 0; if (!tun) return POLLERR; DBG(KERN_INFO "%s: tun_chr_poll\n", tun->dev->name); poll_wait(file, &tun->socket.wait, wait); if (!skb_queue_empty(&tun->readq)) mask |= POLLIN | POLLRDNORM; if (sock_writeable(sk) || (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) && sock_writeable(sk))) mask |= POLLOUT | POLLWRNORM; if (tun->dev->reg_state != NETREG_REGISTERED) mask = POLLERR; tun_put(tun); return mask; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tun/tap: Fix crashes if open() /dev/net/tun and then poll() it. Fix NULL pointer dereference in tun_chr_pool() introduced by commit 33dccbb050bbe35b88ca8cf1228dcf3e4d4b3554 ("tun: Limit amount of queued packets per device") and triggered by this code: int fd; struct pollfd pfd; fd = open("/dev/net/tun", O_RDWR); pfd.fd = fd; pfd.events = POLLIN | POLLOUT; poll(&pfd, 1, 0); Reported-by: Eugene Kapun <abacabadabacaba@gmail.com> Signed-off-by: Mariusz Kozlowski <m.kozlowski@tuxland.pl> 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: parse_tag_11_packet(unsigned char *data, unsigned char *contents, size_t max_contents_bytes, size_t *tag_11_contents_size, size_t *packet_size, size_t max_packet_size) { size_t body_size; size_t length_size; int rc = 0; (*packet_size) = 0; (*tag_11_contents_size) = 0; /* This format is inspired by OpenPGP; see RFC 2440 * packet tag 11 * * Tag 11 identifier (1 byte) * Max Tag 11 packet size (max 3 bytes) * Binary format specifier (1 byte) * Filename length (1 byte) * Filename ("_CONSOLE") (8 bytes) * Modification date (4 bytes) * Literal data (arbitrary) * * We need at least 16 bytes of data for the packet to even be * valid. */ if (max_packet_size < 16) { printk(KERN_ERR "Maximum packet size too small\n"); rc = -EINVAL; goto out; } if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) { printk(KERN_WARNING "Invalid tag 11 packet format\n"); rc = -EINVAL; goto out; } rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size, &length_size); if (rc) { printk(KERN_WARNING "Invalid tag 11 packet format\n"); goto out; } if (body_size < 14) { printk(KERN_WARNING "Invalid body size ([%td])\n", body_size); rc = -EINVAL; goto out; } (*packet_size) += length_size; (*tag_11_contents_size) = (body_size - 14); if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) { printk(KERN_ERR "Packet size exceeds max\n"); rc = -EINVAL; goto out; } if (data[(*packet_size)++] != 0x62) { printk(KERN_WARNING "Unrecognizable packet\n"); rc = -EINVAL; goto out; } if (data[(*packet_size)++] != 0x08) { printk(KERN_WARNING "Unrecognizable packet\n"); rc = -EINVAL; goto out; } (*packet_size) += 12; /* Ignore filename and modification date */ memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size)); (*packet_size) += (*tag_11_contents_size); out: if (rc) { (*packet_size) = 0; (*tag_11_contents_size) = 0; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'eCryptfs: Check Tag 11 literal data buffer size Tag 11 packets are stored in the metadata section of an eCryptfs file to store the key signature(s) used to encrypt the file encryption key. After extracting the packet length field to determine the key signature length, a check is not performed to see if the length would exceed the key signature buffer size that was passed into parse_tag_11_packet(). Thanks to Ramon de Carvalho Valle for finding this bug using fsfuzzer. Signed-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com> Cc: stable@kernel.org (2.6.27 and 30) 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: int huft_build(b, n, s, d, e, t, m) unsigned *b; /* code lengths in bits (all assumed <= BMAX) */ unsigned n; /* number of codes (assumed <= N_MAX) */ unsigned s; /* number of simple-valued codes (0..s-1) */ ush *d; /* list of base values for non-simple codes */ ush *e; /* list of extra bits for non-simple codes */ struct huft **t; /* result: starting table */ int *m; /* maximum lookup bits, returns actual */ /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. */ { unsigned a; /* counter for codes of length k */ unsigned c[BMAX+1]; /* bit length count table */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int h; /* table level */ register unsigned i; /* counter, current code */ register unsigned j; /* counter */ register int k; /* number of bits in current code */ int l; /* bits per table (returned in m) */ register unsigned *p; /* pointer into c[], b[], or v[] */ register struct huft *q; /* points to current table */ struct huft r; /* table entry for structure assignment */ struct huft *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ register int w; /* bits before this table == (l * h) */ unsigned x[BMAX+1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Generate counts for each bit length */ memzero(c, sizeof(c)); p = b; i = n; do { Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? "%c %d\n" : "0x%x %d\n"), n-i, *p)); c[*p]++; /* assume all entries <= BMAX */ p++; /* Can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) /* null input--all zero length codes */ { q = (struct huft *) malloc (2 * sizeof *q); if (!q) return 3; hufts += 2; q[0].v.t = (struct huft *) NULL; q[1].e = 99; /* invalid code marker */ q[1].b = 1; *t = q + 1; *m = 1; return 0; } /* Find minimum and maximum length, bound *m by those */ l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; /* minimum code length */ if ((unsigned)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; /* maximum code length */ if ((unsigned)l > i) l = i; *m = l; /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */ if ((y -= c[i]) < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ *xp++ = (j += *p++); } /* Make a table of values in order of bit lengths */ p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; /* set n to length of v */ /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ h = -1; /* no tables yet--level -1 */ w = -l; /* bits decoded == (l * h) */ u[0] = (struct huft *)NULL; /* just to keep compilers happy */ q = (struct huft *)NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > w + l) { h++; w += l; /* previous table always l bits */ /* compute minimum size table less than or equal to l bits */ z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ { /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; if (j < z) while (++j < z) /* try smaller tables up to z bits */ { if ((f <<= 1) <= *++xp) break; /* enough codes to use up j bits */ f -= *xp; /* else deduct codes from patterns */ } } z = 1 << j; /* table entries for j-bit table */ /* allocate and link in new table */ if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == (struct huft *)NULL) { if (h) huft_free(u[0]); return 3; /* not enough memory */ } hufts += z + 1; /* track memory usage */ *t = q + 1; /* link to list for huft_free() */ *(t = &(q->v.t)) = (struct huft *)NULL; u[h] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (h) { x[h] = i; /* save pattern for backing up */ r.b = (uch)l; /* bits to dump before this table */ r.e = (uch)(16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = i >> (w - l); /* (get around Turbo C bug) */ u[h-1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.b = (uch)(k - w); if (p >= v + n) r.e = 99; /* out of values--invalid code */ else if (*p < s) { r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ r.v.n = (ush)(*p); /* simple code is just the value */ p++; /* one compiler does not like *p++ */ } else { r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[h]) { h--; /* don't need to update q */ w -= l; } } } /* Return true (1) if we were given an incomplete table */ return y != 0 && g != 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'avoid creating an undersized buffer for the hufts table A malformed input file can cause gzip to crash with a segmentation violation or hang in an endless loop. Reported in <http://bugs.debian.org/507263>. * NEWS (Bug fixes): Mention it.'</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 udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); /* * Get and verify the address. */ if (msg->msg_name) { struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name; if (msg->msg_namelen < sizeof(*usin)) return -EINVAL; if (usin->sin_family != AF_INET) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->daddr; dport = inet->dport; /* Open fast path for connected socket. Route will not be used, if at least one option is set. */ connected = 1; } ipc.addr = inet->saddr; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(msg, &ipc); if (err) return err; if (ipc.opt) free = 1; connected = 0; } if (!ipc.opt) ipc.opt = inet->opt; saddr = ipc.addr; ipc.addr = faddr = daddr; if (ipc.opt && ipc.opt->srr) { if (!daddr) return -EINVAL; faddr = ipc.opt->faddr; connected = 0; } tos = RT_TOS(inet->tos); if (sock_flag(sk, SOCK_LOCALROUTE) || (msg->msg_flags & MSG_DONTROUTE) || (ipc.opt && ipc.opt->is_strictroute)) { tos |= RTO_ONLINK; connected = 0; } if (MULTICAST(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } if (connected) rt = (struct rtable*)sk_dst_check(sk, 0); if (rt == NULL) { struct flowi fl = { .oif = ipc.oif, .nl_u = { .ip4_u = { .daddr = faddr, .saddr = saddr, .tos = tos } }, .proto = IPPROTO_UDP, .uli_u = { .ports = { .sport = inet->sport, .dport = dport } } }; security_sk_classify_flow(sk, &fl); err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT)); if (err) goto out; err = -EACCES; if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) goto out; if (connected) sk_dst_set(sk, dst_clone(&rt->u.dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = rt->rt_src; if (!ipc.addr) daddr = ipc.addr = rt->rt_dst; lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n"); err = -EINVAL; goto out; } /* * Now cork the socket to pend data. */ inet->cork.fl.fl4_dst = daddr; inet->cork.fl.fl_ip_dport = dport; inet->cork.fl.fl4_src = saddr; inet->cork.fl.fl_ip_sport = inet->sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk, up); release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) { UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS); return len; } /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS); } return err; do_confirm: dst_confirm(&rt->u.dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '[UDP]: Fix MSG_PROBE crash UDP tracks corking status through the pending variable. The IP layer also tracks it through the socket write queue. It is possible for the two to get out of sync when MSG_PROBE is used. This patch changes UDP to check the write queue to ensure that the two stay in sync. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> 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 int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = 0; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'NET: llc, zero sockaddr_llc struct sllc_arphrd member of sockaddr_llc might not be changed. Zero sllc before copying to the above layer's structure. Signed-off-by: Jiri Slaby <jirislaby@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: static int rose_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_rose *srose = (struct full_sockaddr_rose *)uaddr; struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); int n; if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; for (n = 0; n < rose->dest_ndigis; n++) srose->srose_digis[n] = rose->dest_digis[n]; } else { srose->srose_family = AF_ROSE; srose->srose_addr = rose->source_addr; srose->srose_call = rose->source_call; srose->srose_ndigis = rose->source_ndigis; for (n = 0; n < rose->source_ndigis; n++) srose->srose_digis[n] = rose->source_digis[n]; } *uaddr_len = sizeof(struct full_sockaddr_rose); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'rose: Fix rose_getname() leak rose_getname() can leak kernel memory to user. Signed-off-by: Eric Dumazet <eric.dumazet@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: static int econet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk; struct econet_sock *eo; struct sockaddr_ec *sec = (struct sockaddr_ec *)uaddr; if (peer) return -EOPNOTSUPP; mutex_lock(&econet_mutex); sk = sock->sk; eo = ec_sk(sk); sec->sec_family = AF_ECONET; sec->port = eo->port; sec->addr.station = eo->station; sec->addr.net = eo->net; mutex_unlock(&econet_mutex); *uaddr_len = sizeof(*sec); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'econet: Fix econet_getname() leak econet_getname() can leak kernel memory to user. Signed-off-by: Eric Dumazet <eric.dumazet@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: static int nr_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); lock_sock(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 1; sax->fsa_ax25.sax25_call = nr->user_addr; sax->fsa_digipeater[0] = nr->dest_addr; *uaddr_len = sizeof(struct full_sockaddr_ax25); } else { sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 0; sax->fsa_ax25.sax25_call = nr->source_addr; *uaddr_len = sizeof(struct sockaddr_ax25); } release_sock(sk); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'netrom: Fix nr_getname() leak nr_getname() can leak kernel memory to user. Signed-off-by: Eric Dumazet <eric.dumazet@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: static __inline__ int cbq_dump_ovl(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_ovl opt; opt.strategy = cl->ovl_strategy; opt.priority2 = cl->priority2+1; opt.penalty = (cl->penalty*1000)/HZ; RTA_PUT(skb, TCA_CBQ_OVL_STRATEGY, sizeof(opt), &opt); return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing padding fields in dumped structures Plug holes with padding fields and initialized them to zero. Signed-off-by: Patrick McHardy <kaber@trash.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: static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev, struct prefix_info *pinfo, u32 pid, u32 seq, int event, unsigned int flags) { struct prefixmsg *pmsg; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct prefix_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*pmsg), flags); pmsg = NLMSG_DATA(nlh); pmsg->prefix_family = AF_INET6; pmsg->prefix_ifindex = idev->dev->ifindex; pmsg->prefix_len = pinfo->prefix_len; pmsg->prefix_type = pinfo->type; pmsg->prefix_flags = 0; if (pinfo->onlink) pmsg->prefix_flags |= IF_PREFIX_ONLINK; if (pinfo->autoconf) pmsg->prefix_flags |= IF_PREFIX_AUTOCONF; RTA_PUT(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix); ci.preferred_time = ntohl(pinfo->prefered); ci.valid_time = ntohl(pinfo->valid); RTA_PUT(skb, PREFIX_CACHEINFO, sizeof(ci), &ci); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing padding fields in dumped structures Plug holes with padding fields and initialized them to zero. Signed-off-by: Patrick McHardy <kaber@trash.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: static void ipmr_destroy_unres(struct mfc_cache *c) { struct sk_buff *skb; atomic_dec(&cache_resolve_queue_len); while((skb=skb_dequeue(&c->mfc_un.unres.unresolved))) { if (skb->nh.iph->version == 0) { struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct iphdr)); nlh->nlmsg_type = NLMSG_ERROR; nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); skb_trim(skb, nlh->nlmsg_len); ((struct nlmsgerr*)NLMSG_DATA(nlh))->error = -ETIMEDOUT; netlink_unicast(rtnl, skb, NETLINK_CB(skb).dst_pid, MSG_DONTWAIT); } else kfree_skb(skb); } kmem_cache_free(mrt_cachep, c); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev, u32 pid, u32 seq, int event, unsigned int flags) { struct net_device *dev = idev->dev; __s32 *array = NULL; struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *subattr; __u32 mtu = dev->mtu; struct ifla_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*r), flags); r = NLMSG_DATA(nlh); r->ifi_family = AF_INET6; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev_get_flags(dev); r->ifi_change = 0; RTA_PUT(skb, IFLA_IFNAME, strlen(dev->name)+1, dev->name); if (dev->addr_len) RTA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); RTA_PUT(skb, IFLA_MTU, sizeof(mtu), &mtu); if (dev->ifindex != dev->iflink) RTA_PUT(skb, IFLA_LINK, sizeof(int), &dev->iflink); subattr = (struct rtattr*)skb->tail; RTA_PUT(skb, IFLA_PROTINFO, 0, NULL); /* return the device flags */ RTA_PUT(skb, IFLA_INET6_FLAGS, sizeof(__u32), &idev->if_flags); /* return interface cacheinfo */ ci.max_reasm_len = IPV6_MAXPLEN; ci.tstamp = (__u32)(TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) / HZ * 100 + TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) % HZ * 100 / HZ); ci.reachable_time = idev->nd_parms->reachable_time; ci.retrans_time = idev->nd_parms->retrans_time; RTA_PUT(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci); /* return the device sysctl params */ if ((array = kmalloc(DEVCONF_MAX * sizeof(*array), GFP_ATOMIC)) == NULL) goto rtattr_failure; ipv6_store_devconf(&idev->cnf, array, DEVCONF_MAX * sizeof(*array)); RTA_PUT(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(*array), array); /* XXX - Statistics/MC not implemented */ subattr->rta_len = skb->tail - (u8*)subattr; nlh->nlmsg_len = skb->tail - b; kfree(array); return skb->len; nlmsg_failure: rtattr_failure: if (array) kfree(array); skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: static __inline__ int cbq_dump_police(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_police opt; if (cl->police) { opt.police = cl->police; RTA_PUT(skb, TCA_CBQ_POLICE, sizeof(opt), &opt); } return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; struct tc_action_ops *a_o; struct tc_action a; int ret = 0; struct tcamsg *t = (struct tcamsg *) NLMSG_DATA(cb->nlh); char *kind = find_dump_kind(cb->nlh); if (kind == NULL) { printk("tc_dump_action: action bad kind\n"); return 0; } a_o = tc_lookup_action_n(kind); if (a_o == NULL) { printk("failed to find %s\n", kind); return 0; } memset(&a, 0, sizeof(struct tc_action)); a.ops = a_o; if (a_o->walk == NULL) { printk("tc_dump_action: %s !capable of dumping table\n", kind); goto rtattr_failure; } nlh = NLMSG_PUT(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, cb->nlh->nlmsg_type, sizeof(*t)); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr *) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); ret = a_o->walk(skb, cb, RTM_GETACTION, &a); if (ret < 0) goto rtattr_failure; if (ret > 0) { x->rta_len = skb->tail - (u8 *) x; ret = skb->len; } else skb_trim(skb, (u8*)x - skb->data); nlh->nlmsg_len = skb->tail - b; if (NETLINK_CB(cb->skb).pid && ret) nlh->nlmsg_flags |= NLM_F_MULTI; module_put(a_o->owner); return skb->len; rtattr_failure: nlmsg_failure: module_put(a_o->owner); skb_trim(skb, b - skb->data); return skb->len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: static int neigh_fill_info(struct sk_buff *skb, struct neighbour *n, u32 pid, u32 seq, int event, unsigned int flags) { unsigned long now = jiffies; unsigned char *b = skb->tail; struct nda_cacheinfo ci; int locked = 0; u32 probes; struct nlmsghdr *nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(struct ndmsg), flags); struct ndmsg *ndm = NLMSG_DATA(nlh); ndm->ndm_family = n->ops->family; ndm->ndm_flags = n->flags; ndm->ndm_type = n->type; ndm->ndm_ifindex = n->dev->ifindex; RTA_PUT(skb, NDA_DST, n->tbl->key_len, n->primary_key); read_lock_bh(&n->lock); locked = 1; ndm->ndm_state = n->nud_state; if (n->nud_state & NUD_VALID) RTA_PUT(skb, NDA_LLADDR, n->dev->addr_len, n->ha); ci.ndm_used = now - n->used; ci.ndm_confirmed = now - n->confirmed; ci.ndm_updated = now - n->updated; ci.ndm_refcnt = atomic_read(&n->refcnt) - 1; probes = atomic_read(&n->probes); read_unlock_bh(&n->lock); locked = 0; RTA_PUT(skb, NDA_CACHEINFO, sizeof(ci), &ci); RTA_PUT(skb, NDA_PROBES, sizeof(probes), &probes); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: if (locked) read_unlock_bh(&n->lock); skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: tcf_fill_node(struct sk_buff *skb, struct tcf_proto *tp, unsigned long fh, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = tp->q->dev->ifindex; tcm->tcm_parent = tp->classid; tcm->tcm_info = TC_H_MAKE(tp->prio, tp->protocol); RTA_PUT(skb, TCA_KIND, IFNAMSIZ, tp->ops->kind); tcm->tcm_handle = fh; if (RTM_DELTFILTER != event) { tcm->tcm_handle = 0; if (tp->ops->dump && tp->ops->dump(tp, fh, skb, tcm) < 0) goto rtattr_failure; } nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: static int neightbl_fill_param_info(struct neigh_table *tbl, struct neigh_parms *parms, struct sk_buff *skb, struct netlink_callback *cb) { struct ndtmsg *ndtmsg; struct nlmsghdr *nlh; nlh = NLMSG_NEW_ANSWER(skb, cb, RTM_NEWNEIGHTBL, sizeof(struct ndtmsg), NLM_F_MULTI); ndtmsg = NLMSG_DATA(nlh); read_lock_bh(&tbl->lock); ndtmsg->ndtm_family = tbl->family; RTA_PUT_STRING(skb, NDTA_NAME, tbl->id); if (neightbl_fill_parms(skb, parms) < 0) goto rtattr_failure; read_unlock_bh(&tbl->lock); return NLMSG_END(skb, nlh); rtattr_failure: read_unlock_bh(&tbl->lock); return NLMSG_CANCEL(skb, nlh); nlmsg_failure: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.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: __rta_reserve(struct sk_buff *skb, int attrtype, int attrlen) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; return rta; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Clear padding in netlink messages Signed-off-by: Patrick McHardy <kaber@trash.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: __nlmsg_put(struct sk_buff *skb, u32 pid, u32 seq, int type, int len, int flags) { struct nlmsghdr *nlh; int size = NLMSG_LENGTH(len); nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size)); nlh->nlmsg_type = type; nlh->nlmsg_len = size; nlh->nlmsg_flags = flags; nlh->nlmsg_pid = pid; nlh->nlmsg_seq = seq; return nlh; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Clear padding in netlink messages Signed-off-by: Patrick McHardy <kaber@trash.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: check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(mountpoint, &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: take extra care that mountpoint isn't changed during mount It's possible to trick mount.cifs into mounting onto the wrong directory by replacing the mountpoint with a symlink to a directory. mount.cifs attempts to check the validity of the mountpoint, but there's still a possible race between those checks and the mount(2) syscall. To guard against this, chdir to the mountpoint very early, and only deal with it as "." from then on out. Signed-off-by: Jeff Layton <jlayton@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: int main(int argc, char ** argv) { int c; unsigned long flags = MS_MANDLOCK; char * orgoptions = NULL; char * share_name = NULL; const char * ipaddr = NULL; char * uuid = NULL; char * mountpoint = NULL; char * options = NULL; char * optionstail; char * resolved_path = NULL; char * temp; char * dev_name; int rc = 0; int rsize = 0; int wsize = 0; int nomtab = 0; int uid = 0; int gid = 0; int optlen = 0; int orgoptlen = 0; size_t options_size = 0; size_t current_len; int retry = 0; /* set when we have to retry mount with uppercase */ struct addrinfo *addrhead = NULL, *addr; struct utsname sysinfo; struct mntent mountent; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; FILE * pmntfile; /* setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); */ if(argc && argv) thisprogram = argv[0]; else mount_cifs_usage(stderr); if(thisprogram == NULL) thisprogram = "mount.cifs"; uname(&sysinfo); /* BB add workstation name and domain and pass down */ /* #ifdef _GNU_SOURCE fprintf(stderr, " node: %s machine: %s sysname %s domain %s\n", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname); #endif */ if(argc > 2) { dev_name = argv[1]; share_name = strndup(argv[1], MAX_UNC_LEN); if (share_name == NULL) { fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM)); exit(EX_SYSERR); } mountpoint = argv[2]; } else if (argc == 2) { if ((strcmp(argv[1], "-V") == 0) || (strcmp(argv[1], "--version") == 0)) { print_cifs_mount_version(); exit(0); } if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "-?") == 0) || (strcmp(argv[1], "--help") == 0)) mount_cifs_usage(stdout); mount_cifs_usage(stderr); } else { mount_cifs_usage(stderr); } /* add sharename in opts string as unc= parm */ while ((c = getopt_long (argc, argv, "afFhilL:no:O:rsSU:vVwt:", longopts, NULL)) != -1) { switch (c) { /* No code to do the following options yet */ /* case 'l': list_with_volumelabel = 1; break; case 'L': volumelabel = optarg; break; */ /* case 'a': ++mount_all; break; */ case '?': case 'h': /* help */ mount_cifs_usage(stdout); case 'n': ++nomtab; break; case 'b': #ifdef MS_BIND flags |= MS_BIND; #else fprintf(stderr, "option 'b' (MS_BIND) not supported\n"); #endif break; case 'm': #ifdef MS_MOVE flags |= MS_MOVE; #else fprintf(stderr, "option 'm' (MS_MOVE) not supported\n"); #endif break; case 'o': orgoptions = strdup(optarg); break; case 'r': /* mount readonly */ flags |= MS_RDONLY; break; case 'U': uuid = optarg; break; case 'v': ++verboseflag; break; case 'V': print_cifs_mount_version(); exit (0); case 'w': flags &= ~MS_RDONLY; break; case 'R': rsize = atoi(optarg) ; break; case 'W': wsize = atoi(optarg); break; case '1': if (isdigit(*optarg)) { char *ep; uid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad uid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct passwd *pw; if (!(pw = getpwnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } uid = pw->pw_uid; endpwent(); } break; case '2': if (isdigit(*optarg)) { char *ep; gid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad gid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct group *gr; if (!(gr = getgrnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } gid = gr->gr_gid; endpwent(); } break; case 'u': got_user = 1; user_name = optarg; break; case 'd': domain_name = optarg; /* BB fix this - currently ignored */ got_domain = 1; break; case 'p': if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { got_password = 1; strlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1); } break; case 'S': get_password_from_file(0 /* stdin */,NULL); break; case 't': break; case 'f': ++fakemnt; break; default: fprintf(stderr, "unknown mount option %c\n",c); mount_cifs_usage(stderr); } } if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) { mount_cifs_usage(stderr); } /* make sure mountpoint is legit */ rc = chdir(mountpoint); if (rc) { fprintf(stderr, "Couldn't chdir to %s: %s\n", mountpoint, strerror(errno)); rc = EX_USAGE; goto mount_exit; } rc = check_mountpoint(thisprogram, mountpoint); if (rc) goto mount_exit; /* sanity check for unprivileged mounts */ if (getuid()) { rc = check_fstab(thisprogram, mountpoint, dev_name, &orgoptions); if (rc) goto mount_exit; /* enable any default user mount flags */ flags |= CIFS_SETUID_FLAGS; } if (getenv("PASSWD")) { if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { strlcpy(mountpassword,getenv("PASSWD"),MOUNT_PASSWD_SIZE+1); got_password = 1; } } else if (getenv("PASSWD_FD")) { get_password_from_file(atoi(getenv("PASSWD_FD")),NULL); } else if (getenv("PASSWD_FILE")) { get_password_from_file(0, getenv("PASSWD_FILE")); } if (orgoptions && parse_options(&orgoptions, &flags)) { rc = EX_USAGE; goto mount_exit; } if (getuid()) { #if !CIFS_LEGACY_SETUID_CHECK if (!(flags & (MS_USERS|MS_USER))) { fprintf(stderr, "%s: permission denied\n", thisprogram); rc = EX_USAGE; goto mount_exit; } #endif /* !CIFS_LEGACY_SETUID_CHECK */ if (geteuid()) { fprintf(stderr, "%s: not installed setuid - \"user\" " "CIFS mounts not supported.", thisprogram); rc = EX_FAIL; goto mount_exit; } } flags &= ~(MS_USERS|MS_USER); addrhead = addr = parse_server(&share_name); if((addrhead == NULL) && (got_ip == 0)) { fprintf(stderr, "No ip address specified and hostname not found\n"); rc = EX_USAGE; goto mount_exit; } /* BB save off path and pop after mount returns? */ resolved_path = (char *)malloc(PATH_MAX+1); if (!resolved_path) { fprintf(stderr, "Unable to allocate memory.\n"); rc = EX_SYSERR; goto mount_exit; } /* Note that if we can not canonicalize the name, we get another chance to see if it is valid when we chdir to it */ if(!realpath(".", resolved_path)) { fprintf(stderr, "Unable to resolve %s to canonical path: %s\n", mountpoint, strerror(errno)); rc = EX_SYSERR; goto mount_exit; } mountpoint = resolved_path; if(got_user == 0) { /* Note that the password will not be retrieved from the USER env variable (ie user%password form) as there is already a PASSWD environment varaible */ if (getenv("USER")) user_name = strdup(getenv("USER")); if (user_name == NULL) user_name = getusername(); got_user = 1; } if(got_password == 0) { char *tmp_pass = getpass("Password: "); /* BB obsolete sys call but no good replacement yet. */ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if (!tmp_pass || !mountpassword) { fprintf(stderr, "Password not entered, exiting\n"); exit(EX_USAGE); } strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1); got_password = 1; } /* FIXME launch daemon (handles dfs name resolution and credential change) remember to clear parms and overwrite password field before launching */ if(orgoptions) { optlen = strlen(orgoptions); orgoptlen = optlen; } else optlen = 0; if(share_name) optlen += strlen(share_name) + 4; else { fprintf(stderr, "No server share name specified\n"); fprintf(stderr, "\nMounting the DFS root for server not implemented yet\n"); exit(EX_USAGE); } if(user_name) optlen += strlen(user_name) + 6; optlen += MAX_ADDRESS_LEN + 4; if(mountpassword) optlen += strlen(mountpassword) + 6; mount_retry: SAFE_FREE(options); options_size = optlen + 10 + DOMAIN_SIZE; options = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */); if(options == NULL) { fprintf(stderr, "Could not allocate memory for mount options\n"); exit(EX_SYSERR); } strlcpy(options, "unc=", options_size); strlcat(options,share_name,options_size); /* scan backwards and reverse direction of slash */ temp = strrchr(options, '/'); if(temp > options + 6) *temp = '\\'; if(user_name) { /* check for syntax like user=domain\user */ if(got_domain == 0) domain_name = check_for_domain(&user_name); strlcat(options,",user=",options_size); strlcat(options,user_name,options_size); } if(retry == 0) { if(domain_name) { /* extra length accounted for in option string above */ strlcat(options,",domain=",options_size); strlcat(options,domain_name,options_size); } } strlcat(options,",ver=",options_size); strlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size); if(orgoptions) { strlcat(options,",",options_size); strlcat(options,orgoptions,options_size); } if(prefixpath) { strlcat(options,",prefixpath=",options_size); strlcat(options,prefixpath,options_size); /* no need to cat the / */ } /* convert all '\\' to '/' in share portion so that /proc/mounts looks pretty */ replace_char(dev_name, '\\', '/', strlen(share_name)); if (!got_ip && addr) { strlcat(options, ",ip=", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; switch (addr->ai_addr->sa_family) { case AF_INET6: addr6 = (struct sockaddr_in6 *) addr->ai_addr; ipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail, options_size - current_len); break; case AF_INET: addr4 = (struct sockaddr_in *) addr->ai_addr; ipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail, options_size - current_len); break; default: ipaddr = NULL; } /* if the address looks bogus, try the next one */ if (!ipaddr) { addr = addr->ai_next; if (addr) goto mount_retry; rc = EX_SYSERR; goto mount_exit; } } if (addr->ai_addr->sa_family == AF_INET6 && addr6->sin6_scope_id) { strlcat(options, "%", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; snprintf(optionstail, options_size - current_len, "%u", addr6->sin6_scope_id); } if(verboseflag) fprintf(stderr, "\nmount.cifs kernel mount options: %s", options); if (mountpassword) { /* * Commas have to be doubled, or else they will * look like the parameter separator */ if(retry == 0) check_for_comma(&mountpassword); strlcat(options,",pass=",options_size); strlcat(options,mountpassword,options_size); if (verboseflag) fprintf(stderr, ",pass=********"); } if (verboseflag) fprintf(stderr, "\n"); if (!fakemnt && mount(dev_name, ".", cifs_fstype, flags, options)) { switch (errno) { case ECONNREFUSED: case EHOSTUNREACH: if (addr) { addr = addr->ai_next; if (addr) goto mount_retry; } break; case ENODEV: fprintf(stderr, "mount error: cifs filesystem not supported by the system\n"); break; case ENXIO: if(retry == 0) { retry = 1; if (uppercase_string(dev_name) && uppercase_string(share_name) && uppercase_string(prefixpath)) { fprintf(stderr, "retrying with upper case share name\n"); goto mount_retry; } } } fprintf(stderr, "mount error(%d): %s\n", errno, strerror(errno)); fprintf(stderr, "Refer to the mount.cifs(8) manual page (e.g. man " "mount.cifs)\n"); rc = EX_FAIL; goto mount_exit; } if (nomtab) goto mount_exit; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); goto mount_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto mount_exit; } mountent.mnt_fsname = dev_name; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)cifs_fstype; mountent.mnt_opts = (char *)malloc(220); if(mountent.mnt_opts) { char * mount_user = getusername(); memset(mountent.mnt_opts,0,200); if(flags & MS_RDONLY) strlcat(mountent.mnt_opts,"ro",220); else strlcat(mountent.mnt_opts,"rw",220); if(flags & MS_MANDLOCK) strlcat(mountent.mnt_opts,",mand",220); if(flags & MS_NOEXEC) strlcat(mountent.mnt_opts,",noexec",220); if(flags & MS_NOSUID) strlcat(mountent.mnt_opts,",nosuid",220); if(flags & MS_NODEV) strlcat(mountent.mnt_opts,",nodev",220); if(flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts,",sync",220); if(mount_user) { if(getuid() != 0) { strlcat(mountent.mnt_opts, ",user=", 220); strlcat(mountent.mnt_opts, mount_user, 220); } } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile,&mountent); endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); if (rc) rc = EX_FILEIO; mount_exit: if(mountpassword) { int len = strlen(mountpassword); memset(mountpassword,0,len); SAFE_FREE(mountpassword); } if (addrhead) freeaddrinfo(addrhead); SAFE_FREE(options); SAFE_FREE(orgoptions); SAFE_FREE(resolved_path); SAFE_FREE(share_name); exit(rc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: check for invalid characters in device name and mountpoint It's apparently possible to corrupt the mtab if you pass embedded newlines to addmntent. Apparently tabs are also a problem with certain earlier glibc versions. Backslashes are also a minor issue apparently, but we can't reasonably filter those. Make sure that neither the devname or mountpoint contain any problematic characters before allowing the mount to proceed. Signed-off-by: Jeff Layton <jlayton@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: ReadBMP (const gchar *name, GError **error) { FILE *fd; guchar buffer[64]; gint ColormapSize, rowbytes, Maps; gboolean Grey = FALSE; guchar ColorMap[256][3]; gint32 image_ID; gchar magick[2]; Bitmap_Channel masks[4]; filename = name; fd = g_fopen (filename, "rb"); if (!fd) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Could not open '%s' for reading: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); return -1; } gimp_progress_init_printf (_("Opening '%s'"), gimp_filename_to_utf8 (name)); /* It is a File. Now is it a Bitmap? Read the shortest possible header */ if (!ReadOK (fd, magick, 2) || !(!strncmp (magick, "BA", 2) || !strncmp (magick, "BM", 2) || !strncmp (magick, "IC", 2) || !strncmp (magick, "PI", 2) || !strncmp (magick, "CI", 2) || !strncmp (magick, "CP", 2))) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } while (!strncmp (magick, "BA", 2)) { if (!ReadOK (fd, buffer, 12)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } if (!ReadOK (fd, magick, 2)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } } if (!ReadOK (fd, buffer, 12)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } /* bring them to the right byteorder. Not too nice, but it should work */ Bitmap_File_Head.bfSize = ToL (&buffer[0x00]); Bitmap_File_Head.zzHotX = ToS (&buffer[0x04]); Bitmap_File_Head.zzHotY = ToS (&buffer[0x06]); Bitmap_File_Head.bfOffs = ToL (&buffer[0x08]); if (!ReadOK (fd, buffer, 4)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } Bitmap_File_Head.biSize = ToL (&buffer[0x00]); /* What kind of bitmap is it? */ if (Bitmap_File_Head.biSize == 12) /* OS/2 1.x ? */ { if (!ReadOK (fd, buffer, 8)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error reading BMP file header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } Bitmap_Head.biWidth = ToS (&buffer[0x00]); /* 12 */ Bitmap_Head.biHeight = ToS (&buffer[0x02]); /* 14 */ Bitmap_Head.biPlanes = ToS (&buffer[0x04]); /* 16 */ Bitmap_Head.biBitCnt = ToS (&buffer[0x06]); /* 18 */ Bitmap_Head.biCompr = 0; Bitmap_Head.biSizeIm = 0; Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0; Bitmap_Head.biClrUsed = 0; Bitmap_Head.biClrImp = 0; Bitmap_Head.masks[0] = 0; Bitmap_Head.masks[1] = 0; Bitmap_Head.masks[2] = 0; Bitmap_Head.masks[3] = 0; memset(masks, 0, sizeof(masks)); Maps = 3; } else if (Bitmap_File_Head.biSize == 40) /* Windows 3.x */ { if (!ReadOK (fd, buffer, 36)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error reading BMP file header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } Bitmap_Head.biWidth = ToL (&buffer[0x00]); /* 12 */ Bitmap_Head.biHeight = ToL (&buffer[0x04]); /* 16 */ Bitmap_Head.biPlanes = ToS (&buffer[0x08]); /* 1A */ Bitmap_Head.biBitCnt = ToS (&buffer[0x0A]); /* 1C */ Bitmap_Head.biCompr = ToL (&buffer[0x0C]); /* 1E */ Bitmap_Head.biSizeIm = ToL (&buffer[0x10]); /* 22 */ Bitmap_Head.biXPels = ToL (&buffer[0x14]); /* 26 */ Bitmap_Head.biYPels = ToL (&buffer[0x18]); /* 2A */ Bitmap_Head.biClrUsed = ToL (&buffer[0x1C]); /* 2E */ Bitmap_Head.biClrImp = ToL (&buffer[0x20]); /* 32 */ Bitmap_Head.masks[0] = 0; Bitmap_Head.masks[1] = 0; Bitmap_Head.masks[2] = 0; Bitmap_Head.masks[3] = 0; Maps = 4; memset(masks, 0, sizeof(masks)); if (Bitmap_Head.biCompr == BI_BITFIELDS) { if (!ReadOK (fd, buffer, 3 * sizeof (guint32))) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error reading BMP file header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } Bitmap_Head.masks[0] = ToL(&buffer[0x00]); Bitmap_Head.masks[1] = ToL(&buffer[0x04]); Bitmap_Head.masks[2] = ToL(&buffer[0x08]); ReadChannelMasks (&Bitmap_Head.masks[0], masks, 3); } else switch (Bitmap_Head.biBitCnt) { case 32: masks[0].mask = 0x00ff0000; masks[0].shiftin = 16; masks[0].max_value= (gfloat)255.0; masks[1].mask = 0x0000ff00; masks[1].shiftin = 8; masks[1].max_value= (gfloat)255.0; masks[2].mask = 0x000000ff; masks[2].shiftin = 0; masks[2].max_value= (gfloat)255.0; masks[3].mask = 0xff000000; masks[3].shiftin = 24; masks[3].max_value= (gfloat)255.0; break; case 24: masks[0].mask = 0xff0000; masks[0].shiftin = 16; masks[0].max_value= (gfloat)255.0; masks[1].mask = 0x00ff00; masks[1].shiftin = 8; masks[1].max_value= (gfloat)255.0; masks[2].mask = 0x0000ff; masks[2].shiftin = 0; masks[2].max_value= (gfloat)255.0; masks[3].mask = 0x0; masks[3].shiftin = 0; masks[3].max_value= (gfloat)0.0; break; case 16: masks[0].mask = 0x7c00; masks[0].shiftin = 10; masks[0].max_value= (gfloat)31.0; masks[1].mask = 0x03e0; masks[1].shiftin = 5; masks[1].max_value= (gfloat)31.0; masks[2].mask = 0x001f; masks[2].shiftin = 0; masks[2].max_value= (gfloat)31.0; masks[3].mask = 0x0; masks[3].shiftin = 0; masks[3].max_value= (gfloat)0.0; break; default: break; } } else if (Bitmap_File_Head.biSize >= 56 && Bitmap_File_Head.biSize <= 64) /* enhanced Windows format with bit masks */ { if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error reading BMP file header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } Bitmap_Head.biWidth =ToL (&buffer[0x00]); /* 12 */ Bitmap_Head.biHeight =ToL (&buffer[0x04]); /* 16 */ Bitmap_Head.biPlanes =ToS (&buffer[0x08]); /* 1A */ Bitmap_Head.biBitCnt =ToS (&buffer[0x0A]); /* 1C */ Bitmap_Head.biCompr =ToL (&buffer[0x0C]); /* 1E */ Bitmap_Head.biSizeIm =ToL (&buffer[0x10]); /* 22 */ Bitmap_Head.biXPels =ToL (&buffer[0x14]); /* 26 */ Bitmap_Head.biYPels =ToL (&buffer[0x18]); /* 2A */ Bitmap_Head.biClrUsed =ToL (&buffer[0x1C]); /* 2E */ Bitmap_Head.biClrImp =ToL (&buffer[0x20]); /* 32 */ Bitmap_Head.masks[0] =ToL (&buffer[0x24]); /* 36 */ Bitmap_Head.masks[1] =ToL (&buffer[0x28]); /* 3A */ Bitmap_Head.masks[2] =ToL (&buffer[0x2C]); /* 3E */ Bitmap_Head.masks[3] =ToL (&buffer[0x30]); /* 42 */ Maps = 4; ReadChannelMasks (&Bitmap_Head.masks[0], masks, 4); } else { GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(filename, NULL); if (pixbuf) { gint32 layer_ID; image_ID = gimp_image_new (gdk_pixbuf_get_width (pixbuf), gdk_pixbuf_get_height (pixbuf), GIMP_RGB); layer_ID = gimp_layer_new_from_pixbuf (image_ID, _("Background"), pixbuf, 100., GIMP_NORMAL_MODE, 0, 0); g_object_unref (pixbuf); gimp_image_set_filename (image_ID, filename); gimp_image_add_layer (image_ID, layer_ID, -1); return image_ID; } else { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error reading BMP file header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } } /* Valid bitpdepthis 1, 4, 8, 16, 24, 32 */ /* 16 is awful, we should probably shoot whoever invented it */ /* There should be some colors used! */ ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps; if ((Bitmap_Head.biClrUsed == 0) && (Bitmap_Head.biBitCnt <= 8)) ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt; if (ColormapSize > 256) ColormapSize = 256; /* Sanity checks */ if (Bitmap_Head.biHeight == 0 || Bitmap_Head.biWidth == 0) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } if (Bitmap_Head.biWidth < 0) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } if (Bitmap_Head.biPlanes != 1) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } if (Bitmap_Head.biClrUsed > 256) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a valid BMP file"), gimp_filename_to_utf8 (filename)); return -1; } /* Windows and OS/2 declare filler so that rows are a multiple of * word length (32 bits == 4 bytes) */ rowbytes= ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4; #ifdef DEBUG printf ("\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, " "Comp: %u, Zeile: %u\n", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes); #endif if (Bitmap_Head.biBitCnt <= 8) { #ifdef DEBUG printf ("Colormap read\n"); #endif /* Get the Colormap */ if (!ReadColorMap (fd, ColorMap, ColormapSize, Maps, &Grey)) return -1; } fseek (fd, Bitmap_File_Head.bfOffs, SEEK_SET); /* Get the Image and return the ID or -1 on error*/ image_ID = ReadImage (fd, Bitmap_Head.biWidth, ABS (Bitmap_Head.biHeight), ColorMap, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes, Grey, masks, error); if (image_ID < 0) return -1; if (Bitmap_Head.biXPels > 0 && Bitmap_Head.biYPels > 0) { /* Fixed up from scott@asofyet's changes last year, njl195 */ gdouble xresolution; gdouble yresolution; /* I don't agree with scott's feeling that Gimp should be * trying to "fix" metric resolution translations, in the * long term Gimp should be SI (metric) anyway, but we * haven't told the Americans that yet */ xresolution = Bitmap_Head.biXPels * 0.0254; yresolution = Bitmap_Head.biYPels * 0.0254; gimp_image_set_resolution (image_ID, xresolution, yresolution); } if (Bitmap_Head.biHeight < 0) gimp_image_flip (image_ID, GIMP_ORIENTATION_VERTICAL); return image_ID; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Harden the BMP plugin against integer overflows. Issues discovered by Stefan Cornelius, Secunia Research, advisory SA37232 and CVE identifier CVE-2009-1570. Fixes bug #600484.'</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_layer_block (PSDimage *img_a, FILE *f, GError **error) { PSDlayer **lyr_a; guint32 block_len; guint32 block_end; guint32 block_rem; gint32 read_len; gint32 write_len; gint lidx; /* Layer index */ gint cidx; /* Channel index */ if (fread (&block_len, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); img_a->num_layers = -1; return NULL; } img_a->mask_layer_len = GUINT32_FROM_BE (block_len); IFDBG(1) g_debug ("Layer and mask block size = %d", img_a->mask_layer_len); img_a->transparency = FALSE; img_a->layer_data_len = 0; if (!img_a->mask_layer_len) { img_a->num_layers = 0; return NULL; } else { img_a->mask_layer_start = ftell (f); block_end = img_a->mask_layer_start + img_a->mask_layer_len; /* Get number of layers */ if (fread (&block_len, 4, 1, f) < 1 || fread (&img_a->num_layers, 2, 1, f) < 1) { psd_set_error (feof (f), errno, error); img_a->num_layers = -1; return NULL; } img_a->num_layers = GINT16_FROM_BE (img_a->num_layers); IFDBG(2) g_debug ("Number of layers: %d", img_a->num_layers); if (img_a->num_layers < 0) { img_a->transparency = TRUE; img_a->num_layers = -img_a->num_layers; } if (img_a->num_layers) { /* Read layer records */ PSDlayerres res_a; /* Create pointer array for the layer records */ lyr_a = g_new (PSDlayer *, img_a->num_layers); for (lidx = 0; lidx < img_a->num_layers; ++lidx) { /* Allocate layer record */ lyr_a[lidx] = (PSDlayer *) g_malloc (sizeof (PSDlayer) ); /* Initialise record */ lyr_a[lidx]->drop = FALSE; lyr_a[lidx]->id = 0; if (fread (&lyr_a[lidx]->top, 4, 1, f) < 1 || fread (&lyr_a[lidx]->left, 4, 1, f) < 1 || fread (&lyr_a[lidx]->bottom, 4, 1, f) < 1 || fread (&lyr_a[lidx]->right, 4, 1, f) < 1 || fread (&lyr_a[lidx]->num_channels, 2, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } lyr_a[lidx]->top = GINT32_FROM_BE (lyr_a[lidx]->top); lyr_a[lidx]->left = GINT32_FROM_BE (lyr_a[lidx]->left); lyr_a[lidx]->bottom = GINT32_FROM_BE (lyr_a[lidx]->bottom); lyr_a[lidx]->right = GINT32_FROM_BE (lyr_a[lidx]->right); lyr_a[lidx]->num_channels = GUINT16_FROM_BE (lyr_a[lidx]->num_channels); if (lyr_a[lidx]->num_channels > MAX_CHANNELS) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Too many channels in layer: %d"), lyr_a[lidx]->num_channels); return NULL; } if (lyr_a[lidx]->bottom - lyr_a[lidx]->top > GIMP_MAX_IMAGE_SIZE) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Unsupported or invalid layer height: %d"), lyr_a[lidx]->bottom - lyr_a[lidx]->top); return NULL; } if (lyr_a[lidx]->right - lyr_a[lidx]->left > GIMP_MAX_IMAGE_SIZE) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Unsupported or invalid layer width: %d"), lyr_a[lidx]->right - lyr_a[lidx]->left); return NULL; } IFDBG(2) g_debug ("Layer %d, Coords %d %d %d %d, channels %d, ", lidx, lyr_a[lidx]->left, lyr_a[lidx]->top, lyr_a[lidx]->right, lyr_a[lidx]->bottom, lyr_a[lidx]->num_channels); lyr_a[lidx]->chn_info = g_new (ChannelLengthInfo, lyr_a[lidx]->num_channels); for (cidx = 0; cidx < lyr_a[lidx]->num_channels; ++cidx) { if (fread (&lyr_a[lidx]->chn_info[cidx].channel_id, 2, 1, f) < 1 || fread (&lyr_a[lidx]->chn_info[cidx].data_len, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } lyr_a[lidx]->chn_info[cidx].channel_id = GINT16_FROM_BE (lyr_a[lidx]->chn_info[cidx].channel_id); lyr_a[lidx]->chn_info[cidx].data_len = GUINT32_FROM_BE (lyr_a[lidx]->chn_info[cidx].data_len); img_a->layer_data_len += lyr_a[lidx]->chn_info[cidx].data_len; IFDBG(3) g_debug ("Channel ID %d, data len %d", lyr_a[lidx]->chn_info[cidx].channel_id, lyr_a[lidx]->chn_info[cidx].data_len); } if (fread (lyr_a[lidx]->mode_key, 4, 1, f) < 1 || fread (lyr_a[lidx]->blend_mode, 4, 1, f) < 1 || fread (&lyr_a[lidx]->opacity, 1, 1, f) < 1 || fread (&lyr_a[lidx]->clipping, 1, 1, f) < 1 || fread (&lyr_a[lidx]->flags, 1, 1, f) < 1 || fread (&lyr_a[lidx]->filler, 1, 1, f) < 1 || fread (&lyr_a[lidx]->extra_len, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } if (memcmp (lyr_a[lidx]->mode_key, "8BIM", 4) != 0) { IFDBG(1) g_debug ("Incorrect layer mode signature %.4s", lyr_a[lidx]->mode_key); g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("The file is corrupt!")); return NULL; } lyr_a[lidx]->layer_flags.trans_prot = lyr_a[lidx]->flags & 1 ? TRUE : FALSE; lyr_a[lidx]->layer_flags.visible = lyr_a[lidx]->flags & 2 ? FALSE : TRUE; if (lyr_a[lidx]->flags & 8) lyr_a[lidx]->layer_flags.irrelevant = lyr_a[lidx]->flags & 16 ? TRUE : FALSE; else lyr_a[lidx]->layer_flags.irrelevant = FALSE; lyr_a[lidx]->extra_len = GUINT32_FROM_BE (lyr_a[lidx]->extra_len); block_rem = lyr_a[lidx]->extra_len; IFDBG(2) g_debug ("\n\tLayer mode sig: %.4s\n\tBlend mode: %.4s\n\t" "Opacity: %d\n\tClipping: %d\n\tExtra data len: %d\n\t" "Alpha lock: %d\n\tVisible: %d\n\tIrrelevant: %d", lyr_a[lidx]->mode_key, lyr_a[lidx]->blend_mode, lyr_a[lidx]->opacity, lyr_a[lidx]->clipping, lyr_a[lidx]->extra_len, lyr_a[lidx]->layer_flags.trans_prot, lyr_a[lidx]->layer_flags.visible, lyr_a[lidx]->layer_flags.irrelevant); IFDBG(3) g_debug ("Remaining length %d", block_rem); /* Layer mask data */ if (fread (&block_len, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } block_len = GUINT32_FROM_BE (block_len); block_rem -= (block_len + 4); IFDBG(3) g_debug ("Remaining length %d", block_rem); lyr_a[lidx]->layer_mask_extra.top = 0; lyr_a[lidx]->layer_mask_extra.left = 0; lyr_a[lidx]->layer_mask_extra.bottom = 0; lyr_a[lidx]->layer_mask_extra.right = 0; lyr_a[lidx]->layer_mask.top = 0; lyr_a[lidx]->layer_mask.left = 0; lyr_a[lidx]->layer_mask.bottom = 0; lyr_a[lidx]->layer_mask.right = 0; lyr_a[lidx]->layer_mask.def_color = 0; lyr_a[lidx]->layer_mask.extra_def_color = 0; lyr_a[lidx]->layer_mask.mask_flags.relative_pos = FALSE; lyr_a[lidx]->layer_mask.mask_flags.disabled = FALSE; lyr_a[lidx]->layer_mask.mask_flags.invert = FALSE; switch (block_len) { case 0: break; case 20: if (fread (&lyr_a[lidx]->layer_mask.top, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.left, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.bottom, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.right, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.def_color, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.flags, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.extra_def_color, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.extra_flags, 1, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } lyr_a[lidx]->layer_mask.top = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.top); lyr_a[lidx]->layer_mask.left = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.left); lyr_a[lidx]->layer_mask.bottom = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.bottom); lyr_a[lidx]->layer_mask.right = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.right); lyr_a[lidx]->layer_mask.mask_flags.relative_pos = lyr_a[lidx]->layer_mask.flags & 1 ? TRUE : FALSE; lyr_a[lidx]->layer_mask.mask_flags.disabled = lyr_a[lidx]->layer_mask.flags & 2 ? TRUE : FALSE; lyr_a[lidx]->layer_mask.mask_flags.invert = lyr_a[lidx]->layer_mask.flags & 4 ? TRUE : FALSE; break; case 36: /* If we have a 36 byte mask record assume second data set is correct */ if (fread (&lyr_a[lidx]->layer_mask_extra.top, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask_extra.left, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask_extra.bottom, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask_extra.right, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.extra_def_color, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.extra_flags, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.def_color, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.flags, 1, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.top, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.left, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.bottom, 4, 1, f) < 1 || fread (&lyr_a[lidx]->layer_mask.right, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } lyr_a[lidx]->layer_mask_extra.top = GINT32_FROM_BE (lyr_a[lidx]->layer_mask_extra.top); lyr_a[lidx]->layer_mask_extra.left = GINT32_FROM_BE (lyr_a[lidx]->layer_mask_extra.left); lyr_a[lidx]->layer_mask_extra.bottom = GINT32_FROM_BE (lyr_a[lidx]->layer_mask_extra.bottom); lyr_a[lidx]->layer_mask_extra.right = GINT32_FROM_BE (lyr_a[lidx]->layer_mask_extra.right); lyr_a[lidx]->layer_mask.top = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.top); lyr_a[lidx]->layer_mask.left = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.left); lyr_a[lidx]->layer_mask.bottom = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.bottom); lyr_a[lidx]->layer_mask.right = GINT32_FROM_BE (lyr_a[lidx]->layer_mask.right); lyr_a[lidx]->layer_mask.mask_flags.relative_pos = lyr_a[lidx]->layer_mask.flags & 1 ? TRUE : FALSE; lyr_a[lidx]->layer_mask.mask_flags.disabled = lyr_a[lidx]->layer_mask.flags & 2 ? TRUE : FALSE; lyr_a[lidx]->layer_mask.mask_flags.invert = lyr_a[lidx]->layer_mask.flags & 4 ? TRUE : FALSE; break; default: IFDBG(1) g_debug ("Unknown layer mask record size ... skipping"); if (fseek (f, block_len, SEEK_CUR) < 0) { psd_set_error (feof (f), errno, error); return NULL; } } IFDBG(2) g_debug ("Layer mask coords %d %d %d %d, Rel pos %d", lyr_a[lidx]->layer_mask.left, lyr_a[lidx]->layer_mask.top, lyr_a[lidx]->layer_mask.right, lyr_a[lidx]->layer_mask.bottom, lyr_a[lidx]->layer_mask.mask_flags.relative_pos); IFDBG(3) g_debug ("Default mask color, %d, %d", lyr_a[lidx]->layer_mask.def_color, lyr_a[lidx]->layer_mask.extra_def_color); /* Layer blending ranges */ /* FIXME */ if (fread (&block_len, 4, 1, f) < 1) { psd_set_error (feof (f), errno, error); return NULL; } block_len = GUINT32_FROM_BE (block_len); block_rem -= (block_len + 4); IFDBG(3) g_debug ("Remaining length %d", block_rem); if (block_len > 0) { if (fseek (f, block_len, SEEK_CUR) < 0) { psd_set_error (feof (f), errno, error); return NULL; } } lyr_a[lidx]->name = fread_pascal_string (&read_len, &write_len, 4, f, error); if (*error) return NULL; block_rem -= read_len; IFDBG(3) g_debug ("Remaining length %d", block_rem); /* Adjustment layer info */ /* FIXME */ while (block_rem > 7) { if (get_layer_resource_header (&res_a, f, error) < 0) return NULL; block_rem -= 12; if (res_a.data_len > block_rem) { IFDBG(1) g_debug ("Unexpected end of layer resource data"); g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("The file is corrupt!")); return NULL; } if (load_layer_resource (&res_a, lyr_a[lidx], f, error) < 0) return NULL; block_rem -= res_a.data_len; } if (block_rem > 0) { if (fseek (f, block_rem, SEEK_CUR) < 0) { psd_set_error (feof (f), errno, error); return NULL; } } } img_a->layer_data_start = ftell(f); if (fseek (f, img_a->layer_data_len, SEEK_CUR) < 0) { psd_set_error (feof (f), errno, error); return NULL; } IFDBG(1) g_debug ("Layer image data block size %d", img_a->layer_data_len); } else lyr_a = NULL; /* Read global layer mask record */ /* FIXME */ /* Skip to end of block */ if (fseek (f, block_end, SEEK_SET) < 0) { psd_set_error (feof (f), errno, error); return NULL; } } return lyr_a; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Harden the PSD plugin against integer overflows. Issues discovered by Stefan Cornelius, Secunia Research, advisory SA37232 and CVE identifier CVE-2009-3909. Fixes bug #600741. (cherry picked from commit 9cc8d78ff33b7a36852b74e64b427489cad44d0e)'</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: add_layers (const gint32 image_id, PSDimage *img_a, PSDlayer **lyr_a, FILE *f, GError **error) { PSDchannel **lyr_chn; guchar *pixels; guint16 alpha_chn; guint16 user_mask_chn; guint16 layer_channels; guint16 channel_idx[MAX_CHANNELS]; guint16 *rle_pack_len; gint32 l_x; /* Layer x */ gint32 l_y; /* Layer y */ gint32 l_w; /* Layer width */ gint32 l_h; /* Layer height */ gint32 lm_x; /* Layer mask x */ gint32 lm_y; /* Layer mask y */ gint32 lm_w; /* Layer mask width */ gint32 lm_h; /* Layer mask height */ gint32 layer_size; gint32 layer_id = -1; gint32 mask_id = -1; gint lidx; /* Layer index */ gint cidx; /* Channel index */ gint rowi; /* Row index */ gint coli; /* Column index */ gint i; gboolean alpha; gboolean user_mask; gboolean empty; gboolean empty_mask; GimpDrawable *drawable; GimpPixelRgn pixel_rgn; GimpImageType image_type; GimpLayerModeEffects layer_mode; IFDBG(2) g_debug ("Number of layers: %d", img_a->num_layers); if (img_a->num_layers == 0) { IFDBG(2) g_debug ("No layers to process"); return 0; } /* Layered image - Photoshop 3 style */ if (fseek (f, img_a->layer_data_start, SEEK_SET) < 0) { psd_set_error (feof (f), errno, error); return -1; } for (lidx = 0; lidx < img_a->num_layers; ++lidx) { IFDBG(2) g_debug ("Process Layer No %d.", lidx); if (lyr_a[lidx]->drop) { IFDBG(2) g_debug ("Drop layer %d", lidx); /* Step past layer data */ for (cidx = 0; cidx < lyr_a[lidx]->num_channels; ++cidx) { if (fseek (f, lyr_a[lidx]->chn_info[cidx].data_len, SEEK_CUR) < 0) { psd_set_error (feof (f), errno, error); return -1; } } g_free (lyr_a[lidx]->chn_info); g_free (lyr_a[lidx]->name); } else { /* Empty layer */ if (lyr_a[lidx]->bottom - lyr_a[lidx]->top == 0 || lyr_a[lidx]->right - lyr_a[lidx]->left == 0) empty = TRUE; else empty = FALSE; /* Empty mask */ if (lyr_a[lidx]->layer_mask.bottom - lyr_a[lidx]->layer_mask.top == 0 || lyr_a[lidx]->layer_mask.right - lyr_a[lidx]->layer_mask.left == 0) empty_mask = TRUE; else empty_mask = FALSE; IFDBG(3) g_debug ("Empty mask %d, size %d %d", empty_mask, lyr_a[lidx]->layer_mask.bottom - lyr_a[lidx]->layer_mask.top, lyr_a[lidx]->layer_mask.right - lyr_a[lidx]->layer_mask.left); /* Load layer channel data */ IFDBG(2) g_debug ("Number of channels: %d", lyr_a[lidx]->num_channels); /* Create pointer array for the channel records */ lyr_chn = g_new (PSDchannel *, lyr_a[lidx]->num_channels); for (cidx = 0; cidx < lyr_a[lidx]->num_channels; ++cidx) { guint16 comp_mode = PSD_COMP_RAW; /* Allocate channel record */ lyr_chn[cidx] = g_malloc (sizeof (PSDchannel) ); lyr_chn[cidx]->id = lyr_a[lidx]->chn_info[cidx].channel_id; lyr_chn[cidx]->rows = lyr_a[lidx]->bottom - lyr_a[lidx]->top; lyr_chn[cidx]->columns = lyr_a[lidx]->right - lyr_a[lidx]->left; if (lyr_chn[cidx]->id == PSD_CHANNEL_MASK) { /* Works around a bug in panotools psd files where the layer mask size is given as 0 but data exists. Set mask size to layer size. */ if (empty_mask && lyr_a[lidx]->chn_info[cidx].data_len - 2 > 0) { empty_mask = FALSE; if (lyr_a[lidx]->layer_mask.top == lyr_a[lidx]->layer_mask.bottom) { lyr_a[lidx]->layer_mask.top = lyr_a[lidx]->top; lyr_a[lidx]->layer_mask.bottom = lyr_a[lidx]->bottom; } if (lyr_a[lidx]->layer_mask.right == lyr_a[lidx]->layer_mask.left) { lyr_a[lidx]->layer_mask.right = lyr_a[lidx]->right; lyr_a[lidx]->layer_mask.left = lyr_a[lidx]->left; } } lyr_chn[cidx]->rows = (lyr_a[lidx]->layer_mask.bottom - lyr_a[lidx]->layer_mask.top); lyr_chn[cidx]->columns = (lyr_a[lidx]->layer_mask.right - lyr_a[lidx]->layer_mask.left); } IFDBG(3) g_debug ("Channel id %d, %dx%d", lyr_chn[cidx]->id, lyr_chn[cidx]->columns, lyr_chn[cidx]->rows); /* Only read channel data if there is any channel * data. Note that the channel data can contain a * compression method but no actual data. */ if (lyr_a[lidx]->chn_info[cidx].data_len >= COMP_MODE_SIZE) { if (fread (&comp_mode, COMP_MODE_SIZE, 1, f) < 1) { psd_set_error (feof (f), errno, error); return -1; } comp_mode = GUINT16_FROM_BE (comp_mode); IFDBG(3) g_debug ("Compression mode: %d", comp_mode); } if (lyr_a[lidx]->chn_info[cidx].data_len > COMP_MODE_SIZE) { switch (comp_mode) { case PSD_COMP_RAW: /* Planar raw data */ IFDBG(3) g_debug ("Raw data length: %d", lyr_a[lidx]->chn_info[cidx].data_len - 2); if (read_channel_data (lyr_chn[cidx], img_a->bps, PSD_COMP_RAW, NULL, f, error) < 1) return -1; break; case PSD_COMP_RLE: /* Packbits */ IFDBG(3) g_debug ("RLE channel length %d, RLE length data: %d, " "RLE data block: %d", lyr_a[lidx]->chn_info[cidx].data_len - 2, lyr_chn[cidx]->rows * 2, (lyr_a[lidx]->chn_info[cidx].data_len - 2 - lyr_chn[cidx]->rows * 2)); rle_pack_len = g_malloc (lyr_chn[cidx]->rows * 2); for (rowi = 0; rowi < lyr_chn[cidx]->rows; ++rowi) { if (fread (&rle_pack_len[rowi], 2, 1, f) < 1) { psd_set_error (feof (f), errno, error); return -1; } rle_pack_len[rowi] = GUINT16_FROM_BE (rle_pack_len[rowi]); } IFDBG(3) g_debug ("RLE decode - data"); if (read_channel_data (lyr_chn[cidx], img_a->bps, PSD_COMP_RLE, rle_pack_len, f, error) < 1) return -1; g_free (rle_pack_len); break; case PSD_COMP_ZIP: /* ? */ case PSD_COMP_ZIP_PRED: default: g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Unsupported compression mode: %d"), comp_mode); return -1; break; } } } g_free (lyr_a[lidx]->chn_info); /* Draw layer */ alpha = FALSE; alpha_chn = -1; user_mask = FALSE; user_mask_chn = -1; layer_channels = 0; l_x = 0; l_y = 0; l_w = img_a->columns; l_h = img_a->rows; IFDBG(3) g_debug ("Re-hash channel indices"); for (cidx = 0; cidx < lyr_a[lidx]->num_channels; ++cidx) { if (lyr_chn[cidx]->id == PSD_CHANNEL_MASK) { user_mask = TRUE; user_mask_chn = cidx; } else if (lyr_chn[cidx]->id == PSD_CHANNEL_ALPHA) { alpha = TRUE; alpha_chn = cidx; } else { channel_idx[layer_channels] = cidx; /* Assumes in sane order */ layer_channels++; /* RGB, Lab, CMYK etc. */ } } if (alpha) { channel_idx[layer_channels] = alpha_chn; layer_channels++; } if (empty) { IFDBG(2) g_debug ("Create blank layer"); image_type = get_gimp_image_type (img_a->base_type, TRUE); layer_id = gimp_layer_new (image_id, lyr_a[lidx]->name, img_a->columns, img_a->rows, image_type, 0, GIMP_NORMAL_MODE); g_free (lyr_a[lidx]->name); gimp_image_add_layer (image_id, layer_id, -1); drawable = gimp_drawable_get (layer_id); gimp_drawable_fill (drawable->drawable_id, GIMP_TRANSPARENT_FILL); gimp_drawable_set_visible (drawable->drawable_id, lyr_a[lidx]->layer_flags.visible); if (lyr_a[lidx]->id) gimp_drawable_set_tattoo (drawable->drawable_id, lyr_a[lidx]->id); if (lyr_a[lidx]->layer_flags.irrelevant) gimp_drawable_set_visible (drawable->drawable_id, FALSE); gimp_drawable_flush (drawable); gimp_drawable_detach (drawable); } else { l_x = lyr_a[lidx]->left; l_y = lyr_a[lidx]->top; l_w = lyr_a[lidx]->right - lyr_a[lidx]->left; l_h = lyr_a[lidx]->bottom - lyr_a[lidx]->top; IFDBG(3) g_debug ("Draw layer"); image_type = get_gimp_image_type (img_a->base_type, alpha); IFDBG(3) g_debug ("Layer type %d", image_type); layer_size = l_w * l_h; pixels = g_malloc (layer_size * layer_channels); for (cidx = 0; cidx < layer_channels; ++cidx) { IFDBG(3) g_debug ("Start channel %d", channel_idx[cidx]); for (i = 0; i < layer_size; ++i) pixels[(i * layer_channels) + cidx] = lyr_chn[channel_idx[cidx]]->data[i]; g_free (lyr_chn[channel_idx[cidx]]->data); } layer_mode = psd_to_gimp_blend_mode (lyr_a[lidx]->blend_mode); layer_id = gimp_layer_new (image_id, lyr_a[lidx]->name, l_w, l_h, image_type, lyr_a[lidx]->opacity * 100 / 255, layer_mode); IFDBG(3) g_debug ("Layer tattoo: %d", layer_id); g_free (lyr_a[lidx]->name); gimp_image_add_layer (image_id, layer_id, -1); gimp_layer_set_offsets (layer_id, l_x, l_y); gimp_layer_set_lock_alpha (layer_id, lyr_a[lidx]->layer_flags.trans_prot); drawable = gimp_drawable_get (layer_id); gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, drawable->width, drawable->height, TRUE, FALSE); gimp_pixel_rgn_set_rect (&pixel_rgn, pixels, 0, 0, drawable->width, drawable->height); gimp_drawable_set_visible (drawable->drawable_id, lyr_a[lidx]->layer_flags.visible); if (lyr_a[lidx]->id) gimp_drawable_set_tattoo (drawable->drawable_id, lyr_a[lidx]->id); gimp_drawable_flush (drawable); gimp_drawable_detach (drawable); g_free (pixels); } /* Layer mask */ if (user_mask) { if (empty_mask) { IFDBG(3) g_debug ("Create empty mask"); if (lyr_a[lidx]->layer_mask.def_color == 255) mask_id = gimp_layer_create_mask (layer_id, GIMP_ADD_WHITE_MASK); else mask_id = gimp_layer_create_mask (layer_id, GIMP_ADD_BLACK_MASK); gimp_layer_add_mask (layer_id, mask_id); gimp_layer_set_apply_mask (layer_id, ! lyr_a[lidx]->layer_mask.mask_flags.disabled); } else { /* Load layer mask data */ if (lyr_a[lidx]->layer_mask.mask_flags.relative_pos) { lm_x = lyr_a[lidx]->layer_mask.left; lm_y = lyr_a[lidx]->layer_mask.top; lm_w = lyr_a[lidx]->layer_mask.right - lyr_a[lidx]->layer_mask.left; lm_h = lyr_a[lidx]->layer_mask.bottom - lyr_a[lidx]->layer_mask.top; } else { lm_x = lyr_a[lidx]->layer_mask.left - l_x; lm_y = lyr_a[lidx]->layer_mask.top - l_y; lm_w = lyr_a[lidx]->layer_mask.right - lyr_a[lidx]->layer_mask.left; lm_h = lyr_a[lidx]->layer_mask.bottom - lyr_a[lidx]->layer_mask.top; } IFDBG(3) g_debug ("Mask channel index %d", user_mask_chn); IFDBG(3) g_debug ("Relative pos %d", lyr_a[lidx]->layer_mask.mask_flags.relative_pos); layer_size = lm_w * lm_h; pixels = g_malloc (layer_size); IFDBG(3) g_debug ("Allocate Pixels %d", layer_size); /* Crop mask at layer boundry */ IFDBG(3) g_debug ("Original Mask %d %d %d %d", lm_x, lm_y, lm_w, lm_h); if (lm_x < 0 || lm_y < 0 || lm_w + lm_x > l_w || lm_h + lm_y > l_h) { if (CONVERSION_WARNINGS) g_message ("Warning\n" "The layer mask is partly outside the " "layer boundary. The mask will be " "cropped which may result in data loss."); i = 0; for (rowi = 0; rowi < lm_h; ++rowi) { if (rowi + lm_y >= 0 && rowi + lm_y < l_h) { for (coli = 0; coli < lm_w; ++coli) { if (coli + lm_x >= 0 && coli + lm_x < l_w) { pixels[i] = lyr_chn[user_mask_chn]->data[(rowi * lm_w) + coli]; i++; } } } } if (lm_x < 0) { lm_w += lm_x; lm_x = 0; } if (lm_y < 0) { lm_h += lm_y; lm_y = 0; } if (lm_w + lm_x > l_w) lm_w = l_w - lm_x; if (lm_h + lm_y > l_h) lm_h = l_h - lm_y; } else memcpy (pixels, lyr_chn[user_mask_chn]->data, layer_size); g_free (lyr_chn[user_mask_chn]->data); /* Draw layer mask data */ IFDBG(3) g_debug ("Layer %d %d %d %d", l_x, l_y, l_w, l_h); IFDBG(3) g_debug ("Mask %d %d %d %d", lm_x, lm_y, lm_w, lm_h); if (lyr_a[lidx]->layer_mask.def_color == 255) mask_id = gimp_layer_create_mask (layer_id, GIMP_ADD_WHITE_MASK); else mask_id = gimp_layer_create_mask (layer_id, GIMP_ADD_BLACK_MASK); IFDBG(3) g_debug ("New layer mask %d", mask_id); gimp_layer_add_mask (layer_id, mask_id); drawable = gimp_drawable_get (mask_id); gimp_pixel_rgn_init (&pixel_rgn, drawable, 0 , 0, drawable->width, drawable->height, TRUE, FALSE); gimp_pixel_rgn_set_rect (&pixel_rgn, pixels, lm_x, lm_y, lm_w, lm_h); gimp_drawable_flush (drawable); gimp_drawable_detach (drawable); gimp_layer_set_apply_mask (layer_id, ! lyr_a[lidx]->layer_mask.mask_flags.disabled); g_free (pixels); } } for (cidx = 0; cidx < lyr_a[lidx]->num_channels; ++cidx) if (lyr_chn[cidx]) g_free (lyr_chn[cidx]); g_free (lyr_chn); } g_free (lyr_a[lidx]); } g_free (lyr_a); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Harden the PSD plugin against integer overflows. Issues discovered by Stefan Cornelius, Secunia Research, advisory SA37232 and CVE identifier CVE-2009-3909. Fixes bug #600741. (cherry picked from commit 9cc8d78ff33b7a36852b74e64b427489cad44d0e)'</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: x86_decode_insn(struct x86_emulate_ctxt *ctxt, struct x86_emulate_ops *ops) { struct decode_cache *c = &ctxt->decode; int rc = 0; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, group; /* Shadow copy of register state. Committed on successful emulation. */ memset(c, 0, sizeof(struct decode_cache)); c->eip = kvm_rip_read(ctxt->vcpu); ctxt->cs_base = seg_base(ctxt, VCPU_SREG_CS); memcpy(c->regs, ctxt->vcpu->arch.regs, sizeof c->regs); switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return -1; } c->op_bytes = def_op_bytes; c->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (c->b = insn_fetch(u8, 1, c->eip)) { case 0x66: /* operand-size override */ /* switch between 2/4 bytes */ c->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ c->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ c->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ set_seg_override(c, (c->b >> 3) & 3); break; case 0x64: /* FS override */ case 0x65: /* GS override */ set_seg_override(c, c->b & 7); break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; c->rex_prefix = c->b; continue; case 0xf0: /* LOCK */ c->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ c->rep_prefix = REPNE_PREFIX; break; case 0xf3: /* REP/REPE/REPZ */ c->rep_prefix = REPE_PREFIX; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ c->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (c->rex_prefix) if (c->rex_prefix & 8) c->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ c->d = opcode_table[c->b]; if (c->d == 0) { /* Two-byte opcode? */ if (c->b == 0x0f) { c->twobyte = 1; c->b = insn_fetch(u8, 1, c->eip); c->d = twobyte_table[c->b]; } } if (mode == X86EMUL_MODE_PROT64 && (c->d & No64)) { kvm_report_emulation_failure(ctxt->vcpu, "invalid x86/64 instruction");; return -1; } if (c->d & Group) { group = c->d & GroupMask; c->modrm = insn_fetch(u8, 1, c->eip); --c->eip; group = (group << 3) + ((c->modrm >> 3) & 7); if ((c->d & GroupDual) && (c->modrm >> 6) == 3) c->d = group2_table[group]; else c->d = group_table[group]; } /* Unrecognised? */ if (c->d == 0) { DPRINTF("Cannot emulate %02x\n", c->b); return -1; } if (mode == X86EMUL_MODE_PROT64 && (c->d & Stack)) c->op_bytes = 8; /* ModRM and SIB bytes. */ if (c->d & ModRM) rc = decode_modrm(ctxt, ops); else if (c->d & MemAbs) rc = decode_abs(ctxt, ops); if (rc) goto done; if (!c->has_seg_override) set_seg_override(c, VCPU_SREG_DS); if (!(!c->twobyte && c->b == 0x8d)) c->modrm_ea += seg_override_base(ctxt, c); if (c->ad_bytes != 8) c->modrm_ea = (u32)c->modrm_ea; /* * Decode and fetch the source operand: register, memory * or immediate. */ switch (c->d & SrcMask) { case SrcNone: break; case SrcReg: decode_register_operand(&c->src, c, 0); break; case SrcMem16: c->src.bytes = 2; goto srcmem_common; case SrcMem32: c->src.bytes = 4; goto srcmem_common; case SrcMem: c->src.bytes = (c->d & ByteOp) ? 1 : c->op_bytes; /* Don't fetch the address for invlpg: it could be unmapped. */ if (c->twobyte && c->b == 0x01 && c->modrm_reg == 7) break; srcmem_common: /* * For instructions with a ModR/M byte, switch to register * access if Mod = 3. */ if ((c->d & ModRM) && c->modrm_mod == 3) { c->src.type = OP_REG; c->src.val = c->modrm_val; c->src.ptr = c->modrm_ptr; break; } c->src.type = OP_MEM; break; case SrcImm: case SrcImmU: c->src.type = OP_IMM; c->src.ptr = (unsigned long *)c->eip; c->src.bytes = (c->d & ByteOp) ? 1 : c->op_bytes; if (c->src.bytes == 8) c->src.bytes = 4; /* NB. Immediates are sign-extended as necessary. */ switch (c->src.bytes) { case 1: c->src.val = insn_fetch(s8, 1, c->eip); break; case 2: c->src.val = insn_fetch(s16, 2, c->eip); break; case 4: c->src.val = insn_fetch(s32, 4, c->eip); break; } if ((c->d & SrcMask) == SrcImmU) { switch (c->src.bytes) { case 1: c->src.val &= 0xff; break; case 2: c->src.val &= 0xffff; break; case 4: c->src.val &= 0xffffffff; break; } } break; case SrcImmByte: case SrcImmUByte: c->src.type = OP_IMM; c->src.ptr = (unsigned long *)c->eip; c->src.bytes = 1; if ((c->d & SrcMask) == SrcImmByte) c->src.val = insn_fetch(s8, 1, c->eip); else c->src.val = insn_fetch(u8, 1, c->eip); break; case SrcOne: c->src.bytes = 1; c->src.val = 1; break; } /* * Decode and fetch the second source operand: register, memory * or immediate. */ switch (c->d & Src2Mask) { case Src2None: break; case Src2CL: c->src2.bytes = 1; c->src2.val = c->regs[VCPU_REGS_RCX] & 0x8; break; case Src2ImmByte: c->src2.type = OP_IMM; c->src2.ptr = (unsigned long *)c->eip; c->src2.bytes = 1; c->src2.val = insn_fetch(u8, 1, c->eip); break; case Src2Imm16: c->src2.type = OP_IMM; c->src2.ptr = (unsigned long *)c->eip; c->src2.bytes = 2; c->src2.val = insn_fetch(u16, 2, c->eip); break; case Src2One: c->src2.bytes = 1; c->src2.val = 1; break; } /* Decode and fetch the destination operand: register or memory. */ switch (c->d & DstMask) { case ImplicitOps: /* Special instructions do their own operand decoding. */ return 0; case DstReg: decode_register_operand(&c->dst, c, c->twobyte && (c->b == 0xb6 || c->b == 0xb7)); break; case DstMem: if ((c->d & ModRM) && c->modrm_mod == 3) { c->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes; c->dst.type = OP_REG; c->dst.val = c->dst.orig_val = c->modrm_val; c->dst.ptr = c->modrm_ptr; break; } c->dst.type = OP_MEM; break; case DstAcc: c->dst.type = OP_REG; c->dst.bytes = c->op_bytes; c->dst.ptr = &c->regs[VCPU_REGS_RAX]; switch (c->op_bytes) { case 1: c->dst.val = *(u8 *)c->dst.ptr; break; case 2: c->dst.val = *(u16 *)c->dst.ptr; break; case 4: c->dst.val = *(u32 *)c->dst.ptr; break; } c->dst.orig_val = c->dst.val; break; } if (c->rip_relative) c->modrm_ea += c->eip; done: return (rc == X86EMUL_UNHANDLEABLE) ? -1 : 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86 emulator: limit instructions to 15 bytes While we are never normally passed an instruction that exceeds 15 bytes, smp games can cause us to attempt to interpret one, which will cause large latencies in non-preempt hosts. Cc: stable@kernel.org Signed-off-by: Avi Kivity <avi@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: nma_gconf_settings_new (void) { return (NMAGConfSettings *) g_object_new (NMA_TYPE_GCONF_SETTINGS, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'editor: prevent any registration of objects on the system bus D-Bus access-control is name-based; so requests for a specific name are allowed/denied based on the rules in /etc/dbus-1/system.d. But apparently apps still get a non-named service on the bus, and if we register *any* object even though we don't have a named service, dbus and dbus-glib will happily proxy signals. Since the connection editor shouldn't ever expose anything having to do with connections on any bus, make sure that's the case.'</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: add_connection_real (NMAGConfSettings *self, NMAGConfConnection *connection) { NMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (self); if (connection) { priv->connections = g_slist_prepend (priv->connections, connection); g_signal_connect (connection, "new-secrets-requested", G_CALLBACK (connection_new_secrets_requested_cb), self); g_signal_connect (connection, "removed", G_CALLBACK (connection_removed), self); nm_settings_signal_new_connection (NM_SETTINGS (self), NM_EXPORTED_CONNECTION (connection)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'editor: prevent any registration of objects on the system bus D-Bus access-control is name-based; so requests for a specific name are allowed/denied based on the rules in /etc/dbus-1/system.d. But apparently apps still get a non-named service on the bus, and if we register *any* object even though we don't have a named service, dbus and dbus-glib will happily proxy signals. Since the connection editor shouldn't ever expose anything having to do with connections on any bus, make sure that's the case.'</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: connection_changes_done (gpointer data) { ConnectionChangedInfo *info = (ConnectionChangedInfo *) data; NMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (info->settings); NMAGConfConnection *connection; connection = nma_gconf_settings_get_by_path (info->settings, info->path); if (!connection) { /* New connection */ connection = nma_gconf_connection_new (priv->client, info->path); add_connection_real (info->settings, connection); } else { if (gconf_client_dir_exists (priv->client, info->path, NULL)) { /* Updated connection */ if (!nma_gconf_connection_changed (connection)) priv->connections = g_slist_remove (priv->connections, connection); } } g_hash_table_remove (priv->pending_changes, info->path); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'editor: prevent any registration of objects on the system bus D-Bus access-control is name-based; so requests for a specific name are allowed/denied based on the rules in /etc/dbus-1/system.d. But apparently apps still get a non-named service on the bus, and if we register *any* object even though we don't have a named service, dbus and dbus-glib will happily proxy signals. Since the connection editor shouldn't ever expose anything having to do with connections on any bus, make sure that's the case.'</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_connections (NMAGConfSettings *settings) { NMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (settings); GSList *dir_list; GSList *iter; dir_list = nm_gconf_get_all_connections (priv->client); if (!dir_list) return; for (iter = dir_list; iter; iter = iter->next) { char *dir = (char *) iter->data; add_connection_real (settings, nma_gconf_connection_new (priv->client, dir)); g_free (dir); } g_slist_free (dir_list); priv->connections = g_slist_reverse (priv->connections); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'editor: prevent any registration of objects on the system bus D-Bus access-control is name-based; so requests for a specific name are allowed/denied based on the rules in /etc/dbus-1/system.d. But apparently apps still get a non-named service on the bus, and if we register *any* object even though we don't have a named service, dbus and dbus-glib will happily proxy signals. Since the connection editor shouldn't ever expose anything having to do with connections on any bus, make sure that's the case.'</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: add_connection_real (NMAGConfSettings *self, NMAGConfConnection *connection) { NMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (self); g_return_if_fail (connection != NULL); priv->connections = g_slist_prepend (priv->connections, connection); g_signal_connect (connection, "new-secrets-requested", G_CALLBACK (connection_new_secrets_requested_cb), self); g_signal_connect (connection, "removed", G_CALLBACK (connection_removed), self); /* Export the connection over dbus if requested */ if (priv->bus) { nm_exported_connection_register_object (NM_EXPORTED_CONNECTION (connection), NM_CONNECTION_SCOPE_USER, priv->bus); dbus_g_connection_unref (priv->bus); } nm_settings_signal_new_connection (NM_SETTINGS (self), NM_EXPORTED_CONNECTION (connection)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'applet: fix dbus connection refcounting after 8627880e07c8345f69ed639325280c7f62a8f894'</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: nma_gconf_connection_changed (NMAGConfConnection *self) { NMAGConfConnectionPrivate *priv; GHashTable *settings; NMConnection *wrapped_connection; NMConnection *gconf_connection; GHashTable *new_settings; GError *error = NULL; g_return_val_if_fail (NMA_IS_GCONF_CONNECTION (self), FALSE); priv = NMA_GCONF_CONNECTION_GET_PRIVATE (self); wrapped_connection = nm_exported_connection_get_connection (NM_EXPORTED_CONNECTION (self)); gconf_connection = nm_gconf_read_connection (priv->client, priv->dir); if (!gconf_connection) { g_warning ("No connection read from GConf at %s.", priv->dir); goto invalid; } utils_fill_connection_certs (gconf_connection); if (!nm_connection_verify (gconf_connection, &error)) { utils_clear_filled_connection_certs (gconf_connection); g_warning ("%s: Invalid connection %s: '%s' / '%s' invalid: %d", __func__, priv->dir, g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)), error->message, error->code); goto invalid; } utils_clear_filled_connection_certs (gconf_connection); /* Ignore the GConf update if nothing changed */ if ( nm_connection_compare (wrapped_connection, gconf_connection, NM_SETTING_COMPARE_FLAG_EXACT) && nm_gconf_compare_private_connection_values (wrapped_connection, gconf_connection)) return TRUE; /* Update private values to catch any certificate path changes */ nm_gconf_copy_private_connection_values (wrapped_connection, gconf_connection); utils_fill_connection_certs (gconf_connection); new_settings = nm_connection_to_hash (gconf_connection); utils_clear_filled_connection_certs (gconf_connection); if (!nm_connection_replace_settings (wrapped_connection, new_settings, &error)) { utils_clear_filled_connection_certs (wrapped_connection); g_hash_table_destroy (new_settings); g_warning ("%s: '%s' / '%s' invalid: %d", __func__, error ? g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)) : "(none)", (error && error->message) ? error->message : "(none)", error ? error->code : -1); goto invalid; } g_object_unref (gconf_connection); g_hash_table_destroy (new_settings); fill_vpn_user_name (wrapped_connection); settings = nm_connection_to_hash (wrapped_connection); utils_clear_filled_connection_certs (wrapped_connection); nm_exported_connection_signal_updated (NM_EXPORTED_CONNECTION (self), settings); g_hash_table_destroy (settings); return TRUE; invalid: g_clear_error (&error); nm_exported_connection_signal_removed (NM_EXPORTED_CONNECTION (self)); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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: update_connection (NMConnectionList *list, NMConnectionEditor *editor, NMExportedConnection *original, NMConnection *modified, ConnectionUpdatedFn callback, gpointer user_data) { NMConnectionScope original_scope; ConnectionUpdateInfo *info; info = g_slice_new0 (ConnectionUpdateInfo); info->list = list; info->editor = editor; info->original = g_object_ref (original); info->modified = g_object_ref (modified); info->callback = callback; info->user_data = user_data; original_scope = nm_connection_get_scope (nm_exported_connection_get_connection (original)); if (nm_connection_get_scope (modified) == original_scope) { /* The easy part: Connection is updated */ GHashTable *new_settings; GError *error = NULL; gboolean success; gboolean pending_auth = FALSE; GtkWindow *parent; utils_fill_connection_certs (modified); new_settings = nm_connection_to_hash (modified); /* Hack; make sure that gconf private values are copied */ nm_gconf_copy_private_connection_values (nm_exported_connection_get_connection (original), modified); success = nm_exported_connection_update (original, new_settings, &error); g_hash_table_destroy (new_settings); utils_clear_filled_connection_certs (modified); parent = nm_connection_editor_get_window (editor); if (!success) { if (pk_helper_is_permission_denied_error (error)) { GError *auth_error = NULL; pending_auth = pk_helper_obtain_auth (error, parent, update_connection_cb, info, &auth_error); if (auth_error) { error_dialog (parent, _("Could not update connection"), "%s", auth_error->message); g_error_free (auth_error); } } else { error_dialog (parent, _("Could not update connection"), "%s", error->message); } g_error_free (error); } else { /* Save user-connection vpn secrets */ if (editor && (original_scope == NM_CONNECTION_SCOPE_USER)) nm_connection_editor_save_vpn_secrets (editor); } if (!pending_auth) connection_update_done (info, success); } else { /* The hard part: Connection scope changed: Add the exported connection, if it succeeds, remove the old one. */ add_connection (list, editor, modified, connection_update_add_done, info); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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_one_cert (ReadFromGConfInfo *info, const char *setting_name, const char *key) { char *value = NULL; if (!nm_gconf_get_string_helper (info->client, info->dir, key, setting_name, &value)) return; g_object_set_data_full (G_OBJECT (info->connection), key, value, (GDestroyNotify) g_free); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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: get_8021x_secrets_cb (GtkDialog *dialog, gint response, gpointer user_data) { NM8021xInfo *info = user_data; NMAGConfConnection *gconf_connection; NMConnection *connection = NULL; NMSetting *setting; GHashTable *settings_hash; GHashTable *secrets; GError *err = NULL; /* Got a user response, clear the NMActiveConnection destroy handler for * this dialog since this function will now take over dialog destruction. */ g_object_weak_unref (G_OBJECT (info->active_connection), destroy_8021x_dialog, info); if (response != GTK_RESPONSE_OK) { g_set_error (&err, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_SECRETS_REQUEST_CANCELED, "%s.%d (%s): canceled", __FILE__, __LINE__, __func__); goto done; } connection = nma_wired_dialog_get_connection (info->dialog); if (!connection) { g_set_error (&err, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INTERNAL_ERROR, "%s.%d (%s): couldn't get connection from wired dialog.", __FILE__, __LINE__, __func__); goto done; } setting = nm_connection_get_setting (connection, NM_TYPE_SETTING_802_1X); if (!setting) { g_set_error (&err, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION, "%s.%d (%s): requested setting '802-1x' didn't" " exist in the connection.", __FILE__, __LINE__, __func__); goto done; } utils_fill_connection_certs (NM_CONNECTION (connection)); secrets = nm_setting_to_hash (setting); utils_clear_filled_connection_certs (NM_CONNECTION (connection)); if (!secrets) { g_set_error (&err, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INTERNAL_ERROR, "%s.%d (%s): failed to hash setting '%s'.", __FILE__, __LINE__, __func__, nm_setting_get_name (setting)); goto done; } /* Returned secrets are a{sa{sv}}; this is the outer a{s...} hash that * will contain all the individual settings hashes. */ settings_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy); g_hash_table_insert (settings_hash, g_strdup (nm_setting_get_name (setting)), secrets); dbus_g_method_return (info->context, settings_hash); g_hash_table_destroy (settings_hash); /* Save the connection back to GConf _after_ hashing it, because * saving to GConf might trigger the GConf change notifiers, resulting * in the connection being read back in from GConf which clears secrets. */ gconf_connection = nma_gconf_settings_get_by_connection (info->applet->gconf_settings, connection); if (gconf_connection) nma_gconf_connection_save (gconf_connection); done: if (err) { g_warning ("%s", err->message); dbus_g_method_return_error (info->context, err); g_error_free (err); } if (connection) nm_connection_clear_secrets (connection); destroy_8021x_dialog (info, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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: get_settings (NMExportedConnection *exported) { NMConnection *connection; GHashTable *settings; connection = nm_exported_connection_get_connection (exported); utils_fill_connection_certs (connection); settings = nm_connection_to_hash (connection); utils_clear_filled_connection_certs (connection); return settings; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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: nm_gconf_read_connection (GConfClient *client, const char *dir) { ReadFromGConfInfo info; GSList *list; GError *err = NULL; list = gconf_client_all_dirs (client, dir, &err); if (err) { g_warning ("Error while reading connection: %s", err->message); g_error_free (err); return NULL; } if (!list) { g_warning ("Invalid connection (empty)"); return NULL; } info.connection = nm_connection_new (); info.client = client; info.dir = dir; info.dir_len = strlen (dir); g_slist_foreach (list, read_one_setting, &info); g_slist_free (list); return info.connection; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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 ohci_queue_iso_receive_dualbuffer(struct fw_iso_context *base, struct fw_iso_packet *packet, struct fw_iso_buffer *buffer, unsigned long payload) { struct iso_context *ctx = container_of(base, struct iso_context, base); struct db_descriptor *db = NULL; struct descriptor *d; struct fw_iso_packet *p; dma_addr_t d_bus, page_bus; u32 z, header_z, length, rest; int page, offset, packet_count, header_size; /* * FIXME: Cycle lost behavior should be configurable: lose * packet, retransmit or terminate.. */ p = packet; z = 2; /* * The OHCI controller puts the isochronous header and trailer in the * buffer, so we need at least 8 bytes. */ packet_count = p->header_length / ctx->base.header_size; header_size = packet_count * max(ctx->base.header_size, (size_t)8); /* Get header size in number of descriptors. */ header_z = DIV_ROUND_UP(header_size, sizeof(*d)); page = payload >> PAGE_SHIFT; offset = payload & ~PAGE_MASK; rest = p->payload_length; /* FIXME: make packet-per-buffer/dual-buffer a context option */ while (rest > 0) { d = context_get_descriptors(&ctx->context, z + header_z, &d_bus); if (d == NULL) return -ENOMEM; db = (struct db_descriptor *) d; db->control = cpu_to_le16(DESCRIPTOR_STATUS | DESCRIPTOR_BRANCH_ALWAYS); db->first_size = cpu_to_le16(max(ctx->base.header_size, (size_t)8)); if (p->skip && rest == p->payload_length) { db->control |= cpu_to_le16(DESCRIPTOR_WAIT); db->first_req_count = db->first_size; } else { db->first_req_count = cpu_to_le16(header_size); } db->first_res_count = db->first_req_count; db->first_buffer = cpu_to_le32(d_bus + sizeof(*db)); if (p->skip && rest == p->payload_length) length = 4; else if (offset + rest < PAGE_SIZE) length = rest; else length = PAGE_SIZE - offset; db->second_req_count = cpu_to_le16(length); db->second_res_count = db->second_req_count; page_bus = page_private(buffer->pages[page]); db->second_buffer = cpu_to_le32(page_bus + offset); if (p->interrupt && length == rest) db->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS); context_append(&ctx->context, d, z, header_z); offset = (offset + length) & ~PAGE_MASK; rest -= length; if (offset == 0) page++; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'firewire: ohci: handle receive packets with a data length of zero Queueing to receive an ISO packet with a payload length of zero silently does nothing in dualbuffer mode, and crashes the kernel in packet-per-buffer mode. Return an error in dualbuffer mode, because the DMA controller won't let us do what we want, and work correctly in packet-per-buffer mode. Signed-off-by: Jay Fenlason <fenlason@redhat.com> Signed-off-by: Stefan Richter <stefanr@s5r6.in-berlin.de> Cc: stable@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 unlzw(in, out) int in, out; /* input and output file descriptors */ { REG2 char_type *stackp; REG3 code_int code; REG4 int finchar; REG5 code_int oldcode; REG6 code_int incode; REG7 long inbits; REG8 long posbits; REG9 int outpos; /* REG10 int insize; (global) */ REG11 unsigned bitmask; REG12 code_int free_ent; REG13 code_int maxcode; REG14 code_int maxmaxcode; REG15 int n_bits; REG16 int rsize; #ifdef MAXSEG_64K tab_prefix[0] = tab_prefix0; tab_prefix[1] = tab_prefix1; #endif maxbits = get_byte(); block_mode = maxbits & BLOCK_MODE; if ((maxbits & LZW_RESERVED) != 0) { WARN((stderr, "\n%s: %s: warning, unknown flags 0x%x\n", program_name, ifname, maxbits & LZW_RESERVED)); } maxbits &= BIT_MASK; maxmaxcode = MAXCODE(maxbits); if (maxbits > BITS) { fprintf(stderr, "\n%s: %s: compressed with %d bits, can only handle %d bits\n", program_name, ifname, maxbits, BITS); exit_code = ERROR; return ERROR; } rsize = insize; maxcode = MAXCODE(n_bits = INIT_BITS)-1; bitmask = (1<<n_bits)-1; oldcode = -1; finchar = 0; outpos = 0; posbits = inptr<<3; free_ent = ((block_mode) ? FIRST : 256); clear_tab_prefixof(); /* Initialize the first 256 entries in the table. */ for (code = 255 ; code >= 0 ; --code) { tab_suffixof(code) = (char_type)code; } do { REG1 int i; int e; int o; resetbuf: e = insize-(o = (posbits>>3)); for (i = 0 ; i < e ; ++i) { inbuf[i] = inbuf[i+o]; } insize = e; posbits = 0; if (insize < INBUF_EXTRA) { rsize = read_buffer (in, (char *) inbuf + insize, INBUFSIZ); if (rsize == -1) { read_error(); } insize += rsize; bytes_in += (off_t)rsize; } inbits = ((rsize != 0) ? ((long)insize - insize%n_bits)<<3 : ((long)insize<<3)-(n_bits-1)); while (inbits > posbits) { if (free_ent > maxcode) { posbits = ((posbits-1) + ((n_bits<<3)-(posbits-1+(n_bits<<3))%(n_bits<<3))); ++n_bits; if (n_bits == maxbits) { maxcode = maxmaxcode; } else { maxcode = MAXCODE(n_bits)-1; } bitmask = (1<<n_bits)-1; goto resetbuf; } input(inbuf,posbits,code,n_bits,bitmask); Tracev((stderr, "%d ", code)); if (oldcode == -1) { if (256 <= code) gzip_error ("corrupt input."); outbuf[outpos++] = (char_type)(finchar = (int)(oldcode=code)); continue; } if (code == CLEAR && block_mode) { clear_tab_prefixof(); free_ent = FIRST - 1; posbits = ((posbits-1) + ((n_bits<<3)-(posbits-1+(n_bits<<3))%(n_bits<<3))); maxcode = MAXCODE(n_bits = INIT_BITS)-1; bitmask = (1<<n_bits)-1; goto resetbuf; } incode = code; stackp = de_stack; if (code >= free_ent) { /* Special case for KwKwK string. */ if (code > free_ent) { #ifdef DEBUG char_type *p; posbits -= n_bits; p = &inbuf[posbits>>3]; fprintf(stderr, "code:%ld free_ent:%ld n_bits:%d insize:%u\n", code, free_ent, n_bits, insize); fprintf(stderr, "posbits:%ld inbuf:%02X %02X %02X %02X %02X\n", posbits, p[-1],p[0],p[1],p[2],p[3]); #endif if (!test && outpos > 0) { write_buf(out, (char*)outbuf, outpos); bytes_out += (off_t)outpos; } gzip_error (to_stdout ? "corrupt input." : "corrupt input. Use zcat to recover some data."); } *--stackp = (char_type)finchar; code = oldcode; } while ((cmp_code_int)code >= (cmp_code_int)256) { /* Generate output characters in reverse order */ *--stackp = tab_suffixof(code); code = tab_prefixof(code); } *--stackp = (char_type)(finchar = tab_suffixof(code)); /* And put them out in forward order */ { REG1 int i; if (outpos+(i = (de_stack-stackp)) >= OUTBUFSIZ) { do { if (i > OUTBUFSIZ-outpos) i = OUTBUFSIZ-outpos; if (i > 0) { memcpy(outbuf+outpos, stackp, i); outpos += i; } if (outpos >= OUTBUFSIZ) { if (!test) { write_buf(out, (char*)outbuf, outpos); bytes_out += (off_t)outpos; } outpos = 0; } stackp+= i; } while ((i = (de_stack-stackp)) > 0); } else { memcpy(outbuf+outpos, stackp, i); outpos += i; } } if ((code = free_ent) < maxmaxcode) { /* Generate the new entry. */ tab_prefixof(code) = (unsigned short)oldcode; tab_suffixof(code) = (char_type)finchar; free_ent = code+1; } oldcode = incode; /* Remember previous code. */ } } while (rsize != 0); if (!test && outpos > 0) { write_buf(out, (char*)outbuf, outpos); bytes_out += (off_t)outpos; } return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'gzip -d: do not clobber stack for valid input on x86_64 * unlzw.c (unlzw): Avoid integer overflow. Aki Helin reported the segfault along with an input to trigger the bug. * NEWS (Bug fixes): Mention it.'</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_ot_layout_build_glyph_classes (hb_face_t *face, uint16_t num_total_glyphs, hb_codepoint_t *glyphs, unsigned char *klasses, uint16_t count) { if (HB_OBJECT_IS_INERT (face)) return; hb_ot_layout_t *layout = &face->ot_layout; if (HB_UNLIKELY (!count || !glyphs || !klasses)) return; if (layout->new_gdef.len == 0) { layout->new_gdef.klasses = (unsigned char *) calloc (num_total_glyphs, sizeof (unsigned char)); layout->new_gdef.len = count; } for (unsigned int i = 0; i < count; i++) _hb_ot_layout_set_glyph_class (face, glyphs[i], (hb_ot_layout_glyph_class_t) klasses[i]); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '[HB/GDEF] Fix bug in building synthetic GDEF table'</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: connection_struct *make_connection_snum(struct smbd_server_connection *sconn, int snum, user_struct *vuser, DATA_BLOB password, const char *pdev, NTSTATUS *pstatus) { connection_struct *conn; struct smb_filename *smb_fname_cpath = NULL; fstring dev; int ret; char addr[INET6_ADDRSTRLEN]; bool on_err_call_dis_hook = false; NTSTATUS status; fstrcpy(dev, pdev); if (NT_STATUS_IS_ERR(*pstatus = share_sanity_checks(snum, dev))) { return NULL; } conn = conn_new(sconn); if (!conn) { DEBUG(0,("Couldn't find free connection.\n")); *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES; return NULL; } conn->params->service = snum; status = create_connection_server_info(sconn, conn, snum, vuser ? vuser->server_info : NULL, password, &conn->server_info); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("create_connection_server_info failed: %s\n", nt_errstr(status))); *pstatus = status; conn_free(conn); return NULL; } if ((lp_guest_only(snum)) || (lp_security() == SEC_SHARE)) { conn->force_user = true; } add_session_user(sconn, conn->server_info->unix_name); safe_strcpy(conn->client_address, client_addr(get_client_fd(),addr,sizeof(addr)), sizeof(conn->client_address)-1); conn->num_files_open = 0; conn->lastused = conn->lastused_count = time(NULL); conn->used = True; conn->printer = (strncmp(dev,"LPT",3) == 0); conn->ipc = ( (strncmp(dev,"IPC",3) == 0) || ( lp_enable_asu_support() && strequal(dev,"ADMIN$")) ); /* Case options for the share. */ if (lp_casesensitive(snum) == Auto) { /* We will be setting this per packet. Set to be case * insensitive for now. */ conn->case_sensitive = False; } else { conn->case_sensitive = (bool)lp_casesensitive(snum); } conn->case_preserve = lp_preservecase(snum); conn->short_case_preserve = lp_shortpreservecase(snum); conn->encrypt_level = lp_smb_encrypt(snum); conn->veto_list = NULL; conn->hide_list = NULL; conn->veto_oplock_list = NULL; conn->aio_write_behind_list = NULL; conn->read_only = lp_readonly(SNUM(conn)); conn->admin_user = False; if (*lp_force_user(snum)) { /* * Replace conn->server_info with a completely faked up one * from the username we are forced into :-) */ char *fuser; struct auth_serversupplied_info *forced_serverinfo; fuser = talloc_string_sub(conn, lp_force_user(snum), "%S", lp_servicename(snum)); if (fuser == NULL) { conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } status = make_serverinfo_from_username( conn, fuser, conn->server_info->guest, &forced_serverinfo); if (!NT_STATUS_IS_OK(status)) { conn_free(conn); *pstatus = status; return NULL; } TALLOC_FREE(conn->server_info); conn->server_info = forced_serverinfo; conn->force_user = True; DEBUG(3,("Forced user %s\n", fuser)); } /* * If force group is true, then override * any groupid stored for the connecting user. */ if (*lp_force_group(snum)) { status = find_forced_group( conn->force_user, snum, conn->server_info->unix_name, &conn->server_info->ptok->user_sids[1], &conn->server_info->utok.gid); if (!NT_STATUS_IS_OK(status)) { conn_free(conn); *pstatus = status; return NULL; } /* * We need to cache this gid, to use within * change_to_user() separately from the conn->server_info * struct. We only use conn->server_info directly if * "force_user" was set. */ conn->force_group_gid = conn->server_info->utok.gid; } conn->vuid = (vuser != NULL) ? vuser->vuid : UID_FIELD_INVALID; { char *s = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_pathname(snum)); if (!s) { conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } if (!set_conn_connectpath(conn,s)) { TALLOC_FREE(s); conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } DEBUG(3,("Connect path is '%s' for service [%s]\n",s, lp_servicename(snum))); TALLOC_FREE(s); } /* * New code to check if there's a share security descripter * added from NT server manager. This is done after the * smb.conf checks are done as we need a uid and token. JRA. * */ { bool can_write = False; can_write = share_access_check(conn->server_info->ptok, lp_servicename(snum), FILE_WRITE_DATA); if (!can_write) { if (!share_access_check(conn->server_info->ptok, lp_servicename(snum), FILE_READ_DATA)) { /* No access, read or write. */ DEBUG(0,("make_connection: connection to %s " "denied due to security " "descriptor.\n", lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_ACCESS_DENIED; return NULL; } else { conn->read_only = True; } } } /* Initialise VFS function pointers */ if (!smbd_vfs_init(conn)) { DEBUG(0, ("vfs_init failed for service %s\n", lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_BAD_NETWORK_NAME; return NULL; } /* * If widelinks are disallowed we need to canonicalise the connect * path here to ensure we don't have any symlinks in the * connectpath. We will be checking all paths on this connection are * below this directory. We must do this after the VFS init as we * depend on the realpath() pointer in the vfs table. JRA. */ if (!lp_widelinks(snum)) { if (!canonicalize_connect_path(conn)) { DEBUG(0, ("canonicalize_connect_path failed " "for service %s, path %s\n", lp_servicename(snum), conn->connectpath)); conn_free(conn); *pstatus = NT_STATUS_BAD_NETWORK_NAME; return NULL; } } if ((!conn->printer) && (!conn->ipc)) { conn->notify_ctx = notify_init(conn, server_id_self(), smbd_messaging_context(), smbd_event_context(), conn); } /* ROOT Activities: */ /* * Enforce the max connections parameter. */ if ((lp_max_connections(snum) > 0) && (count_current_connections(lp_servicename(SNUM(conn)), True) >= lp_max_connections(snum))) { DEBUG(1, ("Max connections (%d) exceeded for %s\n", lp_max_connections(snum), lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES; return NULL; } /* * Get us an entry in the connections db */ if (!claim_connection(conn, lp_servicename(snum), 0)) { DEBUG(1, ("Could not store connections entry\n")); conn_free(conn); *pstatus = NT_STATUS_INTERNAL_DB_ERROR; return NULL; } /* Preexecs are done here as they might make the dir we are to ChDir * to below */ /* execute any "root preexec = " line */ if (*lp_rootpreexec(snum)) { char *cmd = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_rootpreexec(snum)); DEBUG(5,("cmd=%s\n",cmd)); ret = smbrun(cmd,NULL); TALLOC_FREE(cmd); if (ret != 0 && lp_rootpreexec_close(snum)) { DEBUG(1,("root preexec gave %d - failing " "connection\n", ret)); yield_connection(conn, lp_servicename(snum)); conn_free(conn); *pstatus = NT_STATUS_ACCESS_DENIED; return NULL; } } /* USER Activites: */ if (!change_to_user(conn, conn->vuid)) { /* No point continuing if they fail the basic checks */ DEBUG(0,("Can't become connected user!\n")); yield_connection(conn, lp_servicename(snum)); conn_free(conn); *pstatus = NT_STATUS_LOGON_FAILURE; return NULL; } /* Remember that a different vuid can connect later without these * checks... */ /* Preexecs are done here as they might make the dir we are to ChDir * to below */ /* execute any "preexec = " line */ if (*lp_preexec(snum)) { char *cmd = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_preexec(snum)); ret = smbrun(cmd,NULL); TALLOC_FREE(cmd); if (ret != 0 && lp_preexec_close(snum)) { DEBUG(1,("preexec gave %d - failing connection\n", ret)); *pstatus = NT_STATUS_ACCESS_DENIED; goto err_root_exit; } } #ifdef WITH_FAKE_KASERVER if (lp_afs_share(snum)) { afs_login(conn); } #endif /* Add veto/hide lists */ if (!IS_IPC(conn) && !IS_PRINT(conn)) { set_namearray( &conn->veto_list, lp_veto_files(snum)); set_namearray( &conn->hide_list, lp_hide_files(snum)); set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(snum)); set_namearray( &conn->aio_write_behind_list, lp_aio_write_behind(snum)); } /* Invoke VFS make connection hook - do this before the VFS_STAT call to allow any filesystems needing user credentials to initialize themselves. */ if (SMB_VFS_CONNECT(conn, lp_servicename(snum), conn->server_info->unix_name) < 0) { DEBUG(0,("make_connection: VFS make connection failed!\n")); *pstatus = NT_STATUS_UNSUCCESSFUL; goto err_root_exit; } /* Any error exit after here needs to call the disconnect hook. */ on_err_call_dis_hook = true; status = create_synthetic_smb_fname(talloc_tos(), conn->connectpath, NULL, NULL, &smb_fname_cpath); if (!NT_STATUS_IS_OK(status)) { *pstatus = status; goto err_root_exit; } /* win2000 does not check the permissions on the directory during the tree connect, instead relying on permission check during individual operations. To match this behaviour I have disabled this chdir check (tridge) */ /* the alternative is just to check the directory exists */ if ((ret = SMB_VFS_STAT(conn, smb_fname_cpath)) != 0 || !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) { if (ret == 0 && !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) { DEBUG(0,("'%s' is not a directory, when connecting to " "[%s]\n", conn->connectpath, lp_servicename(snum))); } else { DEBUG(0,("'%s' does not exist or permission denied " "when connecting to [%s] Error was %s\n", conn->connectpath, lp_servicename(snum), strerror(errno) )); } *pstatus = NT_STATUS_BAD_NETWORK_NAME; goto err_root_exit; } string_set(&conn->origpath,conn->connectpath); #if SOFTLINK_OPTIMISATION /* resolve any soft links early if possible */ if (vfs_ChDir(conn,conn->connectpath) == 0) { TALLOC_CTX *ctx = talloc_tos(); char *s = vfs_GetWd(ctx,s); if (!s) { *status = map_nt_error_from_unix(errno); goto err_root_exit; } if (!set_conn_connectpath(conn,s)) { *status = NT_STATUS_NO_MEMORY; goto err_root_exit; } vfs_ChDir(conn,conn->connectpath); } #endif /* Figure out the characteristics of the underlying filesystem. This * assumes that all the filesystem mounted withing a share path have * the same characteristics, which is likely but not guaranteed. */ conn->fs_capabilities = SMB_VFS_FS_CAPABILITIES(conn, &conn->ts_res); /* * Print out the 'connected as' stuff here as we need * to know the effective uid and gid we will be using * (at least initially). */ if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) { dbgtext( "%s (%s) ", get_remote_machine_name(), conn->client_address ); dbgtext( "%s", srv_is_signing_active(smbd_server_conn) ? "signed " : ""); dbgtext( "connect to service %s ", lp_servicename(snum) ); dbgtext( "initially as user %s ", conn->server_info->unix_name ); dbgtext( "(uid=%d, gid=%d) ", (int)geteuid(), (int)getegid() ); dbgtext( "(pid %d)\n", (int)sys_getpid() ); } /* we've finished with the user stuff - go back to root */ change_to_root_user(); return(conn); err_root_exit: TALLOC_FREE(smb_fname_cpath); change_to_root_user(); if (on_err_call_dis_hook) { /* Call VFS disconnect hook */ SMB_VFS_DISCONNECT(conn); } yield_connection(conn, lp_servicename(snum)); conn_free(conn); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fix bug 7104 - "wide links" and "unix extensions" are incompatible. Change parameter "wide links" to default to "no". Ensure "wide links = no" if "unix extensions = yes" on a share. Fix man pages to refect this. Remove "within share" checks for a UNIX symlink set - even if widelinks = no. The server will not follow that link anyway. Correct DEBUG message in check_reduced_name() to add missing "\n" so it's really clear when a path is being denied as it's outside the enclosing share path. Jeremy.'</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: popup_dialog_idle (GSWindow *window) { gboolean result; char *tmp; GString *command; gs_debug ("Popping up dialog"); tmp = g_build_filename (LIBEXECDIR, "gnome-screensaver-dialog", NULL); command = g_string_new (tmp); g_free (tmp); if (is_logout_enabled (window)) { command = g_string_append (command, " --enable-logout"); g_string_append_printf (command, " --logout-command='%s'", window->priv->logout_command); } if (window->priv->status_message) { char *quoted; quoted = g_shell_quote (window->priv->status_message); g_string_append_printf (command, " --status-message=%s", quoted); g_free (quoted); } if (is_user_switch_enabled (window)) { command = g_string_append (command, " --enable-switch"); } if (gs_debug_enabled ()) { command = g_string_append (command, " --verbose"); } gtk_widget_hide (window->priv->drawing_area); gs_window_clear_to_background_pixmap (window); set_invisible_cursor (GTK_WIDGET (window)->window, FALSE); result = spawn_on_window (window, command->str, &window->priv->lock_pid, (GIOFunc)lock_command_watch, window, &window->priv->lock_watch_id); if (! result) { gs_debug ("Could not start command: %s", command->str); } g_string_free (command, TRUE); window->priv->popup_dialog_idle_id = 0; return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Work around x errors by asking dialog to die on cancel Basically, what is happening is that gnome-screensaver-dialog exits after the 5th failed attempt at unlocking the screen, but before the shake animation finishes. If the timing is slightly unlucky, this results in gnome-screensaver accessing X resources that have already been destroyed (I ran it through xtrace, and that showed this happening) My patch fixes this by making gnome-screensaver-dialog request to gnome-screensaver that it be terminated after the 5th failed attempt (rather than exitting straight away, although there is a fallback timeout too). gnome-screensaver then terminates the dialog after it is finished with the shake animation, to avoid the race condition that is currently making it crash.'</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: auth_check_idle (GSLockPlug *plug) { gboolean res; gboolean again; static guint loop_counter = 0; again = TRUE; res = do_auth_check (plug); if (res) { again = FALSE; g_idle_add ((GSourceFunc)quit_response_ok, NULL); } else { loop_counter++; if (loop_counter < MAX_FAILURES) { gs_debug ("Authentication failed, retrying (%u)", loop_counter); g_timeout_add (3000, (GSourceFunc)reset_idle_cb, plug); } else { gs_debug ("Authentication failed, quitting (max failures)"); again = FALSE; gtk_main_quit (); } } return again; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Work around x errors by asking dialog to die on cancel Basically, what is happening is that gnome-screensaver-dialog exits after the 5th failed attempt at unlocking the screen, but before the shake animation finishes. If the timing is slightly unlucky, this results in gnome-screensaver accessing X resources that have already been destroyed (I ran it through xtrace, and that showed this happening) My patch fixes this by making gnome-screensaver-dialog request to gnome-screensaver that it be terminated after the 5th failed attempt (rather than exitting straight away, although there is a fallback timeout too). gnome-screensaver then terminates the dialog after it is finished with the shake animation, to avoid the race condition that is currently making it crash.'</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 key *find_keyring_by_name(const char *name, bool skip_perm_check) { struct key *keyring; int bucket; keyring = ERR_PTR(-EINVAL); if (!name) goto error; bucket = keyring_hash(name); read_lock(&keyring_name_lock); if (keyring_name_hash[bucket].next) { /* search this hash bucket for a keyring with a matching name * that's readable and that hasn't been revoked */ list_for_each_entry(keyring, &keyring_name_hash[bucket], type_data.link ) { if (keyring->user->user_ns != current_user_ns()) continue; if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) continue; if (strcmp(keyring->description, name) != 0) continue; if (!skip_perm_check && key_permission(make_key_ref(keyring, 0), KEY_SEARCH) < 0) continue; /* we've got a match */ atomic_inc(&keyring->usage); read_unlock(&keyring_name_lock); goto error; } } read_unlock(&keyring_name_lock); keyring = ERR_PTR(-ENOKEY); error: return keyring; } /* end find_keyring_by_name() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'KEYS: find_keyring_by_name() can gain access to a freed keyring find_keyring_by_name() can gain access to a keyring that has had its reference count reduced to zero, and is thus ready to be freed. This then allows the dead keyring to be brought back into use whilst it is being destroyed. The following timeline illustrates the process: |(cleaner) (user) | | free_user(user) sys_keyctl() | | | | key_put(user->session_keyring) keyctl_get_keyring_ID() | || //=> keyring->usage = 0 | | |schedule_work(&key_cleanup_task) lookup_user_key() | || | | kmem_cache_free(,user) | | . |[KEY_SPEC_USER_KEYRING] | . install_user_keyrings() | . || | key_cleanup() [<= worker_thread()] || | | || | [spin_lock(&key_serial_lock)] |[mutex_lock(&key_user_keyr..mutex)] | | || | atomic_read() == 0 || | |{ rb_ease(&key->serial_node,) } || | | || | [spin_unlock(&key_serial_lock)] |find_keyring_by_name() | | ||| | keyring_destroy(keyring) ||[read_lock(&keyring_name_lock)] | || ||| | |[write_lock(&keyring_name_lock)] ||atomic_inc(&keyring->usage) | |. ||| *** GET freeing keyring *** | |. ||[read_unlock(&keyring_name_lock)] | || || | |list_del() |[mutex_unlock(&key_user_k..mutex)] | || | | |[write_unlock(&keyring_name_lock)] ** INVALID keyring is returned ** | | . | kmem_cache_free(,keyring) . | . | atomic_dec(&keyring->usage) v *** DESTROYED *** TIME If CONFIG_SLUB_DEBUG=y then we may see the following message generated: ============================================================================= BUG key_jar: Poison overwritten ----------------------------------------------------------------------------- INFO: 0xffff880197a7e200-0xffff880197a7e200. First byte 0x6a instead of 0x6b INFO: Allocated in key_alloc+0x10b/0x35f age=25 cpu=1 pid=5086 INFO: Freed in key_cleanup+0xd0/0xd5 age=12 cpu=1 pid=10 INFO: Slab 0xffffea000592cb90 objects=16 used=2 fp=0xffff880197a7e200 flags=0x200000000000c3 INFO: Object 0xffff880197a7e200 @offset=512 fp=0xffff880197a7e300 Bytes b4 0xffff880197a7e1f0: 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a ZZZZZZZZZZZZZZZZ Object 0xffff880197a7e200: 6a 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b jkkkkkkkkkkkkkkk Alternatively, we may see a system panic happen, such as: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffff810e61a3>] kmem_cache_alloc+0x5b/0xe9 PGD 6b2b4067 PUD 6a80d067 PMD 0 Oops: 0000 [#1] SMP last sysfs file: /sys/kernel/kexec_crash_loaded CPU 1 ... Pid: 31245, comm: su Not tainted 2.6.34-rc5-nofixed-nodebug #2 D2089/PRIMERGY RIP: 0010:[<ffffffff810e61a3>] [<ffffffff810e61a3>] kmem_cache_alloc+0x5b/0xe9 RSP: 0018:ffff88006af3bd98 EFLAGS: 00010002 RAX: 0000000000000000 RBX: 0000000000000001 RCX: ffff88007d19900b RDX: 0000000100000000 RSI: 00000000000080d0 RDI: ffffffff81828430 RBP: ffffffff81828430 R08: ffff88000a293750 R09: 0000000000000000 R10: 0000000000000001 R11: 0000000000100000 R12: 00000000000080d0 R13: 00000000000080d0 R14: 0000000000000296 R15: ffffffff810f20ce FS: 00007f97116bc700(0000) GS:ffff88000a280000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000000000001 CR3: 000000006a91c000 CR4: 00000000000006e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process su (pid: 31245, threadinfo ffff88006af3a000, task ffff8800374414c0) Stack: 0000000512e0958e 0000000000008000 ffff880037f8d180 0000000000000001 0000000000000000 0000000000008001 ffff88007d199000 ffffffff810f20ce 0000000000008000 ffff88006af3be48 0000000000000024 ffffffff810face3 Call Trace: [<ffffffff810f20ce>] ? get_empty_filp+0x70/0x12f [<ffffffff810face3>] ? do_filp_open+0x145/0x590 [<ffffffff810ce208>] ? tlb_finish_mmu+0x2a/0x33 [<ffffffff810ce43c>] ? unmap_region+0xd3/0xe2 [<ffffffff810e4393>] ? virt_to_head_page+0x9/0x2d [<ffffffff81103916>] ? alloc_fd+0x69/0x10e [<ffffffff810ef4ed>] ? do_sys_open+0x56/0xfc [<ffffffff81008a02>] ? system_call_fastpath+0x16/0x1b Code: 0f 1f 44 00 00 49 89 c6 fa 66 0f 1f 44 00 00 65 4c 8b 04 25 60 e8 00 00 48 8b 45 00 49 01 c0 49 8b 18 48 85 db 74 0d 48 63 45 18 <48> 8b 04 03 49 89 00 eb 14 4c 89 f9 83 ca ff 44 89 e6 48 89 ef RIP [<ffffffff810e61a3>] kmem_cache_alloc+0x5b/0xe9 This problem is that find_keyring_by_name does not confirm that the keyring is valid before accepting it. Skipping keyrings that have been reduced to a zero count seems the way to go. To this end, use atomic_inc_not_zero() to increment the usage count and skip the candidate keyring if that returns false. The following script _may_ cause the bug to happen, but there's no guarantee as the window of opportunity is small: #!/bin/sh LOOP=100000 USER=dummy_user /bin/su -c "exit;" $USER || { /usr/sbin/adduser -m $USER; add=1; } for ((i=0; i<LOOP; i++)) do /bin/su -c "echo '$i' > /dev/null" $USER done (( add == 1 )) && /usr/sbin/userdel -r $USER exit Note that the nominated user must not be in use. An alternative way of testing this may be: for ((i=0; i<100000; i++)) do keyctl session foo /bin/true || break done >&/dev/null as that uses a keyring named "foo" rather than relying on the user and user-session named keyrings. Reported-by: Toshiyuki Okajima <toshi.okajima@jp.fujitsu.com> Signed-off-by: David Howells <dhowells@redhat.com> Tested-by: Toshiyuki Okajima <toshi.okajima@jp.fujitsu.com> Acked-by: Serge Hallyn <serue@us.ibm.com> Signed-off-by: James Morris <jmorris@namei.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 gfs2_adjust_quota(struct gfs2_inode *ip, loff_t loc, s64 change, struct gfs2_quota_data *qd, struct fs_disk_quota *fdq) { struct inode *inode = &ip->i_inode; struct address_space *mapping = inode->i_mapping; unsigned long index = loc >> PAGE_CACHE_SHIFT; unsigned offset = loc & (PAGE_CACHE_SIZE - 1); unsigned blocksize, iblock, pos; struct buffer_head *bh, *dibh; struct page *page; void *kaddr; struct gfs2_quota *qp; s64 value; int err = -EIO; u64 size; if (gfs2_is_stuffed(ip)) gfs2_unstuff_dinode(ip, NULL); page = grab_cache_page(mapping, index); if (!page) return -ENOMEM; blocksize = inode->i_sb->s_blocksize; iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits); if (!page_has_buffers(page)) create_empty_buffers(page, blocksize, 0); bh = page_buffers(page); pos = blocksize; while (offset >= pos) { bh = bh->b_this_page; iblock++; pos += blocksize; } if (!buffer_mapped(bh)) { gfs2_block_map(inode, iblock, bh, 1); if (!buffer_mapped(bh)) goto unlock; } if (PageUptodate(page)) set_buffer_uptodate(bh); if (!buffer_uptodate(bh)) { ll_rw_block(READ_META, 1, &bh); wait_on_buffer(bh); if (!buffer_uptodate(bh)) goto unlock; } gfs2_trans_add_bh(ip->i_gl, bh, 0); kaddr = kmap_atomic(page, KM_USER0); qp = kaddr + offset; value = (s64)be64_to_cpu(qp->qu_value) + change; qp->qu_value = cpu_to_be64(value); qd->qd_qb.qb_value = qp->qu_value; if (fdq) { if (fdq->d_fieldmask & FS_DQ_BSOFT) { qp->qu_warn = cpu_to_be64(fdq->d_blk_softlimit); qd->qd_qb.qb_warn = qp->qu_warn; } if (fdq->d_fieldmask & FS_DQ_BHARD) { qp->qu_limit = cpu_to_be64(fdq->d_blk_hardlimit); qd->qd_qb.qb_limit = qp->qu_limit; } } flush_dcache_page(page); kunmap_atomic(kaddr, KM_USER0); err = gfs2_meta_inode_buffer(ip, &dibh); if (err) goto unlock; size = loc + sizeof(struct gfs2_quota); if (size > inode->i_size) { ip->i_disksize = size; i_size_write(inode, size); } inode->i_mtime = inode->i_atime = CURRENT_TIME; gfs2_trans_add_bh(ip->i_gl, dibh, 1); gfs2_dinode_out(ip, dibh->b_data); brelse(dibh); mark_inode_dirty(inode); unlock: unlock_page(page); page_cache_release(page); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'GFS2: Fix writing to non-page aligned gfs2_quota structures This is the upstream fix for this bug. This patch differs from the RHEL5 fix (Red Hat bz #555754) which simply writes to the 8-byte value field of the quota. In upstream quota code, we're required to write the entire quota (88 bytes) which can be split across a page boundary. We check for such quotas, and read/write the two parts from/to the corresponding pages holding these parts. With this patch, I don't see the bug anymore using the reproducer in Red Hat bz 555754. I successfully ran a couple of simple tests/mounts/ umounts and it doesn't seem like this patch breaks anything else. Signed-off-by: Abhi Das <adas@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: static void reply_sesssetup_and_X_spnego(struct smb_request *req) { const uint8 *p; DATA_BLOB blob1; size_t bufrem; char *tmp; const char *native_os; const char *native_lanman; const char *primary_domain; const char *p2; uint16 data_blob_len = SVAL(req->vwv+7, 0); enum remote_arch_types ra_type = get_remote_arch(); int vuid = req->vuid; user_struct *vuser = NULL; NTSTATUS status = NT_STATUS_OK; uint16 smbpid = req->smbpid; struct smbd_server_connection *sconn = smbd_server_conn; DEBUG(3,("Doing spnego session setup\n")); if (global_client_caps == 0) { global_client_caps = IVAL(req->vwv+10, 0); if (!(global_client_caps & CAP_STATUS32)) { remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES); } } p = req->buf; if (data_blob_len == 0) { /* an invalid request */ reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); return; } bufrem = smbreq_bufrem(req, p); /* pull the spnego blob */ blob1 = data_blob(p, MIN(bufrem, data_blob_len)); #if 0 file_save("negotiate.dat", blob1.data, blob1.length); #endif p2 = (char *)req->buf + data_blob_len; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_os = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_lanman = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); primary_domain = tmp ? tmp : ""; DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n", native_os, native_lanman, primary_domain)); if ( ra_type == RA_WIN2K ) { /* Vista sets neither the OS or lanman strings */ if ( !strlen(native_os) && !strlen(native_lanman) ) set_remote_arch(RA_VISTA); /* Windows 2003 doesn't set the native lanman string, but does set primary domain which is a bug I think */ if ( !strlen(native_lanman) ) { ra_lanman_string( primary_domain ); } else { ra_lanman_string( native_lanman ); } } /* Did we get a valid vuid ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, then try and see if this is an intermediate sessionsetup * for a large SPNEGO packet. */ struct pending_auth_data *pad; pad = get_pending_auth_data(sconn, smbpid); if (pad) { DEBUG(10,("reply_sesssetup_and_X_spnego: found " "pending vuid %u\n", (unsigned int)pad->vuid )); vuid = pad->vuid; } } /* Do we have a valid vuid now ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, start a new authentication setup. */ vuid = register_initial_vuid(sconn); if (vuid == UID_FIELD_INVALID) { data_blob_free(&blob1); reply_nterror(req, nt_status_squash( NT_STATUS_INVALID_PARAMETER)); return; } } vuser = get_partial_auth_user_struct(sconn, vuid); /* This MUST be valid. */ if (!vuser) { smb_panic("reply_sesssetup_and_X_spnego: invalid vuid."); } /* Large (greater than 4k) SPNEGO blobs are split into multiple * sessionsetup requests as the Windows limit on the security blob * field is 4k. Bug #4400. JRA. */ status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1); if (!NT_STATUS_IS_OK(status)) { if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { /* Real error - kill the intermediate vuid */ invalidate_vuid(sconn, vuid); } data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } if (blob1.data[0] == ASN1_APPLICATION(0)) { /* its a negTokenTarg packet */ reply_spnego_negotiate(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (blob1.data[0] == ASN1_CONTEXT(1)) { /* its a auth packet */ reply_spnego_auth(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) { DATA_BLOB chal; if (!vuser->auth_ntlmssp_state) { status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state); if (!NT_STATUS_IS_OK(status)) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } } status = auth_ntlmssp_update(vuser->auth_ntlmssp_state, blob1, &chal); data_blob_free(&blob1); reply_spnego_ntlmssp(req, vuid, &vuser->auth_ntlmssp_state, &chal, status, OID_NTLMSSP, false); data_blob_free(&chal); return; } /* what sort of packet is this? */ DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n")); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 's3: Fix an uninitialized variable read Found by Laurent Gaffie <laurent.gaffie@gmail.com> Thanks for that, Volker Fix bug #7254 (An uninitialized variable read could cause an smbd crash).'</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: _gnutls_x509_oid2mac_algorithm (const char *oid) { gnutls_mac_algorithm_t ret = 0; GNUTLS_HASH_LOOP (if (strcmp (oid, p->oid) == 0) { ret = p->id; break;} ); if (ret == 0) return GNUTLS_MAC_UNKNOWN; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': '(_gnutls_x509_oid2mac_algorithm): Don't crash trying to strcmp the NULL OID value in the hash_algorithms array, which happens when the input OID doesn't match our OIDs for SHA1, MD5, MD2 or RIPEMD160. Reported by satyakumar <satyam_kkd@hyd.hellosoft.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: print_help (void) { /* We split the help text this way to ease translation of individual entries. */ static const char *help[] = { "\n", N_("\ Mandatory arguments to long options are mandatory for short options too.\n\n"), N_("\ Startup:\n"), N_("\ -V, --version display the version of Wget and exit.\n"), N_("\ -h, --help print this help.\n"), N_("\ -b, --background go to background after startup.\n"), N_("\ -e, --execute=COMMAND execute a `.wgetrc'-style command.\n"), "\n", N_("\ Logging and input file:\n"), N_("\ -o, --output-file=FILE log messages to FILE.\n"), N_("\ -a, --append-output=FILE append messages to FILE.\n"), #ifdef ENABLE_DEBUG N_("\ -d, --debug print lots of debugging information.\n"), #endif #ifdef USE_WATT32 N_("\ --wdebug print Watt-32 debug output.\n"), #endif N_("\ -q, --quiet quiet (no output).\n"), N_("\ -v, --verbose be verbose (this is the default).\n"), N_("\ -nv, --no-verbose turn off verboseness, without being quiet.\n"), N_("\ -i, --input-file=FILE download URLs found in local or external FILE.\n"), N_("\ -F, --force-html treat input file as HTML.\n"), N_("\ -B, --base=URL resolves HTML input-file links (-i -F)\n\ relative to URL.\n"), "\n", N_("\ Download:\n"), N_("\ -t, --tries=NUMBER set number of retries to NUMBER (0 unlimits).\n"), N_("\ --retry-connrefused retry even if connection is refused.\n"), N_("\ -O, --output-document=FILE write documents to FILE.\n"), N_("\ -nc, --no-clobber skip downloads that would download to\n\ existing files.\n"), N_("\ -c, --continue resume getting a partially-downloaded file.\n"), N_("\ --progress=TYPE select progress gauge type.\n"), N_("\ -N, --timestamping don't re-retrieve files unless newer than\n\ local.\n"), N_("\ --no-use-server-timestamps don't set the local file's timestamp by\n\ the one on the server.\n"), N_("\ -S, --server-response print server response.\n"), N_("\ --spider don't download anything.\n"), N_("\ -T, --timeout=SECONDS set all timeout values to SECONDS.\n"), N_("\ --dns-timeout=SECS set the DNS lookup timeout to SECS.\n"), N_("\ --connect-timeout=SECS set the connect timeout to SECS.\n"), N_("\ --read-timeout=SECS set the read timeout to SECS.\n"), N_("\ -w, --wait=SECONDS wait SECONDS between retrievals.\n"), N_("\ --waitretry=SECONDS wait 1..SECONDS between retries of a retrieval.\n"), N_("\ --random-wait wait from 0.5*WAIT...1.5*WAIT secs between retrievals.\n"), N_("\ --no-proxy explicitly turn off proxy.\n"), N_("\ -Q, --quota=NUMBER set retrieval quota to NUMBER.\n"), N_("\ --bind-address=ADDRESS bind to ADDRESS (hostname or IP) on local host.\n"), N_("\ --limit-rate=RATE limit download rate to RATE.\n"), N_("\ --no-dns-cache disable caching DNS lookups.\n"), N_("\ --restrict-file-names=OS restrict chars in file names to ones OS allows.\n"), N_("\ --ignore-case ignore case when matching files/directories.\n"), #ifdef ENABLE_IPV6 N_("\ -4, --inet4-only connect only to IPv4 addresses.\n"), N_("\ -6, --inet6-only connect only to IPv6 addresses.\n"), N_("\ --prefer-family=FAMILY connect first to addresses of specified family,\n\ one of IPv6, IPv4, or none.\n"), #endif N_("\ --user=USER set both ftp and http user to USER.\n"), N_("\ --password=PASS set both ftp and http password to PASS.\n"), N_("\ --ask-password prompt for passwords.\n"), N_("\ --no-iri turn off IRI support.\n"), N_("\ --local-encoding=ENC use ENC as the local encoding for IRIs.\n"), N_("\ --remote-encoding=ENC use ENC as the default remote encoding.\n"), "\n", N_("\ Directories:\n"), N_("\ -nd, --no-directories don't create directories.\n"), N_("\ -x, --force-directories force creation of directories.\n"), N_("\ -nH, --no-host-directories don't create host directories.\n"), N_("\ --protocol-directories use protocol name in directories.\n"), N_("\ -P, --directory-prefix=PREFIX save files to PREFIX/...\n"), N_("\ --cut-dirs=NUMBER ignore NUMBER remote directory components.\n"), "\n", N_("\ HTTP options:\n"), N_("\ --http-user=USER set http user to USER.\n"), N_("\ --http-password=PASS set http password to PASS.\n"), N_("\ --no-cache disallow server-cached data.\n"), N_ ("\ --default-page=NAME Change the default page name (normally\n\ this is `index.html'.).\n"), N_("\ -E, --adjust-extension save HTML/CSS documents with proper extensions.\n"), N_("\ --ignore-length ignore `Content-Length' header field.\n"), N_("\ --header=STRING insert STRING among the headers.\n"), N_("\ --max-redirect maximum redirections allowed per page.\n"), N_("\ --proxy-user=USER set USER as proxy username.\n"), N_("\ --proxy-password=PASS set PASS as proxy password.\n"), N_("\ --referer=URL include `Referer: URL' header in HTTP request.\n"), N_("\ --save-headers save the HTTP headers to file.\n"), N_("\ -U, --user-agent=AGENT identify as AGENT instead of Wget/VERSION.\n"), N_("\ --no-http-keep-alive disable HTTP keep-alive (persistent connections).\n"), N_("\ --no-cookies don't use cookies.\n"), N_("\ --load-cookies=FILE load cookies from FILE before session.\n"), N_("\ --save-cookies=FILE save cookies to FILE after session.\n"), N_("\ --keep-session-cookies load and save session (non-permanent) cookies.\n"), N_("\ --post-data=STRING use the POST method; send STRING as the data.\n"), N_("\ --post-file=FILE use the POST method; send contents of FILE.\n"), N_("\ --content-disposition honor the Content-Disposition header when\n\ choosing local file names (EXPERIMENTAL).\n"), N_("\ --auth-no-challenge send Basic HTTP authentication information\n\ without first waiting for the server's\n\ challenge.\n"), "\n", #ifdef HAVE_SSL N_("\ HTTPS (SSL/TLS) options:\n"), N_("\ --secure-protocol=PR choose secure protocol, one of auto, SSLv2,\n\ SSLv3, and TLSv1.\n"), N_("\ --no-check-certificate don't validate the server's certificate.\n"), N_("\ --certificate=FILE client certificate file.\n"), N_("\ --certificate-type=TYPE client certificate type, PEM or DER.\n"), N_("\ --private-key=FILE private key file.\n"), N_("\ --private-key-type=TYPE private key type, PEM or DER.\n"), N_("\ --ca-certificate=FILE file with the bundle of CA's.\n"), N_("\ --ca-directory=DIR directory where hash list of CA's is stored.\n"), N_("\ --random-file=FILE file with random data for seeding the SSL PRNG.\n"), N_("\ --egd-file=FILE file naming the EGD socket with random data.\n"), "\n", #endif /* HAVE_SSL */ N_("\ FTP options:\n"), #ifdef __VMS N_("\ --ftp-stmlf Use Stream_LF format for all binary FTP files.\n"), #endif /* def __VMS */ N_("\ --ftp-user=USER set ftp user to USER.\n"), N_("\ --ftp-password=PASS set ftp password to PASS.\n"), N_("\ --no-remove-listing don't remove `.listing' files.\n"), N_("\ --no-glob turn off FTP file name globbing.\n"), N_("\ --no-passive-ftp disable the \"passive\" transfer mode.\n"), N_("\ --retr-symlinks when recursing, get linked-to files (not dir).\n"), "\n", N_("\ Recursive download:\n"), N_("\ -r, --recursive specify recursive download.\n"), N_("\ -l, --level=NUMBER maximum recursion depth (inf or 0 for infinite).\n"), N_("\ --delete-after delete files locally after downloading them.\n"), N_("\ -k, --convert-links make links in downloaded HTML or CSS point to\n\ local files.\n"), #ifdef __VMS N_("\ -K, --backup-converted before converting file X, back up as X_orig.\n"), #else /* def __VMS */ N_("\ -K, --backup-converted before converting file X, back up as X.orig.\n"), #endif /* def __VMS [else] */ N_("\ -m, --mirror shortcut for -N -r -l inf --no-remove-listing.\n"), N_("\ -p, --page-requisites get all images, etc. needed to display HTML page.\n"), N_("\ --strict-comments turn on strict (SGML) handling of HTML comments.\n"), "\n", N_("\ Recursive accept/reject:\n"), N_("\ -A, --accept=LIST comma-separated list of accepted extensions.\n"), N_("\ -R, --reject=LIST comma-separated list of rejected extensions.\n"), N_("\ -D, --domains=LIST comma-separated list of accepted domains.\n"), N_("\ --exclude-domains=LIST comma-separated list of rejected domains.\n"), N_("\ --follow-ftp follow FTP links from HTML documents.\n"), N_("\ --follow-tags=LIST comma-separated list of followed HTML tags.\n"), N_("\ --ignore-tags=LIST comma-separated list of ignored HTML tags.\n"), N_("\ -H, --span-hosts go to foreign hosts when recursive.\n"), N_("\ -L, --relative follow relative links only.\n"), N_("\ -I, --include-directories=LIST list of allowed directories.\n"), N_("\ -X, --exclude-directories=LIST list of excluded directories.\n"), N_("\ -np, --no-parent don't ascend to the parent directory.\n"), "\n", N_("Mail bug reports and suggestions to <bug-wget@gnu.org>.\n") }; size_t i; printf (_("GNU Wget %s, a non-interactive network retriever.\n"), version_string); print_usage (0); for (i = 0; i < countof (help); i++) fputs (_(help[i]), stdout); exit (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Introduce --trust-server-names. Close CVE-2010-2252.'</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: ftp_loop (struct url *u, char **local_file, int *dt, struct url *proxy, bool recursive, bool glob) { ccon con; /* FTP connection */ uerr_t res; *dt = 0; xzero (con); con.csock = -1; con.st = ON_YOUR_OWN; con.rs = ST_UNIX; con.id = NULL; con.proxy = proxy; /* If the file name is empty, the user probably wants a directory index. We'll provide one, properly HTML-ized. Unless opt.htmlify is 0, of course. :-) */ if (!*u->file && !recursive) { struct fileinfo *f; res = ftp_get_listing (u, &con, &f); if (res == RETROK) { if (opt.htmlify && !opt.spider) { char *filename = (opt.output_document ? xstrdup (opt.output_document) : (con.target ? xstrdup (con.target) : url_file_name (u))); res = ftp_index (filename, u, f); if (res == FTPOK && opt.verbose) { if (!opt.output_document) { struct_stat st; wgint sz; if (stat (filename, &st) == 0) sz = st.st_size; else sz = -1; logprintf (LOG_NOTQUIET, _("Wrote HTML-ized index to %s [%s].\n"), quote (filename), number_to_static_string (sz)); } else logprintf (LOG_NOTQUIET, _("Wrote HTML-ized index to %s.\n"), quote (filename)); } xfree (filename); } freefileinfo (f); } } else { bool ispattern = false; if (glob) { /* Treat the URL as a pattern if the file name part of the URL path contains wildcards. (Don't check for u->file because it is unescaped and therefore doesn't leave users the option to escape literal '*' as %2A.) */ char *file_part = strrchr (u->path, '/'); if (!file_part) file_part = u->path; ispattern = has_wildcards_p (file_part); } if (ispattern || recursive || opt.timestamping) { /* ftp_retrieve_glob is a catch-all function that gets called if we need globbing, time-stamping or recursion. Its third argument is just what we really need. */ res = ftp_retrieve_glob (u, &con, ispattern ? GLOB_GLOBALL : GLOB_GETONE); } else res = ftp_loop_internal (u, NULL, &con, local_file); } if (res == FTPOK) res = RETROK; if (res == RETROK) *dt |= RETROKF; /* If a connection was left, quench it. */ if (con.csock != -1) fd_close (con.csock); xfree_null (con.id); con.id = NULL; xfree_null (con.target); con.target = NULL; return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Introduce --trust-server-names. Close CVE-2010-2252.'</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 Server::msgQueryUsers(ServerUser *uSource, MumbleProto::QueryUsers &msg) { MSG_SETUP(ServerUser::Authenticated); MumbleProto::QueryUsers reply; for (int i=0;i<msg.ids_size();++i) { int id = msg.ids(i); if (id >= 0) { const QString &name = getUserName(id); if (! name.isEmpty()) { reply.add_ids(id); reply.add_names(u8(name)); } } } for (int i=0;i<msg.names_size();++i) { QString name = u8(msg.names(i)); int id = getUserID(name); if (id >= 0) { name = getUserName(id); reply.add_ids(id); reply.add_names(u8(name)); } } sendMessage(uSource, reply); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash on long usernames'</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 Server::getUserID(const QString &name) { if (qhUserIDCache.contains(name)) return qhUserIDCache.value(name); int id = -2; emit nameToIdSig(id, name); if (id != -2) { qhUserIDCache.insert(name, id); qhUserNameCache.insert(id, name); return id; } TransactionHolder th; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `user_id` FROM `%1users` WHERE `server_id` = ? AND `name` like ?"); query.addBindValue(iServerNum); query.addBindValue(name); SQLEXEC(); if (query.next()) { id = query.value(0).toInt(); qhUserIDCache.insert(name, id); qhUserNameCache.insert(id, name); } return id; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash on long usernames'</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: write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = (const char *)status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = (const char *)status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Fix Savannah bug #30054. * src/ftdiff.c, src/ftgrid.c, src/ftmulti.c, src/ftstring.c, src/ftview.c: Use precision for `%s' where appropriate to avoid buffer overflows.'</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: write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = status.encoding != FT_ENCODING_NONE ? "at %g points, first char code = 0x%x" : "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize / 64.0, status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; if ( status.encoding != FT_ENCODING_NONE ) gindex = FTDemo_Get_Index( handle, status.Num ); strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); if ( status.use_custom_lcd_filter ) { int fwi = status.fw_index; unsigned char *fw = status.filter_weights; sprintf( status.header_buffer, "%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s", fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : " ", fwi == 1 ? "[" : " ", fw[1], fwi == 1 ? "]" : " ", fwi == 2 ? "[" : " ", fw[2], fwi == 2 ? "]" : " ", fwi == 3 ? "[" : " ", fw[3], fwi == 3 ? "]" : " ", fwi == 4 ? "[" : " ", fw[4], fwi == 4 ? "]" : " " ); grWriteCellString( display->bitmap, 0, 2 * HEADER_HEIGHT, status.header_buffer, display->fore_color ); } grRefreshSurface( display->surface ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Fix Savannah bug #30054. * src/ftdiff.c, src/ftgrid.c, src/ftmulti.c, src/ftstring.c, src/ftview.c: Use precision for `%s' where appropriate to avoid buffer overflows.'</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: main( int argc, char* argv[] ) { int old_ptsize, orig_ptsize, file; int first_glyph = 0; int XisSetup = 0; char* execname; int option; int file_loaded; grEvent event; execname = ft_basename( argv[0] ); while ( 1 ) { option = getopt( argc, argv, "d:e:f:r:" ); if ( option == -1 ) break; switch ( option ) { case 'd': parse_design_coords( optarg ); break; case 'e': encoding = (FT_Encoding)make_tag( optarg ); break; case 'f': first_glyph = atoi( optarg ); break; case 'r': res = atoi( optarg ); if ( res < 1 ) usage( execname ); break; default: usage( execname ); break; } } argc -= optind; argv += optind; if ( argc <= 1 ) usage( execname ); if ( sscanf( argv[0], "%d", &orig_ptsize ) != 1 ) orig_ptsize = 64; file = 1; /* Initialize engine */ error = FT_Init_FreeType( &library ); if ( error ) PanicZ( "Could not initialize FreeType library" ); NewFile: ptsize = orig_ptsize; hinted = 1; file_loaded = 0; /* Load face */ error = FT_New_Face( library, argv[file], 0, &face ); if ( error ) goto Display_Font; if ( encoding != FT_ENCODING_NONE ) { error = FT_Select_Charmap( face, encoding ); if ( error ) goto Display_Font; } /* retrieve multiple master information */ error = FT_Get_MM_Var( face, &multimaster ); if ( error ) goto Display_Font; /* if the user specified a position, use it, otherwise */ /* set the current position to the median of each axis */ { int n; for ( n = 0; n < (int)multimaster->num_axis; n++ ) { design_pos[n] = n < requested_cnt ? requested_pos[n] : multimaster->axis[n].def; if ( design_pos[n] < multimaster->axis[n].minimum ) design_pos[n] = multimaster->axis[n].minimum; else if ( design_pos[n] > multimaster->axis[n].maximum ) design_pos[n] = multimaster->axis[n].maximum; } } error = FT_Set_Var_Design_Coordinates( face, multimaster->num_axis, design_pos ); if ( error ) goto Display_Font; file_loaded++; Reset_Scale( ptsize ); num_glyphs = face->num_glyphs; glyph = face->glyph; size = face->size; Display_Font: /* initialize graphics if needed */ if ( !XisSetup ) { XisSetup = 1; Init_Display(); } grSetTitle( surface, "FreeType Glyph Viewer - press F1 for help" ); old_ptsize = ptsize; if ( file_loaded >= 1 ) { Fail = 0; Num = first_glyph; if ( Num >= num_glyphs ) Num = num_glyphs - 1; if ( Num < 0 ) Num = 0; } for ( ;; ) { int key; Clear_Display(); if ( file_loaded >= 1 ) { switch ( render_mode ) { case 0: Render_Text( Num ); break; default: Render_All( Num, ptsize ); } sprintf( Header, "%.50s %.50s (file %.100s)", face->family_name, face->style_name, ft_basename( argv[file] ) ); if ( !new_header ) new_header = Header; grWriteCellString( &bit, 0, 0, new_header, fore_color ); new_header = 0; sprintf( Header, "axis: " ); { int n; for ( n = 0; n < (int)multimaster->num_axis; n++ ) { char temp[32]; sprintf( temp, " %s:%g", multimaster->axis[n].name, design_pos[n]/65536. ); strcat( Header, temp ); } } grWriteCellString( &bit, 0, 16, Header, fore_color ); sprintf( Header, "at %d points, first glyph = %d", ptsize, Num ); } else { sprintf( Header, "%.100s: not an MM font file, or could not be opened", ft_basename( argv[file] ) ); } grWriteCellString( &bit, 0, 8, Header, fore_color ); grRefreshSurface( surface ); grListenSurface( surface, 0, &event ); if ( !( key = Process_Event( &event ) ) ) goto End; if ( key == 'n' ) { if ( file_loaded >= 1 ) FT_Done_Face( face ); if ( file < argc - 1 ) file++; goto NewFile; } if ( key == 'p' ) { if ( file_loaded >= 1 ) FT_Done_Face( face ); if ( file > 1 ) file--; goto NewFile; } if ( ptsize != old_ptsize ) { Reset_Scale( ptsize ); old_ptsize = ptsize; } } End: grDoneSurface( surface ); grDoneDevices(); free ( multimaster ); FT_Done_Face ( face ); FT_Done_FreeType( library ); printf( "Execution completed successfully.\n" ); printf( "Fails = %d\n", Fail ); exit( 0 ); /* for safety reasons */ return 0; /* never reached */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'ftmulti: Fix possible buffer overflow. Based on a patch from Marek Kašík <mkasik@redhat.com>. * src/ftmulti.c (main): Limit axis name length in `Header'.'</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: long keyctl_session_to_parent(void) { #ifdef TIF_NOTIFY_RESUME struct task_struct *me, *parent; const struct cred *mycred, *pcred; struct cred *cred, *oldcred; key_ref_t keyring_r; int ret; keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK); if (IS_ERR(keyring_r)) return PTR_ERR(keyring_r); /* our parent is going to need a new cred struct, a new tgcred struct * and new security data, so we allocate them here to prevent ENOMEM in * our parent */ ret = -ENOMEM; cred = cred_alloc_blank(); if (!cred) goto error_keyring; cred->tgcred->session_keyring = key_ref_to_ptr(keyring_r); keyring_r = NULL; me = current; rcu_read_lock(); write_lock_irq(&tasklist_lock); parent = me->real_parent; ret = -EPERM; /* the parent mustn't be init and mustn't be a kernel thread */ if (parent->pid <= 1 || !parent->mm) goto not_permitted; /* the parent must be single threaded */ if (!thread_group_empty(parent)) goto not_permitted; /* the parent and the child must have different session keyrings or * there's no point */ mycred = current_cred(); pcred = __task_cred(parent); if (mycred == pcred || mycred->tgcred->session_keyring == pcred->tgcred->session_keyring) goto already_same; /* the parent must have the same effective ownership and mustn't be * SUID/SGID */ if (pcred->uid != mycred->euid || pcred->euid != mycred->euid || pcred->suid != mycred->euid || pcred->gid != mycred->egid || pcred->egid != mycred->egid || pcred->sgid != mycred->egid) goto not_permitted; /* the keyrings must have the same UID */ if (pcred->tgcred->session_keyring->uid != mycred->euid || mycred->tgcred->session_keyring->uid != mycred->euid) goto not_permitted; /* if there's an already pending keyring replacement, then we replace * that */ oldcred = parent->replacement_session_keyring; /* the replacement session keyring is applied just prior to userspace * restarting */ parent->replacement_session_keyring = cred; cred = NULL; set_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME); write_unlock_irq(&tasklist_lock); rcu_read_unlock(); if (oldcred) put_cred(oldcred); return 0; already_same: ret = 0; not_permitted: write_unlock_irq(&tasklist_lock); rcu_read_unlock(); put_cred(cred); return ret; error_keyring: key_ref_put(keyring_r); return ret; #else /* !TIF_NOTIFY_RESUME */ /* * To be removed when TIF_NOTIFY_RESUME has been implemented on * m68k/xtensa */ #warning TIF_NOTIFY_RESUME not implemented return -EOPNOTSUPP; #endif /* !TIF_NOTIFY_RESUME */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Fix bug in keyctl_session_to_parent() if parent has no session keyring Fix a bug in keyctl_session_to_parent() whereby it tries to check the ownership of the parent process's session keyring whether or not the parent has a session keyring [CVE-2010-2960]. This results in the following oops: BUG: unable to handle kernel NULL pointer dereference at 00000000000000a0 IP: [<ffffffff811ae4dd>] keyctl_session_to_parent+0x251/0x443 ... Call Trace: [<ffffffff811ae2f3>] ? keyctl_session_to_parent+0x67/0x443 [<ffffffff8109d286>] ? __do_fault+0x24b/0x3d0 [<ffffffff811af98c>] sys_keyctl+0xb4/0xb8 [<ffffffff81001eab>] system_call_fastpath+0x16/0x1b if the parent process has no session keyring. If the system is using pam_keyinit then it mostly protected against this as all processes derived from a login will have inherited the session keyring created by pam_keyinit during the log in procedure. To test this, pam_keyinit calls need to be commented out in /etc/pam.d/. Reported-by: Tavis Ormandy <taviso@cmpxchg8b.com> Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Tavis Ormandy <taviso@cmpxchg8b.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: snd_seq_oss_open(struct file *file, int level) { int i, rc; struct seq_oss_devinfo *dp; dp = kzalloc(sizeof(*dp), GFP_KERNEL); if (!dp) { snd_printk(KERN_ERR "can't malloc device info\n"); return -ENOMEM; } debug_printk(("oss_open: dp = %p\n", dp)); dp->cseq = system_client; dp->port = -1; dp->queue = -1; for (i = 0; i < SNDRV_SEQ_OSS_MAX_CLIENTS; i++) { if (client_table[i] == NULL) break; } dp->index = i; if (i >= SNDRV_SEQ_OSS_MAX_CLIENTS) { snd_printk(KERN_ERR "too many applications\n"); rc = -ENOMEM; goto _error; } /* look up synth and midi devices */ snd_seq_oss_synth_setup(dp); snd_seq_oss_midi_setup(dp); if (dp->synth_opened == 0 && dp->max_mididev == 0) { /* snd_printk(KERN_ERR "no device found\n"); */ rc = -ENODEV; goto _error; } /* create port */ debug_printk(("create new port\n")); rc = create_port(dp); if (rc < 0) { snd_printk(KERN_ERR "can't create port\n"); goto _error; } /* allocate queue */ debug_printk(("allocate queue\n")); rc = alloc_seq_queue(dp); if (rc < 0) goto _error; /* set address */ dp->addr.client = dp->cseq; dp->addr.port = dp->port; /*dp->addr.queue = dp->queue;*/ /*dp->addr.channel = 0;*/ dp->seq_mode = level; /* set up file mode */ dp->file_mode = translate_mode(file); /* initialize read queue */ debug_printk(("initialize read queue\n")); if (is_read_mode(dp->file_mode)) { dp->readq = snd_seq_oss_readq_new(dp, maxqlen); if (!dp->readq) { rc = -ENOMEM; goto _error; } } /* initialize write queue */ debug_printk(("initialize write queue\n")); if (is_write_mode(dp->file_mode)) { dp->writeq = snd_seq_oss_writeq_new(dp, maxqlen); if (!dp->writeq) { rc = -ENOMEM; goto _error; } } /* initialize timer */ debug_printk(("initialize timer\n")); dp->timer = snd_seq_oss_timer_new(dp); if (!dp->timer) { snd_printk(KERN_ERR "can't alloc timer\n"); rc = -ENOMEM; goto _error; } debug_printk(("timer initialized\n")); /* set private data pointer */ file->private_data = dp; /* set up for mode2 */ if (level == SNDRV_SEQ_OSS_MODE_MUSIC) snd_seq_oss_synth_setup_midi(dp); else if (is_read_mode(dp->file_mode)) snd_seq_oss_midi_open_all(dp, SNDRV_SEQ_OSS_FILE_READ); client_table[dp->index] = dp; num_clients++; debug_printk(("open done\n")); return 0; _error: snd_seq_oss_writeq_delete(dp->writeq); snd_seq_oss_readq_delete(dp->readq); snd_seq_oss_synth_cleanup(dp); snd_seq_oss_midi_cleanup(dp); delete_port(dp); delete_seq_queue(dp->queue); kfree(dp); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'ALSA: seq/oss - Fix double-free at error path of snd_seq_oss_open() The error handling in snd_seq_oss_open() has several bad codes that do dereferecing released pointers and double-free of kmalloc'ed data. The object dp is release in free_devinfo() that is called via private_free callback. The rest shouldn't touch this object any more. The patch changes delete_port() to call kfree() in any case, and gets rid of unnecessary calls of destructors in snd_seq_oss_open(). Fixes CVE-2010-3080. Reported-and-tested-by: Tavis Ormandy <taviso@cmpxchg8b.com> Cc: <stable@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 inline u16 kvm_read_gs(void) { u16 seg; asm("mov %%gs, %0" : "=g"(seg)); return seg; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@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 int vmx_vcpu_setup(struct vcpu_vmx *vmx) { u32 host_sysenter_cs, msr_low, msr_high; u32 junk; u64 host_pat, tsc_this, tsc_base; unsigned long a; struct desc_ptr dt; int i; unsigned long kvm_vmx_return; u32 exec_control; /* I/O */ vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a)); vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b)); if (cpu_has_vmx_msr_bitmap()) vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy)); vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */ /* Control */ vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmcs_config.pin_based_exec_ctrl); exec_control = vmcs_config.cpu_based_exec_ctrl; if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) { exec_control &= ~CPU_BASED_TPR_SHADOW; #ifdef CONFIG_X86_64 exec_control |= CPU_BASED_CR8_STORE_EXITING | CPU_BASED_CR8_LOAD_EXITING; #endif } if (!enable_ept) exec_control |= CPU_BASED_CR3_STORE_EXITING | CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_INVLPG_EXITING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control); if (cpu_has_secondary_exec_ctrls()) { exec_control = vmcs_config.cpu_based_2nd_exec_ctrl; if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; if (vmx->vpid == 0) exec_control &= ~SECONDARY_EXEC_ENABLE_VPID; if (!enable_ept) { exec_control &= ~SECONDARY_EXEC_ENABLE_EPT; enable_unrestricted_guest = 0; } if (!enable_unrestricted_guest) exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST; if (!ple_gap) exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); } if (ple_gap) { vmcs_write32(PLE_GAP, ple_gap); vmcs_write32(PLE_WINDOW, ple_window); } vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf); vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf); vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */ vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS); /* 22.2.3 */ vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */ vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */ vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_FS_SELECTOR, kvm_read_fs()); /* 22.2.4 */ vmcs_write16(HOST_GS_SELECTOR, kvm_read_gs()); /* 22.2.4 */ vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ #ifdef CONFIG_X86_64 rdmsrl(MSR_FS_BASE, a); vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */ rdmsrl(MSR_GS_BASE, a); vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */ #else vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */ vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */ #endif vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ native_store_idt(&dt); vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */ asm("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return)); vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */ vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0); vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0); vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host)); vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0); vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest)); rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk); vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs); rdmsrl(MSR_IA32_SYSENTER_ESP, a); vmcs_writel(HOST_IA32_SYSENTER_ESP, a); /* 22.2.3 */ rdmsrl(MSR_IA32_SYSENTER_EIP, a); vmcs_writel(HOST_IA32_SYSENTER_EIP, a); /* 22.2.3 */ if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high); host_pat = msr_low | ((u64) msr_high << 32); vmcs_write64(HOST_IA32_PAT, host_pat); } if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high); host_pat = msr_low | ((u64) msr_high << 32); /* Write the default value follow host pat */ vmcs_write64(GUEST_IA32_PAT, host_pat); /* Keep arch.pat sync with GUEST_IA32_PAT */ vmx->vcpu.arch.pat = host_pat; } for (i = 0; i < NR_VMX_MSR; ++i) { u32 index = vmx_msr_index[i]; u32 data_low, data_high; int j = vmx->nmsrs; if (rdmsr_safe(index, &data_low, &data_high) < 0) continue; if (wrmsr_safe(index, data_low, data_high) < 0) continue; vmx->guest_msrs[j].index = i; vmx->guest_msrs[j].data = 0; vmx->guest_msrs[j].mask = -1ull; ++vmx->nmsrs; } vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl); /* 22.2.1, 20.8.1 */ vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl); vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL); vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS; if (enable_ept) vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE; vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits); tsc_base = vmx->vcpu.kvm->arch.vm_init_tsc; rdtscll(tsc_this); if (tsc_this < vmx->vcpu.kvm->arch.vm_init_tsc) tsc_base = tsc_this; guest_write_tsc(0, tsc_base); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@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 inline u16 kvm_read_fs(void) { u16 seg; asm("mov %%fs, %0" : "=g"(seg)); return seg; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@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 inline void kvm_load_gs(u16 sel) { asm("mov %0, %%gs" : : "rm"(sel)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@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 xmlNodePtr xmlXPathNextPrecedingInternal(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if (cur == NULL) { cur = ctxt->context->node; if (cur == NULL) return (NULL); if (cur->type == XML_NAMESPACE_DECL) cur = (xmlNodePtr)((xmlNsPtr)cur)->next; ctxt->ancestor = cur->parent; } if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE)) cur = cur->prev; while (cur->prev == NULL) { cur = cur->parent; if (cur == NULL) return (NULL); if (cur == ctxt->context->doc->children) return (NULL); if (cur != ctxt->ancestor) return (cur); ctxt->ancestor = cur->parent; } cur = cur->prev; while (cur->last != NULL) cur = cur->last; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix the semantic of XPath axis for namespace/attribute context nodes The processing of namespace and attributes nodes was not compliant to the XPath-1.0 specification'</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: */ xmlNodePtr xmlXPathNextPreceding(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) || (ctxt->context->node->type == XML_NAMESPACE_DECL)) return(NULL); if (cur == NULL) cur = ctxt->context->node; if (cur == NULL) return (NULL); if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE)) cur = cur->prev; do { if (cur->prev != NULL) { for (cur = cur->prev; cur->last != NULL; cur = cur->last) ; return (cur); } cur = cur->parent; if (cur == NULL) return (NULL); if (cur == ctxt->context->doc->children) return (NULL); } while (xmlXPathIsAncestor(cur, ctxt->context->node)); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a change of semantic on XPath preceding and following axis This was introduced in the prevous fix, while preceding-sibling and following sibling axis are empty for attributes and namespaces, preceding and following axis should still work based on the parent element. However the parent element is not available for a namespace node, so we keep the axis empty in that case.'</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: */ xmlNodePtr xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) || (ctxt->context->node->type == XML_NAMESPACE_DECL)) return(NULL); if (cur != NULL) { if ((cur->type == XML_ATTRIBUTE_NODE) || (cur->type == XML_NAMESPACE_DECL)) return(NULL); if (cur->children != NULL) return cur->children ; } if (cur == NULL) cur = ctxt->context->node; if (cur == NULL) return(NULL) ; /* ERROR */ if (cur->next != NULL) return(cur->next) ; do { cur = cur->parent; if (cur == NULL) break; if (cur == (xmlNodePtr) ctxt->context->doc) return(NULL); if (cur->next != NULL) return(cur->next); } while (cur != NULL); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a change of semantic on XPath preceding and following axis This was introduced in the prevous fix, while preceding-sibling and following sibling axis are empty for attributes and namespaces, preceding and following axis should still work based on the parent element. However the parent element is not available for a namespace node, so we keep the axis empty in that case.'</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 packet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct net_device *dev; struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr); if (peer) return -EOPNOTSUPP; sll->sll_family = AF_PACKET; sll->sll_ifindex = po->ifindex; sll->sll_protocol = po->num; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex); if (dev) { sll->sll_hatype = dev->type; sll->sll_halen = dev->addr_len; memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len); } else { sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */ sll->sll_halen = 0; } rcu_read_unlock(); *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-909'], 'message': 'net: packet: fix information leak to userland packet_getname_spkt() doesn't initialize all members of sa_data field of sockaddr struct if strlen(dev->name) < 13. This structure is then copied to userland. It leads to leaking of contents of kernel stack memory. We have to fully fill sa_data with strncpy() instead of strlcpy(). The same with packet_getname(): it doesn't initialize sll_pkttype field of sockaddr_ll. Set it to zero. Signed-off-by: Vasiliy Kulikov <segooon@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: static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int r = 0; mutex_lock(&kvm->arch.vpit->pit_state.lock); memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels, sizeof(ps->channels)); ps->flags = kvm->arch.vpit->pit_state.flags; mutex_unlock(&kvm->arch.vpit->pit_state.lock); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'KVM: x86: fix information leak to userland Structures kvm_vcpu_events, kvm_debugregs, kvm_pit_state2 and kvm_clock_data are copied to userland with some padding and reserved fields unitialized. It leads to leaking of contents of kernel stack memory. We have to initialize them to zero. In patch v1 Jan Kiszka suggested to fill reserved fields with zeros instead of memset'ting the whole struct. It makes sense as these fields are explicitly marked as padding. No more fields need zeroing. KVM-Stable-Tag. Signed-off-by: Vasiliy Kulikov <segooon@gmail.com> Signed-off-by: Marcelo Tosatti <mtosatti@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: long kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm *kvm = filp->private_data; void __user *argp = (void __user *)arg; int r = -ENOTTY; /* * This union makes it completely explicit to gcc-3.x * that these two variables' stack usage should be * combined, not added together. */ union { struct kvm_pit_state ps; struct kvm_pit_state2 ps2; struct kvm_pit_config pit_config; } u; switch (ioctl) { case KVM_SET_TSS_ADDR: r = kvm_vm_ioctl_set_tss_addr(kvm, arg); if (r < 0) goto out; break; case KVM_SET_IDENTITY_MAP_ADDR: { u64 ident_addr; r = -EFAULT; if (copy_from_user(&ident_addr, argp, sizeof ident_addr)) goto out; r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr); if (r < 0) goto out; break; } case KVM_SET_NR_MMU_PAGES: r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg); if (r) goto out; break; case KVM_GET_NR_MMU_PAGES: r = kvm_vm_ioctl_get_nr_mmu_pages(kvm); break; case KVM_CREATE_IRQCHIP: { struct kvm_pic *vpic; mutex_lock(&kvm->lock); r = -EEXIST; if (kvm->arch.vpic) goto create_irqchip_unlock; r = -ENOMEM; vpic = kvm_create_pic(kvm); if (vpic) { r = kvm_ioapic_init(kvm); if (r) { kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &vpic->dev); kfree(vpic); goto create_irqchip_unlock; } } else goto create_irqchip_unlock; smp_wmb(); kvm->arch.vpic = vpic; smp_wmb(); r = kvm_setup_default_irq_routing(kvm); if (r) { mutex_lock(&kvm->irq_lock); kvm_ioapic_destroy(kvm); kvm_destroy_pic(kvm); mutex_unlock(&kvm->irq_lock); } create_irqchip_unlock: mutex_unlock(&kvm->lock); break; } case KVM_CREATE_PIT: u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY; goto create_pit; case KVM_CREATE_PIT2: r = -EFAULT; if (copy_from_user(&u.pit_config, argp, sizeof(struct kvm_pit_config))) goto out; create_pit: mutex_lock(&kvm->slots_lock); r = -EEXIST; if (kvm->arch.vpit) goto create_pit_unlock; r = -ENOMEM; kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags); if (kvm->arch.vpit) r = 0; create_pit_unlock: mutex_unlock(&kvm->slots_lock); break; case KVM_IRQ_LINE_STATUS: case KVM_IRQ_LINE: { struct kvm_irq_level irq_event; r = -EFAULT; if (copy_from_user(&irq_event, argp, sizeof irq_event)) goto out; r = -ENXIO; if (irqchip_in_kernel(kvm)) { __s32 status; status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID, irq_event.irq, irq_event.level); if (ioctl == KVM_IRQ_LINE_STATUS) { r = -EFAULT; irq_event.status = status; if (copy_to_user(argp, &irq_event, sizeof irq_event)) goto out; } r = 0; } break; } case KVM_GET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL); r = -ENOMEM; if (!chip) goto out; r = -EFAULT; if (copy_from_user(chip, argp, sizeof *chip)) goto get_irqchip_out; r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto get_irqchip_out; r = kvm_vm_ioctl_get_irqchip(kvm, chip); if (r) goto get_irqchip_out; r = -EFAULT; if (copy_to_user(argp, chip, sizeof *chip)) goto get_irqchip_out; r = 0; get_irqchip_out: kfree(chip); if (r) goto out; break; } case KVM_SET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL); r = -ENOMEM; if (!chip) goto out; r = -EFAULT; if (copy_from_user(chip, argp, sizeof *chip)) goto set_irqchip_out; r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto set_irqchip_out; r = kvm_vm_ioctl_set_irqchip(kvm, chip); if (r) goto set_irqchip_out; r = 0; set_irqchip_out: kfree(chip); if (r) goto out; break; } case KVM_GET_PIT: { r = -EFAULT; if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state))) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_get_pit(kvm, &u.ps); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state))) goto out; r = 0; break; } case KVM_SET_PIT: { r = -EFAULT; if (copy_from_user(&u.ps, argp, sizeof u.ps)) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_set_pit(kvm, &u.ps); if (r) goto out; r = 0; break; } case KVM_GET_PIT2: { r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &u.ps2, sizeof(u.ps2))) goto out; r = 0; break; } case KVM_SET_PIT2: { r = -EFAULT; if (copy_from_user(&u.ps2, argp, sizeof(u.ps2))) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2); if (r) goto out; r = 0; break; } case KVM_REINJECT_CONTROL: { struct kvm_reinject_control control; r = -EFAULT; if (copy_from_user(&control, argp, sizeof(control))) goto out; r = kvm_vm_ioctl_reinject(kvm, &control); if (r) goto out; r = 0; break; } case KVM_XEN_HVM_CONFIG: { r = -EFAULT; if (copy_from_user(&kvm->arch.xen_hvm_config, argp, sizeof(struct kvm_xen_hvm_config))) goto out; r = -EINVAL; if (kvm->arch.xen_hvm_config.flags) goto out; r = 0; break; } case KVM_SET_CLOCK: { struct kvm_clock_data user_ns; u64 now_ns; s64 delta; r = -EFAULT; if (copy_from_user(&user_ns, argp, sizeof(user_ns))) goto out; r = -EINVAL; if (user_ns.flags) goto out; r = 0; local_irq_disable(); now_ns = get_kernel_ns(); delta = user_ns.clock - now_ns; local_irq_enable(); kvm->arch.kvmclock_offset = delta; break; } case KVM_GET_CLOCK: { struct kvm_clock_data user_ns; u64 now_ns; local_irq_disable(); now_ns = get_kernel_ns(); user_ns.clock = kvm->arch.kvmclock_offset + now_ns; local_irq_enable(); user_ns.flags = 0; r = -EFAULT; if (copy_to_user(argp, &user_ns, sizeof(user_ns))) goto out; r = 0; break; } default: ; } out: return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'KVM: x86: fix information leak to userland Structures kvm_vcpu_events, kvm_debugregs, kvm_pit_state2 and kvm_clock_data are copied to userland with some padding and reserved fields unitialized. It leads to leaking of contents of kernel stack memory. We have to initialize them to zero. In patch v1 Jan Kiszka suggested to fill reserved fields with zeros instead of memset'ting the whole struct. It makes sense as these fields are explicitly marked as padding. No more fields need zeroing. KVM-Stable-Tag. Signed-off-by: Vasiliy Kulikov <segooon@gmail.com> Signed-off-by: Marcelo Tosatti <mtosatti@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: int __udp6_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, int proto) { struct net *net = dev_net(skb->dev); struct sock *sk; struct udphdr *uh; struct in6_addr *saddr, *daddr; u32 ulen = 0; if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto short_packet; saddr = &ipv6_hdr(skb)->saddr; daddr = &ipv6_hdr(skb)->daddr; uh = udp_hdr(skb); ulen = ntohs(uh->len); if (ulen > skb->len) goto short_packet; if (proto == IPPROTO_UDP) { /* UDP validates ulen. */ /* Check for jumbo payload */ if (ulen == 0) ulen = skb->len; if (ulen < sizeof(*uh)) goto short_packet; if (ulen < skb->len) { if (pskb_trim_rcsum(skb, ulen)) goto short_packet; saddr = &ipv6_hdr(skb)->saddr; daddr = &ipv6_hdr(skb)->daddr; uh = udp_hdr(skb); } } if (udp6_csum_init(skb, uh, proto)) goto discard; /* * Multicast receive code */ if (ipv6_addr_is_multicast(daddr)) return __udp6_lib_mcast_deliver(net, skb, saddr, daddr, udptable); /* Unicast */ /* * check socket cache ... must talk to Alan about his plans * for sock caches... i'll skip this for now. */ sk = __udp6_lib_lookup_skb(skb, uh->source, uh->dest, udptable); if (sk == NULL) { if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard; if (udp_lib_checksum_complete(skb)) goto discard; UDP6_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0); kfree_skb(skb); return 0; } /* deliver */ bh_lock_sock(sk); if (!sock_owned_by_user(sk)) udpv6_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb)) { atomic_inc(&sk->sk_drops); bh_unlock_sock(sk); sock_put(sk); goto discard; } bh_unlock_sock(sk); sock_put(sk); return 0; short_packet: LIMIT_NETDEBUG(KERN_DEBUG "UDP%sv6: short packet: %d/%u\n", proto == IPPROTO_UDPLITE ? "-Lite" : "", ulen, skb->len); discard: UDP6_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); kfree_skb(skb); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@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: int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested) { int rc = NET_RX_SUCCESS; if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@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: static inline __must_check int sk_add_backlog(struct sock *sk, struct sk_buff *skb) { if (sk->sk_backlog.len >= max(sk->sk_backlog.limit, sk->sk_rcvbuf << 1)) return -ENOBUFS; __sk_add_backlog(sk, skb); sk->sk_backlog.len += skb->truesize; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@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: SCTP_STATIC int sctp_init_sock(struct sock *sk) { struct sctp_endpoint *ep; struct sctp_sock *sp; SCTP_DEBUG_PRINTK("sctp_init_sock(sk: %p)\n", sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = sctp_max_burst; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = sctp_max_retrans_init; sp->initmsg.sinit_max_init_timeo = sctp_rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = sctp_rto_initial; sp->rtoinfo.srto_max = sctp_rto_max; sp->rtoinfo.srto_min = sctp_rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = sctp_max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = sctp_valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = sctp_hb_interval; sp->pathmaxrxt = sctp_max_retrans_path; sp->pathmtu = 0; // allow default discovery sp->sackdelay = sctp_sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!ep) return -ENOMEM; sp->ep = ep; sp->hmac = NULL; SCTP_DBG_OBJCNT_INC(sock); percpu_counter_inc(&sctp_sockets_allocated); /* Set socket backlog limit. */ sk->sk_backlog.limit = sysctl_sctp_rmem[1]; local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@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: MonoReflectionMethod* mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types) { MonoClass *klass; MonoMethod *method, *inflated; MonoMethodInflated *imethod; MonoGenericContext tmp_context; MonoGenericInst *ginst; MonoType **type_argv; int count, i; MONO_ARCH_SAVE_REGS; /*FIXME but this no longer should happen*/ if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) { #ifndef DISABLE_REFLECTION_EMIT MonoReflectionMethodBuilder *mb = NULL; MonoReflectionTypeBuilder *tb; MonoClass *klass; mb = (MonoReflectionMethodBuilder *) rmethod; tb = (MonoReflectionTypeBuilder *) mb->type; klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb)); method = methodbuilder_to_mono_method (klass, mb); #else g_assert_not_reached (); method = NULL; #endif } else { method = rmethod->method; } klass = method->klass; if (method->is_inflated) method = ((MonoMethodInflated *) method)->declaring; count = mono_method_signature (method)->generic_param_count; if (count != mono_array_length (types)) return NULL; type_argv = g_new0 (MonoType *, count); for (i = 0; i < count; i++) { MonoReflectionType *garg = mono_array_get (types, gpointer, i); type_argv [i] = mono_reflection_type_get_handle (garg); } ginst = mono_metadata_get_generic_inst (count, type_argv); g_free (type_argv); tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL; tmp_context.method_inst = ginst; inflated = mono_class_inflate_generic_method (method, &tmp_context); imethod = (MonoMethodInflated *) inflated; /*FIXME but I think this is no longer necessary*/ if (method->klass->image->dynamic) { MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image; /* * This table maps metadata structures representing inflated methods/fields * to the reflection objects representing their generic definitions. */ mono_loader_lock (); mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod); mono_loader_unlock (); } return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Handle invalid instantiation of generic methods. * verify.c: Add new function to internal verifier API to check method instantiations. * reflection.c (mono_reflection_bind_generic_method_parameters): Check the instantiation before returning it. Fixes #655847'</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: handle_smtp_call(int *listen_sockets, int listen_socket_count, int accept_socket, struct sockaddr *accepted) { pid_t pid; union sockaddr_46 interface_sockaddr; EXIM_SOCKLEN_T ifsize = sizeof(interface_sockaddr); int dup_accept_socket = -1; int max_for_this_host = 0; int wfsize = 0; int wfptr = 0; int use_log_write_selector = log_write_selector; uschar *whofrom = NULL; void *reset_point = store_get(0); /* Make the address available in ASCII representation, and also fish out the remote port. */ sender_host_address = host_ntoa(-1, accepted, NULL, &sender_host_port); DEBUG(D_any) debug_printf("Connection request from %s port %d\n", sender_host_address, sender_host_port); /* Set up the output stream, check the socket has duplicated, and set up the input stream. These operations fail only the exceptional circumstances. Note that never_error() won't use smtp_out if it is NULL. */ smtp_out = fdopen(accept_socket, "wb"); if (smtp_out == NULL) { never_error(US"daemon: fdopen() for smtp_out failed", US"", errno); goto ERROR_RETURN; } dup_accept_socket = dup(accept_socket); if (dup_accept_socket < 0) { never_error(US"daemon: couldn't dup socket descriptor", US"Connection setup failed", errno); goto ERROR_RETURN; } smtp_in = fdopen(dup_accept_socket, "rb"); if (smtp_in == NULL) { never_error(US"daemon: fdopen() for smtp_in failed", US"Connection setup failed", errno); goto ERROR_RETURN; } /* Get the data for the local interface address. Panic for most errors, but "connection reset by peer" just means the connection went away. */ if (getsockname(accept_socket, (struct sockaddr *)(&interface_sockaddr), &ifsize) < 0) { log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC), "getsockname() failed: %s", strerror(errno)); smtp_printf("421 Local problem: getsockname() failed; please try again later\r\n"); goto ERROR_RETURN; } interface_address = host_ntoa(-1, &interface_sockaddr, NULL, &interface_port); DEBUG(D_interface) debug_printf("interface address=%s port=%d\n", interface_address, interface_port); /* Build a string identifying the remote host and, if requested, the port and the local interface data. This is for logging; at the end of this function the memory is reclaimed. */ whofrom = string_append(whofrom, &wfsize, &wfptr, 3, "[", sender_host_address, "]"); if ((log_extra_selector & LX_incoming_port) != 0) whofrom = string_append(whofrom, &wfsize, &wfptr, 2, ":", string_sprintf("%d", sender_host_port)); if ((log_extra_selector & LX_incoming_interface) != 0) whofrom = string_append(whofrom, &wfsize, &wfptr, 4, " I=[", interface_address, "]:", string_sprintf("%d", interface_port)); whofrom[wfptr] = 0; /* Terminate the newly-built string */ /* Check maximum number of connections. We do not check for reserved connections or unacceptable hosts here. That is done in the subprocess because it might take some time. */ if (smtp_accept_max > 0 && smtp_accept_count >= smtp_accept_max) { DEBUG(D_any) debug_printf("rejecting SMTP connection: count=%d max=%d\n", smtp_accept_count, smtp_accept_max); smtp_printf("421 Too many concurrent SMTP connections; " "please try again later.\r\n"); log_write(L_connection_reject, LOG_MAIN, "Connection from %s refused: too many connections", whofrom); goto ERROR_RETURN; } /* If a load limit above which only reserved hosts are acceptable is defined, get the load average here, and if there are in fact no reserved hosts, do the test right away (saves a fork). If there are hosts, do the check in the subprocess because it might take time. */ if (smtp_load_reserve >= 0) { load_average = OS_GETLOADAVG(); if (smtp_reserve_hosts == NULL && load_average > smtp_load_reserve) { DEBUG(D_any) debug_printf("rejecting SMTP connection: load average = %.2f\n", (double)load_average/1000.0); smtp_printf("421 Too much load; please try again later.\r\n"); log_write(L_connection_reject, LOG_MAIN, "Connection from %s refused: load average = %.2f", whofrom, (double)load_average/1000.0); goto ERROR_RETURN; } } /* Check that one specific host (strictly, IP address) is not hogging resources. This is done here to prevent a denial of service attack by someone forcing you to fork lots of times before denying service. The value of smtp_accept_max_per_host is a string which is expanded. This makes it possible to provide host-specific limits according to $sender_host address, but because this is in the daemon mainline, only fast expansions (such as inline address checks) should be used. The documentation is full of warnings. */ if (smtp_accept_max_per_host != NULL) { uschar *expanded = expand_string(smtp_accept_max_per_host); if (expanded == NULL) { if (!expand_string_forcedfail) log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host " "failed for %s: %s", whofrom, expand_string_message); } /* For speed, interpret a decimal number inline here */ else { uschar *s = expanded; while (isdigit(*s)) max_for_this_host = max_for_this_host * 10 + *s++ - '0'; if (*s != 0) log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host " "for %s contains non-digit: %s", whofrom, expanded); } } /* If we have fewer connections than max_for_this_host, we can skip the tedious per host_address checks. Note that at this stage smtp_accept_count contains the count of *other* connections, not including this one. */ if ((max_for_this_host > 0) && (smtp_accept_count >= max_for_this_host)) { int i; int host_accept_count = 0; int other_host_count = 0; /* keep a count of non matches to optimise */ for (i = 0; i < smtp_accept_max; ++i) { if (smtp_slots[i].host_address != NULL) { if (Ustrcmp(sender_host_address, smtp_slots[i].host_address) == 0) host_accept_count++; else other_host_count++; /* Testing all these strings is expensive - see if we can drop out early, either by hitting the target, or finding there are not enough connections left to make the target. */ if ((host_accept_count >= max_for_this_host) || ((smtp_accept_count - other_host_count) < max_for_this_host)) break; } } if (host_accept_count >= max_for_this_host) { DEBUG(D_any) debug_printf("rejecting SMTP connection: too many from this " "IP address: count=%d max=%d\n", host_accept_count, max_for_this_host); smtp_printf("421 Too many concurrent SMTP connections " "from this IP address; please try again later.\r\n"); log_write(L_connection_reject, LOG_MAIN, "Connection from %s refused: too many connections " "from that IP address", whofrom); goto ERROR_RETURN; } } /* OK, the connection count checks have been passed. Before we can fork the accepting process, we must first log the connection if requested. This logging used to happen in the subprocess, but doing that means that the value of smtp_accept_count can be out of step by the time it is logged. So we have to do the logging here and accept the performance cost. Note that smtp_accept_count hasn't yet been incremented to take account of this connection. In order to minimize the cost (because this is going to happen for every connection), do a preliminary selector test here. This saves ploughing through the generalized logging code each time when the selector is false. If the selector is set, check whether the host is on the list for logging. If not, arrange to unset the selector in the subprocess. */ if ((log_write_selector & L_smtp_connection) != 0) { uschar *list = hosts_connection_nolog; if (list != NULL && verify_check_host(&list) == OK) use_log_write_selector &= ~L_smtp_connection; else log_write(L_smtp_connection, LOG_MAIN, "SMTP connection from %s " "(TCP/IP connection count = %d)", whofrom, smtp_accept_count + 1); } /* Now we can fork the accepting process; do a lookup tidy, just in case any expansion above did a lookup. */ search_tidyup(); pid = fork(); /* Handle the child process */ if (pid == 0) { int i; int queue_only_reason = 0; int old_pool = store_pool; int save_debug_selector = debug_selector; BOOL local_queue_only; BOOL session_local_queue_only; #ifdef SA_NOCLDWAIT struct sigaction act; #endif smtp_accept_count++; /* So that it includes this process */ /* May have been modified for the subprocess */ log_write_selector = use_log_write_selector; /* Get the local interface address into permanent store */ store_pool = POOL_PERM; interface_address = string_copy(interface_address); store_pool = old_pool; /* Check for a tls-on-connect port */ if (host_is_tls_on_connect_port(interface_port)) tls_on_connect = TRUE; /* Expand smtp_active_hostname if required. We do not do this any earlier, because it may depend on the local interface address (indeed, that is most likely what it depends on.) */ smtp_active_hostname = primary_hostname; if (raw_active_hostname != NULL) { uschar *nah = expand_string(raw_active_hostname); if (nah == NULL) { if (!expand_string_forcedfail) { log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" " "(smtp_active_hostname): %s", raw_active_hostname, expand_string_message); smtp_printf("421 Local configuration error; " "please try again later.\r\n"); mac_smtp_fflush(); search_tidyup(); _exit(EXIT_FAILURE); } } else if (nah[0] != 0) smtp_active_hostname = nah; } /* Initialize the queueing flags */ queue_check_only(); session_local_queue_only = queue_only; /* Close the listening sockets, and set the SIGCHLD handler to SIG_IGN. We also attempt to set things up so that children are automatically reaped, but just in case this isn't available, there's a paranoid waitpid() in the loop too (except for systems where we are sure it isn't needed). See the more extensive comment before the reception loop in exim.c for a fuller explanation of this logic. */ for (i = 0; i < listen_socket_count; i++) (void)close(listen_sockets[i]); #ifdef SA_NOCLDWAIT act.sa_handler = SIG_IGN; sigemptyset(&(act.sa_mask)); act.sa_flags = SA_NOCLDWAIT; sigaction(SIGCHLD, &act, NULL); #else signal(SIGCHLD, SIG_IGN); #endif /* Attempt to get an id from the sending machine via the RFC 1413 protocol. We do this in the sub-process in order not to hold up the main process if there is any delay. Then set up the fullhost information in case there is no HELO/EHLO. If debugging is enabled only for the daemon, we must turn if off while finding the id, but turn it on again afterwards so that information about the incoming connection is output. */ if (debug_daemon) debug_selector = 0; verify_get_ident(IDENT_PORT); host_build_sender_fullhost(); debug_selector = save_debug_selector; DEBUG(D_any) debug_printf("Process %d is handling incoming connection from %s\n", (int)getpid(), sender_fullhost); /* Now disable debugging permanently if it's required only for the daemon process. */ if (debug_daemon) debug_selector = 0; /* If there are too many child processes for immediate delivery, set the session_local_queue_only flag, which is initialized from the configured value and may therefore already be TRUE. Leave logging till later so it will have a message id attached. Note that there is no possibility of re-calculating this per-message, because the value of smtp_accept_count does not change in this subprocess. */ if (smtp_accept_queue > 0 && smtp_accept_count > smtp_accept_queue) { session_local_queue_only = TRUE; queue_only_reason = 1; } /* Handle the start of the SMTP session, then loop, accepting incoming messages from the SMTP connection. The end will come at the QUIT command, when smtp_setup_msg() returns 0. A break in the connection causes the process to die (see accept.c). NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails, because a log line has already been written for all its failure exists (usually "connection refused: <reason>") and writing another one is unnecessary clutter. */ if (!smtp_start_session()) { mac_smtp_fflush(); search_tidyup(); _exit(EXIT_SUCCESS); } for (;;) { int rc; message_id[0] = 0; /* Clear out any previous message_id */ reset_point = store_get(0); /* Save current store high water point */ DEBUG(D_any) debug_printf("Process %d is ready for new message\n", (int)getpid()); /* Smtp_setup_msg() returns 0 on QUIT or if the call is from an unacceptable host or if an ACL "drop" command was triggered, -1 on connection lost, and +1 on validly reaching DATA. Receive_msg() almost always returns TRUE when smtp_input is true; just retry if no message was accepted (can happen for invalid message parameters). However, it can yield FALSE if the connection was forcibly dropped by the DATA ACL. */ if ((rc = smtp_setup_msg()) > 0) { BOOL ok = receive_msg(FALSE); search_tidyup(); /* Close cached databases */ if (!ok) /* Connection was dropped */ { mac_smtp_fflush(); smtp_log_no_mail(); /* Log no mail if configured */ _exit(EXIT_SUCCESS); } if (message_id[0] == 0) continue; /* No message was accepted */ } else { mac_smtp_fflush(); search_tidyup(); smtp_log_no_mail(); /* Log no mail if configured */ _exit((rc == 0)? EXIT_SUCCESS : EXIT_FAILURE); } /* Show the recipients when debugging */ DEBUG(D_receive) { int i; if (sender_address != NULL) debug_printf("Sender: %s\n", sender_address); if (recipients_list != NULL) { debug_printf("Recipients:\n"); for (i = 0; i < recipients_count; i++) debug_printf(" %s\n", recipients_list[i].address); } } /* A message has been accepted. Clean up any previous delivery processes that have completed and are defunct, on systems where they don't go away by themselves (see comments when setting SIG_IGN above). On such systems (if any) these delivery processes hang around after termination until the next message is received. */ #ifndef SIG_IGN_WORKS while (waitpid(-1, NULL, WNOHANG) > 0); #endif /* Reclaim up the store used in accepting this message */ store_reset(reset_point); /* If queue_only is set or if there are too many incoming connections in existence, session_local_queue_only will be TRUE. If it is not, check whether we have received too many messages in this session for immediate delivery. */ if (!session_local_queue_only && smtp_accept_queue_per_connection > 0 && receive_messagecount > smtp_accept_queue_per_connection) { session_local_queue_only = TRUE; queue_only_reason = 2; } /* Initialize local_queue_only from session_local_queue_only. If it is not true, and queue_only_load is set, check that the load average is below it. If local_queue_only is set by this means, we also set if for the session if queue_only_load_latch is true (the default). This means that, once set, local_queue_only remains set for any subsequent messages on the same SMTP connection. This is a deliberate choice; even though the load average may fall, it doesn't seem right to deliver later messages on the same call when not delivering earlier ones. However, the are special circumstances such as very long-lived connections from scanning appliances where this is not the best strategy. In such cases, queue_only_load_latch should be set false. */ local_queue_only = session_local_queue_only; if (!local_queue_only && queue_only_load >= 0) { local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load; if (local_queue_only) { queue_only_reason = 3; if (queue_only_load_latch) session_local_queue_only = TRUE; } } /* Log the queueing here, when it will get a message id attached, but not if queue_only is set (case 0). */ if (local_queue_only) switch(queue_only_reason) { case 1: log_write(L_delay_delivery, LOG_MAIN, "no immediate delivery: too many connections " "(%d, max %d)", smtp_accept_count, smtp_accept_queue); break; case 2: log_write(L_delay_delivery, LOG_MAIN, "no immediate delivery: more than %d messages " "received in one connection", smtp_accept_queue_per_connection); break; case 3: log_write(L_delay_delivery, LOG_MAIN, "no immediate delivery: load average %.2f", (double)load_average/1000.0); break; } /* If a delivery attempt is required, spin off a new process to handle it. If we are not root, we have to re-exec exim unless deliveries are being done unprivileged. */ else if (!queue_only_policy && !deliver_freeze) { pid_t dpid; /* Before forking, ensure that the C output buffer is flushed. Otherwise anything that it in it will get duplicated, leading to duplicate copies of the pending output. */ mac_smtp_fflush(); if ((dpid = fork()) == 0) { (void)fclose(smtp_in); (void)fclose(smtp_out); /* Don't ever molest the parent's SSL connection, but do clean up the data structures if necessary. */ #ifdef SUPPORT_TLS tls_close(FALSE); #endif /* Reset SIGHUP and SIGCHLD in the child in both cases. */ signal(SIGHUP, SIG_DFL); signal(SIGCHLD, SIG_DFL); if (geteuid() != root_uid && !deliver_drop_privilege) { signal(SIGALRM, SIG_DFL); (void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, 2, US"-Mc", message_id); /* Control does not return here. */ } /* No need to re-exec; SIGALRM remains set to the default handler */ (void)deliver_message(message_id, FALSE, FALSE); search_tidyup(); _exit(EXIT_SUCCESS); } if (dpid > 0) { DEBUG(D_any) debug_printf("forked delivery process %d\n", (int)dpid); } else { log_write(0, LOG_MAIN|LOG_PANIC, "daemon: delivery process fork " "failed: %s", strerror(errno)); } } } } /* Carrying on in the parent daemon process... Can't do much if the fork failed. Otherwise, keep count of the number of accepting processes and remember the pid for ticking off when the child completes. */ if (pid < 0) { never_error(US"daemon: accept process fork failed", US"Fork failed", errno); } else { int i; for (i = 0; i < smtp_accept_max; ++i) { if (smtp_slots[i].pid <= 0) { smtp_slots[i].pid = pid; if (smtp_accept_max_per_host != NULL) smtp_slots[i].host_address = string_copy_malloc(sender_host_address); smtp_accept_count++; break; } } DEBUG(D_any) debug_printf("%d SMTP accept process%s running\n", smtp_accept_count, (smtp_accept_count == 1)? "" : "es"); } /* Get here via goto in error cases */ ERROR_RETURN: /* Close the streams associated with the socket which will also close the socket fds in this process. We can't do anything if fclose() fails, but logging brings it to someone's attention. However, "connection reset by peer" isn't really a problem, so skip that one. On Solaris, a dropped connection can manifest itself as a broken pipe, so drop that one too. If the streams don't exist, something went wrong while setting things up. Make sure the socket descriptors are closed, in order to drop the connection. */ if (smtp_out != NULL) { if (fclose(smtp_out) != 0 && errno != ECONNRESET && errno != EPIPE) log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_out) failed: %s", strerror(errno)); smtp_out = NULL; } else (void)close(accept_socket); if (smtp_in != NULL) { if (fclose(smtp_in) != 0 && errno != ECONNRESET && errno != EPIPE) log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_in) failed: %s", strerror(errno)); smtp_in = NULL; } else (void)close(dup_accept_socket); /* Release any store used in this process, including the store used for holding the incoming host address and an expanded active_hostname. */ store_reset(reset_point); sender_host_address = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Set FD_CLOEXEC on SMTP sockets after forking to handle the connection.'</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: readconf_main(void) { int sep = 0; struct stat statbuf; uschar *s, *filename; uschar *list = config_main_filelist; /* Loop through the possible file names */ while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)) != NULL) { /* Cut out all the fancy processing unless specifically wanted */ #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID) uschar *suffix = filename + Ustrlen(filename); /* Try for the node-specific file if a node name exists */ #ifdef CONFIGURE_FILE_USE_NODE struct utsname uts; if (uname(&uts) >= 0) { #ifdef CONFIGURE_FILE_USE_EUID sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename); config_file = Ufopen(filename, "rb"); if (config_file == NULL) #endif /* CONFIGURE_FILE_USE_EUID */ { sprintf(CS suffix, ".%.256s", uts.nodename); config_file = Ufopen(filename, "rb"); } } #endif /* CONFIGURE_FILE_USE_NODE */ /* Otherwise, try the generic name, possibly with the euid added */ #ifdef CONFIGURE_FILE_USE_EUID if (config_file == NULL) { sprintf(CS suffix, ".%ld", (long int)original_euid); config_file = Ufopen(filename, "rb"); } #endif /* CONFIGURE_FILE_USE_EUID */ /* Finally, try the unadorned name */ if (config_file == NULL) { *suffix = 0; config_file = Ufopen(filename, "rb"); } #else /* if neither defined */ /* This is the common case when the fancy processing is not included. */ config_file = Ufopen(filename, "rb"); #endif /* If the file does not exist, continue to try any others. For any other error, break out (and die). */ if (config_file != NULL || errno != ENOENT) break; } /* On success, save the name for verification; config_filename is used when logging configuration errors (it changes for .included files) whereas config_main_filename is the name shown by -bP. Failure to open a configuration file is a serious disaster. */ if (config_file != NULL) { config_filename = config_main_filename = string_copy(filename); } else { if (filename == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): " "%s", config_main_filelist); else log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno, "configuration file %s", filename)); } /* Check the status of the file we have opened, unless it was specified on the command line, in which case privilege was given away at the start. */ if (!config_changed) { if (fstat(fileno(config_file), &statbuf) != 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s", big_buffer); if ((statbuf.st_uid != root_uid && /* owner not root */ statbuf.st_uid != exim_uid /* owner not exim */ #ifdef CONFIGURE_OWNER && statbuf.st_uid != config_uid /* owner not the special one */ #endif ) || /* or */ (statbuf.st_gid != exim_gid /* group not exim & */ #ifdef CONFIGURE_GROUP && statbuf.st_gid != config_gid /* group not the special one */ #endif && (statbuf.st_mode & 020) != 0) || /* group writeable */ /* or */ ((statbuf.st_mode & 2) != 0)) /* world writeable */ log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the " "wrong owner, group, or mode", big_buffer); } /* Process the main configuration settings. They all begin with a lower case letter. If we see something starting with an upper case letter, it is taken as a macro definition. */ while ((s = get_config_line()) != NULL) { if (isupper(s[0])) read_macro_assignment(s); else if (Ustrncmp(s, "domainlist", 10) == 0) read_named_list(&domainlist_anchor, &domainlist_count, MAX_NAMED_LIST, s+10, US"domain list"); else if (Ustrncmp(s, "hostlist", 8) == 0) read_named_list(&hostlist_anchor, &hostlist_count, MAX_NAMED_LIST, s+8, US"host list"); else if (Ustrncmp(s, US"addresslist", 11) == 0) read_named_list(&addresslist_anchor, &addresslist_count, MAX_NAMED_LIST, s+11, US"address list"); else if (Ustrncmp(s, US"localpartlist", 13) == 0) read_named_list(&localpartlist_anchor, &localpartlist_count, MAX_NAMED_LIST, s+13, US"local part list"); else (void) readconf_handle_option(s, optionlist_config, optionlist_config_size, NULL, US"main option \"%s\" unknown"); } /* If local_sender_retain is set, local_from_check must be unset. */ if (local_sender_retain && local_from_check) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and " "local_sender_retain are set; this combination is not allowed"); /* If the timezone string is empty, set it to NULL, implying no TZ variable wanted. */ if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL; /* The max retry interval must not be greater than 24 hours. */ if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60; /* remote_max_parallel must be > 0 */ if (remote_max_parallel <= 0) remote_max_parallel = 1; /* Save the configured setting of freeze_tell, so we can re-instate it at the start of a new SMTP message. */ freeze_tell_config = freeze_tell; /* The primary host name may be required for expansion of spool_directory and log_file_path, so make sure it is set asap. It is obtained from uname(), but if that yields an unqualified value, make a FQDN by using gethostbyname to canonize it. Some people like upper case letters in their host names, so we don't force the case. */ if (primary_hostname == NULL) { uschar *hostname; struct utsname uts; if (uname(&uts) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name"); hostname = US uts.nodename; if (Ustrchr(hostname, '.') == NULL) { int af = AF_INET; struct hostent *hostdata; #if HAVE_IPV6 if (!disable_ipv6 && (dns_ipv4_lookup == NULL || match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN, TRUE, NULL) != OK)) af = AF_INET6; #else af = AF_INET; #endif for (;;) { #if HAVE_IPV6 #if HAVE_GETIPNODEBYNAME int error_num; hostdata = getipnodebyname(CS hostname, af, 0, &error_num); #else hostdata = gethostbyname2(CS hostname, af); #endif #else hostdata = gethostbyname(CS hostname); #endif if (hostdata != NULL) { hostname = US hostdata->h_name; break; } if (af == AF_INET) break; af = AF_INET; } } primary_hostname = string_copy(hostname); } /* Set up default value for smtp_active_hostname */ smtp_active_hostname = primary_hostname; /* If spool_directory wasn't set in the build-time configuration, it must have got set above. Of course, writing to the log may not work if log_file_path is not set, but it will at least get to syslog or somewhere, with any luck. */ if (*spool_directory == 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot " "proceed"); /* Expand the spool directory name; it may, for example, contain the primary host name. Same comment about failure. */ s = expand_string(spool_directory); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory " "\"%s\": %s", spool_directory, expand_string_message); spool_directory = s; /* Expand log_file_path, which must contain "%s" in any component that isn't the null string or "syslog". It is also allowed to contain one instance of %D. However, it must NOT contain % followed by anything else. */ if (*log_file_path != 0) { uschar *ss, *sss; int sep = ':'; /* Fixed for log file path */ s = expand_string(log_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path " "\"%s\": %s", log_file_path, expand_string_message); ss = s; while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL) { uschar *t; if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue; t = Ustrstr(sss, "%s"); if (t == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not " "contain \"%%s\"", sss); *t = 'X'; t = Ustrchr(sss, '%'); if (t != NULL) { if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains " "unexpected \"%%\" character", s); } } log_file_path = s; } /* Interpret syslog_facility into an integer argument for 'ident' param to openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the leading "log_". */ if (syslog_facility_str != NULL) { int i; uschar *s = syslog_facility_str; if ((Ustrlen(syslog_facility_str) >= 4) && (strncmpic(syslog_facility_str, US"log_", 4) == 0)) s += 4; for (i = 0; i < syslog_list_size; i++) { if (strcmpic(s, syslog_list[i].name) == 0) { syslog_facility = syslog_list[i].value; break; } } if (i >= syslog_list_size) { log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "failed to interpret syslog_facility \"%s\"", syslog_facility_str); } } /* Expand pid_file_path */ if (*pid_file_path != 0) { s = expand_string(pid_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path " "\"%s\": %s", pid_file_path, expand_string_message); pid_file_path = s; } /* Compile the regex for matching a UUCP-style "From_" line in an incoming message. */ regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE); /* Unpick the SMTP rate limiting options, if set */ if (smtp_ratelimit_mail != NULL) { unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold, &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit); } if (smtp_ratelimit_rcpt != NULL) { unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold, &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit); } /* The qualify domains default to the primary host name */ if (qualify_domain_sender == NULL) qualify_domain_sender = primary_hostname; if (qualify_domain_recipient == NULL) qualify_domain_recipient = qualify_domain_sender; /* Setting system_filter_user in the configuration sets the gid as well if a name is given, but a numerical value does not. */ if (system_filter_uid_set && !system_filter_gid_set) { struct passwd *pw = getpwuid(system_filter_uid); if (pw == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld", (long int)system_filter_uid); system_filter_gid = pw->pw_gid; system_filter_gid_set = TRUE; } /* If the errors_reply_to field is set, check that it is syntactically valid and ensure it contains a domain. */ if (errors_reply_to != NULL) { uschar *errmess; int start, end, domain; uschar *recipient = parse_extract_address(errors_reply_to, &errmess, &start, &end, &domain, FALSE); if (recipient == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "error in errors_reply_to (%s): %s", errors_reply_to, errmess); if (domain == 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "errors_reply_to (%s) does not contain a domain", errors_reply_to); } /* If smtp_accept_queue or smtp_accept_max_per_host is set, then smtp_accept_max must also be set. */ if (smtp_accept_max == 0 && (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL)) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "smtp_accept_max must be set if smtp_accept_queue or " "smtp_accept_max_per_host is set"); /* Set up the host number if anything is specified. It is an expanded string so that it can be computed from the host name, for example. We do this last so as to ensure that everything else is set up before the expansion. */ if (host_number_string != NULL) { uschar *end; uschar *s = expand_string(host_number_string); long int n = Ustrtol(s, &end, 0); while (isspace(*end)) end++; if (*end != 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number value is not a number: %s", s); if (n > LOCALHOST_MAX) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number is greater than the maximum allowed value (%d)", LOCALHOST_MAX); host_number = n; } #ifdef SUPPORT_TLS /* If tls_verify_hosts is set, tls_verify_certificates must also be set */ if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) && tls_verify_certificates == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_%sverify_hosts is set, but tls_verify_certificates is not set", (tls_verify_hosts != NULL)? "" : "try_"); /* If openssl_options is set, validate it */ if (openssl_options != NULL) { # ifdef USE_GNUTLS log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options is set but we're using GnuTLS"); # else long dummy; if (!(tls_openssl_options_parse(openssl_options, &dummy))) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options parse error: %s", openssl_options); # endif } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't allow a configure file which is writeable by the Exim user or group (Bug 1044, CVE-2010-4345)'</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 tfm_load_file(const char *filename, TFMInfo *info) { int lf, lh, bc, ec, nw, nh, nd, ne; int i, n; Uchar *tfm; Uchar *ptr; struct stat st; int size; FILE *in; Int32 *cb; Int32 *charinfo; Int32 *widths; Int32 *heights; Int32 *depths; Uint32 checksum; in = fopen(filename, "rb"); if(in == NULL) return -1; tfm = NULL; DEBUG((DBG_FONTS, "(mt) reading TFM file `%s'\n", filename)); /* We read the entire TFM file into core */ if(fstat(fileno(in), &st) < 0) return -1; if(st.st_size == 0) goto bad_tfm; /* allocate a word-aligned buffer to hold the file */ size = 4 * ROUND(st.st_size, 4); if(size != st.st_size) mdvi_warning(_("Warning: TFM file `%s' has suspicious size\n"), filename); tfm = (Uchar *)mdvi_malloc(size); if(fread(tfm, st.st_size, 1, in) != 1) goto error; /* we don't need this anymore */ fclose(in); in = NULL; /* not a checksum, but serves a similar purpose */ checksum = 0; ptr = tfm; /* get the counters */ lf = muget2(ptr); lh = muget2(ptr); checksum += 6 + lh; bc = muget2(ptr); ec = muget2(ptr); checksum += ec - bc + 1; nw = muget2(ptr); checksum += nw; nh = muget2(ptr); checksum += nh; nd = muget2(ptr); checksum += nd; checksum += muget2(ptr); /* skip italics correction count */ checksum += muget2(ptr); /* skip lig/kern table size */ checksum += muget2(ptr); /* skip kern table size */ ne = muget2(ptr); checksum += ne; checksum += muget2(ptr); /* skip # of font parameters */ size = ec - bc + 1; cb = (Int32 *)tfm; cb += 6 + lh; charinfo = cb; cb += size; widths = cb; cb += nw; heights = cb; cb += nh; depths = cb; if(widths[0] || heights[0] || depths[0] || checksum != lf || bc - 1 > ec || ec > 255 || ne > 256) goto bad_tfm; /* from this point on, no error checking is done */ /* now we're at the header */ /* get the checksum */ info->checksum = muget4(ptr); /* get the design size */ info->design = muget4(ptr); /* get the coding scheme */ if(lh > 2) { /* get the coding scheme */ i = n = msget1(ptr); if(n < 0 || n > 39) { mdvi_warning(_("%s: font coding scheme truncated to 40 bytes\n"), filename); n = 39; } memcpy(info->coding, ptr, n); info->coding[n] = 0; ptr += i; } else strcpy(info->coding, "FontSpecific"); /* get the font family */ if(lh > 12) { n = msget1(ptr); if(n > 0) { i = Max(n, 63); memcpy(info->family, ptr, i); info->family[i] = 0; } else strcpy(info->family, "unspecified"); ptr += n; } /* now we don't read from `ptr' anymore */ info->loc = bc; info->hic = ec; info->type = DviFontTFM; /* allocate characters */ info->chars = xnalloc(TFMChar, size); #ifdef WORD_LITTLE_ENDIAN /* byte-swap the three arrays at once (they are consecutive in memory) */ swap_array((Uint32 *)widths, nw + nh + nd); #endif /* get the relevant data */ ptr = (Uchar *)charinfo; for(i = bc; i <= ec; ptr += 3, i++) { int ndx; ndx = (int)*ptr; ptr++; info->chars[i-bc].advance = widths[ndx]; /* TFM files lack this information */ info->chars[i-bc].left = 0; info->chars[i-bc].right = widths[ndx]; info->chars[i-bc].present = (ndx != 0); if(ndx) { ndx = ((*ptr >> 4) & 0xf); info->chars[i-bc].height = heights[ndx]; ndx = (*ptr & 0xf); info->chars[i-bc].depth = depths[ndx]; } } /* free everything */ mdvi_free(tfm); return 0; bad_tfm: mdvi_error(_("%s: File corrupted, or not a TFM file\n"), filename); error: if(tfm) mdvi_free(tfm); if(in) fclose(in); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'backends: Fix several security issues in the dvi-backend. See CVE-2010-2640, CVE-2010-2641, CVE-2010-2642 and CVE-2010-2643.'</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 special(DviContext *dvi, int opcode) { char *s; Int32 arg; arg = dugetn(dvi, opcode - DVI_XXX1 + 1); s = mdvi_malloc(arg + 1); dread(dvi, s, arg); s[arg] = 0; mdvi_do_special(dvi, s); SHOWCMD((dvi, "XXXX", opcode - DVI_XXX1 + 1, "[%s]", s)); mdvi_free(s); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'backends: Fix several security issues in the dvi-backend. See CVE-2010-2640, CVE-2010-2641, CVE-2010-2642 and CVE-2010-2643.'</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 vf_load_font(DviParams *params, DviFont *font) { FILE *p; Uchar *macros; int msize; int mlen; Int32 checksum; long alpha, beta, z; int op; int i; int nchars; int loc, hic; DviFontRef *last; macros = NULL; msize = mlen = 0; p = font->in; if(fuget1(p) != 247 || fuget1(p) != 202) goto badvf; mlen = fuget1(p); fseek(p, (long)mlen, SEEK_CUR); checksum = fuget4(p); if(checksum && font->checksum && checksum != font->checksum) { mdvi_warning(_("%s: Checksum mismatch (expected %u, got %u)\n"), font->fontname, font->checksum, checksum); } else if(!font->checksum) font->checksum = checksum; font->design = fuget4(p); /* read all the fonts in the preamble */ last = NULL; /* initialize alpha, beta and z for TFM width computation */ TFMPREPARE(font->scale, z, alpha, beta); op = fuget1(p); while(op >= DVI_FNT_DEF1 && op <= DVI_FNT_DEF4) { DviFontRef *ref; Int32 scale, design; Uint32 checksum; int id; int n; int hdpi; int vdpi; char *name; /* process fnt_def commands */ id = fugetn(p, op - DVI_FNT_DEF1 + 1); checksum = fuget4(p); scale = fuget4(p); design = fuget4(p); /* scale this font according to our parent's scale */ scale = TFMSCALE(scale, z, alpha, beta); design = FROUND(params->tfm_conv * design); /* compute the resolution */ hdpi = FROUND(params->mag * params->dpi * scale / design); vdpi = FROUND(params->mag * params->vdpi * scale / design); n = fuget1(p) + fuget1(p); name = mdvi_malloc(n + 1); fread(name, 1, n, p); name[n] = 0; DEBUG((DBG_FONTS, "(vf) %s: defined font `%s' at %.1fpt (%dx%d dpi)\n", font->fontname, name, (double)scale / (params->tfm_conv * 0x100000), hdpi, vdpi)); /* get the font */ ref = font_reference(params, id, name, checksum, hdpi, vdpi, scale); if(ref == NULL) { mdvi_error(_("(vf) %s: could not load font `%s'\n"), font->fontname, name); goto error; } mdvi_free(name); if(last == NULL) font->subfonts = last = ref; else last->next = ref; ref->next = NULL; op = fuget1(p); } if(op >= DVI_FNT_DEF1 && op <= DVI_FNT_DEF4) goto error; /* This function correctly reads both .vf and .ovf files */ font->chars = xnalloc(DviFontChar, 256); for(i = 0; i < 256; i++) font->chars[i].offset = 0; nchars = 256; loc = -1; hic = -1; /* now read the characters themselves */ while(op <= 242) { int pl; Int32 cc; Int32 tfm; if(op == 242) { pl = fuget4(p); cc = fuget4(p); tfm = fuget4(p); } else { pl = op; cc = fuget1(p); tfm = fuget3(p); } if(loc < 0 || cc < loc) loc = cc; if(hic < 0 || cc > hic) hic = cc; if(cc >= nchars) { font->chars = xresize(font->chars, DviFontChar, cc + 16); for(i = nchars; i < cc + 16; i++) font->chars[i].offset = 0; nchars = cc + 16; } if(font->chars[cc].offset) { mdvi_error(_("(vf) %s: character %d redefined\n"), font->fontname, cc); goto error; } DEBUG((DBG_GLYPHS, "(vf) %s: defined character %d (macro length %d)\n", font->fontname, cc, pl)); font->chars[cc].width = pl + 1; font->chars[cc].code = cc; font->chars[cc].tfmwidth = TFMSCALE(tfm, z, alpha, beta); font->chars[cc].offset = mlen; font->chars[cc].loaded = 1; if(mlen + pl + 1 > msize) { msize = mlen + pl + 256; macros = xresize(macros, Uchar, msize); } if(pl && fread(macros + mlen, 1, pl, p) != pl) break; macros[mlen+pl] = DVI_EOP; mlen += pl + 1; op = fuget1(p); } if(op != 248) { mdvi_error(_("(vf) %s: no postamble\n"), font->fontname); goto error; } /* make macro memory just big enough */ if(msize > mlen) { macros = xresize(macros, Uchar, mlen); msize = mlen; } DEBUG((DBG_FONTS|DBG_GLYPHS, "(vf) %s: macros use %d bytes\n", font->fontname, msize)); if(loc > 0 || hic < nchars-1) { memmove(font->chars, font->chars + loc, (hic - loc + 1) * sizeof(DviFontChar)); font->chars = xresize(font->chars, DviFontChar, hic - loc + 1); } font->loc = loc; font->hic = hic; font->private = macros; return 0; badvf: mdvi_error(_("%s: File corrupted, or not a VF file.\n"), font->fontname); error: if(font->chars) mdvi_free(font->chars); if(macros) mdvi_free(macros); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'backends: Fix several security issues in the dvi-backend. See CVE-2010-2640, CVE-2010-2641, CVE-2010-2642 and CVE-2010-2643.'</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: AvahiDnsPacket *avahi_recv_dns_packet_ipv4( int fd, AvahiIPv4Address *ret_src_address, uint16_t *ret_src_port, AvahiIPv4Address *ret_dst_address, AvahiIfIndex *ret_iface, uint8_t *ret_ttl) { AvahiDnsPacket *p= NULL; struct msghdr msg; struct iovec io; size_t aux[1024 / sizeof(size_t)]; /* for alignment on ia64 ! */ ssize_t l; struct cmsghdr *cmsg; int found_addr = 0; int ms; struct sockaddr_in sa; assert(fd >= 0); if (ioctl(fd, FIONREAD, &ms) < 0) { avahi_log_warn("ioctl(): %s", strerror(errno)); goto fail; } if (ms < 0) { avahi_log_warn("FIONREAD returned negative value."); goto fail; } /* For corrupt packets FIONREAD returns zero size (See rhbz #607297) */ if (!ms) goto fail; p = avahi_dns_packet_new(ms + AVAHI_DNS_PACKET_EXTRA_SIZE); io.iov_base = AVAHI_DNS_PACKET_DATA(p); io.iov_len = p->max_size; memset(&msg, 0, sizeof(msg)); msg.msg_name = &sa; msg.msg_namelen = sizeof(sa); msg.msg_iov = &io; msg.msg_iovlen = 1; msg.msg_control = aux; msg.msg_controllen = sizeof(aux); msg.msg_flags = 0; if ((l = recvmsg(fd, &msg, 0)) < 0) { /* Linux returns EAGAIN when an invalid IP packet has been received. We suppress warnings in this case because this might create quite a bit of log traffic on machines with unstable links. (See #60) */ if (errno != EAGAIN) avahi_log_warn("recvmsg(): %s", strerror(errno)); goto fail; } if (sa.sin_addr.s_addr == INADDR_ANY) { /* Linux 2.4 behaves very strangely sometimes! */ goto fail; } assert(!(msg.msg_flags & MSG_CTRUNC)); assert(!(msg.msg_flags & MSG_TRUNC)); p->size = (size_t) l; if (ret_src_port) *ret_src_port = avahi_port_from_sockaddr((struct sockaddr*) &sa); if (ret_src_address) { AvahiAddress a; avahi_address_from_sockaddr((struct sockaddr*) &sa, &a); *ret_src_address = a.data.ipv4; } if (ret_ttl) *ret_ttl = 255; if (ret_iface) *ret_iface = AVAHI_IF_UNSPEC; for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == IPPROTO_IP) { switch (cmsg->cmsg_type) { #ifdef IP_RECVTTL case IP_RECVTTL: #endif case IP_TTL: if (ret_ttl) *ret_ttl = (uint8_t) (*(int *) CMSG_DATA(cmsg)); break; #ifdef IP_PKTINFO case IP_PKTINFO: { struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg); if (ret_iface) *ret_iface = (int) i->ipi_ifindex; if (ret_dst_address) ret_dst_address->address = i->ipi_addr.s_addr; found_addr = 1; break; } #endif #ifdef IP_RECVIF case IP_RECVIF: { struct sockaddr_dl *sdl = (struct sockaddr_dl *) CMSG_DATA (cmsg); if (ret_iface) #ifdef __sun *ret_iface = *(uint_t*) sdl; #else *ret_iface = (int) sdl->sdl_index; #endif break; } #endif #ifdef IP_RECVDSTADDR case IP_RECVDSTADDR: if (ret_dst_address) memcpy(&ret_dst_address->address, CMSG_DATA (cmsg), 4); found_addr = 1; break; #endif default: avahi_log_warn("Unhandled cmsg_type : %d", cmsg->cmsg_type); break; } } } assert(found_addr); return p; fail: if (p) avahi_dns_packet_free(p); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'socket: Still read corrupt packets from the sockets Else, we end up with an infinite loop with 100% CPU. http://www.avahi.org/ticket/325 https://bugzilla.redhat.com/show_bug.cgi?id=667187'</s>