text
stringlengths 517
228k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPMI_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)
{
TPM_RC rc = TPM_RC_SUCCESS;
if (rc == TPM_RC_SUCCESS) {
rc = TPM_HANDLE_Unmarshal(target, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
switch (*target) {
case TPM_RH_ENDORSEMENT:
break;
case TPM_RH_NULL:
if (allowNull) {
break;
}
default:
rc = TPM_RC_VALUE;
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal
Restore the original value of the memory location where data from
a stream was unmarshalled and the unmarshalled value was found to
be illegal. The goal is to not keep illegal values in memory.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)
{
TPM_RC rc = TPM_RC_SUCCESS;
if (rc == TPM_RC_SUCCESS) {
rc = UINT16_Unmarshal(target, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
switch (*target) {
case TPM_ECC_NONE:
case TPM_ECC_NIST_P192:
case TPM_ECC_NIST_P224:
case TPM_ECC_NIST_P256:
case TPM_ECC_NIST_P384:
case TPM_ECC_NIST_P521:
case TPM_ECC_BN_P256:
case TPM_ECC_BN_P638:
case TPM_ECC_SM2_P256:
break;
default:
rc = TPM_RC_CURVE;
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal
Restore the original value of the memory location where data from
a stream was unmarshalled and the unmarshalled value was found to
be illegal. The goal is to not keep illegal values in memory.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPMI_DH_ENTITY_Unmarshal(TPMI_DH_ENTITY *target, BYTE **buffer, INT32 *size, BOOL allowNull)
{
TPM_RC rc = TPM_RC_SUCCESS;
if (rc == TPM_RC_SUCCESS) {
rc = TPM_HANDLE_Unmarshal(target, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
BOOL isNotOwner = *target != TPM_RH_OWNER;
BOOL isNotEndorsement = *target != TPM_RH_ENDORSEMENT;
BOOL isNotPlatform = *target != TPM_RH_PLATFORM;
BOOL isNotLockout = *target != TPM_RH_LOCKOUT;
BOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);
BOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);
BOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);
BOOL isNotPcr = (*target > PCR_LAST);
BOOL isNotAuth = (*target < TPM_RH_AUTH_00) || (*target > TPM_RH_AUTH_FF);
BOOL isNotLegalNull = (*target != TPM_RH_NULL) || !allowNull;
if (isNotOwner &&
isNotEndorsement &&
isNotPlatform &&
isNotLockout &&
isNotTransient &&
isNotPersistent &&
isNotNv &&
isNotPcr &&
isNotAuth &&
isNotLegalNull) {
rc = TPM_RC_VALUE;
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal
Restore the original value of the memory location where data from
a stream was unmarshalled and the unmarshalled value was found to
be illegal. The goal is to not keep illegal values in memory.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *target, BYTE **buffer, INT32 *size, BOOL allowNull)
{
TPM_RC rc = TPM_RC_SUCCESS;
if (rc == TPM_RC_SUCCESS) {
rc = TPM_ALG_ID_Unmarshal(target, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
switch (*target) {
#if ALG_MGF1
case TPM_ALG_MGF1:
#endif
#if ALG_KDF1_SP800_56A
case TPM_ALG_KDF1_SP800_56A:
#endif
#if ALG_KDF2
case TPM_ALG_KDF2:
#endif
#if ALG_KDF1_SP800_108
case TPM_ALG_KDF1_SP800_108:
#endif
break;
case TPM_ALG_NULL:
if (allowNull) {
break;
}
default:
rc = TPM_RC_KDF;
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal
Restore the original value of the memory location where data from
a stream was unmarshalled and the unmarshalled value was found to
be illegal. The goal is to not keep illegal values in memory.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPMI_DH_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *target, BYTE **buffer, INT32 *size)
{
TPM_RC rc = TPM_RC_SUCCESS;
if (rc == TPM_RC_SUCCESS) {
rc = TPM_HANDLE_Unmarshal(target, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
BOOL isNotHmacSession = (*target < HMAC_SESSION_FIRST ) || (*target > HMAC_SESSION_LAST);
BOOL isNotPolicySession = (*target < POLICY_SESSION_FIRST) || (*target > POLICY_SESSION_LAST);
BOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);
if (isNotHmacSession &&
isNotPolicySession &&
isNotTransient) {
rc = TPM_RC_VALUE;
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal
Restore the original value of the memory location where data from
a stream was unmarshalled and the unmarshalled value was found to
be illegal. The goal is to not keep illegal values in memory.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* context) override {
// boxes: [batch_size, num_anchors, q, 4]
const Tensor& boxes = context->input(0);
// scores: [batch_size, num_anchors, num_classes]
const Tensor& scores = context->input(1);
OP_REQUIRES(
context, (boxes.dim_size(0) == scores.dim_size(0)),
errors::InvalidArgument("boxes and scores must have same batch size"));
// max_output_size: scalar
const Tensor& max_output_size = context->input(2);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(max_output_size.shape()),
errors::InvalidArgument("max_size_per_class must be 0-D, got shape ",
max_output_size.shape().DebugString()));
const int max_size_per_class = max_output_size.scalar<int>()();
// max_total_size: scalar
const Tensor& max_total_size = context->input(3);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(max_total_size.shape()),
errors::InvalidArgument("max_total_size must be 0-D, got shape ",
max_total_size.shape().DebugString()));
const int max_total_size_per_batch = max_total_size.scalar<int>()();
OP_REQUIRES(context, max_total_size_per_batch > 0,
errors::InvalidArgument("max_total_size must be > 0"));
// Throw warning when `max_total_size` is too large as it may cause OOM.
if (max_total_size_per_batch > pow(10, 6)) {
LOG(WARNING) << "Detected a large value for `max_total_size`. This may "
<< "cause OOM error. (max_total_size: "
<< max_total_size.scalar<int>()() << ")";
}
// iou_threshold: scalar
const Tensor& iou_threshold = context->input(4);
OP_REQUIRES(context, TensorShapeUtils::IsScalar(iou_threshold.shape()),
errors::InvalidArgument("iou_threshold must be 0-D, got shape ",
iou_threshold.shape().DebugString()));
const float iou_threshold_val = iou_threshold.scalar<float>()();
// score_threshold: scalar
const Tensor& score_threshold = context->input(5);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(score_threshold.shape()),
errors::InvalidArgument("score_threshold must be 0-D, got shape ",
score_threshold.shape().DebugString()));
const float score_threshold_val = score_threshold.scalar<float>()();
OP_REQUIRES(context, iou_threshold_val >= 0 && iou_threshold_val <= 1,
errors::InvalidArgument("iou_threshold must be in [0, 1]"));
int num_boxes = 0;
const int num_classes = scores.dim_size(2);
ParseAndCheckCombinedNMSBoxSizes(context, boxes, &num_boxes, num_classes);
CheckCombinedNMSScoreSizes(context, num_boxes, scores);
if (!context->status().ok()) {
return;
}
BatchedNonMaxSuppressionOp(context, boxes, scores, num_boxes,
max_size_per_class, max_total_size_per_batch,
score_threshold_val, iou_threshold_val,
pad_per_class_, clip_boxes_);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369', 'CWE-681'], 'message': 'Prevent overflow due to integer conversion to unsigned.
PiperOrigin-RevId: 387738045
Change-Id: Id7e95bc07e02df1c66b72bd09f389608c87bdebe'</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 x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t parent_flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
mbedtls_x509_crt *grandparent;
const mbedtls_md_info_t *md_info;
/* Counting intermediate self signed certificates */
if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )
self_cnt++;
/* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
}
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
}
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the given crt */
*flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );
#endif
/* Look for a grandparent in trusted CAs */
for( grandparent = trust_ca;
grandparent != NULL;
grandparent = grandparent->next )
{
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
if( grandparent != NULL )
{
ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a grandparent upwards the chain */
for( grandparent = parent->next;
grandparent != NULL;
grandparent = grandparent->next )
{
/* +2 because the current step is not yet accounted for
* and because max_pathlen is one higher than it should be.
* Also self signed certificates do not count to the limit. */
if( grandparent->max_pathlen > 0 &&
grandparent->max_pathlen < 2 + path_cnt - self_cnt )
{
continue;
}
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
/* Is our parent part of the chain or at the top? */
if( grandparent != NULL )
{
ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,
profile, path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
/* child is verified to be a child of the parent, call verify callback */
if( NULL != f_vrfy )
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
*flags |= parent_flags;
return( 0 );
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'Only return VERIFY_FAILED from a single point
Everything else is a fatal error. Also improve documentation about that for
the vrfy callback.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,
MessageWriter *input,
MessageReader *output) {
int ret;
UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();
SgxParams *const sgx_params =
reinterpret_cast<SgxParams *>(untrusted_cache->Malloc(sizeof(SgxParams)));
if (!TrustedPrimitives::IsOutsideEnclave(sgx_params, sizeof(SgxParams))) {
TrustedPrimitives::BestEffortAbort(
"UntrustedCall: sgx_param should be in untrusted memory");
}
Cleanup clean_up(
[sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });
sgx_params->input_size = 0;
sgx_params->input = nullptr;
if (input) {
sgx_params->input_size = input->MessageSize();
if (sgx_params->input_size > 0) {
// Allocate and copy data to |input_buffer|.
sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);
if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->input,
sgx_params->input_size)) {
TrustedPrimitives::BestEffortAbort(
"UntrustedCall: sgx_param input should be in untrusted memory");
}
input->Serialize(const_cast<void *>(sgx_params->input));
}
}
sgx_params->output_size = 0;
sgx_params->output = nullptr;
CHECK_OCALL(
ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));
if (sgx_params->input) {
untrusted_cache->Free(const_cast<void *>(sgx_params->input));
}
if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,
sgx_params->output_size)) {
TrustedPrimitives::BestEffortAbort(
"UntrustedCall: sgx_param output should be in untrusted memory");
}
if (sgx_params->output) {
// For the results obtained in |output_buffer|, copy them to |output|
// before freeing the buffer.
output->Deserialize(sgx_params->output, sgx_params->output_size);
TrustedPrimitives::UntrustedLocalFree(sgx_params->output);
}
return PrimitiveStatus::OkStatus();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'Store untrusted input to enclave variable
The untrusted input pointer should be stored to trusted variable before
checking to avoid unexpected modifications after checking.
PiperOrigin-RevId: 362553830
Change-Id: I743f9bd3487de60269e247d74f2188f2ffc06d01'</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 sanitize_ptr_alu(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg,
struct bpf_reg_state *dst_reg,
struct bpf_sanitize_info *info,
const bool commit_window)
{
struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
struct bpf_verifier_state *vstate = env->cur_state;
bool off_is_imm = tnum_is_const(off_reg->var_off);
bool off_is_neg = off_reg->smin_value < 0;
bool ptr_is_dst_reg = ptr_reg == dst_reg;
u8 opcode = BPF_OP(insn->code);
u32 alu_state, alu_limit;
struct bpf_reg_state tmp;
bool ret;
int err;
if (can_skip_alu_sanitation(env, insn))
return 0;
/* We already marked aux for masking from non-speculative
* paths, thus we got here in the first place. We only care
* to explore bad access from here.
*/
if (vstate->speculative)
goto do_sim;
if (!commit_window) {
if (!tnum_is_const(off_reg->var_off) &&
(off_reg->smin_value < 0) != (off_reg->smax_value < 0))
return REASON_BOUNDS;
info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
(opcode == BPF_SUB && !off_is_neg);
}
err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
if (err < 0)
return err;
if (commit_window) {
/* In commit phase we narrow the masking window based on
* the observed pointer move after the simulated operation.
*/
alu_state = info->aux.alu_state;
alu_limit = abs(info->aux.alu_limit - alu_limit);
} else {
alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
alu_state |= ptr_is_dst_reg ?
BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
}
err = update_alu_sanitation_state(aux, alu_state, alu_limit);
if (err < 0)
return err;
do_sim:
/* If we're in commit phase, we're done here given we already
* pushed the truncated dst_reg into the speculative verification
* stack.
*
* Also, when register is a known constant, we rewrite register-based
* operation to immediate-based, and thus do not need masking (and as
* a consequence, do not need to simulate the zero-truncation either).
*/
if (commit_window || off_is_imm)
return 0;
/* Simulate and find potential out-of-bounds access under
* speculative execution from truncation as a result of
* masking when off was not within expected range. If off
* sits in dst, then we temporarily need to move ptr there
* to simulate dst (== 0) +/-= ptr. Needed, for example,
* for cases where we use K-based arithmetic in one direction
* and truncated reg-based in the other in order to explore
* bad access.
*/
if (!ptr_is_dst_reg) {
tmp = *dst_reg;
*dst_reg = *ptr_reg;
}
ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
if (!ptr_is_dst_reg && ret)
*dst_reg = tmp;
return !ret ? REASON_STACK : 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'bpf: Fix leakage under speculation on mispredicted branches
The verifier only enumerates valid control-flow paths and skips paths that
are unreachable in the non-speculative domain. And so it can miss issues
under speculative execution on mispredicted branches.
For example, a type confusion has been demonstrated with the following
crafted program:
// r0 = pointer to a map array entry
// r6 = pointer to readable stack slot
// r9 = scalar controlled by attacker
1: r0 = *(u64 *)(r0) // cache miss
2: if r0 != 0x0 goto line 4
3: r6 = r9
4: if r0 != 0x1 goto line 6
5: r9 = *(u8 *)(r6)
6: // leak r9
Since line 3 runs iff r0 == 0 and line 5 runs iff r0 == 1, the verifier
concludes that the pointer dereference on line 5 is safe. But: if the
attacker trains both the branches to fall-through, such that the following
is speculatively executed ...
r6 = r9
r9 = *(u8 *)(r6)
// leak r9
... then the program will dereference an attacker-controlled value and could
leak its content under speculative execution via side-channel. This requires
to mistrain the branch predictor, which can be rather tricky, because the
branches are mutually exclusive. However such training can be done at
congruent addresses in user space using different branches that are not
mutually exclusive. That is, by training branches in user space ...
A: if r0 != 0x0 goto line C
B: ...
C: if r0 != 0x0 goto line D
D: ...
... such that addresses A and C collide to the same CPU branch prediction
entries in the PHT (pattern history table) as those of the BPF program's
lines 2 and 4, respectively. A non-privileged attacker could simply brute
force such collisions in the PHT until observing the attack succeeding.
Alternative methods to mistrain the branch predictor are also possible that
avoid brute forcing the collisions in the PHT. A reliable attack has been
demonstrated, for example, using the following crafted program:
// r0 = pointer to a [control] map array entry
// r7 = *(u64 *)(r0 + 0), training/attack phase
// r8 = *(u64 *)(r0 + 8), oob address
// [...]
// r0 = pointer to a [data] map array entry
1: if r7 == 0x3 goto line 3
2: r8 = r0
// crafted sequence of conditional jumps to separate the conditional
// branch in line 193 from the current execution flow
3: if r0 != 0x0 goto line 5
4: if r0 == 0x0 goto exit
5: if r0 != 0x0 goto line 7
6: if r0 == 0x0 goto exit
[...]
187: if r0 != 0x0 goto line 189
188: if r0 == 0x0 goto exit
// load any slowly-loaded value (due to cache miss in phase 3) ...
189: r3 = *(u64 *)(r0 + 0x1200)
// ... and turn it into known zero for verifier, while preserving slowly-
// loaded dependency when executing:
190: r3 &= 1
191: r3 &= 2
// speculatively bypassed phase dependency
192: r7 += r3
193: if r7 == 0x3 goto exit
194: r4 = *(u8 *)(r8 + 0)
// leak r4
As can be seen, in training phase (phase != 0x3), the condition in line 1
turns into false and therefore r8 with the oob address is overridden with
the valid map value address, which in line 194 we can read out without
issues. However, in attack phase, line 2 is skipped, and due to the cache
miss in line 189 where the map value is (zeroed and later) added to the
phase register, the condition in line 193 takes the fall-through path due
to prior branch predictor training, where under speculation, it'll load the
byte at oob address r8 (unknown scalar type at that point) which could then
be leaked via side-channel.
One way to mitigate these is to 'branch off' an unreachable path, meaning,
the current verification path keeps following the is_branch_taken() path
and we push the other branch to the verification stack. Given this is
unreachable from the non-speculative domain, this branch's vstate is
explicitly marked as speculative. This is needed for two reasons: i) if
this path is solely seen from speculative execution, then we later on still
want the dead code elimination to kick in in order to sanitize these
instructions with jmp-1s, and ii) to ensure that paths walked in the
non-speculative domain are not pruned from earlier walks of paths walked in
the speculative domain. Additionally, for robustness, we mark the registers
which have been part of the conditional as unknown in the speculative path
given there should be no assumptions made on their content.
The fix in here mitigates type confusion attacks described earlier due to
i) all code paths in the BPF program being explored and ii) existing
verifier logic already ensuring that given memory access instruction
references one specific data structure.
An alternative to this fix that has also been looked at in this scope was to
mark aux->alu_state at the jump instruction with a BPF_JMP_TAKEN state as
well as direction encoding (always-goto, always-fallthrough, unknown), such
that mixing of different always-* directions themselves as well as mixing of
always-* with unknown directions would cause a program rejection by the
verifier, e.g. programs with constructs like 'if ([...]) { x = 0; } else
{ x = 1; }' with subsequent 'if (x == 1) { [...] }'. For unprivileged, this
would result in only single direction always-* taken paths, and unknown taken
paths being allowed, such that the former could be patched from a conditional
jump to an unconditional jump (ja). Compared to this approach here, it would
have two downsides: i) valid programs that otherwise are not performing any
pointer arithmetic, etc, would potentially be rejected/broken, and ii) we are
required to turn off path pruning for unprivileged, where both can be avoided
in this work through pushing the invalid branch to the verification stack.
The issue was originally discovered by Adam and Ofek, and later independently
discovered and reported as a result of Benedict and Piotr's research work.
Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation")
Reported-by: Adam Morrison <mad@cs.tau.ac.il>
Reported-by: Ofek Kirzner <ofekkir@gmail.com>
Reported-by: Benedict Schlueter <benedict.schlueter@rub.de>
Reported-by: Piotr Krysiuk <piotras@gmail.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Reviewed-by: John Fastabend <john.fastabend@gmail.com>
Reviewed-by: Benedict Schlueter <benedict.schlueter@rub.de>
Reviewed-by: Piotr Krysiuk <piotras@gmail.com>
Acked-by: Alexei Starovoitov <ast@kernel.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER)
dev = alloc_netdev(0, "pvceth%d", ether_setup);
else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void bond_setup(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
/* initialize rwlocks */
rwlock_init(&bond->lock);
rwlock_init(&bond->curr_slave_lock);
bond->params = bonding_defaults;
/* Initialize pointers */
bond->dev = bond_dev;
INIT_LIST_HEAD(&bond->vlan_list);
/* Initialize the device entry points */
ether_setup(bond_dev);
bond_dev->netdev_ops = &bond_netdev_ops;
bond_dev->ethtool_ops = &bond_ethtool_ops;
bond_set_mode_ops(bond, bond->params.mode);
bond_dev->destructor = bond_destructor;
/* Initialize the device options */
bond_dev->tx_queue_len = 0;
bond_dev->flags |= IFF_MASTER|IFF_MULTICAST;
bond_dev->priv_flags |= IFF_BONDING;
bond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
/* At first, we block adding VLANs. That's the only way to
* prevent problems that occur when adding VLANs over an
* empty bond. The block will be removed once non-challenged
* slaves are enslaved.
*/
bond_dev->features |= NETIF_F_VLAN_CHALLENGED;
/* don't acquire bond device's netif_tx_lock when
* transmitting */
bond_dev->features |= NETIF_F_LLTX;
/* By default, we declare the bond to be fully
* VLAN hardware accelerated capable. Special
* care is taken in the various xmit functions
* when there are slaves that are not hw accel
* capable
*/
bond_dev->hw_features = BOND_VLAN_FEATURES |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
bond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM);
bond_dev->features |= bond_dev->hw_features;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct kvec *iov = rqst->rq_iov;
int n_vec = rqst->rq_nvec;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
unsigned int i;
size_t total_len = 0, sent;
struct socket *ssocket = server->ssocket;
int val = 1;
cFYI(1, "Sending smb: smb_len=%u", smb_buf_length);
dump_smb(iov[0].iov_base, iov[0].iov_len);
/* cork the socket */
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
rc = smb_send_kvec(server, iov, n_vec, &sent);
if (rc < 0)
goto uncork;
total_len += sent;
/* now walk the page array and send each page in it */
for (i = 0; i < rqst->rq_npages; i++) {
struct kvec p_iov;
cifs_rqst_page_to_kvec(rqst, i, &p_iov);
rc = smb_send_kvec(server, &p_iov, 1, &sent);
kunmap(rqst->rq_pages[i]);
if (rc < 0)
break;
total_len += sent;
}
uncork:
/* uncork it */
val = 0;
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cFYI(1, "partial send (wanted=%u sent=%zu): terminating "
"session", smb_buf_length + 4, total_len);
/*
* If we have only sent part of an SMB then the next SMB could
* be taken as the remainder of this one. We need to kill the
* socket so the server throws away the partial SMB
*/
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cERROR(1, "Error %d sending data on socket to server", rc);
else
rc = 0;
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'cifs: move check for NULL socket into smb_send_rqst
Cai reported this oops:
[90701.616664] BUG: unable to handle kernel NULL pointer dereference at 0000000000000028
[90701.625438] IP: [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.632167] PGD fea319067 PUD 103fda4067 PMD 0
[90701.637255] Oops: 0000 [#1] SMP
[90701.640878] Modules linked in: des_generic md4 nls_utf8 cifs dns_resolver binfmt_misc tun sg igb iTCO_wdt iTCO_vendor_support lpc_ich pcspkr i2c_i801 i2c_core i7core_edac edac_core ioatdma dca mfd_core coretemp kvm_intel kvm crc32c_intel microcode sr_mod cdrom ata_generic sd_mod pata_acpi crc_t10dif ata_piix libata megaraid_sas dm_mirror dm_region_hash dm_log dm_mod
[90701.677655] CPU 10
[90701.679808] Pid: 9627, comm: ls Tainted: G W 3.7.1+ #10 QCI QSSC-S4R/QSSC-S4R
[90701.688950] RIP: 0010:[<ffffffff814a343e>] [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.698383] RSP: 0018:ffff88177b431bb8 EFLAGS: 00010206
[90701.704309] RAX: ffff88177b431fd8 RBX: 00007ffffffff000 RCX: ffff88177b431bec
[90701.712271] RDX: 0000000000000003 RSI: 0000000000000006 RDI: 0000000000000000
[90701.720223] RBP: ffff88177b431bc8 R08: 0000000000000004 R09: 0000000000000000
[90701.728185] R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000001
[90701.736147] R13: ffff88184ef92000 R14: 0000000000000023 R15: ffff88177b431c88
[90701.744109] FS: 00007fd56a1a47c0(0000) GS:ffff88105fc40000(0000) knlGS:0000000000000000
[90701.753137] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[90701.759550] CR2: 0000000000000028 CR3: 000000104f15f000 CR4: 00000000000007e0
[90701.767512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[90701.775465] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[90701.783428] Process ls (pid: 9627, threadinfo ffff88177b430000, task ffff88185ca4cb60)
[90701.792261] Stack:
[90701.794505] 0000000000000023 ffff88177b431c50 ffff88177b431c38 ffffffffa014fcb1
[90701.802809] ffff88184ef921bc 0000000000000000 00000001ffffffff ffff88184ef921c0
[90701.811123] ffff88177b431c08 ffffffff815ca3d9 ffff88177b431c18 ffff880857758000
[90701.819433] Call Trace:
[90701.822183] [<ffffffffa014fcb1>] smb_send_rqst+0x71/0x1f0 [cifs]
[90701.828991] [<ffffffff815ca3d9>] ? schedule+0x29/0x70
[90701.834736] [<ffffffffa014fe6d>] smb_sendv+0x3d/0x40 [cifs]
[90701.841062] [<ffffffffa014fe96>] smb_send+0x26/0x30 [cifs]
[90701.847291] [<ffffffffa015801f>] send_nt_cancel+0x6f/0xd0 [cifs]
[90701.854102] [<ffffffffa015075e>] SendReceive+0x18e/0x360 [cifs]
[90701.860814] [<ffffffffa0134a78>] CIFSFindFirst+0x1a8/0x3f0 [cifs]
[90701.867724] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs]
[90701.875601] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs]
[90701.883477] [<ffffffffa01578e6>] cifs_query_dir_first+0x26/0x30 [cifs]
[90701.890869] [<ffffffffa015480d>] initiate_cifs_search+0xed/0x250 [cifs]
[90701.898354] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.904486] [<ffffffffa01554cb>] cifs_readdir+0x45b/0x8f0 [cifs]
[90701.911288] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.917410] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.923533] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.929657] [<ffffffff81195848>] vfs_readdir+0xb8/0xe0
[90701.935490] [<ffffffff81195b9f>] sys_getdents+0x8f/0x110
[90701.941521] [<ffffffff815d3b99>] system_call_fastpath+0x16/0x1b
[90701.948222] Code: 66 90 55 65 48 8b 04 25 f0 c6 00 00 48 89 e5 53 48 83 ec 08 83 fe 01 48 8b 98 48 e0 ff ff 48 c7 80 48 e0 ff ff ff ff ff ff 74 22 <48> 8b 47 28 ff 50 68 65 48 8b 14 25 f0 c6 00 00 48 89 9a 48 e0
[90701.970313] RIP [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.977125] RSP <ffff88177b431bb8>
[90701.981018] CR2: 0000000000000028
[90701.984809] ---[ end trace 24bd602971110a43 ]---
This is likely due to a race vs. a reconnection event.
The current code checks for a NULL socket in smb_send_kvec, but that's
too late. By the time that check is done, the socket will already have
been passed to kernel_setsockopt. Move the check into smb_send_rqst, so
that it's checked earlier.
In truth, this is a bit of a half-assed fix. The -ENOTSOCK error
return here looks like it could bubble back up to userspace. The locking
rules around the ssocket pointer are really unclear as well. There are
cases where the ssocket pointer is changed without holding the srv_mutex,
but I'm not clear whether there's a potential race here yet or not.
This code seems like it could benefit from some fundamental re-think of
how the socket handling should behave. Until then though, this patch
should at least fix the above oops in most cases.
Cc: <stable@vger.kernel.org> # 3.7+
Reported-and-Tested-by: CAI Qian <caiqian@redhat.com>
Signed-off-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Steve French <smfrench@gmail.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: inline void AveragePool(const PoolParams& params,
const RuntimeShape& input_shape, const int8* input_data,
const RuntimeShape& output_shape, int8* output_data) {
ruy::profiler::ScopeLabel label("AveragePool/8bitWith32bitAccumulator");
// Here, and in other pooling ops, in order to maintain locality of reference,
// to minimize some recalculations, and to load into NEON vector registers, we
// use an inner loop down the depth. Since depths can be large and hence we
// would need arbitrarily large temporary storage, we divide the work up into
// depth tranches just within the batch loop.
static constexpr int kPoolingAccTrancheSize = 256;
TFLITE_DCHECK_LE(params.quantized_activation_min,
params.quantized_activation_max);
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
const int depth = MatchingDim(input_shape, 3, output_shape, 3);
const int input_height = input_shape.Dims(1);
const int input_width = input_shape.Dims(2);
const int output_height = output_shape.Dims(1);
const int output_width = output_shape.Dims(2);
const int stride_height = params.stride_height;
const int stride_width = params.stride_width;
int32 acc[kPoolingAccTrancheSize];
for (int batch = 0; batch < batches; ++batch) {
// We proceed through the depth in tranches (see comment above). The
// depth_base is the depth at the beginning of the tranche. The
// tranche_depth is the depth dimension of the tranche.
for (int depth_base = 0; depth_base < depth;
depth_base += kPoolingAccTrancheSize) {
const int tranche_depth =
std::min(depth - depth_base, kPoolingAccTrancheSize);
for (int out_y = 0; out_y < output_height; ++out_y) {
for (int out_x = 0; out_x < output_width; ++out_x) {
const int in_x_origin =
(out_x * stride_width) - params.padding_values.width;
const int in_y_origin =
(out_y * stride_height) - params.padding_values.height;
const int filter_x_start = std::max(0, -in_x_origin);
const int filter_x_end =
std::min(params.filter_width, input_width - in_x_origin);
const int filter_y_start = std::max(0, -in_y_origin);
const int filter_y_end =
std::min(params.filter_height, input_height - in_y_origin);
const int filter_count =
(filter_x_end - filter_x_start) * (filter_y_end - filter_y_start);
memset(acc, 0, tranche_depth * sizeof(acc[0]));
const int8* input_ptr =
input_data + depth_base +
depth * (in_x_origin +
input_width * (in_y_origin + input_height * batch));
for (int fy = filter_y_start; fy < filter_y_end; fy++) {
const int8* input_row_ptr =
input_ptr + depth * (fy * input_width + filter_x_start);
for (int fx = filter_x_start; fx < filter_x_end; fx++) {
const int8* input_channel_ptr = input_row_ptr;
int channel = 0;
#ifdef USE_NEON
for (; channel <= tranche_depth - 16; channel += 16) {
int16x4_t acc_reg[4];
int8x16_t input_reg = vld1q_s8(input_channel_ptr);
input_channel_ptr += 16;
acc_reg[0] = vget_low_s16(vmovl_s8(vget_low_s8(input_reg)));
acc_reg[1] = vget_high_s16(vmovl_s8(vget_low_s8(input_reg)));
acc_reg[2] = vget_low_s16(vmovl_s8(vget_high_s8(input_reg)));
acc_reg[3] = vget_high_s16(vmovl_s8(vget_high_s8(input_reg)));
for (int i = 0; i < 4; i++) {
vst1q_s32(
acc + channel + 4 * i,
vaddw_s16(vld1q_s32(acc + channel + 4 * i), acc_reg[i]));
}
}
for (; channel <= tranche_depth - 8; channel += 8) {
int16x4_t acc_reg[2];
int16x8_t input_reg = vmovl_s8(vld1_s8(input_channel_ptr));
input_channel_ptr += 8;
acc_reg[0] = vget_low_s16(input_reg);
acc_reg[1] = vget_high_s16(input_reg);
for (int i = 0; i < 2; i++) {
vst1q_s32(
acc + channel + 4 * i,
vaddw_s16(vld1q_s32(acc + channel + 4 * i), acc_reg[i]));
}
}
#endif
for (; channel < tranche_depth; ++channel) {
acc[channel] += *input_channel_ptr++;
}
input_row_ptr += depth;
}
}
int8* output_ptr = output_data + Offset(output_shape, batch, out_y,
out_x, depth_base);
int channel = 0;
#ifdef USE_NEON
for (; channel <= tranche_depth - 8; channel += 8) {
int16 buf[8];
for (int i = 0; i < 8; i++) {
buf[i] =
acc[channel + i] > 0
? (acc[channel + i] + filter_count / 2) / filter_count
: (acc[channel + i] - filter_count / 2) / filter_count;
}
int8x8_t buf8 = vqmovn_s16(vld1q_s16(buf));
buf8 = vmin_s8(buf8, vdup_n_s8(params.quantized_activation_max));
buf8 = vmax_s8(buf8, vdup_n_s8(params.quantized_activation_min));
vst1_s8(output_ptr + channel, buf8);
}
#endif
for (; channel < tranche_depth; ++channel) {
int16 a = acc[channel] > 0
? (acc[channel] + filter_count / 2) / filter_count
: (acc[channel] - filter_count / 2) / filter_count;
a = std::max<int16>(a, params.quantized_activation_min);
a = std::min<int16>(a, params.quantized_activation_max);
output_ptr[channel] = static_cast<int8>(a);
}
}
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.
PiperOrigin-RevId: 385184660
Change-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void AverageEvalQuantizedUint8(TfLiteContext* context, TfLiteNode* node,
TfLitePoolParams* params, OpData* data,
const TfLiteTensor* input,
TfLiteTensor* output) {
int32_t activation_min;
int32_t activation_max;
(void)CalculateActivationRangeQuantized(context, params->activation, output,
&activation_min, &activation_max);
#define TF_LITE_AVERAGE_POOL(type) \
tflite::PoolParams op_params; \
op_params.stride_height = params->stride_height; \
op_params.stride_width = params->stride_width; \
op_params.filter_height = params->filter_height; \
op_params.filter_width = params->filter_width; \
op_params.padding_values.height = data->padding.height; \
op_params.padding_values.width = data->padding.width; \
op_params.quantized_activation_min = activation_min; \
op_params.quantized_activation_max = activation_max; \
type::AveragePool(op_params, GetTensorShape(input), \
GetTensorData<uint8_t>(input), GetTensorShape(output), \
GetTensorData<uint8_t>(output))
if (kernel_type == kReference) {
TF_LITE_AVERAGE_POOL(reference_ops);
} else {
TF_LITE_AVERAGE_POOL(optimized_ops);
}
#undef TF_LITE_AVERAGE_POOL
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.
PiperOrigin-RevId: 385184660
Change-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, const uint8_t *buf, int size)
{
GetBitContext gb;
PutBitContext pb;
MPEG4AudioConfig m4ac;
int off;
init_get_bits(&gb, buf, size * 8);
off = avpriv_mpeg4audio_get_config2(&m4ac, buf, size, 1, s);
if (off < 0)
return off;
skip_bits_long(&gb, off);
adts->objecttype = m4ac.object_type - 1;
adts->sample_rate_index = m4ac.sampling_index;
adts->channel_conf = m4ac.chan_config;
if (adts->objecttype > 3U) {
av_log(s, AV_LOG_ERROR, "MPEG-4 AOT %d is not allowed in ADTS\n", adts->objecttype+1);
return AVERROR_INVALIDDATA;
}
if (adts->sample_rate_index == 15) {
av_log(s, AV_LOG_ERROR, "Escape sample rate index illegal in ADTS\n");
return AVERROR_INVALIDDATA;
}
if (get_bits(&gb, 1)) {
av_log(s, AV_LOG_ERROR, "960/120 MDCT window is not allowed in ADTS\n");
return AVERROR_INVALIDDATA;
}
if (get_bits(&gb, 1)) {
av_log(s, AV_LOG_ERROR, "Scalable configurations are not allowed in ADTS\n");
return AVERROR_INVALIDDATA;
}
if (get_bits(&gb, 1)) {
av_log(s, AV_LOG_ERROR, "Extension flag is not allowed in ADTS\n");
return AVERROR_INVALIDDATA;
}
if (!adts->channel_conf) {
init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);
put_bits(&pb, 3, 5); //ID_PCE
adts->pce_size = (ff_copy_pce_data(&pb, &gb) + 3) / 8;
flush_put_bits(&pb);
}
adts->write_adts = 1;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-252'], 'message': 'avformat/adtsenc: return value check for init_get_bits in adts_decode_extradata
As the second argument for init_get_bits (buf) can be crafted, a return value check for this function call is necessary.
'buf' is part of 'AVPacket pkt'.
replace init_get_bits with init_get_bits8.
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ecma_bigint_to_string (ecma_value_t value, /**< BigInt value */
ecma_bigint_digit_t radix) /**< conversion radix */
{
JERRY_ASSERT (ecma_is_value_bigint (value));
if (value == ECMA_BIGINT_ZERO)
{
return ecma_new_ecma_string_from_code_unit (LIT_CHAR_0);
}
uint32_t char_start_p, char_size_p;
ecma_extended_primitive_t *bigint_p = ecma_get_extended_primitive_from_value (value);
lit_utf8_byte_t *string_buffer_p = ecma_big_uint_to_string (bigint_p, radix, &char_start_p, &char_size_p);
if (JERRY_UNLIKELY (string_buffer_p == NULL))
{
ecma_raise_range_error (ECMA_ERR_MSG ("Cannot allocate memory for a string representation of a BigInt value"));
return NULL;
}
JERRY_ASSERT (char_start_p > 0);
if (bigint_p->u.bigint_sign_and_size & ECMA_BIGINT_SIGN)
{
string_buffer_p[--char_start_p] = LIT_CHAR_MINUS;
}
ecma_string_t *string_p;
string_p = ecma_new_ecma_string_from_utf8 (string_buffer_p + char_start_p, char_size_p - char_start_p);
jmem_heap_free_block (string_buffer_p, char_size_p);
return string_p;
} /* ecma_bigint_to_string */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)
Ascii string length is no longer computed during string allocation.
JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: lexer_token_is_async (parser_context_t *context_p) /**< context */
{
JERRY_ASSERT (context_p->token.type == LEXER_LITERAL
|| context_p->token.type == LEXER_TEMPLATE_LITERAL);
return (context_p->token.keyword_type == LEXER_KEYW_ASYNC
&& !context_p->token.lit_location.has_escape);
} /* lexer_token_is_async */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)
Ascii string length is no longer computed during string allocation.
JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: scanner_append_argument (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p) /**< scanner context */
{
scanner_literal_pool_t *literal_pool_p = scanner_context_p->active_literal_pool_p;
parser_list_iterator_t literal_iterator;
parser_list_iterator_init (&literal_pool_p->literal_pool, &literal_iterator);
lexer_lit_location_t *literal_location_p = &context_p->token.lit_location;
lexer_lit_location_t *literal_p;
const uint8_t *char_p = literal_location_p->char_p;
prop_length_t length = literal_location_p->length;
JERRY_ASSERT (SCANNER_LITERAL_POOL_MAY_HAVE_ARGUMENTS (literal_pool_p->status_flags));
if (JERRY_LIKELY (!context_p->token.lit_location.has_escape))
{
while ((literal_p = (lexer_lit_location_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->length == length)
{
if (JERRY_LIKELY (!literal_p->has_escape))
{
if (memcmp (literal_p->char_p, char_p, length) == 0)
{
break;
}
}
else if (lexer_compare_identifier_to_string (literal_p, char_p, length))
{
break;
}
}
}
}
else
{
while ((literal_p = (lexer_lit_location_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (lexer_compare_identifiers (context_p, literal_p, literal_location_p))
{
break;
}
}
}
uint8_t literal_type = SCANNER_LITERAL_IS_ARG;
if (literal_p != NULL)
{
literal_p->length = 0;
#if JERRY_ESNEXT
if (literal_p->type & SCANNER_LITERAL_IS_USED)
{
literal_type = SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_EARLY_CREATE;
}
#endif /* JERRY_ESNEXT */
}
literal_p = (lexer_lit_location_t *) parser_list_append (context_p, &literal_pool_p->literal_pool);
*literal_p = context_p->token.lit_location;
literal_p->type = literal_type;
return literal_p;
} /* scanner_append_argument */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)
Ascii string length is no longer computed during string allocation.
JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
NTSTATUS ntStatus;
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case TC_IOCTL_GET_DRIVER_VERSION:
case TC_IOCTL_LEGACY_GET_DRIVER_VERSION:
if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput))
{
LONG tmp = VERSION_NUM;
memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4);
Irp->IoStatus.Information = sizeof (LONG);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_GET_DEVICE_REFCOUNT:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
LONG deviceObjectCount = 0;
*(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled;
if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1)
*(int *) Irp->AssociatedIrp.SystemBuffer = TRUE;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_IS_ANY_VOLUME_MOUNTED:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
int drive;
*(int *) Irp->AssociatedIrp.SystemBuffer = 0;
for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)
{
if (GetVirtualVolumeDeviceObject (drive))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = 1;
break;
}
}
if (IsBootDriveMounted())
*(int *) Irp->AssociatedIrp.SystemBuffer = 1;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_OPEN_TEST:
{
OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
OBJECT_ATTRIBUTES ObjectAttributes;
HANDLE NtFileHandle;
UNICODE_STRING FullFileName;
IO_STATUS_BLOCK IoStatus;
LARGE_INTEGER offset;
ACCESS_MASK access = FILE_READ_ATTRIBUTES;
if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput))
break;
EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName));
RtlInitUnicodeString (&FullFileName, opentest->wszFileName);
InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)
access |= FILE_READ_DATA;
ntStatus = ZwCreateFile (&NtFileHandle,
SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL,
0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);
if (NT_SUCCESS (ntStatus))
{
opentest->TCBootLoaderDetected = FALSE;
opentest->FilesystemDetected = FALSE;
memset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed));
memset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs));
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)
{
byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE);
if (!readBuffer)
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem)
{
// Determine if the first sector contains a portion of the VeraCrypt Boot Loader
offset.QuadPart = 0;
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
TC_MAX_VOLUME_SECTOR_SIZE,
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
size_t i;
if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS)
{
// Search for the string "VeraCrypt"
for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i)
{
if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
{
opentest->TCBootLoaderDetected = TRUE;
break;
}
}
}
if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64))
{
switch (BE64 (*(uint64 *) readBuffer))
{
case 0xEB52904E54465320ULL: // NTFS
case 0xEB3C904D53444F53ULL: // FAT16/FAT32
case 0xEB58904D53444F53ULL: // FAT32
case 0xEB76904558464154ULL: // exFAT
case 0x0000005265465300ULL: // ReFS
case 0xEB58906D6B66732EULL: // FAT32 mkfs.fat
case 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs
case 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat
case 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs
opentest->FilesystemDetected = TRUE;
break;
case 0x0000000000000000ULL:
// all 512 bytes are zeroes => unencrypted filesystem like Microsoft reserved partition
if (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8))
opentest->FilesystemDetected = TRUE;
break;
}
}
}
}
if (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected))
{
int volumeType;
// Go through all volume types (e.g., normal, hidden)
for (volumeType = TC_VOLUME_TYPE_NORMAL;
volumeType < TC_VOLUME_TYPE_COUNT;
volumeType++)
{
/* Read the volume header */
switch (volumeType)
{
case TC_VOLUME_TYPE_NORMAL:
offset.QuadPart = TC_VOLUME_HEADER_OFFSET;
break;
case TC_VOLUME_TYPE_HIDDEN:
offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;
break;
}
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
TC_MAX_VOLUME_SECTOR_SIZE,
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
/* compute the ID of this volume: SHA-256 of the effective header */
sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
opentest->VolumeIDComputed[volumeType] = TRUE;
}
}
}
TCfree (readBuffer);
}
}
ZwClose (NtFileHandle);
Dump ("Open test on file %ls success.\n", opentest->wszFileName);
}
else
{
#if 0
Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus);
#endif
}
Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0;
Irp->IoStatus.Status = ntStatus;
}
break;
case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG:
{
GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer;
OBJECT_ATTRIBUTES ObjectAttributes;
HANDLE NtFileHandle;
UNICODE_STRING FullFileName;
IO_STATUS_BLOCK IoStatus;
LARGE_INTEGER offset;
byte readBuffer [TC_SECTOR_SIZE_BIOS];
if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput))
break;
EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath));
RtlInitUnicodeString (&FullFileName, request->DevicePath);
InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
ntStatus = ZwCreateFile (&NtFileHandle,
SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL,
FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0);
if (NT_SUCCESS (ntStatus))
{
// Determine if the first sector contains a portion of the VeraCrypt Boot Loader
offset.QuadPart = 0; // MBR
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
sizeof(readBuffer),
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
size_t i;
// Check for dynamic drive
request->DriveIsDynamic = FALSE;
if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa)
{
int i;
for (i = 0; i < 4; ++i)
{
if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM)
{
request->DriveIsDynamic = TRUE;
break;
}
}
}
request->BootLoaderVersion = 0;
request->Configuration = 0;
request->UserConfiguration = 0;
request->CustomUserMessage[0] = 0;
// Search for the string "VeraCrypt"
for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i)
{
if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
{
request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET));
request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET];
if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM)
{
request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET];
memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH);
}
break;
}
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (*request);
}
else
{
Irp->IoStatus.Status = ntStatus;
Irp->IoStatus.Information = 0;
}
ZwClose (NtFileHandle);
}
else
{
Irp->IoStatus.Status = ntStatus;
Irp->IoStatus.Information = 0;
}
}
break;
case TC_IOCTL_WIPE_PASSWORD_CACHE:
WipeCache ();
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_PASSWORD_CACHE_STATUS:
Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_SET_PORTABLE_MODE_STATUS:
if (!UserCanAccessDriveDevice())
{
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
}
else
{
PortableMode = TRUE;
Dump ("Setting portable mode\n");
}
break;
case TC_IOCTL_GET_PORTABLE_MODE_STATUS:
Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_MOUNTED_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput))
{
MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice;
int drive;
list->ulMountedDrives = 0;
for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)
{
PEXTENSION ListExtension;
ListDevice = GetVirtualVolumeDeviceObject (drive);
if (!ListDevice)
continue;
ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
{
list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo);
RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume);
RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel);
memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE);
list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength;
list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea;
if (ListExtension->cryptoInfo->hiddenVolume)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume
else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented)
else if (ListExtension->cryptoInfo->bProtectHiddenVolume)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected)
else
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume
list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode;
}
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT);
}
break;
case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput))
{
// Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes.
// The user could render the system unbootable by downgrading when boot encryption
// is active or being set up.
memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
*(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
}
break;
case TC_IOCTL_GET_VOLUME_PROPERTIES:
if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput))
{
VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo);
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
if (ListDevice)
{
PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
{
prop->uniqueId = ListExtension->UniqueVolumeId;
RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume);
RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel);
memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE);
prop->bDriverSetLabel = ListExtension->bDriverSetLabel;
prop->diskLength = ListExtension->DiskLength;
prop->ea = ListExtension->cryptoInfo->ea;
prop->mode = ListExtension->cryptoInfo->mode;
prop->pkcs5 = ListExtension->cryptoInfo->pkcs5;
prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations;
prop->volumePim = ListExtension->cryptoInfo->volumePim;
#if 0
prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time;
prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time;
#endif
prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags;
prop->readOnly = ListExtension->bReadOnly;
prop->removable = ListExtension->bRemovable;
prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope;
prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume;
if (ListExtension->cryptoInfo->bProtectHiddenVolume)
prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE;
else
prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE;
prop->totalBytesRead = ListExtension->Queue.TotalBytesRead;
prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten;
prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT);
}
}
}
break;
case TC_IOCTL_GET_RESOLVED_SYMLINK:
if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput))
{
RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName));
ntStatus = SymbolicLinkToTarget (resolve->symLinkName,
resolve->targetName,
sizeof (resolve->targetName));
Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case TC_IOCTL_GET_DRIVE_PARTITION_INFO:
if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput))
{
DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
PARTITION_INFORMATION_EX pi;
NTSTATUS ntStatus;
EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName));
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi));
if (NT_SUCCESS(ntStatus))
{
memset (&info->partInfo, 0, sizeof (info->partInfo));
info->partInfo.PartitionLength = pi.PartitionLength;
info->partInfo.PartitionNumber = pi.PartitionNumber;
info->partInfo.StartingOffset = pi.StartingOffset;
if (pi.PartitionStyle == PARTITION_STYLE_MBR)
{
info->partInfo.PartitionType = pi.Mbr.PartitionType;
info->partInfo.BootIndicator = pi.Mbr.BootIndicator;
}
info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT;
}
else
{
// Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo));
info->IsGPT = FALSE;
}
if (!NT_SUCCESS (ntStatus))
{
GET_LENGTH_INFORMATION lengthInfo;
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo));
if (NT_SUCCESS (ntStatus))
{
memset (&info->partInfo, 0, sizeof (info->partInfo));
info->partInfo.PartitionLength = lengthInfo.Length;
}
}
info->IsDynamic = FALSE;
if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6)
{
# define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS)
if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic))))
info->IsDynamic = FALSE;
}
Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case TC_IOCTL_GET_DRIVE_GEOMETRY:
if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput))
{
DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));
Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry));
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case VC_IOCTL_GET_DRIVE_GEOMETRY_EX:
if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput))
{
DISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
PVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data
if (buffer)
{
EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));
Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
NULL, 0, buffer, 256);
if (NT_SUCCESS(ntStatus))
{
PDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer;
memcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY));
g->DiskSize.QuadPart = pGeo->DiskSize.QuadPart;
}
else
{
DISK_GEOMETRY dg = {0};
Dump ("Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL, 0, &dg, sizeof (dg));
if (NT_SUCCESS(ntStatus))
{
memcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY));
g->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector;
if (OsMajorVersion >= 6)
{
STORAGE_READ_CAPACITY storage = {0};
NTSTATUS lStatus;
storage.Version = sizeof (STORAGE_READ_CAPACITY);
Dump ("Calling IOCTL_STORAGE_READ_CAPACITY on %ls\n", g->deviceName);
lStatus = TCDeviceIoControl (g->deviceName,
IOCTL_STORAGE_READ_CAPACITY,
NULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY));
if ( NT_SUCCESS(lStatus)
&& (storage.Size == sizeof (STORAGE_READ_CAPACITY))
)
{
g->DiskSize.QuadPart = storage.DiskLength.QuadPart;
}
}
}
}
TCfree (buffer);
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
else
{
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
Irp->IoStatus.Information = 0;
}
}
}
break;
case TC_IOCTL_PROBE_REAL_DRIVE_SIZE:
if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput))
{
ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer;
NTSTATUS status;
UNICODE_STRING name;
PFILE_OBJECT fileObject;
PDEVICE_OBJECT deviceObject;
EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName));
RtlInitUnicodeString (&name, request->DeviceName);
status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject);
if (!NT_SUCCESS (status))
{
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
break;
}
status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize);
ObDereferenceObject (fileObject);
if (status == STATUS_TIMEOUT)
{
request->TimeOut = TRUE;
Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
else if (!NT_SUCCESS (status))
{
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
}
else
{
request->TimeOut = FALSE;
Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);
Irp->IoStatus.Status = status;
}
}
break;
case TC_IOCTL_MOUNT_VOLUME:
if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput))
{
MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD
|| mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID
|| mount->VolumePim < -1 || mount->VolumePim == INT_MAX
|| mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID
|| (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE)
)
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
break;
}
EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume));
EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel));
Irp->IoStatus.Information = sizeof (MOUNT_STRUCT);
Irp->IoStatus.Status = MountDevice (DeviceObject, mount);
burn (&mount->VolumePassword, sizeof (mount->VolumePassword));
burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword));
burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf));
burn (&mount->VolumePim, sizeof (mount->VolumePim));
burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode));
burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf));
burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim));
}
break;
case TC_IOCTL_DISMOUNT_VOLUME:
if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))
{
UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo);
unmount->nReturnCode = ERR_DRIVE_NOT_FOUND;
if (ListDevice)
{
PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles);
}
Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_DISMOUNT_ALL_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))
{
UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles);
Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_BOOT_ENCRYPTION_SETUP:
Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP:
Irp->IoStatus.Status = AbortBootEncryptionSetup();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:
GetBootEncryptionStatus (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT:
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = GetSetupResult();
break;
case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:
GetBootDriveVolumeProperties (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_LOADER_VERSION:
GetBootLoaderVersion (Irp, irpSp);
break;
case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER:
ReopenBootVolumeHeader (Irp, irpSp);
break;
case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT:
GetBootLoaderFingerprint (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME:
GetBootEncryptionAlgorithmName (Irp, irpSp);
break;
case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_START_DECOY_SYSTEM_WIPE:
Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE:
Irp->IoStatus.Status = AbortDecoySystemWipe();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT:
Irp->IoStatus.Status = GetDecoySystemWipeResult();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS:
GetDecoySystemWipeStatus (Irp, irpSp);
break;
case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR:
Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_WARNING_FLAGS:
if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput))
{
GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer;
flags->PagingFileCreationPrevented = PagingFileCreationPrevented;
PagingFileCreationPrevented = FALSE;
flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty;
SystemFavoriteVolumeDirty = FALSE;
Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY:
if (UserCanAccessDriveDevice())
{
SystemFavoriteVolumeDirty = TRUE;
Irp->IoStatus.Status = STATUS_SUCCESS;
}
else
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_REREAD_DRIVER_CONFIG:
Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG:
if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput))
&& (Irp->RequestorMode == KernelMode)
)
{
GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer;
request->BootDriveFilterExtension = GetBootDriveFilterExtension();
if (IsBootDriveMounted() && request->BootDriveFilterExtension)
{
request->HwEncryptionEnabled = IsHwEncryptionEnabled();
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (*request);
}
else
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
}
}
break;
default:
return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0);
}
#if defined(DEBUG) || defined(DEBUG_TRACE)
if (!NT_SUCCESS (Irp->IoStatus.Status))
{
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case TC_IOCTL_GET_MOUNTED_VOLUMES:
case TC_IOCTL_GET_PASSWORD_CACHE_STATUS:
case TC_IOCTL_GET_PORTABLE_MODE_STATUS:
case TC_IOCTL_SET_PORTABLE_MODE_STATUS:
case TC_IOCTL_OPEN_TEST:
case TC_IOCTL_GET_RESOLVED_SYMLINK:
case TC_IOCTL_GET_DRIVE_PARTITION_INFO:
case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:
case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:
case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:
break;
default:
Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status);
}
}
#endif
return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Windows: fix low severity vulnerability in driver that allowed reading 3 bytes of kernel stack memory (with a rare possibility of 25 additional bytes). Reported by Tim Harrison.'</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: std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)
{
std::vector<GetLengthType> results;
GetLengthType retval;
retval.startOrder = target.startOrder;
retval.startRow = target.startRow;
// Are we trying to reach a certain pattern position?
const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;
const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;
SEQUENCEINDEX sequence = target.sequence;
if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();
const ModSequence &orderList = Order(sequence);
GetLengthMemory memory(*this);
CSoundFile::PlayState &playState = *memory.state;
// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)
RowVisitor visitedRows(*this, sequence);
playState.m_nNextRow = playState.m_nRow = target.startRow;
playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;
// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.
std::bitset<MAX_EFFECTS> forbiddenCommands;
std::bitset<MAX_VOLCMDS> forbiddenVolCommands;
if(adjustSamplePos)
{
forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);
forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);
forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);
forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);
forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);
// Optimize away channels for which it's pointless to adjust sample positions
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++)
{
if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())
{
// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.
const PATTERNINDEX seekPat = orderList[target.pos.order];
if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))
{
const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)
{
if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())
|| (m->IsNote() && !m->IsPortamento()))
{
memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
}
}
}
}
// If samples are being synced, force them to resync if tick duration changes
uint32 oldTickDuration = 0;
for (;;)
{
// Time target reached.
if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)
{
retval.targetReached = true;
break;
}
uint32 rowDelay = 0, tickDelay = 0;
playState.m_nRow = playState.m_nNextRow;
playState.m_nCurrentOrder = playState.m_nNextOrder;
if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())
{
playState.m_nRow = 0;
if(m_playBehaviour[kFT2LoopE60Restart])
{
playState.m_nRow = playState.m_nNextPatStartRow;
playState.m_nNextPatStartRow = 0;
}
playState.m_nCurrentOrder = ++playState.m_nNextOrder;
}
// Check if pattern is valid
playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();
bool positionJumpOnThisRow = false;
bool patternBreakOnThisRow = false;
bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;
if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)
{
// Early test: Target is inside +++ or non-existing pattern
retval.targetReached = true;
break;
}
while(playState.m_nPattern >= Patterns.Size())
{
// End of song?
if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))
{
if(playState.m_nCurrentOrder == orderList.GetRestartPos())
break;
else
playState.m_nCurrentOrder = orderList.GetRestartPos();
} else
{
playState.m_nCurrentOrder++;
}
playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();
playState.m_nNextOrder = playState.m_nCurrentOrder;
if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nCurrentOrder = playState.m_nNextOrder;
playState.m_nPattern = orderList[playState.m_nCurrentOrder];
playState.m_nNextRow = playState.m_nRow;
break;
}
}
}
if(playState.m_nNextOrder == ORDERINDEX_INVALID)
{
// GetFirstUnvisitedRow failed, so there is nothing more to play
break;
}
// Skip non-existing patterns
if(!Patterns.IsValidPat(playState.m_nPattern))
{
// If there isn't even a tune, we should probably stop here.
if(playState.m_nCurrentOrder == orderList.GetRestartPos())
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nNextRow = playState.m_nRow;
continue;
}
}
playState.m_nNextOrder = playState.m_nCurrentOrder + 1;
continue;
}
// Should never happen
if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())
playState.m_nRow = 0;
// Check whether target was reached.
if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)
{
retval.targetReached = true;
break;
}
if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nNextRow = playState.m_nRow;
continue;
}
}
retval.endOrder = playState.m_nCurrentOrder;
retval.endRow = playState.m_nRow;
// Update next position
playState.m_nNextRow = playState.m_nRow + 1;
// Jumped to invalid pattern row?
if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())
{
playState.m_nRow = 0;
}
// New pattern?
if(!playState.m_nRow)
{
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
memory.chnSettings[chn].patLoop = memory.elapsedTime;
memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;
}
}
ModChannel *pChn = playState.Chn;
// For various effects, we need to know first how many ticks there are in this row.
const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
if(p->IsPcNote())
{
#ifndef NO_PLUGINS
if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)
{
memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();
}
#endif // NO_PLUGINS
pChn[nChn].rowCommand.Clear();
continue;
}
pChn[nChn].rowCommand = *p;
switch(p->command)
{
case CMD_SPEED:
SetSpeed(playState, p->param);
break;
case CMD_TEMPO:
if(m_playBehaviour[kMODVBlankTiming])
{
// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.
if(p->param != 0) SetSpeed(playState, p->param);
}
break;
case CMD_S3MCMDEX:
if((p->param & 0xF0) == 0x60)
{
// Fine Pattern Delay
tickDelay += (p->param & 0x0F);
} else if((p->param & 0xF0) == 0xE0 && !rowDelay)
{
// Pattern Delay
if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)
{
// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),
// Scream Tracker 3 simply ignores such commands.
rowDelay = 1 + (p->param & 0x0F);
}
}
break;
case CMD_MODCMDEX:
if((p->param & 0xF0) == 0xE0)
{
// Pattern Delay
rowDelay = 1 + (p->param & 0x0F);
}
break;
}
}
if(rowDelay == 0) rowDelay = 1;
const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;
const uint32 nonRowTicks = numTicks - rowDelay;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
ModCommand::NOTE note = pChn->rowCommand.note;
if (pChn->rowCommand.instr)
{
pChn->nNewIns = pChn->rowCommand.instr;
pChn->nLastNote = NOTE_NONE;
memory.chnSettings[nChn].vol = 0xFF;
}
if (pChn->rowCommand.IsNote()) pChn->nLastNote = note;
// Update channel panning
if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)
{
SAMPLEINDEX smp = 0;
if(GetNumInstruments())
{
ModInstrument *pIns;
if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)
{
if(pIns->dwFlags[INS_SETPANNING])
pChn->nPan = pIns->nPan;
if(ModCommand::IsNote(note))
smp = pIns->Keyboard[note - NOTE_MIN];
}
} else
{
smp = pChn->nNewIns;
}
if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])
{
pChn->nPan = Samples[smp].nPan;
}
}
switch(pChn->rowCommand.volcmd)
{
case VOLCMD_VOLUME:
memory.chnSettings[nChn].vol = pChn->rowCommand.vol;
break;
case VOLCMD_VOLSLIDEUP:
case VOLCMD_VOLSLIDEDOWN:
if(pChn->rowCommand.vol != 0)
pChn->nOldVolParam = pChn->rowCommand.vol;
break;
}
switch(command)
{
// Position Jump
case CMD_POSITIONJUMP:
positionJumpOnThisRow = true;
playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));
playState.m_nNextPatStartRow = 0; // FT2 E60 bug
// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx
// Test case: PatternJump.mod
if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))
playState.m_nNextRow = 0;
if (adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
break;
// Pattern Break
case CMD_PATTERNBREAK:
{
ROWINDEX row = PatternBreak(playState, nChn, param);
if(row != ROWINDEX_INVALID)
{
patternBreakOnThisRow = true;
playState.m_nNextRow = row;
if(!positionJumpOnThisRow)
{
playState.m_nNextOrder = playState.m_nCurrentOrder + 1;
}
if(adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
}
}
break;
// Set Tempo
case CMD_TEMPO:
if(!m_playBehaviour[kMODVBlankTiming])
{
TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);
if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);
}
if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;
else
{
// Tempo Slide
TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);
if ((tempo.GetInt() & 0xF0) == 0x10)
{
playState.m_nMusicTempo += tempoDiff;
} else
{
if(tempoDiff < playState.m_nMusicTempo)
playState.m_nMusicTempo -= tempoDiff;
else
playState.m_nMusicTempo.Set(0);
}
}
TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();
if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode
{
tempoMax.Set(255);
}
Limit(playState.m_nMusicTempo, tempoMin, tempoMax);
}
break;
case CMD_S3MCMDEX:
switch(param & 0xF0)
{
case 0x90:
if(param <= 0x91)
{
pChn->dwFlags.set(CHN_SURROUND, param == 0x91);
}
break;
case 0xA0:
// High sample offset
pChn->nOldHiOffset = param & 0x0F;
break;
case 0xB0:
// Pattern Loop
if (param & 0x0F)
{
patternLoopEndedOnThisRow = true;
} else
{
CHANNELINDEX firstChn = nChn, lastChn = nChn;
if(GetType() == MOD_TYPE_S3M)
{
// ST3 has only one global loop memory.
firstChn = 0;
lastChn = GetNumChannels() - 1;
}
for(CHANNELINDEX c = firstChn; c <= lastChn; c++)
{
memory.chnSettings[c].patLoop = memory.elapsedTime;
memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[c].patLoopStart = playState.m_nRow;
}
patternLoopStartedOnThisRow = true;
}
break;
case 0xF0:
// Active macro
pChn->nActiveMacro = param & 0x0F;
break;
}
break;
case CMD_MODCMDEX:
switch(param & 0xF0)
{
case 0x60:
// Pattern Loop
if (param & 0x0F)
{
playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug
patternLoopEndedOnThisRow = true;
} else
{
patternLoopStartedOnThisRow = true;
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[nChn].patLoopStart = playState.m_nRow;
}
break;
case 0xF0:
// Active macro
pChn->nActiveMacro = param & 0x0F;
break;
}
break;
case CMD_XFINEPORTAUPDOWN:
// ignore high offset in compatible mode
if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;
break;
}
// The following calculations are not interesting if we just want to get the song length.
if (!(adjustMode & eAdjust)) continue;
switch(command)
{
// Portamento Up/Down
case CMD_PORTAMENTOUP:
if(param)
{
// FT2 compatibility: Separate effect memory for all portamento commands
// Test case: Porta-LinkMem.xm
if(!m_playBehaviour[kFT2PortaUpDownMemory])
pChn->nOldPortaDown = param;
pChn->nOldPortaUp = param;
}
break;
case CMD_PORTAMENTODOWN:
if(param)
{
// FT2 compatibility: Separate effect memory for all portamento commands
// Test case: Porta-LinkMem.xm
if(!m_playBehaviour[kFT2PortaUpDownMemory])
pChn->nOldPortaUp = param;
pChn->nOldPortaDown = param;
}
break;
// Tone-Portamento
case CMD_TONEPORTAMENTO:
if (param) pChn->nPortamentoSlide = param << 2;
break;
// Offset
case CMD_OFFSET:
if (param) pChn->oldOffset = param << 8;
break;
// Volume Slide
case CMD_VOLUMESLIDE:
case CMD_TONEPORTAVOL:
if (param) pChn->nOldVolumeSlide = param;
break;
// Set Volume
case CMD_VOLUME:
memory.chnSettings[nChn].vol = param;
break;
// Global Volume
case CMD_GLOBALVOLUME:
if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;
// IT compatibility 16. ST3 and IT ignore out-of-range values
if(param <= 128)
{
playState.m_nGlobalVolume = param * 2;
} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))
{
playState.m_nGlobalVolume = 256;
}
break;
// Global Volume Slide
case CMD_GLOBALVOLSLIDE:
if(m_playBehaviour[kPerChannelGlobalVolSlide])
{
// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)
if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;
} else
{
if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;
}
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
param >>= 4;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume += param << 1;
} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume -= param;
} else if (param & 0xF0)
{
param >>= 4;
param <<= 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume += param * nonRowTicks;
} else
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume -= param * nonRowTicks;
}
Limit(playState.m_nGlobalVolume, 0, 256);
break;
case CMD_CHANNELVOLUME:
if (param <= 64) pChn->nGlobalVol = param;
break;
case CMD_CHANNELVOLSLIDE:
{
if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;
int32 volume = pChn->nGlobalVol;
if((param & 0x0F) == 0x0F && (param & 0xF0))
volume += (param >> 4); // Fine Up
else if((param & 0xF0) == 0xF0 && (param & 0x0F))
volume -= (param & 0x0F); // Fine Down
else if(param & 0x0F) // Down
volume -= (param & 0x0F) * nonRowTicks;
else // Up
volume += ((param & 0xF0) >> 4) * nonRowTicks;
Limit(volume, 0, 64);
pChn->nGlobalVol = volume;
}
break;
case CMD_PANNING8:
Panning(pChn, param, Pan8bit);
break;
case CMD_MODCMDEX:
if(param < 0x10)
{
// LED filter
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));
}
}
MPT_FALLTHROUGH;
case CMD_S3MCMDEX:
if((param & 0xF0) == 0x80)
{
Panning(pChn, (param & 0x0F), Pan4bit);
}
break;
case CMD_VIBRATOVOL:
if (param) pChn->nOldVolumeSlide = param;
param = 0;
MPT_FALLTHROUGH;
case CMD_VIBRATO:
Vibrato(pChn, param);
break;
case CMD_FINEVIBRATO:
FineVibrato(pChn, param);
break;
case CMD_TREMOLO:
Tremolo(pChn, param);
break;
case CMD_PANBRELLO:
Panbrello(pChn, param);
break;
}
switch(pChn->rowCommand.volcmd)
{
case VOLCMD_PANNING:
Panning(pChn, pChn->rowCommand.vol, Pan6bit);
break;
case VOLCMD_VIBRATOSPEED:
// FT2 does not automatically enable vibrato with the "set vibrato speed" command
if(m_playBehaviour[kFT2VolColVibrato])
pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;
else
Vibrato(pChn, pChn->rowCommand.vol << 4);
break;
case VOLCMD_VIBRATODEPTH:
Vibrato(pChn, pChn->rowCommand.vol);
break;
}
// Process vibrato / tremolo / panbrello
switch(pChn->rowCommand.command)
{
case CMD_VIBRATO:
case CMD_FINEVIBRATO:
case CMD_VIBRATOVOL:
if(adjustMode & eAdjust)
{
uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;
uint32 inc = pChn->nVibratoSpeed * vibTicks;
if(m_playBehaviour[kITVibratoTremoloPanbrello])
inc *= 4;
pChn->nVibratoPos += static_cast<uint8>(inc);
}
break;
case CMD_TREMOLO:
if(adjustMode & eAdjust)
{
uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;
uint32 inc = pChn->nTremoloSpeed * tremTicks;
if(m_playBehaviour[kITVibratoTremoloPanbrello])
inc *= 4;
pChn->nTremoloPos += static_cast<uint8>(inc);
}
break;
case CMD_PANBRELLO:
if(adjustMode & eAdjust)
{
// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row
pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1));
ProcessPanbrello(pChn);
}
break;
}
}
// Interpret F00 effect in XM files as "stop song"
if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)
{
break;
}
playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;
if(Patterns[playState.m_nPattern].GetOverrideSignature())
{
playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();
}
const uint32 tickDuration = GetTickDuration(playState);
const uint32 rowDuration = tickDuration * numTicks;
memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq);
playState.m_lTotalSampleCount += rowDuration;
if(adjustSamplePos)
{
// Super experimental and dirty sample seeking
pChn = playState.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)
{
if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)
continue;
uint32 startTick = 0;
const ModCommand &m = pChn->rowCommand;
uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;
bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;
bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync...
if(m.instr) pChn->proTrackerOffset = 0;
if(m.IsNote())
{
if(porta && memory.chnSettings[nChn].incChanged)
{
// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()
pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);
}
int32 setPan = pChn->nPan;
pChn->nNewNote = pChn->nLastNote;
if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);
NoteChange(pChn, m.note, porta);
memory.chnSettings[nChn].incChanged = true;
if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)
{
startTick = paramLo;
} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)
{
startTick = paramHi;
}
if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);
}
if(!porta) memory.chnSettings[nChn].ticksToRender = 0;
// Panning commands have to be re-applied after a note change with potential pan change.
if(m.command == CMD_PANNING8
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)
|| m.volcmd == VOLCMD_PANNING)
{
pChn->nPan = setPan;
}
if(m.command == CMD_OFFSET)
{
bool isExtended = false;
SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);
if(!isExtended)
{
offset <<= 8;
if(offset == 0) offset = pChn->oldOffset;
offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16;
}
SampleOffset(*pChn, offset);
} else if(m.command == CMD_OFFSETPERCENTAGE)
{
SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));
} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
ReverseSampleOffset(*pChn, m.param);
startTick = playState.m_nMusicSpeed - 1;
} else if(m.volcmd == VOLCMD_OFFSET)
{
if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)
{
SmpLength offset;
if(m.vol == 0)
offset = pChn->oldOffset;
else
offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];
SampleOffset(*pChn, offset);
}
}
}
if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)
|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))
{
stopNote = true;
}
if(m.command == CMD_VOLUME)
{
pChn->nVolume = m.param * 4;
} else if(m.volcmd == VOLCMD_VOLUME)
{
pChn->nVolume = m.vol * 4;
}
if(pChn->pModSample && !stopNote)
{
// Check if we don't want to emulate some effect and thus stop processing.
if(m.command < MAX_EFFECTS)
{
if(forbiddenCommands[m.command])
{
stopNote = true;
} else if(m.command == CMD_MODCMDEX)
{
// Special case: Slides using extended commands
switch(m.param & 0xF0)
{
case 0x10:
case 0x20:
stopNote = true;
}
}
}
if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])
{
stopNote = true;
}
}
if(stopNote)
{
pChn->Stop();
memory.chnSettings[nChn].ticksToRender = 0;
} else
{
if(oldTickDuration != tickDuration && oldTickDuration != 0)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
}
switch(m.command)
{
case CMD_TONEPORTAVOL:
case CMD_VOLUMESLIDE:
case CMD_VIBRATOVOL:
if(m.param || (GetType() != MOD_TYPE_MOD))
{
for(uint32 i = 0; i < numTicks; i++)
{
pChn->isFirstTick = (i == 0);
VolumeSlide(pChn, m.param);
}
}
break;
case CMD_MODCMDEX:
if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))
{
pChn->isFirstTick = true;
switch(m.param & 0xF0)
{
case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;
case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;
}
}
break;
case CMD_S3MCMDEX:
if(m.param == 0x9E)
{
// Play forward
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.reset(CHN_PINGPONGFLAG);
} else if(m.param == 0x9F)
{
// Reverse
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.set(CHN_PINGPONGFLAG);
if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))
{
pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);
}
} else if((m.param & 0xF0) == 0x70)
{
// TODO
//ExtendedS3MCommands(nChn, param);
}
break;
}
pChn->isFirstTick = true;
switch(m.volcmd)
{
case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;
case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;
case VOLCMD_VOLSLIDEUP:
case VOLCMD_VOLSLIDEDOWN:
{
// IT Compatibility: Volume column volume slides have their own memory
// Test case: VolColMemory.it
ModCommand::VOL vol = m.vol;
if(vol == 0 && m_playBehaviour[kITVolColMemory])
{
vol = pChn->nOldVolParam;
if(vol == 0)
break;
}
if(m.volcmd == VOLCMD_VOLSLIDEUP)
vol <<= 4;
for(uint32 i = 0; i < numTicks; i++)
{
pChn->isFirstTick = (i == 0);
VolumeSlide(pChn, vol);
}
}
break;
}
if(porta)
{
// Portamento needs immediate syncing, as the pitch changes on each tick
uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;
memory.chnSettings[nChn].ticksToRender += numTicks;
memory.RenderChannel(nChn, tickDuration, portaTick);
} else
{
memory.chnSettings[nChn].ticksToRender += (numTicks - startTick);
}
}
}
}
oldTickDuration = tickDuration;
// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.
// Pattern loop is not executed in IT if there are any position jump commands on the same row.
// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm
// Test case for IT: exception: LoopBreak.it
if(patternLoopEndedOnThisRow
&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))
&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))
{
std::map<double, int> startTimes;
// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.
// If one of them starts or ends "in between", it will most likely calculate a wrong duration.
// For S3M files, it's also way off.
pChn = playState.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)
|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))
{
const double start = memory.chnSettings[nChn].patLoop;
if(!startTimes[start]) startTimes[start] = 1;
startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));
}
}
for(const auto &i : startTimes)
{
memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
if(memory.chnSettings[nChn].patLoop == i.first)
{
playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);
if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))
{
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;
}
break;
}
}
}
if(GetType() == MOD_TYPE_IT)
{
// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)
{
if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))
{
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
}
}
}
}
}
// Now advance the sample positions for sample seeking on channels that are still playing
if(adjustSamplePos)
{
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)
{
if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)
{
memory.RenderChannel(nChn, oldTickDuration);
}
}
}
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
retval.lastOrder = playState.m_nCurrentOrder;
retval.lastRow = playState.m_nRow;
}
retval.duration = memory.elapsedTime;
results.push_back(retval);
// Store final variables
if(adjustMode & eAdjust)
{
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
// Target found, or there is no target (i.e. play whole song)...
m_PlayState = std::move(playState);
m_PlayState.m_nNextRow = m_PlayState.m_nRow;
m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;
m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;
m_PlayState.m_bPositionChanged = true;
for(CHANNELINDEX n = 0; n < GetNumChannels(); n++)
{
if(m_PlayState.Chn[n].nLastNote != NOTE_NONE)
{
m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;
}
if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)
{
m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;
}
}
#ifndef NO_PLUGINS
// If there were any PC events, update plugin parameters to their latest value.
std::bitset<MAX_MIXPLUGINS> plugSetProgram;
for(const auto ¶m : memory.plugParams)
{
PLUGINDEX plug = param.first.first - 1;
IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;
if(plugin != nullptr)
{
if(!plugSetProgram[plug])
{
// Used for bridged plugins to avoid sending out individual messages for each parameter.
plugSetProgram.set(plug);
plugin->BeginSetProgram();
}
plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));
}
}
if(plugSetProgram.any())
{
for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)
{
if(plugSetProgram[i])
{
m_MixPlugins[i].pMixPlugin->EndSetProgram();
}
}
}
#endif // NO_PLUGINS
} else if(adjustMode != eAdjustOnSuccess)
{
// Target not found (e.g. when jumping to a hidden sub song), reset global variables...
m_PlayState.m_nMusicSpeed = m_nDefaultSpeed;
m_PlayState.m_nMusicTempo = m_nDefaultTempo;
m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;
}
// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.
if(sequence != Order.GetCurrentSequenceIndex())
{
Order.SetSequence(sequence);
}
visitedSongRows.Set(visitedRows);
}
return results;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QInt16() {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-908', 'CWE-787'], 'message': 'Default initialize fixed point Eigen types.
In certain cases, tensors are filled with default values of the type. But, for these fixed point types, these values were uninitialized. Thus, we would have uninitialized memory access bugs, some of which were caught by MSAN.
PiperOrigin-RevId: 344101137
Change-Id: I14555fda74dca3b5f1582da9008901937e3f14e2'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int ghash_update(struct shash_desc *desc,
const u8 *src, unsigned int srclen)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *dst = dctx->buffer;
if (dctx->bytes) {
int n = min(srclen, dctx->bytes);
u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes);
dctx->bytes -= n;
srclen -= n;
while (n--)
*pos++ ^= *src++;
if (!dctx->bytes)
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
}
while (srclen >= GHASH_BLOCK_SIZE) {
crypto_xor(dst, src, GHASH_BLOCK_SIZE);
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
src += GHASH_BLOCK_SIZE;
srclen -= GHASH_BLOCK_SIZE;
}
if (srclen) {
dctx->bytes = GHASH_BLOCK_SIZE - srclen;
while (srclen--)
*dst++ ^= *src++;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'crypto: ghash - Avoid null pointer dereference if no key is set
The ghash_update function passes a pointer to gf128mul_4k_lle which will
be NULL if ghash_setkey is not called or if the most recent call to
ghash_setkey failed to allocate memory. This causes an oops. Fix this
up by returning an error code in the null case.
This is trivially triggered from unprivileged userspace through the
AF_ALG interface by simply writing to the socket without setting a key.
The ghash_final function has a similar issue, but triggering it requires
a memory allocation failure in ghash_setkey _after_ at least one
successful call to ghash_update.
BUG: unable to handle kernel NULL pointer dereference at 00000670
IP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul]
*pde = 00000000
Oops: 0000 [#1] PREEMPT SMP
Modules linked in: ghash_generic gf128mul algif_hash af_alg nfs lockd nfs_acl sunrpc bridge ipv6 stp llc
Pid: 1502, comm: hashatron Tainted: G W 3.1.0-rc9-00085-ge9308cf #32 Bochs Bochs
EIP: 0060:[<d88c92d4>] EFLAGS: 00000202 CPU: 0
EIP is at gf128mul_4k_lle+0x23/0x60 [gf128mul]
EAX: d69db1f0 EBX: d6b8ddac ECX: 00000004 EDX: 00000000
ESI: 00000670 EDI: d6b8ddac EBP: d6b8ddc8 ESP: d6b8dda4
DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
Process hashatron (pid: 1502, ti=d6b8c000 task=d6810000 task.ti=d6b8c000)
Stack:
00000000 d69db1f0 00000163 00000000 d6b8ddc8 c101a520 d69db1f0 d52aa000
00000ff0 d6b8dde8 d88d310f d6b8a3f8 d52aa000 00001000 d88d502c d6b8ddfc
00001000 d6b8ddf4 c11676ed d69db1e8 d6b8de24 c11679ad d52aa000 00000000
Call Trace:
[<c101a520>] ? kmap_atomic_prot+0x37/0xa6
[<d88d310f>] ghash_update+0x85/0xbe [ghash_generic]
[<c11676ed>] crypto_shash_update+0x18/0x1b
[<c11679ad>] shash_ahash_update+0x22/0x36
[<c11679cc>] shash_async_update+0xb/0xd
[<d88ce0ba>] hash_sendpage+0xba/0xf2 [algif_hash]
[<c121b24c>] kernel_sendpage+0x39/0x4e
[<d88ce000>] ? 0xd88cdfff
[<c121b298>] sock_sendpage+0x37/0x3e
[<c121b261>] ? kernel_sendpage+0x4e/0x4e
[<c10b4dbc>] pipe_to_sendpage+0x56/0x61
[<c10b4e1f>] splice_from_pipe_feed+0x58/0xcd
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b51f5>] __splice_from_pipe+0x36/0x55
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b6383>] splice_from_pipe+0x51/0x64
[<c10b63c2>] ? default_file_splice_write+0x2c/0x2c
[<c10b63d5>] generic_splice_sendpage+0x13/0x15
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b527f>] do_splice_from+0x5d/0x67
[<c10b6865>] sys_splice+0x2bf/0x363
[<c129373b>] ? sysenter_exit+0xf/0x16
[<c104dc1e>] ? trace_hardirqs_on_caller+0x10e/0x13f
[<c129370c>] sysenter_do_call+0x12/0x32
Code: 83 c4 0c 5b 5e 5f c9 c3 55 b9 04 00 00 00 89 e5 57 8d 7d e4 56 53 8d 5d e4 83 ec 18 89 45 e0 89 55 dc 0f b6 70 0f c1 e6 04 01 d6 <f3> a5 be 0f 00 00 00 4e 89 d8 e8 48 ff ff ff 8b 45 e0 89 da 0f
EIP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul] SS:ESP 0068:d6b8dda4
CR2: 0000000000000670
---[ end trace 4eaa2a86a8e2da24 ]---
note: hashatron[1502] exited with preempt_count 1
BUG: scheduling while atomic: hashatron/1502/0x10000002
INFO: lockdep is turned off.
[...]
Signed-off-by: Nick Bowler <nbowler@elliptictech.com>
Cc: stable@kernel.org [2.6.37+]
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: hb_set_set (hb_set_t *set,
const hb_set_t *other)
{
if (unlikely (hb_object_is_immutable (set)))
return;
set->set (*other);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': '[set] Make all operators null-safe again
Changed my mind.
Also for hb_map_clear().
Part of https://github.com/harfbuzz/harfbuzz/pull/3162'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options,
struct rusage32 __user *, ur)
{
struct rusage r;
long ret, err;
mm_segment_t old_fs;
if (!ur)
return sys_wait4(pid, ustatus, options, NULL);
old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r);
set_fs (old_fs);
if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur)))
return -EFAULT;
err = 0;
err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec);
err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec);
err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec);
err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec);
err |= __put_user(r.ru_maxrss, &ur->ru_maxrss);
err |= __put_user(r.ru_ixrss, &ur->ru_ixrss);
err |= __put_user(r.ru_idrss, &ur->ru_idrss);
err |= __put_user(r.ru_isrss, &ur->ru_isrss);
err |= __put_user(r.ru_minflt, &ur->ru_minflt);
err |= __put_user(r.ru_majflt, &ur->ru_majflt);
err |= __put_user(r.ru_nswap, &ur->ru_nswap);
err |= __put_user(r.ru_inblock, &ur->ru_inblock);
err |= __put_user(r.ru_oublock, &ur->ru_oublock);
err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd);
err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv);
err |= __put_user(r.ru_nsignals, &ur->ru_nsignals);
err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw);
err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw);
return err ? err : ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-264', 'CWE-189'], 'message': 'alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: Richard Henderson <rth@twiddle.net>
Cc: Ivan Kokshaysky <ink@jurassic.park.msu.ru>
Cc: Matt Turner <mattst88@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void FilterManager::maybeEndEncode(bool end_stream) {
if (end_stream) {
filter_manager_callbacks_.endStream();
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2021-43825
Response filter manager crash
Signed-off-by: Yan Avlasov <yavlasov@google.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int ext4_split_unwritten_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path,
int flags)
{
struct ext4_extent *ex, newex, orig_ex;
struct ext4_extent *ex1 = NULL;
struct ext4_extent *ex2 = NULL;
struct ext4_extent *ex3 = NULL;
ext4_lblk_t ee_block, eof_block;
unsigned int allocated, ee_len, depth;
ext4_fsblk_t newblock;
int err = 0;
int may_zeroout;
ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
allocated = ee_len - (map->m_lblk - ee_block);
newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);
ex2 = ex;
orig_ex.ee_block = ex->ee_block;
orig_ex.ee_len = cpu_to_le16(ee_len);
ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
may_zeroout = ee_block + ee_len <= eof_block;
/*
* If the uninitialized extent begins at the same logical
* block where the write begins, and the write completely
* covers the extent, then we don't need to split it.
*/
if ((map->m_lblk == ee_block) && (allocated <= map->m_len))
return allocated;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* ex1: ee_block to map->m_lblk - 1 : uninitialized */
if (map->m_lblk > ee_block) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/*
* for sanity, update the length of the ex2 extent before
* we insert ex3, if ex1 is NULL. This is to avoid temporary
* overlap of blocks.
*/
if (!ex1 && allocated > map->m_len)
ex2->ee_len = cpu_to_le16(map->m_len);
/* ex3: to ee_block + ee_len : uninitialised */
if (allocated > map->m_len) {
unsigned int newdepth;
ex3 = &newex;
ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);
ext4_ext_store_pblock(ex3, newblock + map->m_len);
ex3->ee_len = cpu_to_le16(allocated - map->m_len);
ext4_ext_mark_uninitialized(ex3);
err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zeroed the full extent */
/* blocks available from map->m_lblk */
return allocated;
} else if (err)
goto fix_extent_len;
/*
* The depth, and hence eh & ex might change
* as part of the insert above.
*/
newdepth = ext_depth(inode);
/*
* update the extent length after successful insert of the
* split extent
*/
ee_len -= ext4_ext_get_actual_len(ex3);
orig_ex.ee_len = cpu_to_le16(ee_len);
may_zeroout = ee_block + ee_len <= eof_block;
depth = newdepth;
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk, path);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
ex = path[depth].p_ext;
if (ex2 != &newex)
ex2 = ex;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
allocated = map->m_len;
}
/*
* If there was a change of depth as part of the
* insertion of ex3 above, we need to update the length
* of the ex1 extent again here
*/
if (ex1 && ex1 != ex) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/*
* ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written
* using direct I/O, uninitialised still.
*/
ex2->ee_block = cpu_to_le32(map->m_lblk);
ext4_ext_store_pblock(ex2, newblock);
ex2->ee_len = cpu_to_le16(allocated);
ext4_ext_mark_uninitialized(ex2);
if (ex2 != ex)
goto insert;
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + depth);
ext_debug("out here\n");
goto out;
insert:
err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zero out the first half */
return allocated;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err ? err : allocated;
fix_extent_len:
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_mark_uninitialized(ex);
ext4_ext_dirty(handle, inode, path + depth);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'ext4: reimplement convert and split_unwritten
Reimplement ext4_ext_convert_to_initialized() and
ext4_split_unwritten_extents() using ext4_split_extent()
Signed-off-by: Yongqiang Yang <xiaoqiangnk@gmail.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Tested-by: Allison Henderson <achender@linux.vnet.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state);
else
nfs4_close_sync(&path, state, flags);
out_putcred:
put_rpccred(cred);
out:
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL)))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags,
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS kodak_c603_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
merror (pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread (pixel, raw_width, 3, ifp) < 3) derror();
for (col=0; col < width; col++) {
y = pixel[width*2*(row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2)+1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS kodak_rgb_load_raw()
{
short buf[768], *bp;
int row, col, len, c, i, rgb[3],ret;
ushort *ip=image[0];
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=256) {
len = MIN (256, width-col);
ret = kodak_65000_decode (buf, len*3);
memset (rgb, 0, sizeof rgb);
for (bp=buf, i=0; i < len; i++, ip+=4)
#ifdef LIBRAW_LIBRARY_BUILD
if(load_flags == 12)
{
FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
}
else
#endif
FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
s->s_flags = flags;
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_alloc_root(inode);
if (!s->s_root) {
iput(inode);
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
ecryptfs_set_dentry_lower(s->s_root, path.dentry);
ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt);
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-284', 'CWE-264'], 'message': 'Ecryptfs: Add mount option to check uid of device being mounted = expect uid
Close a TOCTOU race for mounts done via ecryptfs-mount-private. The mount
source (device) can be raced when the ownership test is done in userspace.
Provide Ecryptfs a means to force the uid check at mount time.
Signed-off-by: John Johansen <john.johansen@canonical.com>
Cc: <stable@kernel.org>
Signed-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: char *compose_path(ctrl_t *ctrl, char *path)
{
struct stat st;
static char rpath[PATH_MAX];
char *name, *ptr;
char dir[PATH_MAX] = { 0 };
strlcpy(dir, ctrl->cwd, sizeof(dir));
DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: "");
if (!path || !strlen(path))
goto check;
if (path) {
if (path[0] != '/') {
if (dir[strlen(dir) - 1] != '/')
strlcat(dir, "/", sizeof(dir));
}
strlcat(dir, path, sizeof(dir));
}
check:
while ((ptr = strstr(dir, "//")))
memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);
if (!chrooted) {
size_t len = strlen(home);
DBG("Server path from CWD: %s", dir);
if (len > 0 && home[len - 1] == '/')
len--;
memmove(dir + len, dir, strlen(dir) + 1);
memcpy(dir, home, len);
DBG("Resulting non-chroot path: %s", dir);
}
/*
* Handle directories slightly differently, since dirname() on a
* directory returns the parent directory. So, just squash ..
*/
if (!stat(dir, &st) && S_ISDIR(st.st_mode)) {
if (!realpath(dir, rpath))
return NULL;
} else {
/*
* Check realpath() of directory containing the file, a
* STOR may want to save a new file. Then append the
* file and return it.
*/
name = basename(path);
ptr = dirname(dir);
memset(rpath, 0, sizeof(rpath));
if (!realpath(ptr, rpath)) {
INFO("Failed realpath(%s): %m", ptr);
return NULL;
}
if (rpath[1] != 0)
strlcat(rpath, "/", sizeof(rpath));
strlcat(rpath, name, sizeof(rpath));
}
if (!chrooted && strncmp(dir, home, strlen(home))) {
DBG("Failed non-chroot dir:%s vs home:%s", dir, home);
return NULL;
}
return rpath;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'FTP/TFTP: Fix directory traversal regression, reported by Aaron Esau
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int cuse_channel_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = file->private_data;
struct cuse_conn *cc = fc_to_cc(fud->fc);
int rc;
/* remove from the conntbl, no more access from this point on */
mutex_lock(&cuse_lock);
list_del_init(&cc->list);
mutex_unlock(&cuse_lock);
/* remove device */
if (cc->dev)
device_unregister(cc->dev);
if (cc->cdev) {
unregister_chrdev_region(cc->cdev->dev, 1);
cdev_del(cc->cdev);
}
rc = fuse_dev_release(inode, file); /* puts the base reference */
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'cuse: fix memory leak
The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc,
and the original ref count is never dropped.
Reported-by: Colin Ian King <colin.king@canonical.com>
Signed-off-by: Miklos Szeredi <miklos@szeredi.hu>
Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure")
Cc: <stable@vger.kernel.org> # v4.2+'</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 get_rock_ridge_filename(struct iso_directory_record *de,
char *retname, struct inode *inode)
{
struct rock_state rs;
struct rock_ridge *rr;
int sig;
int retnamlen = 0;
int truncate = 0;
int ret = 0;
if (!ISOFS_SB(inode->i_sb)->s_rock)
return 0;
*retname = 0;
init_rock_state(&rs, inode);
setup_rock_ridge(de, inode, &rs);
repeat:
while (rs.len > 2) { /* There may be one byte for padding somewhere */
rr = (struct rock_ridge *)rs.chr;
/*
* Ignore rock ridge info if rr->len is out of range, but
* don't return -EIO because that would make the file
* invisible.
*/
if (rr->len < 3)
goto out; /* Something got screwed up here */
sig = isonum_721(rs.chr);
if (rock_check_overflow(&rs, sig))
goto eio;
rs.chr += rr->len;
rs.len -= rr->len;
/*
* As above, just ignore the rock ridge info if rr->len
* is bogus.
*/
if (rs.len < 0)
goto out; /* Something got screwed up here */
switch (sig) {
case SIG('R', 'R'):
if ((rr->u.RR.flags[0] & RR_NM) == 0)
goto out;
break;
case SIG('S', 'P'):
if (check_sp(rr, inode))
goto out;
break;
case SIG('C', 'E'):
rs.cont_extent = isonum_733(rr->u.CE.extent);
rs.cont_offset = isonum_733(rr->u.CE.offset);
rs.cont_size = isonum_733(rr->u.CE.size);
break;
case SIG('N', 'M'):
if (truncate)
break;
if (rr->len < 5)
break;
/*
* If the flags are 2 or 4, this indicates '.' or '..'.
* We don't want to do anything with this, because it
* screws up the code that calls us. We don't really
* care anyways, since we can just use the non-RR
* name.
*/
if (rr->u.NM.flags & 6)
break;
if (rr->u.NM.flags & ~1) {
printk("Unsupported NM flag settings (%d)\n",
rr->u.NM.flags);
break;
}
if ((strlen(retname) + rr->len - 5) >= 254) {
truncate = 1;
break;
}
strncat(retname, rr->u.NM.name, rr->len - 5);
retnamlen += rr->len - 5;
break;
case SIG('R', 'E'):
kfree(rs.buffer);
return -1;
default:
break;
}
}
ret = rock_continue(&rs);
if (ret == 0)
goto repeat;
if (ret == 1)
return retnamlen; /* If 0, this file did not have a NM field */
out:
kfree(rs.buffer);
return ret;
eio:
ret = -EIO;
goto out;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'get_rock_ridge_filename(): handle malformed NM entries
Payloads of NM entries are not supposed to contain NUL. When we run
into such, only the part prior to the first NUL goes into the
concatenation (i.e. the directory entry name being encoded by a bunch
of NM entries). We do stop when the amount collected so far + the
claimed amount in the current NM entry exceed 254. So far, so good,
but what we return as the total length is the sum of *claimed*
sizes, not the actual amount collected. And that can grow pretty
large - not unlimited, since you'd need to put CE entries in
between to be able to get more than the maximum that could be
contained in one isofs directory entry / continuation chunk and
we are stop once we'd encountered 32 CEs, but you can get about 8Kb
easily. And that's what will be passed to readdir callback as the
name length. 8Kb __copy_to_user() from a buffer allocated by
__get_free_page()
Cc: stable@vger.kernel.org # 0.98pl6+ (yes, really)
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
{
FormData_pg_sequence seqform;
FormData_pg_sequence_data seqdataform;
bool need_seq_rewrite;
List *owned_by;
CreateStmt *stmt = makeNode(CreateStmt);
Oid seqoid;
ObjectAddress address;
Relation rel;
HeapTuple tuple;
TupleDesc tupDesc;
Datum value[SEQ_COL_LASTCOL];
bool null[SEQ_COL_LASTCOL];
Datum pgs_values[Natts_pg_sequence];
bool pgs_nulls[Natts_pg_sequence];
int i;
/*
* If if_not_exists was given and a relation with the same name already
* exists, bail out. (Note: we needn't check this when not if_not_exists,
* because DefineRelation will complain anyway.)
*/
if (seq->if_not_exists)
{
RangeVarGetAndCheckCreationNamespace(seq->sequence, NoLock, &seqoid);
if (OidIsValid(seqoid))
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" already exists, skipping",
seq->sequence->relname)));
return InvalidObjectAddress;
}
}
/* Check and set all option values */
init_params(pstate, seq->options, seq->for_identity, true,
&seqform, &seqdataform,
&need_seq_rewrite, &owned_by);
/*
* Create relation (and fill value[] and null[] for the tuple)
*/
stmt->tableElts = NIL;
for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
{
ColumnDef *coldef = makeNode(ColumnDef);
coldef->inhcount = 0;
coldef->is_local = true;
coldef->is_not_null = true;
coldef->is_from_type = false;
coldef->storage = 0;
coldef->raw_default = NULL;
coldef->cooked_default = NULL;
coldef->collClause = NULL;
coldef->collOid = InvalidOid;
coldef->constraints = NIL;
coldef->location = -1;
null[i - 1] = false;
switch (i)
{
case SEQ_COL_LASTVAL:
coldef->typeName = makeTypeNameFromOid(INT8OID, -1);
coldef->colname = "last_value";
value[i - 1] = Int64GetDatumFast(seqdataform.last_value);
break;
case SEQ_COL_LOG:
coldef->typeName = makeTypeNameFromOid(INT8OID, -1);
coldef->colname = "log_cnt";
value[i - 1] = Int64GetDatum((int64) 0);
break;
case SEQ_COL_CALLED:
coldef->typeName = makeTypeNameFromOid(BOOLOID, -1);
coldef->colname = "is_called";
value[i - 1] = BoolGetDatum(false);
break;
}
stmt->tableElts = lappend(stmt->tableElts, coldef);
}
stmt->relation = seq->sequence;
stmt->inhRelations = NIL;
stmt->constraints = NIL;
stmt->options = NIL;
stmt->oncommit = ONCOMMIT_NOOP;
stmt->tablespacename = NULL;
stmt->if_not_exists = seq->if_not_exists;
address = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);
seqoid = address.objectId;
Assert(seqoid != InvalidOid);
rel = table_open(seqoid, AccessExclusiveLock);
tupDesc = RelationGetDescr(rel);
/* now initialize the sequence's data */
tuple = heap_form_tuple(tupDesc, value, null);
fill_seq_with_data(rel, tuple);
/* process OWNED BY if given */
if (owned_by)
process_owned_by(rel, owned_by, seq->for_identity);
table_close(rel, NoLock);
/* fill in pg_sequence */
rel = table_open(SequenceRelationId, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
memset(pgs_nulls, 0, sizeof(pgs_nulls));
pgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);
pgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);
pgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);
pgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);
pgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);
pgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);
pgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);
pgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);
tuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);
CatalogTupleInsert(rel, tuple);
heap_freetuple(tuple);
table_close(rel, RowExclusiveLock);
return address;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.
Previously, if an extension script did CREATE OR REPLACE and there was
an existing object not belonging to the extension, it would overwrite
the object and adopt it into the extension. This is problematic, first
because the overwrite is probably unintentional, and second because we
didn't change the object's ownership. Thus a hostile user could create
an object in advance of an expected CREATE EXTENSION command, and would
then have ownership rights on an extension object, which could be
modified for trojan-horse-type attacks.
Hence, forbid CREATE OR REPLACE of an existing object unless it already
belongs to the extension. (Note that we've always forbidden replacing
an object that belongs to some other extension; only the behavior for
previously-free-standing objects changes here.)
For the same reason, also fail CREATE IF NOT EXISTS when there is
an existing object that doesn't belong to the extension.
Our thanks to Sven Klemm for reporting this problem.
Security: CVE-2022-2625'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {
len = ff_amf_tag_size(data, data_end);
if (len < 0)
len = data_end - data;
data += len;
}
if (data_end - data < 3)
return -1;
data++;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (size < 0 || size >= data_end - data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || len >= data_end - data)
return -1;
data += len;
}
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2
Fixes: out of array accesses
Found-by: JunDong Xie of Ant-financial Light-Year Security Lab
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bit_write_UMC (Bit_Chain *dat, BITCODE_UMC val)
{
int i, j;
int negative;
unsigned char byte[5];
BITCODE_UMC mask;
BITCODE_UMC value;
value = val;
mask = 0x0000007f;
for (i = 4, j = 0; i >= 0; i--, j += 7)
{
byte[i] = (unsigned char)((value & mask) >> j);
byte[i] |= 0x80;
mask = mask << 7;
}
for (i = 0; i < 4; i++)
if (byte[i] & 0x7f)
break;
if (byte[i] & 0x40)
i--;
byte[i] &= 0x7f;
for (j = 4; j >= i; j--)
bit_write_RC (dat, byte[j]);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'encode: protect from stack under-flow
From GH #178 fuzzing'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
Rec2.RecordLength=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2) / 3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
ReplaceImageInList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2) / 3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/654'</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: gimp_channel_is_empty (GimpChannel *channel)
{
g_return_val_if_fail (GIMP_IS_CHANNEL (channel), FALSE);
return GIMP_CHANNEL_GET_CLASS (channel)->is_empty (channel);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'app: fix #8230 crash in gimp_layer_invalidate_boundary when channel is NULL
gimp_channel_is_empty returns FALSE if channel is NULL. This causes
gimp_layer_invalidate_boundary to crash if the mask channel is NULL.
With a NULL channel gimp_channel_is_empty should return TRUE, just like
the similar gimp_image_is_empty does, because returning FALSE here
suggests we have a non empty channel.
(cherry picked from commit 22af0bcfe67c1c86381f33975ca7fdbde6b36b39)'</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 ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int mtu;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size
If the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track
of this when appending the second frame on a corked socket. This results
in the following splat:
[37598.993962] ------------[ cut here ]------------
[37598.994008] kernel BUG at net/core/skbuff.c:2064!
[37598.994008] invalid opcode: 0000 [#1] SMP
[37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat
+nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi
+scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm
[37598.994008] snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc
+dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video
[37598.994008] CPU 0
[37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG
[37598.994008] RIP: 0010:[<ffffffff815443a5>] [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330
[37598.994008] RSP: 0018:ffff88003670da18 EFLAGS: 00010202
[37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0
[37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00
[37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040
[37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8
[37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000
[37598.994008] FS: 00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000
[37598.994008] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0
[37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0)
[37598.994008] Stack:
[37598.994008] ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8
[37598.994008] ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200
[37598.994008] 0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4
[37598.994008] Call Trace:
[37598.994008] [<ffffffff815fc21f>] ip6_append_data+0xccf/0xfe0
[37598.994008] [<ffffffff8158d9f0>] ? ip_copy_metadata+0x1a0/0x1a0
[37598.994008] [<ffffffff81661f66>] ? _raw_spin_lock_bh+0x16/0x40
[37598.994008] [<ffffffff8161548d>] udpv6_sendmsg+0x1ed/0xc10
[37598.994008] [<ffffffff812a2845>] ? sock_has_perm+0x75/0x90
[37598.994008] [<ffffffff815c3693>] inet_sendmsg+0x63/0xb0
[37598.994008] [<ffffffff812a2973>] ? selinux_socket_sendmsg+0x23/0x30
[37598.994008] [<ffffffff8153a450>] sock_sendmsg+0xb0/0xe0
[37598.994008] [<ffffffff810135d1>] ? __switch_to+0x181/0x4a0
[37598.994008] [<ffffffff8153d97d>] sys_sendto+0x12d/0x180
[37598.994008] [<ffffffff810dfb64>] ? __audit_syscall_entry+0x94/0xf0
[37598.994008] [<ffffffff81020ed1>] ? syscall_trace_enter+0x231/0x240
[37598.994008] [<ffffffff8166a7e7>] tracesys+0xdd/0xe2
[37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48
[37598.994008] RIP [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330
[37598.994008] RSP <ffff88003670da18>
[37599.007323] ---[ end trace d69f6a17f8ac8eee ]---
While there, also check if path mtu discovery is activated for this
socket. The logic was adapted from ip6_append_data when first writing
on the corked socket.
This bug was introduced with commit
0c1833797a5a6ec23ea9261d979aa18078720b74 ("ipv6: fix incorrect ipsec
fragment").
v2:
a) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE.
b) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao
feng, thanks!).
c) Change mtu to unsigned int, else we get a warning about
non-matching types because of the min()-macro type-check.
Acked-by: Gao feng <gaofeng@cn.fujitsu.com>
Cc: YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int __net_init sctp_net_init(struct net *net)
{
int status;
/*
* 14. Suggested SCTP Protocol Parameter Values
*/
/* The following protocol parameters are RECOMMENDED: */
/* RTO.Initial - 3 seconds */
net->sctp.rto_initial = SCTP_RTO_INITIAL;
/* RTO.Min - 1 second */
net->sctp.rto_min = SCTP_RTO_MIN;
/* RTO.Max - 60 seconds */
net->sctp.rto_max = SCTP_RTO_MAX;
/* RTO.Alpha - 1/8 */
net->sctp.rto_alpha = SCTP_RTO_ALPHA;
/* RTO.Beta - 1/4 */
net->sctp.rto_beta = SCTP_RTO_BETA;
/* Valid.Cookie.Life - 60 seconds */
net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE;
/* Whether Cookie Preservative is enabled(1) or not(0) */
net->sctp.cookie_preserve_enable = 1;
/* Default sctp sockets to use md5 as their hmac alg */
#if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)
net->sctp.sctp_hmac_alg = "md5";
#elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)
net->sctp.sctp_hmac_alg = "sha1";
#else
net->sctp.sctp_hmac_alg = NULL;
#endif
/* Max.Burst - 4 */
net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST;
/* Association.Max.Retrans - 10 attempts
* Path.Max.Retrans - 5 attempts (per destination address)
* Max.Init.Retransmits - 8 attempts
*/
net->sctp.max_retrans_association = 10;
net->sctp.max_retrans_path = 5;
net->sctp.max_retrans_init = 8;
/* Sendbuffer growth - do per-socket accounting */
net->sctp.sndbuf_policy = 0;
/* Rcvbuffer growth - do per-socket accounting */
net->sctp.rcvbuf_policy = 0;
/* HB.interval - 30 seconds */
net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT;
/* delayed SACK timeout */
net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK;
/* Disable ADDIP by default. */
net->sctp.addip_enable = 0;
net->sctp.addip_noauth = 0;
net->sctp.default_auto_asconf = 0;
/* Enable PR-SCTP by default. */
net->sctp.prsctp_enable = 1;
/* Disable AUTH by default. */
net->sctp.auth_enable = 0;
/* Set SCOPE policy to enabled */
net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;
/* Set the default rwnd update threshold */
net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;
/* Initialize maximum autoclose timeout. */
net->sctp.max_autoclose = INT_MAX / HZ;
status = sctp_sysctl_net_register(net);
if (status)
goto err_sysctl_register;
/* Allocate and initialise sctp mibs. */
status = init_sctp_mibs(net);
if (status)
goto err_init_mibs;
/* Initialize proc fs directory. */
status = sctp_proc_init(net);
if (status)
goto err_init_proc;
sctp_dbg_objcnt_init(net);
/* Initialize the control inode/socket for handling OOTB packets. */
if ((status = sctp_ctl_sock_init(net))) {
pr_err("Failed to initialize the SCTP control sock\n");
goto err_ctl_sock_init;
}
/* Initialize the local address list. */
INIT_LIST_HEAD(&net->sctp.local_addr_list);
spin_lock_init(&net->sctp.local_addr_lock);
sctp_get_local_addr_list(net);
/* Initialize the address event list */
INIT_LIST_HEAD(&net->sctp.addr_waitq);
INIT_LIST_HEAD(&net->sctp.auto_asconf_splist);
spin_lock_init(&net->sctp.addr_wq_lock);
net->sctp.addr_wq_timer.expires = 0;
setup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler,
(unsigned long)net);
return 0;
err_ctl_sock_init:
sctp_dbg_objcnt_exit(net);
sctp_proc_exit(net);
err_init_proc:
cleanup_sctp_mibs(net);
err_init_mibs:
sctp_sysctl_net_unregister(net);
err_sysctl_register:
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sctp: fix race on protocol/netns initialization
Consider sctp module is unloaded and is being requested because an user
is creating a sctp socket.
During initialization, sctp will add the new protocol type and then
initialize pernet subsys:
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_net_ops);
The problem is that after those calls to sctp_v{4,6}_protosw_init(), it
is possible for userspace to create SCTP sockets like if the module is
already fully loaded. If that happens, one of the possible effects is
that we will have readers for net->sctp.local_addr_list list earlier
than expected and sctp_net_init() does not take precautions while
dealing with that list, leading to a potential panic but not limited to
that, as sctp_sock_init() will copy a bunch of blank/partially
initialized values from net->sctp.
The race happens like this:
CPU 0 | CPU 1
socket() |
__sock_create | socket()
inet_create | __sock_create
list_for_each_entry_rcu( |
answer, &inetsw[sock->type], |
list) { | inet_create
/* no hits */ |
if (unlikely(err)) { |
... |
request_module() |
/* socket creation is blocked |
* the module is fully loaded |
*/ |
sctp_init |
sctp_v4_protosw_init |
inet_register_protosw |
list_add_rcu(&p->list, |
last_perm); |
| list_for_each_entry_rcu(
| answer, &inetsw[sock->type],
sctp_v6_protosw_init | list) {
| /* hit, so assumes protocol
| * is already loaded
| */
| /* socket creation continues
| * before netns is initialized
| */
register_pernet_subsys |
Simply inverting the initialization order between
register_pernet_subsys() and sctp_v4_protosw_init() is not possible
because register_pernet_subsys() will create a control sctp socket, so
the protocol must be already visible by then. Deferring the socket
creation to a work-queue is not good specially because we loose the
ability to handle its errors.
So, as suggested by Vlad, the fix is to split netns initialization in
two moments: defaults and control socket, so that the defaults are
already loaded by when we register the protocol, while control socket
initialization is kept at the same moment it is today.
Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace")
Signed-off-by: Vlad Yasevich <vyasevich@gmail.com>
Signed-off-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ::tensorflow::Status ValidateInputs(
std::vector<ConstFlatSplits> rt_nested_splits,
const Tensor& rt_dense_values_in) {
for (int i = 0; i < rt_nested_splits.size(); ++i) {
if (rt_nested_splits[i].size() == 0) {
return InvalidArgument("ragged splits may not be empty.");
}
if (rt_nested_splits[i](0) != 0) {
return InvalidArgument("First value of ragged splits must be 0.");
}
if (i > 0) {
SPLITS_TYPE last_split =
rt_nested_splits[i - 1](rt_nested_splits[i - 1].size() - 1);
if (rt_nested_splits[i].size() != last_split + 1) {
return InvalidArgument(
"Final value of ragged splits must match the length "
"the corresponding ragged values.");
}
}
}
if (rt_dense_values_in.dim_size(0) !=
rt_nested_splits.back()(rt_nested_splits.back().size() - 1)) {
return InvalidArgument(
"Final value of ragged splits must match the length "
"the corresponding ragged values.");
}
return ::tensorflow::Status::OK();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Add missing validation to `RaggedTensorToSparse`.
There needs to be a check that the splits allow for valid ragged tensors.
PiperOrigin-RevId: 387712169
Change-Id: I2499175324b82b65d159a260c7f83b98ceb5cc7d'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: AcpiNsEvaluate (
ACPI_EVALUATE_INFO *Info)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsEvaluate);
if (!Info)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (!Info->Node)
{
/*
* Get the actual namespace node for the target object if we
* need to. Handles these cases:
*
* 1) Null node, valid pathname from root (absolute path)
* 2) Node and valid pathname (path relative to Node)
* 3) Node, Null pathname
*/
Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname,
ACPI_NS_NO_UPSEARCH, &Info->Node);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
}
/*
* For a method alias, we must grab the actual method node so that
* proper scoping context will be established before execution.
*/
if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS)
{
Info->Node = ACPI_CAST_PTR (
ACPI_NAMESPACE_NODE, Info->Node->Object);
}
/* Complete the info block initialization */
Info->ReturnObject = NULL;
Info->NodeFlags = Info->Node->Flags;
Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node);
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s [%p] Value %p\n",
Info->RelativePathname, Info->Node,
AcpiNsGetAttachedObject (Info->Node)));
/* Get info if we have a predefined name (_HID, etc.) */
Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii);
/* Get the full pathname to the object, for use in warning messages */
Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE);
if (!Info->FullPathname)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Count the number of arguments being passed in */
Info->ParamCount = 0;
if (Info->Parameters)
{
while (Info->Parameters[Info->ParamCount])
{
Info->ParamCount++;
}
/* Warn on impossible argument count */
if (Info->ParamCount > ACPI_METHOD_NUM_ARGS)
{
ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS,
"Excess arguments (%u) - using only %u",
Info->ParamCount, ACPI_METHOD_NUM_ARGS));
Info->ParamCount = ACPI_METHOD_NUM_ARGS;
}
}
/*
* For predefined names: Check that the declared argument count
* matches the ACPI spec -- otherwise this is a BIOS error.
*/
AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node,
Info->Predefined);
/*
* For all names: Check that the incoming argument count for
* this method/object matches the actual ASL/AML definition.
*/
AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node,
Info->ParamCount, Info->Predefined);
/* For predefined names: Typecheck all incoming arguments */
AcpiNsCheckArgumentTypes (Info);
/*
* Three major evaluation cases:
*
* 1) Object types that cannot be evaluated by definition
* 2) The object is a control method -- execute it
* 3) The object is not a method -- just return it's current value
*/
switch (AcpiNsGetType (Info->Node))
{
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_EVENT:
case ACPI_TYPE_MUTEX:
case ACPI_TYPE_REGION:
case ACPI_TYPE_THERMAL:
case ACPI_TYPE_LOCAL_SCOPE:
/*
* 1) Disallow evaluation of certain object types. For these,
* object evaluation is undefined and not supported.
*/
ACPI_ERROR ((AE_INFO,
"%s: Evaluation of object type [%s] is not supported",
Info->FullPathname,
AcpiUtGetTypeName (Info->Node->Type)));
Status = AE_TYPE;
goto Cleanup;
case ACPI_TYPE_METHOD:
/*
* 2) Object is a control method - execute it
*/
/* Verify that there is a method object associated with this node */
if (!Info->ObjDesc)
{
ACPI_ERROR ((AE_INFO, "%s: Method has no attached sub-object",
Info->FullPathname));
Status = AE_NULL_OBJECT;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"**** Execute method [%s] at AML address %p length %X\n",
Info->FullPathname,
Info->ObjDesc->Method.AmlStart + 1,
Info->ObjDesc->Method.AmlLength - 1));
/*
* Any namespace deletion must acquire both the namespace and
* interpreter locks to ensure that no thread is using the portion of
* the namespace that is being deleted.
*
* Execute the method via the interpreter. The interpreter is locked
* here before calling into the AML parser
*/
AcpiExEnterInterpreter ();
Status = AcpiPsExecuteMethod (Info);
AcpiExExitInterpreter ();
break;
default:
/*
* 3) All other non-method objects -- get the current object value
*/
/*
* Some objects require additional resolution steps (e.g., the Node
* may be a field that must be read, etc.) -- we can't just grab
* the object out of the node.
*
* Use ResolveNodeToValue() to get the associated value.
*
* NOTE: we can get away with passing in NULL for a walk state because
* the Node is guaranteed to not be a reference to either a method
* local or a method argument (because this interface is never called
* from a running method.)
*
* Even though we do not directly invoke the interpreter for object
* resolution, we must lock it because we could access an OpRegion.
* The OpRegion access code assumes that the interpreter is locked.
*/
AcpiExEnterInterpreter ();
/* TBD: ResolveNodeToValue has a strange interface, fix */
Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node);
Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR (
ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL);
AcpiExExitInterpreter ();
if (ACPI_FAILURE (Status))
{
Info->ReturnObject = NULL;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Returned object %p [%s]\n",
Info->ReturnObject,
AcpiUtGetObjectTypeName (Info->ReturnObject)));
Status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */
break;
}
/*
* For predefined names, check the return value against the ACPI
* specification. Some incorrect return value types are repaired.
*/
(void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount,
Status, &Info->ReturnObject);
/* Check if there is a return value that must be dealt with */
if (Status == AE_CTRL_RETURN_VALUE)
{
/* If caller does not want the return value, delete it */
if (Info->Flags & ACPI_IGNORE_RETURN_VALUE)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
/* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */
Status = AE_OK;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,
"*** Completed evaluation of object %s ***\n",
Info->RelativePathname));
Cleanup:
/*
* Namespace was unlocked by the handling AcpiNs* function, so we
* just free the pathname and return
*/
ACPI_FREE (Info->FullPathname);
Info->FullPathname = NULL;
return_ACPI_STATUS (Status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'acpi: acpica: fix acpi operand cache leak in nseval.c
I found an ACPI cache leak in ACPI early termination and boot continuing case.
When early termination occurs due to malicious ACPI table, Linux kernel
terminates ACPI function and continues to boot process. While kernel terminates
ACPI function, kmem_cache_destroy() reports Acpi-Operand cache leak.
Boot log of ACPI operand cache leak is as follows:
>[ 0.464168] ACPI: Added _OSI(Module Device)
>[ 0.467022] ACPI: Added _OSI(Processor Device)
>[ 0.469376] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.471647] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.477997] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)
>[ 0.482706] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)
>[ 0.487503] ACPI Error: Method parse/execution failed [\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.492136] ACPI Error: Method parse/execution failed [\_SB._INI] (Node ffff88021710a618), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.497683] ACPI: Interpreter enabled
>[ 0.499385] ACPI: (supports S0)
>[ 0.501151] ACPI: Using IOAPIC for interrupt routing
>[ 0.503342] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)
>[ 0.506522] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)
>[ 0.510463] ACPI Error: Method parse/execution failed [\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.514477] ACPI Error: Method parse/execution failed [\_PIC] (Node ffff88021710ab18), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.518867] ACPI Exception: AE_AML_INTERNAL, Evaluating _PIC (20170303/bus-991)
>[ 0.522384] kmem_cache_destroy Acpi-Operand: Slab cache still has objects
>[ 0.524597] CPU: 1 PID: 1 Comm: swapper/0 Not tainted 4.12.0-rc5 #26
>[ 0.526795] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS VirtualBox 12/01/2006
>[ 0.529668] Call Trace:
>[ 0.530811] ? dump_stack+0x5c/0x81
>[ 0.532240] ? kmem_cache_destroy+0x1aa/0x1c0
>[ 0.533905] ? acpi_os_delete_cache+0xa/0x10
>[ 0.535497] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.537237] ? acpi_terminate+0xa/0x14
>[ 0.538701] ? acpi_init+0x2af/0x34f
>[ 0.540008] ? acpi_sleep_proc_init+0x27/0x27
>[ 0.541593] ? do_one_initcall+0x4e/0x1a0
>[ 0.543008] ? kernel_init_freeable+0x19e/0x21f
>[ 0.546202] ? rest_init+0x80/0x80
>[ 0.547513] ? kernel_init+0xa/0x100
>[ 0.548817] ? ret_from_fork+0x25/0x30
>[ 0.550587] vgaarb: loaded
>[ 0.551716] EDAC MC: Ver: 3.0.0
>[ 0.553744] PCI: Probing PCI hardware
>[ 0.555038] PCI host bridge to bus 0000:00
> ... Continue to boot and log is omitted ...
I analyzed this memory leak in detail and found AcpiNsEvaluate() function
only removes Info->ReturnObject in AE_CTRL_RETURN_VALUE case. But, when errors
occur, the status value is not AE_CTRL_RETURN_VALUE, and Info->ReturnObject is
also not null. Therefore, this causes acpi operand memory leak.
This cache leak causes a security threat because an old kernel (<= 4.9) shows
memory locations of kernel functions in stack dump. Some malicious users
could use this information to neutralize kernel ASLR.
I made a patch to fix ACPI operand cache leak.
Signed-off-by: Seunghun Han <kkamagui@gmail.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct page *alloc_huge_page(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct hstate *h = hstate_vma(vma);
struct page *page;
struct address_space *mapping = vma->vm_file->f_mapping;
struct inode *inode = mapping->host;
long chg;
/*
* Processes that did not create the mapping will have no reserves and
* will not have accounted against quota. Check that the quota can be
* made before satisfying the allocation
* MAP_NORESERVE mappings may also need pages and quota allocated
* if no reserve mapping overlaps.
*/
chg = vma_needs_reservation(h, vma, addr);
if (chg < 0)
return ERR_PTR(-VM_FAULT_OOM);
if (chg)
if (hugetlb_get_quota(inode->i_mapping, chg))
return ERR_PTR(-VM_FAULT_SIGBUS);
spin_lock(&hugetlb_lock);
page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);
spin_unlock(&hugetlb_lock);
if (!page) {
page = alloc_buddy_huge_page(h, NUMA_NO_NODE);
if (!page) {
hugetlb_put_quota(inode->i_mapping, chg);
return ERR_PTR(-VM_FAULT_SIGBUS);
}
}
set_page_private(page, (unsigned long) mapping);
vma_commit_reservation(h, vma, addr);
return page;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <abarry@cray.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Cc: Hugh Dickins <hughd@google.com>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Minchan Kim <minchan.kim@gmail.com>
Cc: Hillf Danton <dhillf@gmail.com>
Cc: Paul Mackerras <paulus@samba.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void hugetlb_put_quota(struct address_space *mapping, long delta)
{
struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(mapping->host->i_sb);
if (sbinfo->free_blocks > -1) {
spin_lock(&sbinfo->stat_lock);
sbinfo->free_blocks += delta;
spin_unlock(&sbinfo->stat_lock);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <abarry@cray.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Cc: Hugh Dickins <hughd@google.com>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Minchan Kim <minchan.kim@gmail.com>
Cc: Hillf Danton <dhillf@gmail.com>
Cc: Paul Mackerras <paulus@samba.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415', 'CWE-125'], 'message': 'bug #248, fix Out-Of-Bounds Read in read_image_tga'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool WebContents::SendIPCMessageToFrame(bool internal,
int32_t frame_id,
const std::string& channel,
v8::Local<v8::Value> args) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, args, &message)) {
isolate->ThrowException(v8::Exception::Error(
gin::StringToV8(isolate, "Failed to serialize arguments")));
return false;
}
auto frames = web_contents()->GetAllFrames();
auto iter = std::find_if(frames.begin(), frames.end(), [frame_id](auto* f) {
return f->GetRoutingID() == frame_id;
});
if (iter == frames.end())
return false;
if (!(*iter)->IsRenderFrameLive())
return false;
mojo::AssociatedRemote<mojom::ElectronRenderer> electron_renderer;
(*iter)->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer);
electron_renderer->Message(internal, channel, std::move(message),
0 /* sender_id */);
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'fix: restrict sendToFrame to same-process frames by default (#26875)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: agoo_ws_create_req(agooCon c, long mlen) {
uint8_t op = 0x0F & *c->buf;
if (NULL == (c->req = agoo_req_create(mlen))) {
agoo_log_cat(&agoo_error_cat, "Out of memory attempting to allocate request.");
return true;
}
if (NULL == c->up || agoo_server.ctx_nil_value == c->up->ctx) {
return true;
}
memset(c->req, 0, sizeof(struct _agooReq));
if ((long)c->bcnt <= mlen) {
memcpy(c->req->msg, c->buf, c->bcnt);
if ((long)c->bcnt < mlen) {
memset(c->req->msg + c->bcnt, 0, mlen - c->bcnt);
}
} else {
memcpy(c->req->msg, c->buf, mlen);
}
c->req->msg[mlen] = '\0';
c->req->mlen = mlen;
c->req->method = (AGOO_WS_OP_BIN == op) ? AGOO_ON_BIN : AGOO_ON_MSG;
c->req->upgrade = AGOO_UP_NONE;
c->req->up = c->up;
c->req->res = NULL;
if (c->up->on_msg) {
c->req->hook = agoo_hook_create(AGOO_NONE, NULL, c->up->ctx, PUSH_HOOK, &agoo_server.eval_queue);
}
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-444', 'CWE-61'], 'message': 'Remote addr (#99)
* REMOTE_ADDR added
* Ready for merge'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Unsupported TGA bpp/alphabit combinations should error gracefully
Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are
really supported. All other combinations will be rejected with a warning.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool PM_io_parser<PMDEC>::read_hedge(Halfedge_handle e)
{ // syntax: index { opposite, prev, next, vertex, face, mark }
int n, eo, epr, ene, v, f; bool m;
if ( !(in >> n) ||
!check_sep("{") ||
!(in >> eo) || !check_sep(",") ||
!(in >> epr) || !check_sep(",") ||
!(in >> ene) || !check_sep(",") ||
!(in >> v) || !check_sep(",") ||
!(in >> f) || !check_sep(",") ||
!(in >> m) || !check_sep("}") )
return false;
CGAL_assertion_msg
(eo >= 0 || (std::size_t) eo < en || epr >= 0 || (std::size_t) epr < en || ene >= 0 || (std::size_t) ene < en ||
v >= 0 || (std::size_t) v < vn || f >= 0 || (std::size_t) f < fn ,
"wrong index in read_hedge");
// precond: objects exist!
CGAL_assertion(EI[e->opposite()]);
e->set_prev(Halfedge_of[epr]);
e->set_next(Halfedge_of[ene]);
e->set_vertex(Vertex_of[v]);
e->set_face(Face_of[f]);
mark(e) = m;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'Fix Nef_2 and Nef_S2 IO'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CollationCreate(const char *collname, Oid collnamespace,
Oid collowner,
char collprovider,
bool collisdeterministic,
int32 collencoding,
const char *collcollate, const char *collctype,
const char *collversion,
bool if_not_exists,
bool quiet)
{
Relation rel;
TupleDesc tupDesc;
HeapTuple tup;
Datum values[Natts_pg_collation];
bool nulls[Natts_pg_collation];
NameData name_name,
name_collate,
name_ctype;
Oid oid;
ObjectAddress myself,
referenced;
AssertArg(collname);
AssertArg(collnamespace);
AssertArg(collowner);
AssertArg(collcollate);
AssertArg(collctype);
/*
* Make sure there is no existing collation of same name & encoding.
*
* This would be caught by the unique index anyway; we're just giving a
* friendlier error message. The unique index provides a backstop against
* race conditions.
*/
if (SearchSysCacheExists3(COLLNAMEENCNSP,
PointerGetDatum(collname),
Int32GetDatum(collencoding),
ObjectIdGetDatum(collnamespace)))
{
if (quiet)
return InvalidOid;
else if (if_not_exists)
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT),
collencoding == -1
? errmsg("collation \"%s\" already exists, skipping",
collname)
: errmsg("collation \"%s\" for encoding \"%s\" already exists, skipping",
collname, pg_encoding_to_char(collencoding))));
return InvalidOid;
}
else
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
collencoding == -1
? errmsg("collation \"%s\" already exists",
collname)
: errmsg("collation \"%s\" for encoding \"%s\" already exists",
collname, pg_encoding_to_char(collencoding))));
}
/* open pg_collation; see below about the lock level */
rel = table_open(CollationRelationId, ShareRowExclusiveLock);
/*
* Also forbid a specific-encoding collation shadowing an any-encoding
* collation, or an any-encoding collation being shadowed (see
* get_collation_name()). This test is not backed up by the unique index,
* so we take a ShareRowExclusiveLock earlier, to protect against
* concurrent changes fooling this check.
*/
if ((collencoding == -1 &&
SearchSysCacheExists3(COLLNAMEENCNSP,
PointerGetDatum(collname),
Int32GetDatum(GetDatabaseEncoding()),
ObjectIdGetDatum(collnamespace))) ||
(collencoding != -1 &&
SearchSysCacheExists3(COLLNAMEENCNSP,
PointerGetDatum(collname),
Int32GetDatum(-1),
ObjectIdGetDatum(collnamespace))))
{
if (quiet)
{
table_close(rel, NoLock);
return InvalidOid;
}
else if (if_not_exists)
{
table_close(rel, NoLock);
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("collation \"%s\" already exists, skipping",
collname)));
return InvalidOid;
}
else
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("collation \"%s\" already exists",
collname)));
}
tupDesc = RelationGetDescr(rel);
/* form a tuple */
memset(nulls, 0, sizeof(nulls));
namestrcpy(&name_name, collname);
oid = GetNewOidWithIndex(rel, CollationOidIndexId,
Anum_pg_collation_oid);
values[Anum_pg_collation_oid - 1] = ObjectIdGetDatum(oid);
values[Anum_pg_collation_collname - 1] = NameGetDatum(&name_name);
values[Anum_pg_collation_collnamespace - 1] = ObjectIdGetDatum(collnamespace);
values[Anum_pg_collation_collowner - 1] = ObjectIdGetDatum(collowner);
values[Anum_pg_collation_collprovider - 1] = CharGetDatum(collprovider);
values[Anum_pg_collation_collisdeterministic - 1] = BoolGetDatum(collisdeterministic);
values[Anum_pg_collation_collencoding - 1] = Int32GetDatum(collencoding);
namestrcpy(&name_collate, collcollate);
values[Anum_pg_collation_collcollate - 1] = NameGetDatum(&name_collate);
namestrcpy(&name_ctype, collctype);
values[Anum_pg_collation_collctype - 1] = NameGetDatum(&name_ctype);
if (collversion)
values[Anum_pg_collation_collversion - 1] = CStringGetTextDatum(collversion);
else
nulls[Anum_pg_collation_collversion - 1] = true;
tup = heap_form_tuple(tupDesc, values, nulls);
/* insert a new tuple */
CatalogTupleInsert(rel, tup);
Assert(OidIsValid(oid));
/* set up dependencies for the new collation */
myself.classId = CollationRelationId;
myself.objectId = oid;
myself.objectSubId = 0;
/* create dependency on namespace */
referenced.classId = NamespaceRelationId;
referenced.objectId = collnamespace;
referenced.objectSubId = 0;
recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
/* create dependency on owner */
recordDependencyOnOwner(CollationRelationId, oid, collowner);
/* dependency on extension */
recordDependencyOnCurrentExtension(&myself, false);
/* Post creation hook for new collation */
InvokeObjectPostCreateHook(CollationRelationId, oid, 0);
heap_freetuple(tup);
table_close(rel, NoLock);
return oid;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.
Previously, if an extension script did CREATE OR REPLACE and there was
an existing object not belonging to the extension, it would overwrite
the object and adopt it into the extension. This is problematic, first
because the overwrite is probably unintentional, and second because we
didn't change the object's ownership. Thus a hostile user could create
an object in advance of an expected CREATE EXTENSION command, and would
then have ownership rights on an extension object, which could be
modified for trojan-horse-type attacks.
Hence, forbid CREATE OR REPLACE of an existing object unless it already
belongs to the extension. (Note that we've always forbidden replacing
an object that belongs to some other extension; only the behavior for
previously-free-standing objects changes here.)
For the same reason, also fail CREATE IF NOT EXISTS when there is
an existing object that doesn't belong to the extension.
Our thanks to Sven Klemm for reporting this problem.
Security: CVE-2022-2625'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
if(subobj_len == 0)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13048/RSVP: fix decoding of Fast Reroute objects
In rsvp_obj_print() the case block for Class-Num 205 (FAST_REROUTE) from
RFC 4090 Section 4.1 could over-read accessing the buffer contents before
making the bounds check. Rearrange those steps the correct way around.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* const context) override {
// node_id_range
const Tensor* node_id_range_t;
OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t));
const auto node_id_range = node_id_range_t->vec<int32>();
const int32_t node_id_first = node_id_range(0); // inclusive
const int32_t node_id_last = node_id_range(1); // exclusive
const Tensor* stats_summary_indices_t;
OP_REQUIRES_OK(context, context->input("stats_summary_indices",
&stats_summary_indices_t));
const auto stats_summary_indices = stats_summary_indices_t->matrix<int32>();
const int32_t num_sparse_entries = stats_summary_indices_t->dim_size(0);
const Tensor* stats_summary_values_t;
OP_REQUIRES_OK(context, context->input("stats_summary_values",
&stats_summary_values_t));
const auto stats_summary_values = stats_summary_values_t->vec<float>();
const Tensor* stats_summary_shape_t;
OP_REQUIRES_OK(
context, context->input("stats_summary_shape", &stats_summary_shape_t));
const auto stats_summary_shape = stats_summary_shape_t->vec<int32>();
const int32_t num_buckets = stats_summary_shape(2) - 1;
const int32_t stats_dims = stats_summary_shape(3);
const Tensor* l1_t;
OP_REQUIRES_OK(context, context->input("l1", &l1_t));
const auto l1 = l1_t->scalar<float>()();
const Tensor* l2_t;
OP_REQUIRES_OK(context, context->input("l2", &l2_t));
const auto l2 = l2_t->scalar<float>()();
const Tensor* tree_complexity_t;
OP_REQUIRES_OK(context,
context->input("tree_complexity", &tree_complexity_t));
const auto tree_complexity = tree_complexity_t->scalar<float>()();
const Tensor* min_node_weight_t;
OP_REQUIRES_OK(context,
context->input("min_node_weight", &min_node_weight_t));
const auto min_node_weight = min_node_weight_t->scalar<float>()();
std::vector<int32> output_node_ids;
std::vector<float> output_gains;
std::vector<int32> output_feature_dimensions;
std::vector<int32> output_thresholds;
std::vector<float> output_left_node_contribs;
std::vector<float> output_right_node_contribs;
std::vector<string> output_split_types;
FeatureMap f_map;
int32_t previous_node_id = -1;
for (int idx = 0; idx < num_sparse_entries; ++idx) {
int32_t node_id = stats_summary_indices(idx, 0);
if (node_id != previous_node_id) {
process_node(f_map, &output_node_ids, &output_gains,
&output_feature_dimensions, &output_thresholds,
&output_left_node_contribs, &output_right_node_contribs,
&output_split_types, previous_node_id, min_node_weight, l1,
l2, num_buckets);
f_map.clear();
}
previous_node_id = node_id;
DCHECK_LE(node_id_first, node_id);
DCHECK_LT(node_id, node_id_last);
const int32_t feature_dim = stats_summary_indices(idx, 1);
const int32_t bucket_id = stats_summary_indices(idx, 2);
const int32_t stat_dim = stats_summary_indices(idx, 3);
std::pair<FeatureMapIterator, bool> const& f_insert_result = f_map.insert(
FeatureMapIterator::value_type(feature_dim, BucketMap()));
auto& b_map = f_insert_result.first->second;
std::pair<BucketMapIterator, bool> const& b_insert_result =
b_map.insert(BucketMapIterator::value_type(
bucket_id, std::vector<float>(stats_dims)));
auto& stats = b_insert_result.first->second;
stats[stat_dim] = stats_summary_values(idx);
} // for node_id
// process the last node id
process_node(f_map, &output_node_ids, &output_gains,
&output_feature_dimensions, &output_thresholds,
&output_left_node_contribs, &output_right_node_contribs,
&output_split_types, previous_node_id, min_node_weight, l1, l2,
num_buckets);
const int num_nodes = output_node_ids.size();
// output_node_ids
Tensor* output_node_ids_t = nullptr;
OP_REQUIRES_OK(context, context->allocate_output("node_ids", {num_nodes},
&output_node_ids_t));
auto output_node_ids_vec = output_node_ids_t->vec<int32>();
// output_gains
Tensor* output_gains_t;
OP_REQUIRES_OK(context, context->allocate_output("gains", {num_nodes},
&output_gains_t));
auto output_gains_vec = output_gains_t->vec<float>();
// output_feature_dimensions
Tensor* output_feature_dimension_t;
OP_REQUIRES_OK(context,
context->allocate_output("feature_dimensions", {num_nodes},
&output_feature_dimension_t));
auto output_feature_dimensions_vec =
output_feature_dimension_t->vec<int32>();
// output_thresholds
Tensor* output_thresholds_t;
OP_REQUIRES_OK(context, context->allocate_output("thresholds", {num_nodes},
&output_thresholds_t));
auto output_thresholds_vec = output_thresholds_t->vec<int32>();
// output_left_node_contribs
Tensor* output_left_node_contribs_t;
OP_REQUIRES_OK(
context, context->allocate_output("left_node_contribs", {num_nodes, 1},
&output_left_node_contribs_t));
auto output_left_node_contribs_matrix =
output_left_node_contribs_t->matrix<float>();
// output_right_node_contribs
Tensor* output_right_node_contribs_t;
OP_REQUIRES_OK(
context, context->allocate_output("right_node_contribs", {num_nodes, 1},
&output_right_node_contribs_t));
auto output_right_node_contribs_matrix =
output_right_node_contribs_t->matrix<float>();
// split type
Tensor* output_split_types_t;
OP_REQUIRES_OK(
context, context->allocate_output("split_with_default_directions",
{num_nodes}, &output_split_types_t));
auto output_split_types_vec = output_split_types_t->vec<tstring>();
// Sets output tensors from vectors.
for (int i = 0; i < num_nodes; ++i) {
output_node_ids_vec(i) = output_node_ids[i];
// Adjust the gains to penalize by tree complexity.
output_gains_vec(i) = output_gains[i] - tree_complexity;
output_feature_dimensions_vec(i) = output_feature_dimensions[i];
output_thresholds_vec(i) = output_thresholds[i];
// TODO(crawles): change this for multi-class.
output_left_node_contribs_matrix(i, 0) = output_left_node_contribs[i];
output_right_node_contribs_matrix(i, 0) = output_right_node_contribs[i];
output_split_types_vec(i) = output_split_types[i];
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-369'], 'message': 'In tf.raw_ops.BoostedTreesSparseCalculateBestFeatureSplit, limit stat_dim in stats_summary_indices to under stats_dims in stats_summary_shape
PiperOrigin-RevId: 387171191
Change-Id: I83ca8a75b22aa78c037e8b98779da6cced16bfaa'</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 ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
{
if (avctx->internal->pkt) {
frame->pkt_pts = avctx->internal->pkt->pts;
av_frame_set_pkt_pos (frame, avctx->internal->pkt->pos);
av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);
av_frame_set_pkt_size (frame, avctx->internal->pkt->size);
} else {
frame->pkt_pts = AV_NOPTS_VALUE;
av_frame_set_pkt_pos (frame, -1);
av_frame_set_pkt_duration(frame, 0);
av_frame_set_pkt_size (frame, -1);
}
frame->reordered_opaque = avctx->reordered_opaque;
switch (avctx->codec->type) {
case AVMEDIA_TYPE_VIDEO:
if (frame->format < 0)
frame->format = avctx->pix_fmt;
if (!frame->sample_aspect_ratio.num)
frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
av_frame_set_colorspace(frame, avctx->colorspace);
if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
av_frame_set_color_range(frame, avctx->color_range);
break;
case AVMEDIA_TYPE_AUDIO:
if (!frame->sample_rate)
frame->sample_rate = avctx->sample_rate;
if (frame->format < 0)
frame->format = avctx->sample_fmt;
if (!frame->channel_layout) {
if (avctx->channel_layout) {
if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
"configuration.\n");
return AVERROR(EINVAL);
}
frame->channel_layout = avctx->channel_layout;
} else {
if (avctx->channels > FF_SANE_NB_CHANNELS) {
av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
avctx->channels);
return AVERROR(ENOSYS);
}
}
}
av_frame_set_channels(frame, avctx->channels);
break;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'avcodec/utils: set AVFrame format unconditional
Fixes inconsistency and out of array accesses
Fixes: 10cdd7e63e7f66e3e66273939e0863dd-asan_heap-oob_1a4ff32_7078_cov_4056274555_mov_h264_aac__mp4box_frag.mp4
Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
return AVERROR(ENOSYS);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/ac3_parser: Check init_get_bits8() for failure
Fixes: null pointer dereference
Fixes: ffmpeg_crash_6.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Reviewed-by: Paul B Mahol <onemda@gmail.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void kdc_post_fork(struct task_server *task, struct process_details *pd)
{
struct kdc_server *kdc;
krb5_kdc_configuration *kdc_config = NULL;
NTSTATUS status;
krb5_error_code ret;
int ldb_ret;
if (task == NULL) {
task_server_terminate(task, "kdc: Null task", true);
return;
}
if (task->private_data == NULL) {
task_server_terminate(task, "kdc: No kdc_server info", true);
return;
}
kdc = talloc_get_type_abort(task->private_data, struct kdc_server);
/* get a samdb connection */
kdc->samdb = samdb_connect(kdc,
kdc->task->event_ctx,
kdc->task->lp_ctx,
system_session(kdc->task->lp_ctx),
NULL,
0);
if (!kdc->samdb) {
DBG_WARNING("kdc_task_init: unable to connect to samdb\n");
task_server_terminate(task, "kdc: krb5_init_context samdb connect failed", true);
return;
}
ldb_ret = samdb_rodc(kdc->samdb, &kdc->am_rodc);
if (ldb_ret != LDB_SUCCESS) {
DBG_WARNING("kdc_task_init: "
"Cannot determine if we are an RODC: %s\n",
ldb_errstring(kdc->samdb));
task_server_terminate(task, "kdc: krb5_init_context samdb RODC connect failed", true);
return;
}
kdc->proxy_timeout = lpcfg_parm_int(kdc->task->lp_ctx, NULL, "kdc", "proxy timeout", 5);
initialize_krb5_error_table();
ret = smb_krb5_init_context(kdc, task->lp_ctx, &kdc->smb_krb5_context);
if (ret) {
DBG_WARNING("kdc_task_init: krb5_init_context failed (%s)\n",
error_message(ret));
task_server_terminate(task, "kdc: krb5_init_context failed", true);
return;
}
krb5_add_et_list(kdc->smb_krb5_context->krb5_context, initialize_hdb_error_table_r);
ret = krb5_kdc_get_config(kdc->smb_krb5_context->krb5_context,
&kdc_config);
if(ret) {
task_server_terminate(task, "kdc: failed to get KDC configuration", true);
return;
}
kdc_config->logf = (krb5_log_facility *)kdc->smb_krb5_context->pvt_log_data;
kdc_config->db = talloc(kdc, struct HDB *);
if (!kdc_config->db) {
task_server_terminate(task, "kdc: out of memory", true);
return;
}
kdc_config->num_db = 1;
/*
* This restores the behavior before
* commit 255e3e18e00f717d99f3bc57c8a8895ff624f3c3
* s4:heimdal: import lorikeet-heimdal-201107150856
* (commit 48936803fae4a2fb362c79365d31f420c917b85b)
*
* as_use_strongest_session_key,preauth_use_strongest_session_key
* and tgs_use_strongest_session_key are input to the
* _kdc_find_etype() function. The old bahavior is in
* the use_strongest_session_key=FALSE code path.
* (The only remaining difference in _kdc_find_etype()
* is the is_preauth parameter.)
*
* The old behavior in the _kdc_get_preferred_key()
* function is use_strongest_server_key=TRUE.
*/
kdc_config->tgt_use_strongest_session_key = false;
kdc_config->preauth_use_strongest_session_key = true;
kdc_config->svc_use_strongest_session_key = false;
kdc_config->use_strongest_server_key = true;
kdc_config->force_include_pa_etype_salt = true;
/*
* For Samba CVE-2020-25719 Require PAC to be present
* This instructs Heimdal to match AD behaviour,
* as seen after Microsoft's CVE-2021-42287 when
* PacRequestorEnforcement is set to 2.
*
* Samba BUG: https://bugzilla.samba.org/show_bug.cgi?id=14686
* REF: https://support.microsoft.com/en-au/topic/kb5008380-authentication-updates-cve-2021-42287-9dafac11-e0d0-4cb8-959a-143bd0201041
*/
kdc_config->require_pac = true;
/*
* By default we enable RFC6113/FAST support,
* but we have an option to disable in order to
* test against a KDC with FAST support.
*/
kdc_config->enable_fast = lpcfg_kdc_enable_fast(task->lp_ctx);
/*
* Match Windows and RFC6113 and Windows but break older
* Heimdal clients.
*/
kdc_config->enable_armored_pa_enc_timestamp = false;
/* Register hdb-samba4 hooks for use as a keytab */
kdc->base_ctx = talloc_zero(kdc, struct samba_kdc_base_context);
if (!kdc->base_ctx) {
task_server_terminate(task, "kdc: out of memory", true);
return;
}
kdc->base_ctx->ev_ctx = task->event_ctx;
kdc->base_ctx->lp_ctx = task->lp_ctx;
kdc->base_ctx->msg_ctx = task->msg_ctx;
status = hdb_samba4_create_kdc(kdc->base_ctx,
kdc->smb_krb5_context->krb5_context,
&kdc_config->db[0]);
if (!NT_STATUS_IS_OK(status)) {
task_server_terminate(task, "kdc: hdb_samba4_create_kdc (setup KDC database) failed", true);
return;
}
ret = krb5_plugin_register(kdc->smb_krb5_context->krb5_context,
PLUGIN_TYPE_DATA, "hdb_samba4_interface",
&hdb_samba4_interface);
if(ret) {
task_server_terminate(task, "kdc: failed to register hdb plugin", true);
return;
}
kdc->keytab_name = talloc_asprintf(kdc, "HDB:samba4:&%p", kdc->base_ctx);
if (kdc->keytab_name == NULL) {
task_server_terminate(task,
"kdc: Failed to set keytab name",
true);
return;
}
ret = krb5_kt_register(kdc->smb_krb5_context->krb5_context, &hdb_kt_ops);
if(ret) {
task_server_terminate(task, "kdc: failed to register keytab plugin", true);
return;
}
/* Register KDC hooks */
ret = krb5_plugin_register(kdc->smb_krb5_context->krb5_context,
PLUGIN_TYPE_DATA, "kdc",
&kdc_plugin_table);
if(ret) {
task_server_terminate(task, "kdc: failed to register kdc plugin", true);
return;
}
ret = krb5_kdc_plugin_init(kdc->smb_krb5_context->krb5_context);
if(ret) {
task_server_terminate(task, "kdc: failed to init kdc plugin", true);
return;
}
ret = krb5_kdc_pkinit_config(kdc->smb_krb5_context->krb5_context, kdc_config);
if(ret) {
task_server_terminate(task, "kdc: failed to init kdc pkinit subsystem", true);
return;
}
kdc->private_data = kdc_config;
status = IRPC_REGISTER(task->msg_ctx, irpc, KDC_CHECK_GENERIC_KERBEROS,
kdc_check_generic_kerberos, kdc);
if (!NT_STATUS_IS_OK(status)) {
task_server_terminate(task, "kdc failed to setup monitoring", true);
return;
}
irpc_add_name(task->msg_ctx, "kdc_server");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-288'], 'message': 'CVE-2022-32744 s4:kdc: Don't allow HDB keytab iteration
A fallback in krb5_rd_req_ctx() means that Samba's kpasswd service will
try many inappropriate keys to decrypt the ticket supplied to it. For
example, it will accept a ticket encrypted with the Administrator's key,
when it should rather accept only tickets encrypted with the krbtgt's
key (and not an RODC krbtgt). To fix this, declare the HDB keytab using
the HDBGET ops, which do not support iteration.
BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074
Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Reviewed-by: Andreas Schneider <asn@samba.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 bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) {
int i;
struct minidump_handle_operation_list *handle_operation_list;
struct minidump_memory_list *memory_list;
struct minidump_memory64_list *memory64_list;
struct minidump_memory_info_list *memory_info_list;
struct minidump_module_list *module_list;
struct minidump_thread_list *thread_list;
struct minidump_thread_ex_list *thread_ex_list;
struct minidump_thread_info_list *thread_info_list;
struct minidump_unloaded_module_list *unloaded_module_list;
struct avrf_handle_operation *handle_operations;
struct minidump_memory_descriptor *memories;
struct minidump_memory_descriptor64 *memories64;
struct minidump_memory_info *memory_infos;
struct minidump_module *modules;
struct minidump_thread *threads;
struct minidump_thread_ex *ex_threads;
struct minidump_thread_info *thread_infos;
struct minidump_unloaded_module *unloaded_modules;
/* We could confirm data sizes but a malcious MDMP will always get around
** this! But we can ensure that the data is not outside of the file */
if (entry->location.rva + entry->location.data_size > obj->b->length) {
eprintf("[ERROR] Size Mismatch - Stream data is larger than file size!\n");
return false;
}
switch (entry->stream_type) {
case THREAD_LIST_STREAM:
thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread.format", "ddddq?? "
"ThreadId SuspendCount PriorityClass Priority "
"Teb (mdmp_memory_descriptor)Stack "
"(mdmp_location_descriptor)ThreadContext", 0);
sdb_num_set (obj->kv, "mdmp_thread_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_list.format",
sdb_fmt ("d[%i]? "
"NumberOfThreads (mdmp_thread)Threads",
thread_list->number_of_threads),
0);
/* TODO: Not yet fully parsed or utilised */
for (i = 0; i < thread_list->number_of_threads; i++) {
threads = (struct minidump_thread *)(&(thread_list->threads));
r_list_append (obj->streams.threads, &(threads[i]));
}
break;
case MODULE_LIST_STREAM:
module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_module.format", "qddtd???qq "
"BaseOfImage SizeOfImage CheckSum "
"TimeDateStamp ModuleNameRVA "
"(mdmp_vs_fixedfileinfo)VersionInfo "
"(mdmp_location_descriptor)CvRecord "
"(mdmp_location_descriptor)MiscRecord "
"Reserved0 Reserved1", 0);
sdb_num_set (obj->kv, "mdmp_module_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_module_list.format",
sdb_fmt ("d[%i]? "
"NumberOfModule (mdmp_module)Modules",
module_list->number_of_modules,
0),
0);
for (i = 0; i < module_list->number_of_modules; i++) {
modules = (struct minidump_module *)(&(module_list->modules));
r_list_append(obj->streams.modules, &(modules[i]));
}
break;
case MEMORY_LIST_STREAM:
memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_memory_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory_list.format",
sdb_fmt ("d[%i]? "
"NumberOfMemoryRanges "
"(mdmp_memory_descriptor)MemoryRanges ",
memory_list->number_of_memory_ranges,
0),
0);
for (i = 0; i < memory_list->number_of_memory_ranges; i++) {
memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges));
r_list_append (obj->streams.memories, &(memories[i]));
}
break;
case EXCEPTION_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_exception.format", "[4]E[4]Eqqdd[15]q "
"(mdmp_exception_code)ExceptionCode "
"(mdmp_exception_flags)ExceptionFlags "
"ExceptionRecord ExceptionAddress "
"NumberParameters __UnusedAlignment "
"ExceptionInformation", 0);
sdb_num_set (obj->kv, "mdmp_exception_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_exception_stream.format", "dd?? "
"ThreadId __Alignment "
"(mdmp_exception)ExceptionRecord "
"(mdmp_location_descriptor)ThreadContext", 0);
break;
case SYSTEM_INFO_STREAM:
obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_system_info.offset",
entry->location.rva, 0);
/* TODO: We need E as a byte! */
sdb_set (obj->kv, "mdmp_system_info.format", "[2]EwwbBddd[4]Ed[2]Ew[2]q "
"(mdmp_processor_architecture)ProcessorArchitecture "
"ProcessorLevel ProcessorRevision NumberOfProcessors "
"(mdmp_product_type)ProductType "
"MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId "
"CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures", 0);
break;
case THREAD_EX_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread_ex.format", "ddddq??? "
"ThreadId SuspendCount PriorityClass Priority "
"Teb (mdmp_memory_descriptor)Stack "
"(mdmp_location_descriptor)ThreadContext "
"(mdmp_memory_descriptor)BackingStore", 0);
sdb_num_set (obj->kv, "mdmp_thread_ex_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_ex_list.format",
sdb_fmt ("d[%i]? NumberOfThreads "
"(mdmp_thread_ex)Threads",
thread_ex_list->number_of_threads, 0),
0);
for (i = 0; i < thread_ex_list->number_of_threads; i++) {
ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads));
r_list_append (obj->streams.ex_threads, &(ex_threads[i]));
}
break;
case MEMORY_64_LIST_STREAM:
memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_memory64_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory64_list.format",
sdb_fmt ("qq[%i]? NumberOfMemoryRanges "
"BaseRva "
"(mdmp_memory_descriptor64)MemoryRanges",
memory64_list->number_of_memory_ranges),
0);
obj->streams.memories64.base_rva = memory64_list->base_rva;
for (i = 0; i < memory64_list->number_of_memory_ranges; i++) {
memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges));
r_list_append (obj->streams.memories64.memories, &(memories64[i]));
}
break;
case COMMENT_STREAM_A:
/* TODO: Not yet fully parsed or utilised */
obj->streams.comments_a = obj->b->buf + entry->location.rva;
sdb_num_set (obj->kv, "mdmp_comment_stream_a.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_comment_stream_a.format",
"s CommentA", 0);
break;
case COMMENT_STREAM_W:
/* TODO: Not yet fully parsed or utilised */
obj->streams.comments_w = obj->b->buf + entry->location.rva;
sdb_num_set (obj->kv, "mdmp_comment_stream_w.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_comment_stream_w.format",
"s CommentW", 0);
break;
case HANDLE_DATA_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_handle_data_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_handle_data_stream.format", "dddd "
"SizeOfHeader SizeOfDescriptor "
"NumberOfDescriptors Reserved", 0);
break;
case FUNCTION_TABLE_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_function_table_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_function_table_stream.format", "dddddd "
"SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor "
"SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad",
0);
break;
case UNLOADED_MODULE_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_unloaded_module.format", "qddtd "
"BaseOfImage SizeOfImage CheckSum TimeDateStamp "
"ModuleNameRva", 0);
sdb_num_set (obj->kv, "mdmp_unloaded_module_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_unloaded_module_list.format", "ddd "
"SizeOfHeader SizeOfEntry NumberOfEntries", 0);
for (i = 0; i < unloaded_module_list->number_of_entries; i++) {
unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list));
r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i]));
}
break;
case MISC_INFO_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva);
/* TODO: Handle different sizes */
sdb_num_set (obj->kv, "mdmp_misc_info.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_misc_info.format", "d[4]Bdtttddddd "
"SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId "
"ProcessCreateTime ProcessUserTime ProcessKernelTime "
"ProcessorMaxMhz ProcessorCurrentMhz "
"ProcessorMhzLimit ProcessorMaxIdleState "
"ProcessorCurrentIdleState", 0);
break;
case MEMORY_INFO_LIST_STREAM:
memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_memory_info.format",
"qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase "
"(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize "
"(mdmp_mem_state)State (mdmp_page_protect)Protect "
"(mdmp_mem_type)Type __Alignment2", 0);
sdb_num_set (obj->kv, "mdmp_memory_info_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory_info_list.format",
sdb_fmt ("ddq[%i]? SizeOfHeader SizeOfEntry "
"NumberOfEntries (mdmp_memory_info)MemoryInfo",
memory_info_list->number_of_entries),
0);
for (i = 0; i < memory_info_list->number_of_entries; i++) {
memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list));
r_list_append (obj->streams.memory_infos, &(memory_infos[i]));
}
break;
case THREAD_INFO_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread_info.format", "ddddttttqq "
"ThreadId DumpFlags DumpError ExitStatus CreateTime "
"ExitTime KernelTime UserTime StartAddress Affinity",
0);
sdb_num_set (obj->kv, "mdmp_thread_info_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_info_list.format", "ddd "
"SizeOfHeader SizeOfEntry NumberOfEntries", 0);
for (i = 0; i < thread_info_list->number_of_entries; i++) {
thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list));
r_list_append (obj->streams.thread_infos, &(thread_infos[i]));
}
break;
case HANDLE_OPERATION_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_handle_operation_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_handle_operation_list.format", "dddd "
"SizeOfHeader SizeOfEntry NumberOfEntries Reserved", 0);
for (i = 0; i < handle_operation_list->number_of_entries; i++) {
handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list));
r_list_append (obj->streams.operations, &(handle_operations[i]));
}
break;
case LAST_RESERVED_STREAM:
/* TODO: Not yet fully parsed or utilised */
break;
case UNUSED_STREAM:
case RESERVED_STREAM_0:
case RESERVED_STREAM_1:
/* Silently ignore reserved streams */
break;
default:
eprintf ("[WARN] Invalid or unsupported enumeration encountered %i\n", entry->stream_type);
return false;
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10464 - oobread crash in mdmp (#10683)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <ahonig@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: STATIC U8 *
S_reghop3(U8 *s, SSize_t off, const U8* lim)
{
/* return the position 'off' UTF-8 characters away from 's', forward if
* 'off' >= 0, backwards if negative. But don't go outside of position
* 'lim', which better be < s if off < 0 */
PERL_ARGS_ASSERT_REGHOP3;
if (off >= 0) {
while (off-- && s < lim) {
/* XXX could check well-formedness here */
s += UTF8SKIP(s);
}
}
else {
while (off++ && s > lim) {
s--;
if (UTF8_IS_CONTINUED(*s)) {
while (s > lim && UTF8_IS_CONTINUATION(*s))
s--;
}
/* XXX could check well-formedness here */
}
}
return s; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'PATCH [perl #123562] Regexp-matching "hangs"
The regex engine got into an infinite loop because of the malformation.
It is trying to back-up over a sequence of UTF-8 continuation bytes.
But the character just before the sequence should be a start byte. If
not, there is a malformation. I added a test to croak if that isn't the
case so that it doesn't just infinitely loop. I did this also in the
similar areas of regexec.c.
Comments long ago added to the code suggested that we check for
malformations in the vicinity of the new tests. But that was never
done. These new tests should be good enough to prevent looping, anyway.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CBINDInstallDlg::UpdateService(CString StartName) {
SC_HANDLE hSCManager;
SC_HANDLE hService;
if(m_toolsOnly)
return;
SetCurrent(IDS_OPEN_SCM);
hSCManager= OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!hSCManager) {
MsgBox(IDS_ERR_OPEN_SCM, GetErrMessage());
return;
}
DWORD dwStart = SERVICE_DEMAND_START;
if (m_autoStart)
dwStart = SERVICE_AUTO_START;
DWORD dwServiceType = SERVICE_WIN32_OWN_PROCESS;
CString namedLoc;
namedLoc.Format("%s\\bin\\named.exe", m_targetDir);
SetCurrent(IDS_OPEN_SERVICE);
hService = OpenService(hSCManager, BIND_SERVICE_NAME,
SERVICE_CHANGE_CONFIG);
if (!hService)
{
MsgBox(IDS_ERR_OPEN_SERVICE, GetErrMessage());
if (hSCManager)
CloseServiceHandle(hSCManager);
return;
} else {
if (ChangeServiceConfig(hService, dwServiceType, dwStart,
SERVICE_ERROR_NORMAL, namedLoc, NULL, NULL, NULL,
StartName, m_accountPassword, BIND_DISPLAY_NAME)
!= TRUE) {
DWORD err = GetLastError();
MsgBox(IDS_ERR_UPDATE_SERVICE, GetErrMessage());
}
}
if (hService)
CloseServiceHandle(hService);
if (hSCManager)
CloseServiceHandle(hSCManager);
SetItemStatus(IDC_REG_SERVICE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': '[master] quote service registry paths
4532. [security] The BIND installer on Windows used an unquoted
service path, which can enable privilege escalation.
(CVE-2017-3141) [RT #45229]'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_F(QuantizedConv2DTest, SmallWithNoZero) {
const int stride = 1;
TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D")
.Input(FakeInput(DT_QUINT8))
.Input(FakeInput(DT_QUINT8))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Attr("out_type", DataTypeToEnum<qint32>::v())
.Attr("strides", {1, stride, stride, 1})
.Attr("padding", "SAME")
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
// Here we're testing a slow implementation path, where zero is not
// representable in the image data and so simple border padding is not
// possible, so we have a min value greater than 0.
const float image_min = 1.0f;
const float image_max = 12.0f;
Tensor image_float(DT_FLOAT,
{image_batch_count, image_height, image_width, depth});
test::FillValues<float>(&image_float,
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
Tensor image_quantized =
FloatTensorToQuantized<quint8>(image_float, image_min, image_max);
const int filter_size = 3;
const int filter_count = 1;
const float filter_min = 1.0f;
const float filter_max = 9.0f;
Tensor filter_float(DT_FLOAT,
{filter_size, filter_size, depth, filter_count});
test::FillValues<float>(&filter_float, {1, 4, 7, 2, 5, 8, 3, 6, 9});
Tensor filter_quantized =
FloatTensorToQuantized<quint8>(filter_float, filter_min, filter_max);
AddInputFromArray<quint8>(image_quantized.shape(),
image_quantized.flat<quint8>());
AddInputFromArray<quint8>(filter_quantized.shape(),
filter_quantized.flat<quint8>());
AddInputFromArray<float>(TensorShape({1}), {image_min});
AddInputFromArray<float>(TensorShape({1}), {image_max});
AddInputFromArray<float>(TensorShape({1}), {filter_min});
AddInputFromArray<float>(TensorShape({1}), {filter_max});
TF_ASSERT_OK(RunOpKernel());
const int expected_width = image_width;
const int expected_height = image_height * filter_count;
Tensor expected_float(
DT_FLOAT, TensorShape({image_batch_count, expected_height, expected_width,
filter_count}));
test::FillValues<float>(&expected_float, {105, 150, 183, 95, 235, 312, 357,
178, 187, 234, 261, 121});
const Tensor& output_quantized = *GetOutput(0);
const float output_min = GetOutput(1)->flat<float>()(0);
const float output_max = GetOutput(2)->flat<float>()(0);
Tensor output_float =
QuantizedTensorToFloat<qint32>(output_quantized, output_min, output_max);
test::ExpectTensorNear<float>(expected_float, output_float, 1.0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix undefined behavior in QuantizedConv2D
Added more input validation and tests. Prior to this, we could get
`nullptr` exceptions when attempting to access 0th elements of 0-sized
inputs, leading to security vulnerability bugs.
Also needed to modify `quantized_conv_ops_test.cc` for consistency.
Previously the CPU kernel did technically support passing tensors
of rank larger than 0 for min/max values. However, the XLA kernels do not.
PiperOrigin-RevId: 445518507'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void WriteBinaryGltfStream(std::ostream &stream,
const std::string &content,
const std::vector<unsigned char> &binBuffer) {
const std::string header = "glTF";
const int version = 2;
const uint32_t content_size = uint32_t(content.size());
const uint32_t binBuffer_size = uint32_t(binBuffer.size());
// determine number of padding bytes required to ensure 4 byte alignment
const uint32_t content_padding_size = content_size % 4 == 0 ? 0 : 4 - content_size % 4;
const uint32_t bin_padding_size = binBuffer_size % 4 == 0 ? 0 : 4 - binBuffer_size % 4;
// 12 bytes for header, JSON content length, 8 bytes for JSON chunk info.
// Chunk data must be located at 4-byte boundary, which may require padding
const uint32_t length =
12 + 8 + content_size + content_padding_size +
(binBuffer_size ? (8 + binBuffer_size + bin_padding_size) : 0);
stream.write(header.c_str(), std::streamsize(header.size()));
stream.write(reinterpret_cast<const char *>(&version), sizeof(version));
stream.write(reinterpret_cast<const char *>(&length), sizeof(length));
// JSON chunk info, then JSON data
const uint32_t model_length = uint32_t(content.size()) + content_padding_size;
const uint32_t model_format = 0x4E4F534A;
stream.write(reinterpret_cast<const char *>(&model_length),
sizeof(model_length));
stream.write(reinterpret_cast<const char *>(&model_format),
sizeof(model_format));
stream.write(content.c_str(), std::streamsize(content.size()));
// Chunk must be multiplies of 4, so pad with spaces
if (content_padding_size > 0) {
const std::string padding = std::string(size_t(content_padding_size), ' ');
stream.write(padding.c_str(), std::streamsize(padding.size()));
}
if (binBuffer.size() > 0) {
// BIN chunk info, then BIN data
const uint32_t bin_length = uint32_t(binBuffer.size()) + bin_padding_size;
const uint32_t bin_format = 0x004e4942;
stream.write(reinterpret_cast<const char *>(&bin_length),
sizeof(bin_length));
stream.write(reinterpret_cast<const char *>(&bin_format),
sizeof(bin_format));
stream.write(reinterpret_cast<const char *>(binBuffer.data()),
std::streamsize(binBuffer.size()));
// Chunksize must be multiplies of 4, so pad with zeroes
if (bin_padding_size > 0) {
const std::vector<unsigned char> padding =
std::vector<unsigned char>(size_t(bin_padding_size), 0);
stream.write(reinterpret_cast<const char *>(padding.data()),
std::streamsize(padding.size()));
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Do not expand file path since its not necessary for glTF asset path(URI) and for security reason(`wordexp`).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline int ccid_hc_rx_getsockopt(struct ccid *ccid, struct sock *sk,
const int optname, int len,
u32 __user *optval, int __user *optlen)
{
int rc = -ENOPROTOOPT;
if (ccid->ccid_ops->ccid_hc_rx_getsockopt != NULL)
rc = ccid->ccid_ops->ccid_hc_rx_getsockopt(sk, optname, len,
optval, optlen);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'dccp: check ccid before dereferencing
ccid_hc_rx_getsockopt() and ccid_hc_tx_getsockopt() might be called with
a NULL ccid pointer leading to a NULL pointer dereference. This could
lead to a privilege escalation if the attacker is able to map page 0 and
prepare it with a fake ccid_ops pointer.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Gerrit Renker <gerrit@erg.abdn.ac.uk>
Cc: stable@vger.kernel.org
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static uint32_t estimate_re_size(const RE *re0, std::vector<StackItem> &stack)
{
// the estimated size of the last sub-RE visited by DFS
uint32_t size = 0;
const StackItem i0 = {re0, 0, 0};
stack.push_back(i0);
while (!stack.empty()) {
const StackItem i = stack.back();
stack.pop_back();
const RE *re = i.re;
if (re->type == RE::NIL) {
size = 0;
}
else if (re->type == RE::SYM || re->type == RE::TAG) {
size = 1;
}
else if (re->type == RE::ALT) {
if (i.succ == 0) {
// recurse into the left sub-RE
StackItem k = {re, 0, 1};
stack.push_back(k);
StackItem j = {re->alt.re1, 0, 0};
stack.push_back(j);
}
else if (i.succ == 1) {
// recurse into the right sub-RE
StackItem k = {re, size, 2};
stack.push_back(k);
StackItem j = {re->alt.re2, 0, 0};
stack.push_back(j);
}
else {
// both sub-RE visited, recursive return
size = i.size // left sub-RE (saved on stack)
+ size // right sub-RE (just visited by DFS)
+ 1; // additional state for alternative
}
}
else if (re->type == RE::CAT) {
if (i.succ == 0) {
// recurse into the left sub-RE
StackItem k = {re, 0, 1};
stack.push_back(k);
StackItem j = {re->cat.re1, 0, 0};
stack.push_back(j);
}
else if (i.succ == 1) {
// recurse into the right sub-RE
StackItem k = {re, size, 2};
stack.push_back(k);
StackItem j = {re->cat.re2, 0, 0};
stack.push_back(j);
}
else {
// both sub-RE visited, recursive return
size = i.size // left sub-RE (saved on stack)
+ size; // right sub-RE (just visited by DFS)
}
}
else if (re->type == RE::ITER) {
if (i.succ == 0) {
// recurse into the sub-RE
StackItem k = {re, 0, 1};
stack.push_back(k);
StackItem j = {re->iter.re, 0, 0};
stack.push_back(j);
}
else {
// sub-RE visited, recursive return
const uint32_t min = re->iter.min, max = re->iter.max;
size = max == AST::MANY
? size * min + 1
: size * max + (max - min);
}
}
}
DASSERT(stack.empty());
return size;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Limit maximum allowed NFA and DFA size.
Instead of failing with an out of memory exception or crashing with a
stack overflow, emit an error message and exit. This is a partial fix
for bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc",
where re2c hit stack overflow on a counted repetition regexp with high
upper bound.
The patch adds the following limits:
1. the number of NFA states
2. NFA depth (maximum length of a non-looping path from start to end)
3. the number of DFA states
3. total DFA size (sum total of all NFA substates in all DFA states)
There are tests for the first three limits, but not for the DFA size as
all examples that trigger this behavior take a long time to finish (a
few seconds), which increases test run time almost twice.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
GC_REFCOUNT(ht) = 1;
GC_TYPE_INFO(ht) = IS_ARRAY;
ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;
ht->nTableSize = zend_hash_check_size(nSize);
ht->nTableMask = HT_MIN_MASK;
HT_SET_DATA_ADDR(ht, &uninitialized_bucket);
ht->nNumUsed = 0;
ht->nNumOfElements = 0;
ht->nInternalPointer = HT_INVALID_IDX;
ht->nNextFreeElement = 0;
ht->pDestructor = pDestructor;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Fix #73832 - leave the table in a safe state if the size is too big.'</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: double ConvertAnyFormat(void * ValuePtr, int Format)
{
double Value;
Value = 0;
switch(Format){
case FMT_SBYTE: Value = *(signed char *)ValuePtr; break;
case FMT_BYTE: Value = *(uchar *)ValuePtr; break;
case FMT_USHORT: Value = Get16u(ValuePtr); break;
case FMT_ULONG: Value = Get32u(ValuePtr); break;
case FMT_URATIONAL:
case FMT_SRATIONAL:
{
int Num,Den;
Num = Get32s(ValuePtr);
Den = Get32s(4+(char *)ValuePtr);
if (Den == 0){
Value = 0;
}else{
if (Format == FMT_SRATIONAL){
Value = (double)Num/Den;
}else{
Value = (double)(unsigned)Num/(double)(unsigned)Den;
}
}
break;
}
case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break;
case FMT_SLONG: Value = Get32s(ValuePtr); break;
// Not sure if this is correct (never seen float used in Exif format)
case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break;
case FMT_DOUBLE: Value = *(double *)ValuePtr; break;
default:
ErrNonfatal("Illegal format code %d in Exif header",Format,0);
}
return Value;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'Make pointer range checks more consistent.
Also twiddle the unused floating point print code (not used in real exif files),
but fuzz testing hits it. New code is equivalent but doesn't cause bus error (don't understand why, but this is all a very bogus thing anyway, just trying to avoid fuzz testing hits.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static unsigned int nft_parse_register(const struct nlattr *attr)
{
unsigned int reg;
reg = ntohl(nla_get_be32(attr));
switch (reg) {
case NFT_REG_VERDICT...NFT_REG_4:
return reg * NFT_REG_SIZE / NFT_REG32_SIZE;
default:
return reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: validate registers coming from userspace.
Bail out in case userspace uses unsupported registers.
Fixes: 49499c3e6e18 ("netfilter: nf_tables: switch registers to 32 bit addressing")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: hermesBuiltinApply(void *, Runtime *runtime, NativeArgs args) {
GCScopeMarkerRAII marker{runtime};
Handle<Callable> fn = args.dyncastArg<Callable>(0);
if (LLVM_UNLIKELY(!fn)) {
return runtime->raiseTypeErrorForValue(
args.getArgHandle(0), " is not a function");
}
Handle<JSArray> argArray = args.dyncastArg<JSArray>(1);
if (LLVM_UNLIKELY(!argArray)) {
return runtime->raiseTypeError("args must be an array");
}
uint32_t len = JSArray::getLength(*argArray);
bool isConstructor = args.getArgCount() == 2;
MutableHandle<> thisVal{runtime};
if (isConstructor) {
auto thisValRes = Callable::createThisForConstruct(fn, runtime);
if (LLVM_UNLIKELY(thisValRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
thisVal = *thisValRes;
} else {
thisVal = args.getArg(2);
}
ScopedNativeCallFrame newFrame{
runtime, len, *fn, isConstructor, thisVal.getHermesValue()};
for (uint32_t i = 0; i < len; ++i) {
newFrame->getArgRef(i) = argArray->at(runtime, i);
}
return isConstructor ? Callable::construct(fn, runtime, thisVal)
: Callable::call(fn, runtime);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Added stack overflow check for hermes::vm:: hermesBuiltinApply
Summary: This adds a missing check for stack overflow.
Reviewed By: tmikov
Differential Revision: D20104955
fbshipit-source-id: 1f37e23d2e28ebcd3aa4176d134b8418e7059ebd'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void __init netlink_add_usersock_entry(void)
{
struct listeners *listeners;
int groups = 32;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
netlink_table_grab();
nl_table[NETLINK_USERSOCK].groups = groups;
rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
nl_table[NETLINK_USERSOCK].registered = 1;
netlink_table_ungrab();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'netlink: fix possible spoofing from non-root processes
Non-root user-space processes can send Netlink messages to other
processes that are well-known for being subscribed to Netlink
asynchronous notifications. This allows ilegitimate non-root
process to send forged messages to Netlink subscribers.
The userspace process usually verifies the legitimate origin in
two ways:
a) Socket credentials. If UID != 0, then the message comes from
some ilegitimate process and the message needs to be dropped.
b) Netlink portID. In general, portID == 0 means that the origin
of the messages comes from the kernel. Thus, discarding any
message not coming from the kernel.
However, ctnetlink sets the portID in event messages that has
been triggered by some user-space process, eg. conntrack utility.
So other processes subscribed to ctnetlink events, eg. conntrackd,
know that the event was triggered by some user-space action.
Neither of the two ways to discard ilegitimate messages coming
from non-root processes can help for ctnetlink.
This patch adds capability validation in case that dst_pid is set
in netlink_sendmsg(). This approach is aggressive since existing
applications using any Netlink bus to deliver messages between
two user-space processes will break. Note that the exception is
NETLINK_USERSOCK, since it is reserved for netlink-to-netlink
userspace communication.
Still, if anyone wants that his Netlink bus allows netlink-to-netlink
userspace, then they can set NL_NONROOT_SEND. However, by default,
I don't think it makes sense to allow to use NETLINK_ROUTE to
communicate two processes that are sending no matter what information
that is not related to link/neighbouring/routing. They should be using
NETLINK_USERSOCK instead for that.
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &epk,
const uint256 &esk,
const uint256 &pk_d,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingNotePlaintext ret;
ss >> ret;
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
assert(ss.size() == 0);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-755', 'CWE-787'], 'message': 'Ignore exceptions when deserializing note plaintexts'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13053/BGP: fix VPN route target bounds checks
decode_rt_routing_info() didn't check bounds before fetching 4 octets of
the origin AS field and could over-read the input buffer, put it right.
It also fetched the varying number of octets of the route target field
from 4 octets lower than the correct offset, put it right.
It also used the same temporary buffer explicitly through as_printf()
and implicitly through bgp_vpn_rd_print() so the end result of snprintf()
was not what was originally intended.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPML_TAGGED_TPM_PROPERTY_Unmarshal(TPML_TAGGED_TPM_PROPERTY *target, BYTE **buffer, INT32 *size)
{
TPM_RC rc = TPM_RC_SUCCESS;
UINT32 i;
if (rc == TPM_RC_SUCCESS) {
rc = UINT32_Unmarshal(&target->count, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
if (target->count > MAX_TPM_PROPERTIES) {
rc = TPM_RC_SIZE;
}
}
for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {
rc = TPMS_TAGGED_PROPERTY_Unmarshal(&target->tpmProperty[i], buffer, size);
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size
Reset the buffer size indicator in a TPM2B type of buffer after it failed
the test for the maximum buffer size it allows. This prevents having bad
buffer sizes in memory that can come to haunt us when writing the volatile
state for example.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TPML_ALG_PROPERTY_Unmarshal(TPML_ALG_PROPERTY *target, BYTE **buffer, INT32 *size)
{
TPM_RC rc = TPM_RC_SUCCESS;
UINT32 i;
if (rc == TPM_RC_SUCCESS) {
rc = UINT32_Unmarshal(&target->count, buffer, size);
}
if (rc == TPM_RC_SUCCESS) {
if (target->count > MAX_CAP_ALGS) {
rc = TPM_RC_SIZE;
}
}
for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {
rc = TPMS_ALG_PROPERTY_Unmarshal(&target->algProperties[i], buffer, size);
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size
Reset the buffer size indicator in a TPM2B type of buffer after it failed
the test for the maximum buffer size it allows. This prevents having bad
buffer sizes in memory that can come to haunt us when writing the volatile
state for example.
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)
{
GF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;
int i;
u32 tmp_strsize;
char *tmp_str;
GF_Err e;
ISOM_DECREASE_SIZE(ptr, 25)
ptr->bootstrapinfo_version = gf_bs_read_u32(bs);
ptr->profile = gf_bs_read_int(bs, 2);
ptr->live = gf_bs_read_int(bs, 1);
ptr->update = gf_bs_read_int(bs, 1);
ptr->reserved = gf_bs_read_int(bs, 4);
ptr->time_scale = gf_bs_read_u32(bs);
ptr->current_media_time = gf_bs_read_u64(bs);
ptr->smpte_time_code_offset = gf_bs_read_u64(bs);
i=0;
if (ptr->size<8) return GF_ISOM_INVALID_FILE;
tmp_strsize =(u32)ptr->size;
tmp_str = gf_malloc(sizeof(char)*tmp_strsize);
if (!tmp_str) return GF_OUT_OF_MEM;
memset(tmp_str, 0, sizeof(char)*tmp_strsize);
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->movie_identifier = gf_strdup(tmp_str);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->server_entry_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->server_entry_count; i++) {
int j=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[j] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[j])
break;
j++;
}
if (j) {
gf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);
}
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->quality_entry_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->quality_entry_count; i++) {
int j=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[j] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[j])
break;
j++;
}
if (j) {
gf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);
}
}
i=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->drm_data = gf_strdup(tmp_str);
}
i=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->meta_data = gf_strdup(tmp_str);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->segment_run_table_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->segment_run_table_count; i++) {
GF_AdobeSegmentRunTableBox *asrt = NULL;
e = gf_isom_box_parse((GF_Box **)&asrt, bs);
if (e) {
if (asrt) gf_isom_box_del((GF_Box*)asrt);
gf_free(tmp_str);
return e;
}
gf_list_add(ptr->segment_run_table_entries, asrt);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->fragment_run_table_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->fragment_run_table_count; i++) {
GF_AdobeFragmentRunTableBox *afrt = NULL;
e = gf_isom_box_parse((GF_Box **)&afrt, bs);
if (e) {
if (afrt) gf_isom_box_del((GF_Box*)afrt);
gf_free(tmp_str);
return e;
}
gf_list_add(ptr->fragment_run_table_entries, afrt);
}
gf_free(tmp_str);
return GF_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1733'</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 read_uids_guids(long long *table_start)
{
int res, i;
int bytes = SQUASHFS_ID_BYTES(sBlk.s.no_ids);
int indexes = SQUASHFS_ID_BLOCKS(sBlk.s.no_ids);
long long id_index_table[indexes];
TRACE("read_uids_guids: no_ids %d\n", sBlk.s.no_ids);
id_table = malloc(bytes);
if(id_table == NULL) {
ERROR("read_uids_guids: failed to allocate id table\n");
return FALSE;
}
res = read_fs_bytes(fd, sBlk.s.id_table_start,
SQUASHFS_ID_BLOCK_BYTES(sBlk.s.no_ids), id_index_table);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id index table\n");
return FALSE;
}
SQUASHFS_INSWAP_ID_BLOCKS(id_index_table, indexes);
/*
* id_index_table[0] stores the start of the compressed id blocks.
* This by definition is also the end of the previous filesystem
* table - this may be the exports table if it is present, or the
* fragments table if it isn't.
*/
*table_start = id_index_table[0];
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
res = read_block(fd, id_index_table[i], NULL, expected,
((char *) id_table) + i * SQUASHFS_METADATA_SIZE);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id table block"
"\n");
return FALSE;
}
}
SQUASHFS_INSWAP_INTS(id_table, sBlk.s.no_ids);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <phillip@squashfs.org.uk>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)
{
struct ndpi_packet_struct *packet = &flow->packet;
u_int16_t dport = 0, sport = 0;
NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n");
if(packet->tcp != NULL) {
sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);
NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n");
/* Oracle Database 9g,10g,11g */
if ((dport == 1521 || sport == 1521)
&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))
|| ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01))
&& (packet->payload[1] != 0x00)
&& (packet->payload[2] == 0x00)
&& (packet->payload[3] == 0x00)))) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
} else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&
packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&
packet->payload[3] == 0x00 ) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
}
} else {
NDPI_EXCLUDE_PROTO(ndpi_struct, flow);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Adds bound check in oracle protocol
Found by oss-fuzz
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=21780'</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 sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg,
struct fb_info *info,
int type, int fb_depth, unsigned long fb_size)
{
switch(cmd) {
case FBIOGTYPE: {
struct fbtype __user *f = (struct fbtype __user *) arg;
if (put_user(type, &f->fb_type) ||
__put_user(info->var.yres, &f->fb_height) ||
__put_user(info->var.xres, &f->fb_width) ||
__put_user(fb_depth, &f->fb_depth) ||
__put_user(0, &f->fb_cmsize) ||
__put_user(fb_size, &f->fb_cmsize))
return -EFAULT;
return 0;
}
case FBIOPUTCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
struct fb_cmap cmap;
u16 red, green, blue;
u8 red8, green8, blue8;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
int index, count, i;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
cmap.len = 1;
cmap.red = &red;
cmap.green = &green;
cmap.blue = &blue;
cmap.transp = NULL;
for (i = 0; i < count; i++) {
int err;
if (get_user(red8, &ured[i]) ||
get_user(green8, &ugreen[i]) ||
get_user(blue8, &ublue[i]))
return -EFAULT;
red = red8 << 8;
green = green8 << 8;
blue = blue8 << 8;
cmap.start = index + i;
err = fb_set_cmap(&cmap, info);
if (err)
return err;
}
return 0;
}
case FBIOGETCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
struct fb_cmap *cmap = &info->cmap;
int index, count, i;
u8 red, green, blue;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
if (index + count > cmap->len)
return -EINVAL;
for (i = 0; i < count; i++) {
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
if (put_user(red, &ured[i]) ||
put_user(green, &ugreen[i]) ||
put_user(blue, &ublue[i]))
return -EFAULT;
}
return 0;
}
default:
return -EINVAL;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'fbdev: Fixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in sbusfb_ioctl_helper().
Fixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in
sbusfb_ioctl_helper().
'index' is defined as an int in sbusfb_ioctl_helper().
We retrieve this from the user:
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
and then we use 'index' in the following way:
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
This is a classic information leak vulnerability. 'index' should be
an unsigned int, given its usage above.
This patch is straight-forward; it changes 'index' to unsigned int
in two switch-cases: FBIOGETCMAP_SPARC && FBIOPUTCMAP_SPARC.
This patch fixes CVE-2018-6412.
Signed-off-by: Peter Malone <peter.malone@gmail.com>
Acked-by: Mathieu Malaterre <malat@debian.org>
Signed-off-by: Bartlomiej Zolnierkiewicz <b.zolnierkie@samsung.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: sasl_process_packet(struct sasl_session *const restrict p, char *const restrict buf, const size_t len)
{
struct sasl_output_buf outbuf = {
.buf = NULL,
.len = 0,
.flags = ASASL_OUTFLAG_NONE,
};
enum sasl_mechanism_result rc;
bool have_responded = false;
if (! p->mechptr && ! len)
{
// First piece of data in a session is the name of the SASL mechanism that will be used
if (! (p->mechptr = sasl_mechanism_find(buf)))
{
(void) sasl_sts(p->uid, 'M', sasl_mechlist_string);
return false;
}
(void) sasl_sourceinfo_recreate(p);
if (p->mechptr->mech_start)
rc = p->mechptr->mech_start(p, &outbuf);
else
rc = ASASL_MRESULT_CONTINUE;
}
else if (! p->mechptr)
{
(void) slog(LG_DEBUG, "%s: session has no mechanism?", MOWGLI_FUNC_NAME);
return false;
}
else
{
rc = sasl_process_input(p, buf, len, &outbuf);
}
if (outbuf.buf && outbuf.len)
{
if (! sasl_process_output(p, &outbuf))
return false;
have_responded = true;
}
// Some progress has been made, reset timeout.
p->flags &= ~ASASL_SFLAG_MARKED_FOR_DELETION;
switch (rc)
{
case ASASL_MRESULT_CONTINUE:
{
if (! have_responded)
/* We want more data from the client, but we haven't sent any of our own.
* Send an empty string to advance the session. -- amdj
*/
(void) sasl_sts(p->uid, 'C', "+");
return true;
}
case ASASL_MRESULT_SUCCESS:
{
struct user *const u = user_find(p->uid);
struct myuser *const mu = sasl_user_can_login(p);
if (! mu)
{
if (u)
(void) notice(saslsvs->nick, u->nick, LOGIN_CANCELLED_STR);
return false;
}
/* If the user is already on the network, attempt to log them in immediately.
* Otherwise, we will log them in on introduction of user to network
*/
if (u && ! sasl_handle_login(p, u, mu))
return false;
return sasl_session_success(p, mu, (u != NULL));
}
case ASASL_MRESULT_FAILURE:
{
if (*p->authceid)
{
/* If we reach this, they failed SASL auth, so if they were trying
* to authenticate as a specific user, run bad_password() on them.
*/
struct myuser *const mu = myuser_find_uid(p->authceid);
if (! mu)
return false;
/* We might have more information to construct a more accurate sourceinfo now?
* TODO: Investigate whether this is necessary
*/
(void) sasl_sourceinfo_recreate(p);
(void) logcommand(p->si, CMDLOG_LOGIN, "failed LOGIN (%s) to \2%s\2 (bad password)",
p->mechptr->name, entity(mu)->name);
(void) bad_password(p->si, mu);
}
return false;
}
case ASASL_MRESULT_ERROR:
return false;
}
/* This is only here to keep GCC happy -- Clang can see that the switch() handles all legal
* values of the enumeration, and so knows that this function will never get to this point;
* GCC is dumb, and warns that control reaches the end of this non-void function. -- amdj
*/
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-288'], 'message': 'saslserv/main: Track EID we're pending login to
The existing model does not remember that we've sent a SVSLOGIN for a
given SASL session, and simply assumes that if a client is introduced
with a SASL session open, that session must have succeeded. The security
of this approach requires ircd to implicitly abort SASL sessions on
client registration.
This also means that if a client successfully authenticates and then
does something else its pending login is forgotten about, even though a
SVSLOGIN has been sent for it, and the ircd is going to think it's
logged in.
This change removes the dependency on ircd's state machine by keeping
explicit track of the pending login, i.e. the one we've most recently
sent a SVSLOGIN for. The next commit will ensure that a client abort
(even an implicit one) doesn't blow that information away.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* context) override {
// Here's the basic idea:
// Batch and depth dimension are independent from row and col dimension. And
// because FractionalAvgPool currently only support pooling along row and
// col, we can basically think of this 4D tensor backpropagation as
// operation of a series of 2D planes.
//
// For each element of a 'slice' (2D plane) of output_backprop, we need to
// figure out its contributors when doing FractionalAvgPool operation. This
// can be done based on row_pooling_sequence, col_pooling_seq and
// overlapping.
// Once we figure out the original contributors, we just need to evenly
// divide the value of this element among these contributors.
//
// Internally, we divide the out_backprop tensor and store it in a temporary
// tensor of double type. And cast it to the corresponding type.
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
ConstEigenMatrixMap;
typedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>
EigenDoubleMatrixMap;
// Grab the inputs.
const Tensor& orig_input_tensor_shape = context->input(0);
OP_REQUIRES(context,
orig_input_tensor_shape.dims() == 1 &&
orig_input_tensor_shape.NumElements() == 4,
errors::InvalidArgument("original input tensor shape must be"
"1-dimensional and 4 elements"));
const Tensor& out_backprop = context->input(1);
const Tensor& row_seq_tensor = context->input(2);
const Tensor& col_seq_tensor = context->input(3);
const int64_t out_batch = out_backprop.dim_size(0);
const int64_t out_rows = out_backprop.dim_size(1);
const int64_t out_cols = out_backprop.dim_size(2);
const int64_t out_depth = out_backprop.dim_size(3);
OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,
errors::InvalidArgument("Given out_backprop shape ",
out_backprop.shape().DebugString(),
", row_seq_tensor must have at least ",
out_rows + 1, " elements, but got ",
row_seq_tensor.NumElements()));
OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,
errors::InvalidArgument("Given out_backprop shape ",
out_backprop.shape().DebugString(),
", col_seq_tensor must have at least ",
out_cols + 1, " elements, but got ",
col_seq_tensor.NumElements()));
auto row_seq_tensor_flat = row_seq_tensor.flat<int64>();
auto col_seq_tensor_flat = col_seq_tensor.flat<int64>();
auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat<int64>();
const int64_t in_batch = orig_input_tensor_shape_flat(0);
const int64_t in_rows = orig_input_tensor_shape_flat(1);
const int64_t in_cols = orig_input_tensor_shape_flat(2);
const int64_t in_depth = orig_input_tensor_shape_flat(3);
constexpr int tensor_in_and_out_dims = 4;
// Transform orig_input_tensor_shape into TensorShape
TensorShape in_shape;
for (auto i = 0; i < tensor_in_and_out_dims; ++i) {
in_shape.AddDim(orig_input_tensor_shape_flat(i));
}
// Create intermediate in_backprop.
Tensor in_backprop_tensor_temp;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(
{0}, DataTypeToEnum<double>::v(), in_shape,
&in_backprop_tensor_temp));
in_backprop_tensor_temp.flat<double>().setZero();
// Transform 4D tensor to 2D matrix.
EigenDoubleMatrixMap in_backprop_tensor_temp_mat(
in_backprop_tensor_temp.flat<double>().data(), in_depth,
in_cols * in_rows * in_batch);
ConstEigenMatrixMap out_backprop_mat(out_backprop.flat<T>().data(),
out_depth,
out_cols * out_rows * out_batch);
// Loop through each element of out_backprop and evenly distribute the
// element to the corresponding pooling cell.
const int64_t in_max_row_index = in_rows - 1;
const int64_t in_max_col_index = in_cols - 1;
for (int64_t b = 0; b < out_batch; ++b) {
for (int64_t r = 0; r < out_rows; ++r) {
const int64_t in_row_start = row_seq_tensor_flat(r);
int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)
: row_seq_tensor_flat(r + 1) - 1;
in_row_end = std::min(in_row_end, in_max_row_index);
for (int64_t c = 0; c < out_cols; ++c) {
const int64_t in_col_start = col_seq_tensor_flat(c);
int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)
: col_seq_tensor_flat(c + 1) - 1;
in_col_end = std::min(in_col_end, in_max_col_index);
const int64_t num_elements_in_pooling_cell =
(in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);
const int64_t out_index = (b * out_rows + r) * out_cols + c;
// Now we can evenly distribute out_backprop(b, h, w, *) to
// in_backprop(b, hs:he, ws:we, *).
for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {
for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {
const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;
// Walk through each channel (depth).
for (int64_t d = 0; d < out_depth; ++d) {
const double out_backprop_element = static_cast<double>(
out_backprop_mat.coeffRef(d, out_index));
double& in_backprop_ref =
in_backprop_tensor_temp_mat.coeffRef(d, in_index);
in_backprop_ref +=
out_backprop_element / num_elements_in_pooling_cell;
}
}
}
}
}
}
// Depending on the type, cast double to type T.
Tensor* in_backprop_tensor = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 0, in_shape, &in_backprop_tensor));
auto in_backprop_tensor_flat = in_backprop_tensor->flat<T>();
auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat<double>();
for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {
in_backprop_tensor_flat(i) =
static_cast<T>(in_backprop_tensor_temp_flat(i));
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Validate dimensions of input tensor in `FractionalAvgPoolGrad`
PiperOrigin-RevId: 388286227
Change-Id: Ieb7566155e92acc8993a2212c76deacadc0edc8a'</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_bmap_alloc(struct inode *inode, const sector_t lblock,
struct buffer_head *bh_map, struct metapath *mp,
const unsigned int sheight,
const unsigned int height,
const unsigned int maxlen)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn, dblock = 0;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
unsigned dblks = 0;
unsigned ptrs_per_blk;
const unsigned end_of_metadata = height - 1;
int eob = 0;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(sheight < 1);
BUG_ON(dibh == NULL);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (height == sheight) {
struct buffer_head *bh;
/* Bottom indirect block exists, find unalloced extent size */
ptr = metapointer(end_of_metadata, mp);
bh = mp->mp_bh[end_of_metadata];
dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
&eob);
BUG_ON(dblks < 1);
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
if (height == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = height - sheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = height - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (height - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = sheight;
do {
int error;
n = blks - alloced;
error = gfs2_alloc_block(ip, &bn, &n);
if (error)
return error;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_add_unrevoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == height - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < height; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
/* Branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < height)
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
for (; i < height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == height)
state = ALLOC_DATA;
if (n == 0)
break;
/* Tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
dblock = bn;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
break;
}
} while ((state != ALLOC_DATA) || !dblock);
ip->i_height = height;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
map_bh(bh_map, inode->i_sb, dblock);
bh_map->b_size = dblks << inode->i_blkbits;
set_buffer_new(bh_map);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com>
Signed-off-by: Steven Whitehouse <swhiteho@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void HierarchicalBitmapRequester::PrepareForDecoding(void)
{
#if ACCUSOFT_CODE
UBYTE i;
BuildCommon();
if (m_ppDecodingMCU == NULL) {
m_ppDecodingMCU = (struct Line **)m_pEnviron->AllocMem(sizeof(struct Line *) * m_ucCount*8);
memset(m_ppDecodingMCU,0,sizeof(struct Line *) * m_ucCount * 8);
}
if (m_ppUpsampler == NULL) {
m_ppUpsampler = (class UpsamplerBase **)m_pEnviron->AllocMem(sizeof(class UpsamplerBase *) * m_ucCount);
memset(m_ppUpsampler,0,sizeof(class Upsampler *) * m_ucCount);
for(i = 0;i < m_ucCount;i++) {
class Component *comp = m_pFrame->ComponentOf(i);
UBYTE sx = comp->SubXOf();
UBYTE sy = comp->SubYOf();
if (sx > 1 || sy > 1) {
m_ppUpsampler[i] = UpsamplerBase::CreateUpsampler(m_pEnviron,sx,sy,
m_ulPixelWidth,m_ulPixelHeight,
m_pFrame->TablesOf()->isChromaCentered());
m_bSubsampling = true;
}
}
}
if (m_pLargestScale)
m_pLargestScale->PrepareForDecoding();
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'The code now checks for consistency of the MCU sizes across
hierarchical levels, and fails in case they are different.'</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 oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx,
struct oz_usb_hdr *usb_hdr, int len)
{
struct oz_data *data_hdr = (struct oz_data *)usb_hdr;
switch (data_hdr->format) {
case OZ_DATA_F_MULTIPLE_FIXED: {
struct oz_multiple_fixed *body =
(struct oz_multiple_fixed *)data_hdr;
u8 *data = body->data;
int n;
if (!body->unit_size)
break;
n = (len - sizeof(struct oz_multiple_fixed)+1)
/ body->unit_size;
while (n--) {
oz_hcd_data_ind(usb_ctx->hport, body->endpoint,
data, body->unit_size);
data += body->unit_size;
}
}
break;
case OZ_DATA_F_ISOC_FIXED: {
struct oz_isoc_fixed *body =
(struct oz_isoc_fixed *)data_hdr;
int data_len = len-sizeof(struct oz_isoc_fixed)+1;
int unit_size = body->unit_size;
u8 *data = body->data;
int count;
int i;
if (!unit_size)
break;
count = data_len/unit_size;
for (i = 0; i < count; i++) {
oz_hcd_data_ind(usb_ctx->hport,
body->endpoint, data, unit_size);
data += unit_size;
}
}
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'ozwpan: unchecked signed subtraction leads to DoS
The subtraction here was using a signed integer and did not have any
bounds checking at all. This commit adds proper bounds checking, made
easy by use of an unsigned integer. This way, a single packet won't be
able to remotely trigger a massive loop, locking up the system for a
considerable amount of time. A PoC follows below, which requires
ozprotocol.h from this module.
=-=-=-=-=-=
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <endian.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#define u8 uint8_t
#define u16 uint16_t
#define u32 uint32_t
#define __packed __attribute__((__packed__))
#include "ozprotocol.h"
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int hwaddr_aton(const char *txt, uint8_t *addr)
{
int i;
for (i = 0; i < 6; i++) {
int a, b;
a = hex2num(*txt++);
if (a < 0)
return -1;
b = hex2num(*txt++);
if (b < 0)
return -1;
*addr++ = (a << 4) | b;
if (i < 5 && *txt++ != ':')
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]);
return 1;
}
uint8_t dest_mac[6];
if (hwaddr_aton(argv[2], dest_mac)) {
fprintf(stderr, "Invalid mac address.\n");
return 1;
}
int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
if (sockfd < 0) {
perror("socket");
return 1;
}
struct ifreq if_idx;
int interface_index;
strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1);
if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) {
perror("SIOCGIFINDEX");
return 1;
}
interface_index = if_idx.ifr_ifindex;
if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) {
perror("SIOCGIFHWADDR");
return 1;
}
uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data;
struct {
struct ether_header ether_header;
struct oz_hdr oz_hdr;
struct oz_elt oz_elt;
struct oz_elt_connect_req oz_elt_connect_req;
struct oz_elt oz_elt2;
struct oz_multiple_fixed oz_multiple_fixed;
} __packed packet = {
.ether_header = {
.ether_type = htons(OZ_ETHERTYPE),
.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },
.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }
},
.oz_hdr = {
.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),
.last_pkt_num = 0,
.pkt_num = htole32(0)
},
.oz_elt = {
.type = OZ_ELT_CONNECT_REQ,
.length = sizeof(struct oz_elt_connect_req)
},
.oz_elt_connect_req = {
.mode = 0,
.resv1 = {0},
.pd_info = 0,
.session_id = 0,
.presleep = 0,
.ms_isoc_latency = 0,
.host_vendor = 0,
.keep_alive = 0,
.apps = htole16((1 << OZ_APPID_USB) | 0x1),
.max_len_div16 = 0,
.ms_per_isoc = 0,
.up_audio_buf = 0,
.ms_per_elt = 0
},
.oz_elt2 = {
.type = OZ_ELT_APP_DATA,
.length = sizeof(struct oz_multiple_fixed) - 3
},
.oz_multiple_fixed = {
.app_id = OZ_APPID_USB,
.elt_seq_num = 0,
.type = OZ_USB_ENDPOINT_DATA,
.endpoint = 0,
.format = OZ_DATA_F_MULTIPLE_FIXED,
.unit_size = 1,
.data = {0}
}
};
struct sockaddr_ll socket_address = {
.sll_ifindex = interface_index,
.sll_halen = ETH_ALEN,
.sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }
};
if (sendto(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {
perror("sendto");
return 1;
}
return 0;
}
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Acked-by: Dan Carpenter <dan.carpenter@oracle.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CarbonProtocolReader::skip(const FieldType ft) {
switch (ft) {
case FieldType::True:
case FieldType::False: {
break;
}
case FieldType::Int8: {
readRaw<int8_t>();
break;
}
case FieldType::Int16: {
readRaw<int16_t>();
break;
}
case FieldType::Int32: {
readRaw<int32_t>();
break;
}
case FieldType::Int64: {
readRaw<int64_t>();
break;
}
case FieldType::Double: {
readRaw<double>();
break;
}
case FieldType::Float: {
readRaw<float>();
break;
}
case FieldType::Binary: {
readRaw<std::string>();
break;
}
case FieldType::List: {
skipLinearContainer();
break;
}
case FieldType::Struct: {
readStructBegin();
while (true) {
const auto fieldType = readFieldHeader().first;
if (fieldType == FieldType::Stop) {
break;
}
skip(fieldType);
}
readStructEnd();
break;
}
case FieldType::Set: {
skipLinearContainer();
break;
}
case FieldType::Map: {
skipKVContainer();
break;
}
default: { break; }
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-522', 'CWE-674'], 'message': 'Attempt to make CarbonProtocolReader::skip tail recursive
Reviewed By: edenzik
Differential Revision: D17967570
fbshipit-source-id: fdc32e190a521349c7c8f4d6081902fa18eb0284'</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: __acquires(¤t->sighand->siglock)
{
bool gstop_done = false;
if (arch_ptrace_stop_needed(exit_code, info)) {
/*
* The arch code has something special to do before a
* ptrace stop. This is allowed to block, e.g. for faults
* on user stack pages. We can't keep the siglock while
* calling arch_ptrace_stop, so we must release it now.
* To preserve proper semantics, we must do this before
* any signal bookkeeping like checking group_stop_count.
* Meanwhile, a SIGKILL could come in before we retake the
* siglock. That must prevent us from sleeping in TASK_TRACED.
* So after regaining the lock, we must check for SIGKILL.
*/
spin_unlock_irq(¤t->sighand->siglock);
arch_ptrace_stop(exit_code, info);
spin_lock_irq(¤t->sighand->siglock);
if (sigkill_pending(current))
return;
}
/*
* We're committing to trapping. TRACED should be visible before
* TRAPPING is cleared; otherwise, the tracer might fail do_wait().
* Also, transition to TRACED and updates to ->jobctl should be
* atomic with respect to siglock and should be done after the arch
* hook as siglock is released and regrabbed across it.
*/
set_current_state(TASK_TRACED);
current->last_siginfo = info;
current->exit_code = exit_code;
/*
* If @why is CLD_STOPPED, we're trapping to participate in a group
* stop. Do the bookkeeping. Note that if SIGCONT was delievered
* across siglock relocks since INTERRUPT was scheduled, PENDING
* could be clear now. We act as if SIGCONT is received after
* TASK_TRACED is entered - ignore it.
*/
if (why == CLD_STOPPED && (current->jobctl & JOBCTL_STOP_PENDING))
gstop_done = task_participate_group_stop(current);
/* any trap clears pending STOP trap, STOP trap clears NOTIFY */
task_clear_jobctl_pending(current, JOBCTL_TRAP_STOP);
if (info && info->si_code >> 8 == PTRACE_EVENT_STOP)
task_clear_jobctl_pending(current, JOBCTL_TRAP_NOTIFY);
/* entering a trap, clear TRAPPING */
task_clear_jobctl_trapping(current);
spin_unlock_irq(¤t->sighand->siglock);
read_lock(&tasklist_lock);
if (may_ptrace_stop()) {
/*
* Notify parents of the stop.
*
* While ptraced, there are two parents - the ptracer and
* the real_parent of the group_leader. The ptracer should
* know about every stop while the real parent is only
* interested in the completion of group stop. The states
* for the two don't interact with each other. Notify
* separately unless they're gonna be duplicates.
*/
do_notify_parent_cldstop(current, true, why);
if (gstop_done && ptrace_reparented(current))
do_notify_parent_cldstop(current, false, why);
/*
* Don't want to allow preemption here, because
* sys_ptrace() needs this task to be inactive.
*
* XXX: implement read_unlock_no_resched().
*/
preempt_disable();
read_unlock(&tasklist_lock);
preempt_enable_no_resched();
freezable_schedule();
} else {
/*
* By the time we got the lock, our tracer went away.
* Don't drop the lock yet, another tracer may come.
*
* If @gstop_done, the ptracer went away between group stop
* completion and here. During detach, it would have set
* JOBCTL_STOP_PENDING on us and we'll re-enter
* TASK_STOPPED in do_signal_stop() on return, so notifying
* the real parent of the group stop completion is enough.
*/
if (gstop_done)
do_notify_parent_cldstop(current, false, why);
__set_current_state(TASK_RUNNING);
if (clear_code)
current->exit_code = 0;
read_unlock(&tasklist_lock);
}
/*
* We are back. Now reacquire the siglock before touching
* last_siginfo, so that we are sure to have synchronized with
* any signal-sending on another CPU that wants to examine it.
*/
spin_lock_irq(¤t->sighand->siglock);
current->last_siginfo = NULL;
/* LISTENING can be set only during STOP traps, clear it */
current->jobctl &= ~JOBCTL_LISTENING;
/*
* Queued signals ignored us while we were stopped for tracing.
* So check for any that we should take before resuming user mode.
* This sets TIF_SIGPENDING, but never clears it.
*/
recalc_sigpending_tsk(current);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-362'], 'message': 'ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL
putreg() assumes that the tracee is not running and pt_regs_access() can
safely play with its stack. However a killed tracee can return from
ptrace_stop() to the low-level asm code and do RESTORE_REST, this means
that debugger can actually read/modify the kernel stack until the tracee
does SAVE_REST again.
set_task_blockstep() can race with SIGKILL too and in some sense this
race is even worse, the very fact the tracee can be woken up breaks the
logic.
As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()
call, this ensures that nobody can ever wakeup the tracee while the
debugger looks at it. Not only this fixes the mentioned problems, we
can do some cleanups/simplifications in arch_ptrace() paths.
Probably ptrace_unfreeze_traced() needs more callers, for example it
makes sense to make the tracee killable for oom-killer before
access_process_vm().
While at it, add the comment into may_ptrace_stop() to explain why
ptrace_stop() still can't rely on SIGKILL and signal_pending_state().
Reported-by: Salman Qazi <sqazi@google.com>
Reported-by: Suleiman Souhlal <suleiman@google.com>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Oleg Nesterov <oleg@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p)
{
u_int length = h->len;
u_int caplen = h->caplen;
u_int family;
if (caplen < NULL_HDRLEN) {
ND_PRINT((ndo, "[|null]"));
return (NULL_HDRLEN);
}
memcpy((char *)&family, (const char *)p, sizeof(family));
/*
* This isn't necessarily in our host byte order; if this is
* a DLT_LOOP capture, it's in network byte order, and if
* this is a DLT_NULL capture from a machine with the opposite
* byte-order, it's in the opposite byte order from ours.
*
* If the upper 16 bits aren't all zero, assume it's byte-swapped.
*/
if ((family & 0xFFFF0000) != 0)
family = SWAPLONG(family);
if (ndo->ndo_eflag)
null_hdr_print(ndo, family, length);
length -= NULL_HDRLEN;
caplen -= NULL_HDRLEN;
p += NULL_HDRLEN;
switch (family) {
case BSD_AFNUM_INET:
ip_print(ndo, p, length);
break;
case BSD_AFNUM_INET6_BSD:
case BSD_AFNUM_INET6_FREEBSD:
case BSD_AFNUM_INET6_DARWIN:
ip6_print(ndo, p, length);
break;
case BSD_AFNUM_ISO:
isoclns_print(ndo, p, length, caplen);
break;
case BSD_AFNUM_APPLETALK:
atalk_print(ndo, p, length);
break;
case BSD_AFNUM_IPX:
ipx_print(ndo, p, length);
break;
default:
/* unknown AF_ value */
if (!ndo->ndo_eflag)
null_hdr_print(ndo, family, length + NULL_HDRLEN);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
return (NULL_HDRLEN);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).'</s> |
<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: isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).'</s> |
<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 SFS_Expression(ScriptParser *parser)
{
u32 val = gf_bs_read_int(parser->bs, NUMBITS_EXPR_TYPE);
if (parser->codec->LastError) return;
switch(val) {
case ET_CURVED_EXPR:
SFS_AddString(parser, "(");
SFS_CompoundExpression(parser);
SFS_AddString(parser, ")");
break;
case ET_NEGATIVE:
SFS_AddString(parser, "-");
SFS_Expression(parser);
break;
case ET_NOT:
SFS_AddString(parser, "!");
SFS_Expression(parser);
break;
case ET_ONESCOMP:
SFS_AddString(parser, "~");
SFS_Expression(parser);
break;
case ET_INCREMENT:
SFS_AddString(parser, "++");
SFS_Expression(parser);
break;
case ET_DECREMENT:
SFS_AddString(parser, "--");
SFS_Expression(parser);
break;
case ET_POST_INCREMENT:
SFS_Expression(parser);
SFS_AddString(parser, "++");
break;
case ET_POST_DECREMENT:
SFS_Expression(parser);
SFS_AddString(parser, "--");
break;
case ET_CONDTEST:
SFS_Expression(parser);
SFS_AddString(parser, " ? ");
SFS_Expression(parser);
SFS_AddString(parser, " : ");
SFS_Expression(parser);
break;
case ET_STRING:
SFS_AddString(parser, "'");
SFS_GetString(parser);
SFS_AddString(parser, "'");
break;
case ET_NUMBER:
SFS_GetNumber(parser);
break;
case ET_IDENTIFIER:
SFS_Identifier(parser);
break;
case ET_FUNCTION_CALL:
SFS_FunctionCall(parser);
break;
case ET_NEW:
SFS_NewObject(parser);
break;
case ET_OBJECT_MEMBER_ACCESS:
SFS_ObjectMemberAccess(parser);
break;
case ET_OBJECT_METHOD_CALL:
SFS_ObjectMethodCall(parser);
break;
case ET_ARRAY_DEREFERENCE:
SFS_ArrayDeref(parser);
break;
case ET_MULTIPLY:
SFS_Expression(parser);
SFS_AddString(parser, "*");
SFS_Expression(parser);
break;
case ET_DIVIDE:
SFS_Expression(parser);
SFS_AddString(parser, "/");
SFS_Expression(parser);
break;
case ET_MOD:
SFS_Expression(parser);
SFS_AddString(parser, "%");
SFS_Expression(parser);
break;
case ET_PLUS:
SFS_Expression(parser);
SFS_AddString(parser, "+");
SFS_Expression(parser);
break;
case ET_MINUS:
SFS_Expression(parser);
SFS_AddString(parser, "-");
SFS_Expression(parser);
break;
case ET_LSHIFT:
SFS_Expression(parser);
SFS_AddString(parser, "<<");
SFS_Expression(parser);
break;
case ET_RSHIFT:
SFS_Expression(parser);
SFS_AddString(parser, ">>");
SFS_Expression(parser);
break;
case ET_RSHIFTFILL:
SFS_Expression(parser);
SFS_AddString(parser, ">>>");
SFS_Expression(parser);
break;
case ET_AND:
SFS_Expression(parser);
SFS_AddString(parser, "&");
SFS_Expression(parser);
break;
case ET_XOR:
SFS_Expression(parser);
SFS_AddString(parser, "^");
SFS_Expression(parser);
break;
case ET_OR:
SFS_Expression(parser);
SFS_AddString(parser, "|");
SFS_Expression(parser);
break;
case ET_LT:
SFS_Expression(parser);
SFS_AddString(parser, "<");
SFS_Expression(parser);
break;
case ET_LE:
SFS_Expression(parser);
SFS_AddString(parser, "<=");
SFS_Expression(parser);
break;
case ET_GT:
SFS_Expression(parser);
SFS_AddString(parser, ">");
SFS_Expression(parser);
break;
case ET_GE:
SFS_Expression(parser);
SFS_AddString(parser, ">=");
SFS_Expression(parser);
break;
case ET_EQ:
SFS_Expression(parser);
SFS_AddString(parser, "==");
SFS_Expression(parser);
break;
case ET_NE:
SFS_Expression(parser);
SFS_AddString(parser, "!=");
SFS_Expression(parser);
break;
case ET_LAND:
SFS_Expression(parser);
SFS_AddString(parser, "&&");
SFS_Expression(parser);
break;
case ET_LOR:
SFS_Expression(parser);
SFS_AddString(parser, "||");
SFS_Expression(parser);
break;
case ET_ASSIGN:
SFS_Expression(parser);
SFS_AddString(parser, "=");
SFS_Expression(parser);
break;
case ET_PLUSEQ:
SFS_Expression(parser);
SFS_AddString(parser, "+=");
SFS_Expression(parser);
break;
case ET_MINUSEQ:
SFS_Expression(parser);
SFS_AddString(parser, "-=");
SFS_Expression(parser);
break;
case ET_MULTIPLYEQ:
SFS_Expression(parser);
SFS_AddString(parser, "*=");
SFS_Expression(parser);
break;
case ET_DIVIDEEQ:
SFS_Expression(parser);
SFS_AddString(parser, "/=");
SFS_Expression(parser);
break;
case ET_MODEQ:
SFS_Expression(parser);
SFS_AddString(parser, "%=");
SFS_Expression(parser);
break;
case ET_LSHIFTEQ:
SFS_Expression(parser);
SFS_AddString(parser, "<<=");
SFS_Expression(parser);
break;
case ET_RSHIFTEQ:
SFS_Expression(parser);
SFS_AddString(parser, ">>=");
SFS_Expression(parser);
break;
case ET_RSHIFTFILLEQ:
SFS_Expression(parser);
SFS_AddString(parser, ">>>=");
SFS_Expression(parser);
break;
case ET_ANDEQ:
SFS_Expression(parser);
SFS_AddString(parser, "&=");
SFS_Expression(parser);
break;
case ET_XOREQ:
SFS_Expression(parser);
SFS_AddString(parser, "^=");
SFS_Expression(parser);
break;
case ET_OREQ:
SFS_Expression(parser);
SFS_AddString(parser, "|=");
SFS_Expression(parser);
break;
case ET_BOOLEAN:
SFS_GetBoolean(parser);
break;
case ET_VAR:
SFS_AddString(parser, "var ");
SFS_Arguments(parser, GF_TRUE);
break;
case ET_FUNCTION_ASSIGN:
SFS_AddString(parser, "function ");
SFS_Arguments(parser, GF_FALSE);
SFS_StatementBlock(parser, GF_TRUE);
break;
default:
parser->codec->LastError = GF_NON_COMPLIANT_BITSTREAM;
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'fixed #2238'</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: NO_INLINE JsVar *jspeStatement() {
#ifdef USE_DEBUGGER
if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE &&
lex->tk!=';' &&
JSP_SHOULD_EXECUTE) {
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
jsiDebuggerLoop();
}
#endif
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL ||
lex->tk==LEX_REGEX ||
lex->tk==LEX_R_NEW ||
lex->tk==LEX_R_NULL ||
lex->tk==LEX_R_UNDEFINED ||
lex->tk==LEX_R_TRUE ||
lex->tk==LEX_R_FALSE ||
lex->tk==LEX_R_THIS ||
lex->tk==LEX_R_DELETE ||
lex->tk==LEX_R_TYPEOF ||
lex->tk==LEX_R_VOID ||
lex->tk==LEX_R_SUPER ||
lex->tk==LEX_PLUSPLUS ||
lex->tk==LEX_MINUSMINUS ||
lex->tk=='!' ||
lex->tk=='-' ||
lex->tk=='+' ||
lex->tk=='~' ||
lex->tk=='[' ||
lex->tk=='(') {
/* Execute a simple statement that only contains basic arithmetic... */
return jspeExpression();
} else if (lex->tk=='{') {
/* A block of code */
jspeBlock();
return 0;
} else if (lex->tk==';') {
/* Empty statement - to allow things like ;;; */
JSP_ASSERT_MATCH(';');
return 0;
} else if (lex->tk==LEX_R_VAR ||
lex->tk==LEX_R_LET ||
lex->tk==LEX_R_CONST) {
return jspeStatementVar();
} else if (lex->tk==LEX_R_IF) {
return jspeStatementIf();
} else if (lex->tk==LEX_R_DO) {
return jspeStatementDoOrWhile(false);
} else if (lex->tk==LEX_R_WHILE) {
return jspeStatementDoOrWhile(true);
} else if (lex->tk==LEX_R_FOR) {
return jspeStatementFor();
} else if (lex->tk==LEX_R_TRY) {
return jspeStatementTry();
} else if (lex->tk==LEX_R_RETURN) {
return jspeStatementReturn();
} else if (lex->tk==LEX_R_THROW) {
return jspeStatementThrow();
} else if (lex->tk==LEX_R_FUNCTION) {
return jspeStatementFunctionDecl(false/* function */);
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_R_CLASS) {
return jspeStatementFunctionDecl(true/* class */);
#endif
} else if (lex->tk==LEX_R_CONTINUE) {
JSP_ASSERT_MATCH(LEX_R_CONTINUE);
if (JSP_SHOULD_EXECUTE) {
if (!(execInfo.execute & EXEC_IN_LOOP))
jsExceptionHere(JSET_SYNTAXERROR, "CONTINUE statement outside of FOR or WHILE loop");
else
execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE;
}
} else if (lex->tk==LEX_R_BREAK) {
JSP_ASSERT_MATCH(LEX_R_BREAK);
if (JSP_SHOULD_EXECUTE) {
if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH)))
jsExceptionHere(JSET_SYNTAXERROR, "BREAK statement outside of SWITCH, FOR or WHILE loop");
else
execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK;
}
} else if (lex->tk==LEX_R_SWITCH) {
return jspeStatementSwitch();
} else if (lex->tk==LEX_R_DEBUGGER) {
JSP_ASSERT_MATCH(LEX_R_DEBUGGER);
#ifdef USE_DEBUGGER
if (JSP_SHOULD_EXECUTE)
jsiDebuggerLoop();
#endif
} else JSP_MATCH(LEX_EOF);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-674'], 'message': 'Fix stack overflow if interpreting a file full of '{' (fix #1448)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool inode_capable(const struct inode *inode, int cap)
{
struct user_namespace *ns = current_user_ns();
return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Serge Hallyn <serge.hallyn@ubuntu.com>
Cc: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Dave Chinner <david@fromorbit.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mark_trusted_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991'</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 decode_slice_header(H264Context *h, H264Context *h0)
{
unsigned int first_mb_in_slice;
unsigned int pps_id;
int ret;
unsigned int slice_type, tmp, i, j;
int last_pic_structure, last_pic_droppable;
int must_reinit;
int needs_reinit = 0;
int field_pic_flag, bottom_field_flag;
h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
first_mb_in_slice = get_ue_golomb_long(&h->gb);
if (first_mb_in_slice == 0) { // FIXME better field boundary detection
if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
field_end(h, 1);
}
h0->current_slice = 0;
if (!h0->first_field) {
if (h->cur_pic_ptr && !h->droppable) {
ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
h->picture_structure == PICT_BOTTOM_FIELD);
}
h->cur_pic_ptr = NULL;
}
}
slice_type = get_ue_golomb_31(&h->gb);
if (slice_type > 9) {
av_log(h->avctx, AV_LOG_ERROR,
"slice type %d too large at %d %d\n",
slice_type, h->mb_x, h->mb_y);
return AVERROR_INVALIDDATA;
}
if (slice_type > 4) {
slice_type -= 5;
h->slice_type_fixed = 1;
} else
h->slice_type_fixed = 0;
slice_type = golomb_to_pict_type[slice_type];
h->slice_type = slice_type;
h->slice_type_nos = slice_type & 3;
if (h->nal_unit_type == NAL_IDR_SLICE &&
h->slice_type_nos != AV_PICTURE_TYPE_I) {
av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
return AVERROR_INVALIDDATA;
}
// to make a few old functions happy, it's wrong though
h->pict_type = h->slice_type;
pps_id = get_ue_golomb(&h->gb);
if (pps_id >= MAX_PPS_COUNT) {
av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
return AVERROR_INVALIDDATA;
}
if (!h0->pps_buffers[pps_id]) {
av_log(h->avctx, AV_LOG_ERROR,
"non-existing PPS %u referenced\n",
pps_id);
return AVERROR_INVALIDDATA;
}
if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
av_log(h->avctx, AV_LOG_ERROR,
"PPS change from %d to %d forbidden\n",
h0->au_pps_id, pps_id);
return AVERROR_INVALIDDATA;
}
h->pps = *h0->pps_buffers[pps_id];
if (!h0->sps_buffers[h->pps.sps_id]) {
av_log(h->avctx, AV_LOG_ERROR,
"non-existing SPS %u referenced\n",
h->pps.sps_id);
return AVERROR_INVALIDDATA;
}
if (h->pps.sps_id != h->sps.sps_id ||
h->pps.sps_id != h->current_sps_id ||
h0->sps_buffers[h->pps.sps_id]->new) {
h->sps = *h0->sps_buffers[h->pps.sps_id];
if (h->mb_width != h->sps.mb_width ||
h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
h->cur_chroma_format_idc != h->sps.chroma_format_idc
)
needs_reinit = 1;
if (h->bit_depth_luma != h->sps.bit_depth_luma ||
h->chroma_format_idc != h->sps.chroma_format_idc) {
h->bit_depth_luma = h->sps.bit_depth_luma;
h->chroma_format_idc = h->sps.chroma_format_idc;
needs_reinit = 1;
}
if ((ret = h264_set_parameter_from_sps(h)) < 0)
return ret;
}
h->avctx->profile = ff_h264_get_profile(&h->sps);
h->avctx->level = h->sps.level_idc;
h->avctx->refs = h->sps.ref_frame_count;
must_reinit = (h->context_initialized &&
( 16*h->sps.mb_width != h->avctx->coded_width
|| 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
|| h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
|| h->cur_chroma_format_idc != h->sps.chroma_format_idc
|| av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
|| h->mb_width != h->sps.mb_width
|| h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
));
if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
must_reinit = 1;
h->mb_width = h->sps.mb_width;
h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
h->mb_num = h->mb_width * h->mb_height;
h->mb_stride = h->mb_width + 1;
h->b_stride = h->mb_width * 4;
h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
h->width = 16 * h->mb_width;
h->height = 16 * h->mb_height;
ret = init_dimensions(h);
if (ret < 0)
return ret;
if (h->sps.video_signal_type_present_flag) {
h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
: AVCOL_RANGE_MPEG;
if (h->sps.colour_description_present_flag) {
if (h->avctx->colorspace != h->sps.colorspace)
needs_reinit = 1;
h->avctx->color_primaries = h->sps.color_primaries;
h->avctx->color_trc = h->sps.color_trc;
h->avctx->colorspace = h->sps.colorspace;
}
}
if (h->context_initialized &&
(h->width != h->avctx->coded_width ||
h->height != h->avctx->coded_height ||
must_reinit ||
needs_reinit)) {
if (h != h0) {
av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
"slice %d\n", h0->current_slice + 1);
return AVERROR_INVALIDDATA;
}
flush_change(h);
if ((ret = get_pixel_format(h, 1)) < 0)
return ret;
h->avctx->pix_fmt = ret;
av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
"pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
if ((ret = h264_slice_header_init(h, 1)) < 0) {
av_log(h->avctx, AV_LOG_ERROR,
"h264_slice_header_init() failed\n");
return ret;
}
}
if (!h->context_initialized) {
if (h != h0) {
av_log(h->avctx, AV_LOG_ERROR,
"Cannot (re-)initialize context during parallel decoding.\n");
return AVERROR_PATCHWELCOME;
}
if ((ret = get_pixel_format(h, 1)) < 0)
return ret;
h->avctx->pix_fmt = ret;
if ((ret = h264_slice_header_init(h, 0)) < 0) {
av_log(h->avctx, AV_LOG_ERROR,
"h264_slice_header_init() failed\n");
return ret;
}
}
if (h == h0 && h->dequant_coeff_pps != pps_id) {
h->dequant_coeff_pps = pps_id;
init_dequant_tables(h);
}
h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
h->mb_mbaff = 0;
h->mb_aff_frame = 0;
last_pic_structure = h0->picture_structure;
last_pic_droppable = h0->droppable;
h->droppable = h->nal_ref_idc == 0;
if (h->sps.frame_mbs_only_flag) {
h->picture_structure = PICT_FRAME;
} else {
if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
return -1;
}
field_pic_flag = get_bits1(&h->gb);
if (field_pic_flag) {
bottom_field_flag = get_bits1(&h->gb);
h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
} else {
h->picture_structure = PICT_FRAME;
h->mb_aff_frame = h->sps.mb_aff;
}
}
h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
if (h0->current_slice != 0) {
if (last_pic_structure != h->picture_structure ||
last_pic_droppable != h->droppable) {
av_log(h->avctx, AV_LOG_ERROR,
"Changing field mode (%d -> %d) between slices is not allowed\n",
last_pic_structure, h->picture_structure);
h->picture_structure = last_pic_structure;
h->droppable = last_pic_droppable;
return AVERROR_INVALIDDATA;
} else if (!h0->cur_pic_ptr) {
av_log(h->avctx, AV_LOG_ERROR,
"unset cur_pic_ptr on slice %d\n",
h0->current_slice + 1);
return AVERROR_INVALIDDATA;
}
} else {
/* Shorten frame num gaps so we don't have to allocate reference
* frames just to throw them away */
if (h->frame_num != h->prev_frame_num) {
int unwrap_prev_frame_num = h->prev_frame_num;
int max_frame_num = 1 << h->sps.log2_max_frame_num;
if (unwrap_prev_frame_num > h->frame_num)
unwrap_prev_frame_num -= max_frame_num;
if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
if (unwrap_prev_frame_num < 0)
unwrap_prev_frame_num += max_frame_num;
h->prev_frame_num = unwrap_prev_frame_num;
}
}
/* See if we have a decoded first field looking for a pair...
* Here, we're using that to see if we should mark previously
* decode frames as "finished".
* We have to do that before the "dummy" in-between frame allocation,
* since that can modify h->cur_pic_ptr. */
if (h0->first_field) {
assert(h0->cur_pic_ptr);
assert(h0->cur_pic_ptr->f.buf[0]);
assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
/* Mark old field/frame as completed */
if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
last_pic_structure == PICT_BOTTOM_FIELD);
}
/* figure out if we have a complementary field pair */
if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
/* Previous field is unmatched. Don't display it, but let it
* remain for reference if marked as such. */
if (last_pic_structure != PICT_FRAME) {
ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
last_pic_structure == PICT_TOP_FIELD);
}
} else {
if (h0->cur_pic_ptr->frame_num != h->frame_num) {
/* This and previous field were reference, but had
* different frame_nums. Consider this field first in
* pair. Throw away previous field except for reference
* purposes. */
if (last_pic_structure != PICT_FRAME) {
ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
last_pic_structure == PICT_TOP_FIELD);
}
} else {
/* Second field in complementary pair */
if (!((last_pic_structure == PICT_TOP_FIELD &&
h->picture_structure == PICT_BOTTOM_FIELD) ||
(last_pic_structure == PICT_BOTTOM_FIELD &&
h->picture_structure == PICT_TOP_FIELD))) {
av_log(h->avctx, AV_LOG_ERROR,
"Invalid field mode combination %d/%d\n",
last_pic_structure, h->picture_structure);
h->picture_structure = last_pic_structure;
h->droppable = last_pic_droppable;
return AVERROR_INVALIDDATA;
} else if (last_pic_droppable != h->droppable) {
avpriv_request_sample(h->avctx,
"Found reference and non-reference fields in the same frame, which");
h->picture_structure = last_pic_structure;
h->droppable = last_pic_droppable;
return AVERROR_PATCHWELCOME;
}
}
}
}
while (h->frame_num != h->prev_frame_num && !h0->first_field &&
h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
h->frame_num, h->prev_frame_num);
if (!h->sps.gaps_in_frame_num_allowed_flag)
for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
h->last_pocs[i] = INT_MIN;
ret = h264_frame_start(h);
if (ret < 0) {
h0->first_field = 0;
return ret;
}
h->prev_frame_num++;
h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
h->cur_pic_ptr->frame_num = h->prev_frame_num;
ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
ret = ff_generate_sliding_window_mmcos(h, 1);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
return ret;
ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
return ret;
/* Error concealment: If a ref is missing, copy the previous ref
* in its place.
* FIXME: Avoiding a memcpy would be nice, but ref handling makes
* many assumptions about there being no actual duplicates.
* FIXME: This does not copy padding for out-of-frame motion
* vectors. Given we are concealing a lost frame, this probably
* is not noticeable by comparison, but it should be fixed. */
if (h->short_ref_count) {
if (prev) {
av_image_copy(h->short_ref[0]->f.data,
h->short_ref[0]->f.linesize,
(const uint8_t **)prev->f.data,
prev->f.linesize,
h->avctx->pix_fmt,
h->mb_width * 16,
h->mb_height * 16);
h->short_ref[0]->poc = prev->poc + 2;
}
h->short_ref[0]->frame_num = h->prev_frame_num;
}
}
/* See if we have a decoded first field looking for a pair...
* We're using that to see whether to continue decoding in that
* frame, or to allocate a new one. */
if (h0->first_field) {
assert(h0->cur_pic_ptr);
assert(h0->cur_pic_ptr->f.buf[0]);
assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
/* figure out if we have a complementary field pair */
if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
/* Previous field is unmatched. Don't display it, but let it
* remain for reference if marked as such. */
h0->cur_pic_ptr = NULL;
h0->first_field = FIELD_PICTURE(h);
} else {
if (h0->cur_pic_ptr->frame_num != h->frame_num) {
ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
h0->picture_structure==PICT_BOTTOM_FIELD);
/* This and the previous field had different frame_nums.
* Consider this field first in pair. Throw away previous
* one except for reference purposes. */
h0->first_field = 1;
h0->cur_pic_ptr = NULL;
} else {
/* Second field in complementary pair */
h0->first_field = 0;
}
}
} else {
/* Frame or first field in a potentially complementary pair */
h0->first_field = FIELD_PICTURE(h);
}
if (!FIELD_PICTURE(h) || h0->first_field) {
if (h264_frame_start(h) < 0) {
h0->first_field = 0;
return AVERROR_INVALIDDATA;
}
} else {
release_unused_pictures(h, 0);
}
/* Some macroblocks can be accessed before they're available in case
* of lost slices, MBAFF or threading. */
if (FIELD_PICTURE(h)) {
for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
} else {
memset(h->slice_table, -1,
(h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
}
h0->last_slice_type = -1;
}
if (h != h0 && (ret = clone_slice(h, h0)) < 0)
return ret;
/* can't be in alloc_tables because linesize isn't known there.
* FIXME: redo bipred weight to not require extra buffer? */
for (i = 0; i < h->slice_context_count; i++)
if (h->thread_context[i]) {
ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
if (ret < 0)
return ret;
}
h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
av_assert1(h->mb_num == h->mb_width * h->mb_height);
if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
first_mb_in_slice >= h->mb_num) {
av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
return AVERROR_INVALIDDATA;
}
h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
FIELD_OR_MBAFF_PICTURE(h);
if (h->picture_structure == PICT_BOTTOM_FIELD)
h->resync_mb_y = h->mb_y = h->mb_y + 1;
av_assert1(h->mb_y < h->mb_height);
if (h->picture_structure == PICT_FRAME) {
h->curr_pic_num = h->frame_num;
h->max_pic_num = 1 << h->sps.log2_max_frame_num;
} else {
h->curr_pic_num = 2 * h->frame_num + 1;
h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
}
if (h->nal_unit_type == NAL_IDR_SLICE)
get_ue_golomb(&h->gb); /* idr_pic_id */
if (h->sps.poc_type == 0) {
h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
h->delta_poc_bottom = get_se_golomb(&h->gb);
}
if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
h->delta_poc[0] = get_se_golomb(&h->gb);
if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
h->delta_poc[1] = get_se_golomb(&h->gb);
}
ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
if (h->pps.redundant_pic_cnt_present)
h->redundant_pic_count = get_ue_golomb(&h->gb);
ret = ff_set_ref_count(h);
if (ret < 0)
return ret;
if (slice_type != AV_PICTURE_TYPE_I &&
(h0->current_slice == 0 ||
slice_type != h0->last_slice_type ||
memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
ff_h264_fill_default_ref_list(h);
}
if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
ret = ff_h264_decode_ref_pic_list_reordering(h);
if (ret < 0) {
h->ref_count[1] = h->ref_count[0] = 0;
return ret;
}
}
if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
(h->pps.weighted_bipred_idc == 1 &&
h->slice_type_nos == AV_PICTURE_TYPE_B))
ff_pred_weight_table(h);
else if (h->pps.weighted_bipred_idc == 2 &&
h->slice_type_nos == AV_PICTURE_TYPE_B) {
implicit_weight_table(h, -1);
} else {
h->use_weight = 0;
for (i = 0; i < 2; i++) {
h->luma_weight_flag[i] = 0;
h->chroma_weight_flag[i] = 0;
}
}
// If frame-mt is enabled, only update mmco tables for the first slice
// in a field. Subsequent slices can temporarily clobber h->mmco_index
// or h->mmco, which will cause ref list mix-ups and decoding errors
// further down the line. This may break decoding if the first slice is
// corrupt, thus we only do this if frame-mt is enabled.
if (h->nal_ref_idc) {
ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
!(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
h0->current_slice == 0);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
return AVERROR_INVALIDDATA;
}
if (FRAME_MBAFF(h)) {
ff_h264_fill_mbaff_ref_list(h);
if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
implicit_weight_table(h, 0);
implicit_weight_table(h, 1);
}
}
if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
ff_h264_direct_dist_scale_factor(h);
ff_h264_direct_ref_list_init(h);
if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
tmp = get_ue_golomb_31(&h->gb);
if (tmp > 2) {
av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
return AVERROR_INVALIDDATA;
}
h->cabac_init_idc = tmp;
}
h->last_qscale_diff = 0;
tmp = h->pps.init_qp + get_se_golomb(&h->gb);
if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
return AVERROR_INVALIDDATA;
}
h->qscale = tmp;
h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
// FIXME qscale / qp ... stuff
if (h->slice_type == AV_PICTURE_TYPE_SP)
get_bits1(&h->gb); /* sp_for_switch_flag */
if (h->slice_type == AV_PICTURE_TYPE_SP ||
h->slice_type == AV_PICTURE_TYPE_SI)
get_se_golomb(&h->gb); /* slice_qs_delta */
h->deblocking_filter = 1;
h->slice_alpha_c0_offset = 52;
h->slice_beta_offset = 52;
if (h->pps.deblocking_filter_parameters_present) {
tmp = get_ue_golomb_31(&h->gb);
if (tmp > 2) {
av_log(h->avctx, AV_LOG_ERROR,
"deblocking_filter_idc %u out of range\n", tmp);
return AVERROR_INVALIDDATA;
}
h->deblocking_filter = tmp;
if (h->deblocking_filter < 2)
h->deblocking_filter ^= 1; // 1<->0
if (h->deblocking_filter) {
h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
if (h->slice_alpha_c0_offset > 104U ||
h->slice_beta_offset > 104U) {
av_log(h->avctx, AV_LOG_ERROR,
"deblocking filter parameters %d %d out of range\n",
h->slice_alpha_c0_offset, h->slice_beta_offset);
return AVERROR_INVALIDDATA;
}
}
}
if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
(h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
h->slice_type_nos != AV_PICTURE_TYPE_I) ||
(h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
h->slice_type_nos == AV_PICTURE_TYPE_B) ||
(h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
h->nal_ref_idc == 0))
h->deblocking_filter = 0;
if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
/* Cheat slightly for speed:
* Do not bother to deblock across slices. */
h->deblocking_filter = 2;
} else {
h0->max_contexts = 1;
if (!h0->single_decode_warning) {
av_log(h->avctx, AV_LOG_INFO,
"Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
h0->single_decode_warning = 1;
}
if (h != h0) {
av_log(h->avctx, AV_LOG_ERROR,
"Deblocking switched inside frame.\n");
return 1;
}
}
}
h->qp_thresh = 15 + 52 -
FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
FFMAX3(0,
h->pps.chroma_qp_index_offset[0],
h->pps.chroma_qp_index_offset[1]) +
6 * (h->sps.bit_depth_luma - 8);
h0->last_slice_type = slice_type;
memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
h->slice_num = ++h0->current_slice;
if (h->slice_num)
h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
&& h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
&& h->slice_num >= MAX_SLICES) {
//in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
}
for (j = 0; j < 2; j++) {
int id_list[16];
int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
for (i = 0; i < 16; i++) {
id_list[i] = 60;
if (j < h->list_count && i < h->ref_count[j] &&
h->ref_list[j][i].f.buf[0]) {
int k;
AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
for (k = 0; k < h->short_ref_count; k++)
if (h->short_ref[k]->f.buf[0]->buffer == buf) {
id_list[i] = k;
break;
}
for (k = 0; k < h->long_ref_count; k++)
if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
id_list[i] = h->short_ref_count + k;
break;
}
}
}
ref2frm[0] =
ref2frm[1] = -1;
for (i = 0; i < 16; i++)
ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
ref2frm[18 + 0] =
ref2frm[18 + 1] = -1;
for (i = 16; i < 48; i++)
ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
(h->ref_list[j][i].reference & 3);
}
if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
h->er.ref_count = h->ref_count[0];
h0->au_pps_id = pps_id;
h->sps.new =
h0->sps_buffers[h->pps.sps_id]->new = 0;
h->current_sps_id = h->pps.sps_id;
if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(h->avctx, AV_LOG_DEBUG,
"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
h->slice_num,
(h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
first_mb_in_slice,
av_get_picture_type_char(h->slice_type),
h->slice_type_fixed ? " fix" : "",
h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
pps_id, h->frame_num,
h->cur_pic_ptr->field_poc[0],
h->cur_pic_ptr->field_poc[1],
h->ref_count[0], h->ref_count[1],
h->qscale,
h->deblocking_filter,
h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
h->use_weight,
h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/h264: more completely check the loop filter parameters
Fixes out of array read
Fixes: caa65cc01655505705129b677189f036-signal_sigsegv_fdcc43_2681_cov_3043376737_PPH422I5_Panasonic_A.264
Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</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: __getcwd_generic (char *buf, size_t size)
{
/* Lengths of big file name components and entire file names, and a
deep level of file name nesting. These numbers are not upper
bounds; they are merely large values suitable for initial
allocations, designed to be large enough for most real-world
uses. */
enum
{
BIG_FILE_NAME_COMPONENT_LENGTH = 255,
BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
DEEP_NESTING = 100
};
#if HAVE_OPENAT_SUPPORT
int fd = AT_FDCWD;
bool fd_needs_closing = false;
#else
char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
char *dotlist = dots;
size_t dotsize = sizeof dots;
size_t dotlen = 0;
#endif
DIR *dirstream = NULL;
dev_t rootdev, thisdev;
ino_t rootino, thisino;
char *dir;
register char *dirp;
struct __stat64_t64 st;
size_t allocated = size;
size_t used;
#if HAVE_MINIMALLY_WORKING_GETCWD
/* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
this is much slower than the system getcwd (at least on
GNU/Linux). So trust the system getcwd's results unless they
look suspicious.
Use the system getcwd even if we have openat support, since the
system getcwd works even when a parent is unreadable, while the
openat-based approach does not.
But on AIX 5.1..7.1, the system getcwd is not even minimally
working: If the current directory name is slightly longer than
PATH_MAX, it omits the first directory component and returns
this wrong result with errno = 0. */
# undef getcwd
dir = getcwd_system (buf, size);
if (dir || (size && errno == ERANGE))
return dir;
/* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
internal magic that lets it work even if an ancestor directory is
inaccessible, which is better in many cases. So in this case try
again with a buffer that's almost always big enough. */
if (errno == EINVAL && buf == NULL && size == 0)
{
char big_buffer[BIG_FILE_NAME_LENGTH + 1];
dir = getcwd_system (big_buffer, sizeof big_buffer);
if (dir)
return strdup (dir);
}
# if HAVE_PARTLY_WORKING_GETCWD
/* The system getcwd works, except it sometimes fails when it
shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */
if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)
return NULL;
# endif
#endif
if (size == 0)
{
if (buf != NULL)
{
__set_errno (EINVAL);
return NULL;
}
allocated = BIG_FILE_NAME_LENGTH + 1;
}
if (buf == NULL)
{
dir = malloc (allocated);
if (dir == NULL)
return NULL;
}
else
dir = buf;
dirp = dir + allocated;
*--dirp = '\0';
if (__lstat64_time64 (".", &st) < 0)
goto lose;
thisdev = st.st_dev;
thisino = st.st_ino;
if (__lstat64_time64 ("/", &st) < 0)
goto lose;
rootdev = st.st_dev;
rootino = st.st_ino;
while (!(thisdev == rootdev && thisino == rootino))
{
struct dirent64 *d;
dev_t dotdev;
ino_t dotino;
bool mount_point;
int parent_status;
size_t dirroom;
size_t namlen;
bool use_d_ino = true;
/* Look at the parent directory. */
#if HAVE_OPENAT_SUPPORT
fd = __openat64 (fd, "..", O_RDONLY);
if (fd < 0)
goto lose;
fd_needs_closing = true;
parent_status = __fstat64_time64 (fd, &st);
#else
dotlist[dotlen++] = '.';
dotlist[dotlen++] = '.';
dotlist[dotlen] = '\0';
parent_status = __lstat64_time64 (dotlist, &st);
#endif
if (parent_status != 0)
goto lose;
if (dirstream && __closedir (dirstream) != 0)
{
dirstream = NULL;
goto lose;
}
/* Figure out if this directory is a mount point. */
dotdev = st.st_dev;
dotino = st.st_ino;
mount_point = dotdev != thisdev;
/* Search for the last directory. */
#if HAVE_OPENAT_SUPPORT
dirstream = __fdopendir (fd);
if (dirstream == NULL)
goto lose;
fd_needs_closing = false;
#else
dirstream = __opendir (dotlist);
if (dirstream == NULL)
goto lose;
dotlist[dotlen++] = '/';
#endif
for (;;)
{
/* Clear errno to distinguish EOF from error if readdir returns
NULL. */
__set_errno (0);
d = __readdir64 (dirstream);
/* When we've iterated through all directory entries without finding
one with a matching d_ino, rewind the stream and consider each
name again, but this time, using lstat. This is necessary in a
chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
.., ../.., ../../.., etc. all had the same device number, yet the
d_ino values for entries in / did not match those obtained
via lstat. */
if (d == NULL && errno == 0 && use_d_ino)
{
use_d_ino = false;
__rewinddir (dirstream);
d = __readdir64 (dirstream);
}
if (d == NULL)
{
if (errno == 0)
/* EOF on dirstream, which can mean e.g., that the current
directory has been removed. */
__set_errno (ENOENT);
goto lose;
}
if (d->d_name[0] == '.' &&
(d->d_name[1] == '\0' ||
(d->d_name[1] == '.' && d->d_name[2] == '\0')))
continue;
if (use_d_ino)
{
bool match = (MATCHING_INO (d, thisino) || mount_point);
if (! match)
continue;
}
{
int entry_status;
#if HAVE_OPENAT_SUPPORT
entry_status = __fstatat64_time64 (fd, d->d_name, &st,
AT_SYMLINK_NOFOLLOW);
#else
/* Compute size needed for this file name, or for the file
name ".." in the same directory, whichever is larger.
Room for ".." might be needed the next time through
the outer loop. */
size_t name_alloc = _D_ALLOC_NAMLEN (d);
size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
if (filesize < dotlen)
goto memory_exhausted;
if (dotsize < filesize)
{
/* My, what a deep directory tree you have, Grandma. */
size_t newsize = MAX (filesize, dotsize * 2);
size_t i;
if (newsize < dotsize)
goto memory_exhausted;
if (dotlist != dots)
free (dotlist);
dotlist = malloc (newsize);
if (dotlist == NULL)
goto lose;
dotsize = newsize;
i = 0;
do
{
dotlist[i++] = '.';
dotlist[i++] = '.';
dotlist[i++] = '/';
}
while (i < dotlen);
}
memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
entry_status = __lstat64_time64 (dotlist, &st);
#endif
/* We don't fail here if we cannot stat() a directory entry.
This can happen when (network) file systems fail. If this
entry is in fact the one we are looking for we will find
out soon as we reach the end of the directory without
having found anything. */
if (entry_status == 0 && S_ISDIR (st.st_mode)
&& st.st_dev == thisdev && st.st_ino == thisino)
break;
}
}
dirroom = dirp - dir;
namlen = _D_EXACT_NAMLEN (d);
if (dirroom <= namlen)
{
if (size != 0)
{
__set_errno (ERANGE);
goto lose;
}
else
{
char *tmp;
size_t oldsize = allocated;
allocated += MAX (allocated, namlen);
if (allocated < oldsize
|| ! (tmp = realloc (dir, allocated)))
goto memory_exhausted;
/* Move current contents up to the end of the buffer.
This is guaranteed to be non-overlapping. */
dirp = memcpy (tmp + allocated - (oldsize - dirroom),
tmp + dirroom,
oldsize - dirroom);
dir = tmp;
}
}
dirp -= namlen;
memcpy (dirp, d->d_name, namlen);
*--dirp = '/';
thisdev = dotdev;
thisino = dotino;
}
if (dirstream && __closedir (dirstream) != 0)
{
dirstream = NULL;
goto lose;
}
if (dirp == &dir[allocated - 1])
*--dirp = '/';
#if ! HAVE_OPENAT_SUPPORT
if (dotlist != dots)
free (dotlist);
#endif
used = dir + allocated - dirp;
memmove (dir, dirp, used);
if (size == 0)
/* Ensure that the buffer is only as large as necessary. */
buf = (used < allocated ? realloc (dir, used) : dir);
if (buf == NULL)
/* Either buf was NULL all along, or 'realloc' failed but
we still have the original string. */
buf = dir;
return buf;
memory_exhausted:
__set_errno (ENOMEM);
lose:
{
int save = errno;
if (dirstream)
__closedir (dirstream);
#if HAVE_OPENAT_SUPPORT
if (fd_needs_closing)
__close_nocancel_nostatus (fd);
#else
if (dotlist != dots)
free (dotlist);
#endif
if (buf == NULL)
free (dir);
__set_errno (save);
}
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'getcwd: Set errno to ERANGE for size == 1 (CVE-2021-3999)
No valid path returned by getcwd would fit into 1 byte, so reject the
size early and return NULL with errno set to ERANGE. This change is
prompted by CVE-2021-3999, which describes a single byte buffer
underflow and overflow when all of the following conditions are met:
- The buffer size (i.e. the second argument of getcwd) is 1 byte
- The current working directory is too long
- '/' is also mounted on the current working directory
Sequence of events:
- In sysdeps/unix/sysv/linux/getcwd.c, the syscall returns ENAMETOOLONG
because the linux kernel checks for name length before it checks
buffer size
- The code falls back to the generic getcwd in sysdeps/posix
- In the generic func, the buf[0] is set to '\0' on line 250
- this while loop on line 262 is bypassed:
while (!(thisdev == rootdev && thisino == rootino))
since the rootfs (/) is bind mounted onto the directory and the flow
goes on to line 449, where it puts a '/' in the byte before the
buffer.
- Finally on line 458, it moves 2 bytes (the underflowed byte and the
'\0') to the buf[0] and buf[1], resulting in a 1 byte buffer overflow.
- buf is returned on line 469 and errno is not set.
This resolves BZ #28769.
Reviewed-by: Andreas Schwab <schwab@linux-m68k.org>
Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
Signed-off-by: Qualys Security Advisory <qsa@qualys.com>
Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.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 install_relocation_handler(int num_cpus, size_t save_state_size)
{
struct smm_loader_params smm_params = {
.per_cpu_stack_size = CONFIG_SMM_STUB_STACK_SIZE,
.num_concurrent_stacks = num_cpus,
.per_cpu_save_state_size = save_state_size,
.num_concurrent_save_states = 1,
.handler = smm_do_relocation,
};
/* Allow callback to override parameters. */
if (mp_state.ops.adjust_smm_params != NULL)
mp_state.ops.adjust_smm_params(&smm_params, 0);
if (smm_setup_relocation_handler(&smm_params))
return -1;
adjust_smm_apic_id_map(&smm_params);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'cpu/x86/smm: Introduce SMM module loader version 2
Xeon-SP Skylake Scalable Processor can have 36 CPU threads (18 cores).
Current coreboot SMM is unable to handle more than ~32 CPU threads.
This patch introduces a version 2 of the SMM module loader which
addresses this problem. Having two versions of the SMM module loader
prevents any issues to current projects. Future Xeon-SP products will
be using this version of the SMM loader. Subsequent patches will
enable board specific functionality for Xeon-SP.
The reason for moving to version 2 is the state save area begins to
encroach upon the SMI handling code when more than 32 CPU threads are
in the system. This can cause system hangs, reboots, etc. The second
change is related to staggered entry points with simple near jumps. In
the current loader, near jumps will not work because the CPU is jumping
within the same code segment. In version 2, "far" address jumps are
necessary therefore protected mode must be enabled first. The SMM
layout and how the CPUs are staggered are documented in the code.
By making the modifications above, this allows the smm module loader to
expand easily as more CPU threads are added.
TEST=build for Tiogapass platform under OCP mainboard. Enable the
following in Kconfig.
select CPU_INTEL_COMMON_SMM
select SOC_INTEL_COMMON_BLOCK_SMM
select SMM_TSEG
select HAVE_SMI_HANDLER
select ACPI_INTEL_HARDWARE_SLEEP_VALUES
Debug console will show all 36 cores relocated. Further tested by
generating SMI's to port 0xb2 using XDP/ITP HW debugger and ensured all
cores entering and exiting SMM properly. In addition, booted to Linux
5.4 kernel and observed no issues during mp init.
Change-Id: I00a23a5f2a46110536c344254868390dbb71854c
Signed-off-by: Rocky Phagura <rphagura@fb.com>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/43684
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Angel Pons <th3fanbus@gmail.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ip6_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
register const struct ip6_hdr *ip6;
register int advance;
u_int len;
const u_char *ipend;
register const u_char *cp;
register u_int payload_len;
int nh;
int fragmented = 0;
u_int flow;
ip6 = (const struct ip6_hdr *)bp;
ND_TCHECK(*ip6);
if (length < sizeof (struct ip6_hdr)) {
ND_PRINT((ndo, "truncated-ip6 %u", length));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP6 "));
if (IP6_VERSION(ip6) != 6) {
ND_PRINT((ndo,"version error: %u != 6", IP6_VERSION(ip6)));
return;
}
payload_len = EXTRACT_16BITS(&ip6->ip6_plen);
len = payload_len + sizeof(struct ip6_hdr);
if (length < len)
ND_PRINT((ndo, "truncated-ip6 - %u bytes missing!",
len - length));
if (ndo->ndo_vflag) {
flow = EXTRACT_32BITS(&ip6->ip6_flow);
ND_PRINT((ndo, "("));
#if 0
/* rfc1883 */
if (flow & 0x0f000000)
ND_PRINT((ndo, "pri 0x%02x, ", (flow & 0x0f000000) >> 24));
if (flow & 0x00ffffff)
ND_PRINT((ndo, "flowlabel 0x%06x, ", flow & 0x00ffffff));
#else
/* RFC 2460 */
if (flow & 0x0ff00000)
ND_PRINT((ndo, "class 0x%02x, ", (flow & 0x0ff00000) >> 20));
if (flow & 0x000fffff)
ND_PRINT((ndo, "flowlabel 0x%05x, ", flow & 0x000fffff));
#endif
ND_PRINT((ndo, "hlim %u, next-header %s (%u) payload length: %u) ",
ip6->ip6_hlim,
tok2str(ipproto_values,"unknown",ip6->ip6_nxt),
ip6->ip6_nxt,
payload_len));
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
cp = (const u_char *)ip6;
advance = sizeof(struct ip6_hdr);
nh = ip6->ip6_nxt;
while (cp < ndo->ndo_snapend && advance > 0) {
cp += advance;
len -= advance;
if (cp == (const u_char *)(ip6 + 1) &&
nh != IPPROTO_TCP && nh != IPPROTO_UDP &&
nh != IPPROTO_DCCP && nh != IPPROTO_SCTP) {
ND_PRINT((ndo, "%s > %s: ", ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
}
switch (nh) {
case IPPROTO_HOPOPTS:
advance = hbhopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_DSTOPTS:
advance = dstopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_FRAGMENT:
advance = frag6_print(ndo, cp, (const u_char *)ip6);
if (advance < 0 || ndo->ndo_snapend <= cp + advance)
return;
nh = *cp;
fragmented = 1;
break;
case IPPROTO_MOBILITY_OLD:
case IPPROTO_MOBILITY:
/*
* XXX - we don't use "advance"; RFC 3775 says that
* the next header field in a mobility header
* should be IPPROTO_NONE, but speaks of
* the possiblity of a future extension in
* which payload can be piggybacked atop a
* mobility header.
*/
advance = mobility_print(ndo, cp, (const u_char *)ip6);
nh = *cp;
return;
case IPPROTO_ROUTING:
advance = rt6_print(ndo, cp, (const u_char *)ip6);
nh = *cp;
break;
case IPPROTO_SCTP:
sctp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_DCCP:
dccp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_TCP:
tcp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_UDP:
udp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_ICMPV6:
icmp6_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_AH:
advance = ah_print(ndo, cp);
nh = *cp;
break;
case IPPROTO_ESP:
{
int enh, padlen;
advance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen);
nh = enh & 0xff;
len -= padlen;
break;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, cp);
/*
* Either this has decompressed the payload and
* printed it, in which case there's nothing more
* to do, or it hasn't, in which case there's
* nothing more to do.
*/
advance = -1;
break;
}
case IPPROTO_PIM:
pim_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_OSPF:
ospf6_print(ndo, cp, len);
return;
case IPPROTO_IPV6:
ip6_print(ndo, cp, len);
return;
case IPPROTO_IPV4:
ip_print(ndo, cp, len);
return;
case IPPROTO_PGM:
pgm_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_GRE:
gre_print(ndo, cp, len);
return;
case IPPROTO_RSVP:
rsvp_print(ndo, cp, len);
return;
case IPPROTO_NONE:
ND_PRINT((ndo, "no next header"));
return;
default:
ND_PRINT((ndo, "ip-proto-%d %d", nh, len));
return;
}
}
return;
trunc:
ND_PRINT((ndo, "[|ip6]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12985/IPv6: Check for print routines returning -1 when running past the end.
rt6_print(), ah_print(), and esp_print() return -1 if they run up
against the end of the packet while dissecting; if that happens, stop
dissecting, don't try to fetch the next header value, because 1) *it*
might be past the end of the packet and 2) we won't be using it in any
case, as we'll be exiting the loop.
Also, change mobility_print() to return -1 if it runs up against the
end of the packet, and stop dissecting if it does so.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add tests using the capture files supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
size_t *out_len, const unsigned char *key,
size_t key_len)
{
PSKeyTransport_gost *pst = NULL;
EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
int pkey_nid = EVP_PKEY_base_id(pubk);
unsigned char expkeys[64];
EVP_PKEY *sec_key = NULL;
int ret = 0;
int mac_nid = NID_undef;
size_t mac_len = 0;
int exp_len = 0, iv_len = 0;
unsigned char *exp_buf = NULL;
int key_is_ephemeral = 0;
switch (data->cipher_nid) {
case NID_magma_ctr:
mac_nid = NID_magma_mac;
mac_len = 8;
iv_len = 4;
break;
case NID_grasshopper_ctr:
mac_nid = NID_grasshopper_mac;
mac_len = 16;
iv_len = 8;
break;
default:
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);
return -1;
break;
}
exp_len = key_len + mac_len;
exp_buf = OPENSSL_malloc(exp_len);
if (!exp_buf) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
return -1;
}
sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
if (!sec_key)
{
sec_key = EVP_PKEY_new();
if (sec_key == NULL) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );
goto err;
}
if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
|| !EVP_PKEY_copy_parameters(sec_key, pubk)
|| !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
GOST_R_ERROR_COMPUTING_SHARED_KEY);
goto err;
}
key_is_ephemeral = 1;
}
if (data->shared_ukm_size == 0) {
if (RAND_bytes(data->shared_ukm, 32) <= 0) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);
goto err;
}
data->shared_ukm_size = 32;
}
if (gost_keg(data->shared_ukm, pkey_nid,
EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
EVP_PKEY_get0(sec_key), expkeys) <= 0) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
goto err;
}
if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,
mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,
exp_buf, &exp_len) <= 0) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
goto err;
}
pst = PSKeyTransport_gost_new();
if (!pst) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
pst->ukm = ASN1_OCTET_STRING_new();
if (pst->ukm == NULL) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {
GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
goto err;
}
if ((*out_len = i2d_PSKeyTransport_gost(pst, out ? &out : NULL)) > 0)
ret = 1;
err:
OPENSSL_cleanse(expkeys, sizeof(expkeys));
if (key_is_ephemeral)
EVP_PKEY_free(sec_key);
PSKeyTransport_gost_free(pst);
OPENSSL_free(exp_buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Fix buffer overrun in creating key transport blob according to RFC 9189, 4.2.4.1
Resolves: CVE-2022-29242'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const TensorShape& input_shape = input.shape();
const int32_t input_dims = input_shape.dims();
const Tensor& segment_id = context->input(1);
const TensorShape& segment_id_shape = segment_id.shape();
const int32_t segment_dims = segment_id_shape.dims();
const Tensor& num_segments_tensor = context->input(2);
OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,
errors::InvalidArgument("Number of segments cannot be empty."));
auto num_segments = num_segments_tensor.scalar<NUM_SEGMENTS_TYPE>()();
OP_REQUIRES(
context, num_segments >= 0,
errors::InvalidArgument(
"Number of segments must be non-negative but got ", num_segments));
OP_REQUIRES(context, segment_dims != 0,
errors::InvalidArgument("Segment_id cannot have rank 0"));
OP_REQUIRES(
context, segment_dims <= input_dims,
errors::OutOfRange("Invalid segment_id rank ", segment_dims,
" for input with ", input_dims, " dimension(s)"));
for (auto i = 0; i < segment_dims; i++) {
OP_REQUIRES(
context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),
errors::InvalidArgument(
"Segment dimension is ", segment_id_shape.dim_size(i),
" while input dimension is ", input_dims, " in rank ", i));
}
// Making output tensor.
Tensor* output_tensor = nullptr;
TensorShape output_shape =
GetOutputShape(input_shape, segment_id_shape, num_segments);
OP_REQUIRES_OK(context, context->allocate_output("output", output_shape,
&output_tensor));
// Preparating flat tensors.
auto output_flat = output_tensor->flat<tstring>();
auto flat_segment_id = segment_id.flat<INDICES_TYPE>();
auto flat_input = input.flat<tstring>();
for (int i = 0; i < flat_segment_id.size(); i++) {
OP_REQUIRES(
context,
((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),
errors::InvalidArgument(
"segment_ids are not allowed to exceed num_segments or"
" to have negative values."));
}
int64_t big_stride;
int64_t small_stride;
std::tie(big_stride, small_stride) =
GetStrides<INDICES_TYPE>(input_shape, segment_id_shape);
auto relative_offset_set =
GetFlattenedRelativeOffsets<INDICES_TYPE>(small_stride, big_stride);
for (auto start_offset = 0; start_offset < big_stride; start_offset++) {
for (auto i = 0; i < relative_offset_set.size(); i++) {
auto output_index = start_offset + flat_segment_id(i) * big_stride;
auto offset = start_offset + relative_offset_set[i];
if (output_flat(output_index).length() != 0)
output_flat(output_index).append(separator_.c_str());
output_flat(output_index).append(flat_input(offset));
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fix tf.raw_ops.UnsortedSegmentJoin vulnerability with invalid num_segments.
Check that input is actually a scalar before treating it as such.
PiperOrigin-RevId: 445206880'</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 read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams &&
v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
v->needed = 0;
for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
i++) {
if (v->parent->streams[i]->discard < AVDISCARD_ALL)
v->needed = 1;
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
ret = open_input(c, v);
if (ret < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
return ret;
}
just_opened = 1;
}
ret = read_from_url(v, buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ffurl_close(v->input);
v->input = NULL;
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'avformat/hls: Fix DoS due to infinite loop
Fixes: loop.m3u
The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Previous version reviewed-by: Steven Liu <lingjiujianke@gmail.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
(cherry picked from commit 7ec414892ddcad88313848494b6fc5f437c9ca4a)
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
// TODO: check when we should use source_file
// The state machine consists of five registers
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
//eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx);
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'fix #6872'</s> |