text
stringlengths 478
483k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline int xrstor_state(struct xsave_struct *fx, u64 mask)
{
int err = 0;
u32 lmask = mask;
u32 hmask = mask >> 32;
/*
* Use xrstors to restore context if it is enabled. xrstors supports
* compacted format of xsave area which is not supported by xrstor.
*/
alternative_input(
"1: " XRSTOR,
"1: " XRSTORS,
X86_FEATURE_XSAVES,
"D" (fx), "m" (*fx), "a" (lmask), "d" (hmask)
: "memory");
asm volatile("2:\n"
xstate_fault
: "0" (0)
: "memory");
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'x86/fpu/xsaves: Fix improper uses of __ex_table
Commit:
f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area")
introduced alternative instructions for XSAVES/XRSTORS and commit:
adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time")
added support for the XSAVES/XRSTORS instructions at boot time.
Unfortunately both failed to properly protect them against faulting:
The 'xstate_fault' macro will use the closest label named '1'
backward and that ends up in the .altinstr_replacement section
rather than in .text. This means that the kernel will never find
in the __ex_table the .text address where this instruction might
fault, leading to serious problems if userspace manages to
trigger the fault.
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: Jamie Iles <[email protected]>
[ Improved the changelog, fixed some whitespace noise. ]
Acked-by: Borislav Petkov <[email protected]>
Acked-by: Linus Torvalds <[email protected]>
Cc: <[email protected]>
Cc: Allan Xavier <[email protected]>
Cc: H. Peter Anvin <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time")
Fixes: f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area")
Signed-off-by: Ingo Molnar <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 xrstor_state_booting(struct xsave_struct *fx, u64 mask)
{
u32 lmask = mask;
u32 hmask = mask >> 32;
int err = 0;
WARN_ON(system_state != SYSTEM_BOOTING);
if (boot_cpu_has(X86_FEATURE_XSAVES))
asm volatile("1:"XRSTORS"\n\t"
"2:\n\t"
: : "D" (fx), "m" (*fx), "a" (lmask), "d" (hmask)
: "memory");
else
asm volatile("1:"XRSTOR"\n\t"
"2:\n\t"
: : "D" (fx), "m" (*fx), "a" (lmask), "d" (hmask)
: "memory");
asm volatile(xstate_fault
: "0" (0)
: "memory");
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'x86/fpu/xsaves: Fix improper uses of __ex_table
Commit:
f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area")
introduced alternative instructions for XSAVES/XRSTORS and commit:
adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time")
added support for the XSAVES/XRSTORS instructions at boot time.
Unfortunately both failed to properly protect them against faulting:
The 'xstate_fault' macro will use the closest label named '1'
backward and that ends up in the .altinstr_replacement section
rather than in .text. This means that the kernel will never find
in the __ex_table the .text address where this instruction might
fault, leading to serious problems if userspace manages to
trigger the fault.
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: Jamie Iles <[email protected]>
[ Improved the changelog, fixed some whitespace noise. ]
Acked-by: Borislav Petkov <[email protected]>
Acked-by: Linus Torvalds <[email protected]>
Cc: <[email protected]>
Cc: Allan Xavier <[email protected]>
Cc: H. Peter Anvin <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time")
Fixes: f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area")
Signed-off-by: Ingo Molnar <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
{
if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
return; // server buffer
QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
#ifdef HAVE_QCA2
putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
#else
putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
#endif
emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Improve the message-splitting algorithm for PRIVMSG and CTCP
This introduces a new message splitting algorithm based on
QTextBoundaryFinder. It works by first starting with the entire
message to be sent, encoding it, and checking to see if it is over
the maximum message length. If it is, it uses QTBF to find the
word boundary most immediately preceding the maximum length. If no
suitable boundary can be found, it falls back to searching for
grapheme boundaries. It repeats this process until the entire
message has been sent.
Unlike what it replaces, the new splitting code is not recursive
and cannot cause stack overflows. Additionally, if it is unable
to split a string, it will give up gracefully and not crash the
core or cause a thread to run away.
This patch fixes two bugs. The first is garbage characters caused
by accidentally splitting the string in the middle of a multibyte
character. Since the new code splits at a character level instead
of a byte level, this will no longer be an issue. The second is
the core crash caused by sending an overlength CTCP query ("/me")
containing only multibyte characters. This bug was caused by the
old CTCP splitter using the byte index from lastParamOverrun() as
a character index for a QString.'</s> |
<s>[INST] Given the following code containing errors, provide 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 CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher)
{
// Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,
// so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted
// version is short enough...
// TODO: check out how the various possible encryption methods behave length-wise and make
// this clean by predicting the length of the crypted msg.
// For example, blowfish-ebc seems to create 8-char chunks.
static const char *cmd = "PRIVMSG";
static const char *splitter = " .,-!?";
int maxSplitPos = message.count();
int splitPos = maxSplitPos;
forever {
QByteArray crypted = message.left(splitPos);
bool isEncrypted = false;
#ifdef HAVE_QCA2
if (cipher && !cipher->key().isEmpty() && !message.isEmpty()) {
isEncrypted = cipher->encrypt(crypted);
}
#endif
int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted);
if (overrun) {
// In case this is not an encrypted msg, we can just cut off at the end
if (!isEncrypted)
maxSplitPos = message.count() - overrun;
splitPos = -1;
for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {
splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
}
if (splitPos <= 0 || splitPos > maxSplitPos)
splitPos = maxSplitPos;
maxSplitPos = splitPos - 1;
if (maxSplitPos <= 0) { // this should never happen, but who knows...
qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data());
return;
}
continue; // we never come back here for !encrypted!
}
// now we have found a valid splitpos (or didn't need to split to begin with)
putCmd(cmd, QList<QByteArray>() << target << crypted);
if (splitPos < message.count())
putPrivmsg(target, message.mid(splitPos), cipher);
return;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Improve the message-splitting algorithm for PRIVMSG and CTCP
This introduces a new message splitting algorithm based on
QTextBoundaryFinder. It works by first starting with the entire
message to be sent, encoding it, and checking to see if it is over
the maximum message length. If it is, it uses QTBF to find the
word boundary most immediately preceding the maximum length. If no
suitable boundary can be found, it falls back to searching for
grapheme boundaries. It repeats this process until the entire
message has been sent.
Unlike what it replaces, the new splitting code is not recursive
and cannot cause stack overflows. Additionally, if it is unable
to split a string, it will give up gracefully and not crash the
core or cause a thread to run away.
This patch fixes two bugs. The first is garbage characters caused
by accidentally splitting the string in the middle of a multibyte
character. Since the new code splits at a character level instead
of a byte level, this will no longer be an issue. The second is
the core crash caused by sending an overlength CTCP query ("/me")
containing only multibyte characters. This bug was caused by the
old CTCP splitter using the byte index from lastParamOverrun() as
a character index for a QString.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent)
: BasicHandler(parent),
_network(parent)
{
connect(this, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
network(), SLOT(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
connect(this, SIGNAL(putCmd(QString, const QList<QByteArray> &, const QByteArray &)),
network(), SLOT(putCmd(QString, const QList<QByteArray> &, const QByteArray &)));
connect(this, SIGNAL(putRawLine(const QByteArray &)),
network(), SLOT(putRawLine(const QByteArray &)));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Improve the message-splitting algorithm for PRIVMSG and CTCP
This introduces a new message splitting algorithm based on
QTextBoundaryFinder. It works by first starting with the entire
message to be sent, encoding it, and checking to see if it is over
the maximum message length. If it is, it uses QTBF to find the
word boundary most immediately preceding the maximum length. If no
suitable boundary can be found, it falls back to searching for
grapheme boundaries. It repeats this process until the entire
message has been sent.
Unlike what it replaces, the new splitting code is not recursive
and cannot cause stack overflows. Additionally, if it is unable
to split a string, it will give up gracefully and not crash the
core or cause a thread to run away.
This patch fixes two bugs. The first is garbage characters caused
by accidentally splitting the string in the middle of a multibyte
character. Since the new code splits at a character level instead
of a byte level, this will no longer be an issue. The second is
the core crash caused by sending an overlength CTCP query ("/me")
containing only multibyte characters. This bug was caused by the
old CTCP splitter using the byte index from lastParamOverrun() as
a character index for a QString.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static xmlNodePtr master_to_xml_int(encodePtr encode, zval *data, int style, xmlNodePtr parent, int check_class_map TSRMLS_DC)
{
xmlNodePtr node = NULL;
int add_type = 0;
/* Special handling of class SoapVar */
if (data &&
Z_TYPE_P(data) == IS_OBJECT &&
Z_OBJCE_P(data) == soap_var_class_entry) {
zval **ztype, **zdata, **zns, **zstype, **zname, **znamens;
encodePtr enc = NULL;
HashTable *ht = Z_OBJPROP_P(data);
if (zend_hash_find(ht, "enc_type", sizeof("enc_type"), (void **)&ztype) == FAILURE) {
soap_error0(E_ERROR, "Encoding: SoapVar has no 'enc_type' property");
}
if (zend_hash_find(ht, "enc_stype", sizeof("enc_stype"), (void **)&zstype) == SUCCESS) {
if (zend_hash_find(ht, "enc_ns", sizeof("enc_ns"), (void **)&zns) == SUCCESS) {
enc = get_encoder(SOAP_GLOBAL(sdl), Z_STRVAL_PP(zns), Z_STRVAL_PP(zstype));
} else {
zns = NULL;
enc = get_encoder_ex(SOAP_GLOBAL(sdl), Z_STRVAL_PP(zstype), Z_STRLEN_PP(zstype));
}
if (enc == NULL && SOAP_GLOBAL(typemap)) {
encodePtr *new_enc;
smart_str nscat = {0};
if (zns != NULL) {
smart_str_appendl(&nscat, Z_STRVAL_PP(zns), Z_STRLEN_PP(zns));
smart_str_appendc(&nscat, ':');
}
smart_str_appendl(&nscat, Z_STRVAL_PP(zstype), Z_STRLEN_PP(zstype));
smart_str_0(&nscat);
if (zend_hash_find(SOAP_GLOBAL(typemap), nscat.c, nscat.len + 1, (void**)&new_enc) == SUCCESS) {
enc = *new_enc;
}
smart_str_free(&nscat);
}
}
if (enc == NULL) {
enc = get_conversion(Z_LVAL_P(*ztype));
}
if (enc == NULL) {
enc = encode;
}
if (zend_hash_find(ht, "enc_value", sizeof("enc_value"), (void **)&zdata) == FAILURE) {
node = master_to_xml(enc, NULL, style, parent TSRMLS_CC);
} else {
node = master_to_xml(enc, *zdata, style, parent TSRMLS_CC);
}
if (style == SOAP_ENCODED || (SOAP_GLOBAL(sdl) && encode != enc)) {
if (zend_hash_find(ht, "enc_stype", sizeof("enc_stype"), (void **)&zstype) == SUCCESS) {
if (zend_hash_find(ht, "enc_ns", sizeof("enc_ns"), (void **)&zns) == SUCCESS) {
set_ns_and_type_ex(node, Z_STRVAL_PP(zns), Z_STRVAL_PP(zstype));
} else {
set_ns_and_type_ex(node, NULL, Z_STRVAL_PP(zstype));
}
}
}
if (zend_hash_find(ht, "enc_name", sizeof("enc_name"), (void **)&zname) == SUCCESS) {
xmlNodeSetName(node, BAD_CAST(Z_STRVAL_PP(zname)));
}
if (zend_hash_find(ht, "enc_namens", sizeof("enc_namens"), (void **)&znamens) == SUCCESS) {
xmlNsPtr nsp = encode_add_ns(node, Z_STRVAL_PP(znamens));
xmlSetNs(node, nsp);
}
} else {
if (check_class_map && SOAP_GLOBAL(class_map) && data &&
Z_TYPE_P(data) == IS_OBJECT &&
!Z_OBJPROP_P(data)->nApplyCount) {
zend_class_entry *ce = Z_OBJCE_P(data);
HashPosition pos;
zval **tmp;
char *type_name = NULL;
uint type_len;
ulong idx;
for (zend_hash_internal_pointer_reset_ex(SOAP_GLOBAL(class_map), &pos);
zend_hash_get_current_data_ex(SOAP_GLOBAL(class_map), (void **) &tmp, &pos) == SUCCESS;
zend_hash_move_forward_ex(SOAP_GLOBAL(class_map), &pos)) {
if (Z_TYPE_PP(tmp) == IS_STRING &&
ce->name_length == Z_STRLEN_PP(tmp) &&
zend_binary_strncasecmp(ce->name, ce->name_length, Z_STRVAL_PP(tmp), ce->name_length, ce->name_length) == 0 &&
zend_hash_get_current_key_ex(SOAP_GLOBAL(class_map), &type_name, &type_len, &idx, 0, &pos) == HASH_KEY_IS_STRING) {
/* TODO: namespace isn't stored */
encodePtr enc = NULL;
if (SOAP_GLOBAL(sdl)) {
enc = get_encoder(SOAP_GLOBAL(sdl), SOAP_GLOBAL(sdl)->target_ns, type_name);
if (!enc) {
enc = find_encoder_by_type_name(SOAP_GLOBAL(sdl), type_name);
}
}
if (enc) {
if (encode != enc && style == SOAP_LITERAL) {
add_type = 1;
}
encode = enc;
}
break;
}
}
}
if (encode == NULL) {
encode = get_conversion(UNKNOWN_TYPE);
}
if (SOAP_GLOBAL(typemap) && encode->details.type_str) {
smart_str nscat = {0};
encodePtr *new_enc;
if (encode->details.ns) {
smart_str_appends(&nscat, encode->details.ns);
smart_str_appendc(&nscat, ':');
}
smart_str_appends(&nscat, encode->details.type_str);
smart_str_0(&nscat);
if (zend_hash_find(SOAP_GLOBAL(typemap), nscat.c, nscat.len + 1, (void**)&new_enc) == SUCCESS) {
encode = *new_enc;
}
smart_str_free(&nscat);
}
if (encode->to_xml) {
node = encode->to_xml(&encode->details, data, style, parent TSRMLS_CC);
if (add_type) {
set_ns_and_type(node, &encode->details);
}
}
}
return node;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'</s> |
<s>[INST] Given the following code containing errors, provide 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 basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
zval **login, **password;
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS &&
!zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) {
unsigned char* buf;
int len;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
smart_str_appendc(&auth, ':');
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS) {
smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
}
smart_str_0(&auth);
buf = php_base64_encode((unsigned char*)auth.c, auth.len, &len);
smart_str_append_const(soap_headers, "Authorization: Basic ");
smart_str_appendl(soap_headers, (char*)buf, len);
smart_str_append_const(soap_headers, "\r\n");
efree(buf);
smart_str_free(&auth);
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'</s> |
<s>[INST] Given the following code containing errors, provide 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 proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
zval **login, **password;
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) {
unsigned char* buf;
int len;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
smart_str_appendc(&auth, ':');
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) {
smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
}
smart_str_0(&auth);
buf = php_base64_encode((unsigned char*)auth.c, auth.len, &len);
smart_str_append_const(soap_headers, "Proxy-Authorization: Basic ");
smart_str_appendl(soap_headers, (char*)buf, len);
smart_str_append_const(soap_headers, "\r\n");
efree(buf);
smart_str_free(&auth);
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'</s> |
<s>[INST] Given the following code containing errors, provide 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 bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev);
struct {
uint32_t addr;
uint32_t size;
} prd;
int l, len;
pci_dma_sglist_init(&s->sg, pci_dev,
s->nsector / (BMDMA_PAGE_SIZE / 512) + 1);
s->io_buffer_size = 0;
for(;;) {
if (bm->cur_prd_len == 0) {
/* end of table (with a fail safe of one page) */
if (bm->cur_prd_last ||
(bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE)
return s->io_buffer_size != 0;
pci_dma_read(pci_dev, bm->cur_addr, &prd, 8);
bm->cur_addr += 8;
prd.addr = le32_to_cpu(prd.addr);
prd.size = le32_to_cpu(prd.size);
len = prd.size & 0xfffe;
if (len == 0)
len = 0x10000;
bm->cur_prd_len = len;
bm->cur_prd_addr = prd.addr;
bm->cur_prd_last = (prd.size & 0x80000000);
}
l = bm->cur_prd_len;
if (l > 0) {
qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);
bm->cur_prd_addr += l;
bm->cur_prd_len -= l;
s->io_buffer_size += l;
}
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'ide: Correct handling of malformed/short PRDTs
This impacts both BMDMA and AHCI HBA interfaces for IDE.
Currently, we confuse the difference between a PRDT having
"0 bytes" and a PRDT having "0 complete sectors."
When we receive an incomplete sector, inconsistent error checking
leads to an infinite loop wherein the call succeeds, but it
didn't give us enough bytes -- leading us to re-call the
DMA chain over and over again. This leads to, in the BMDMA case,
leaked memory for short PRDTs, and infinite loops and resource
usage in the AHCI case.
The .prepare_buf() callback is reworked to return the number of
bytes that it successfully prepared. 0 is a valid, non-error
answer that means the table was empty and described no bytes.
-1 indicates an error.
Our current implementation uses the io_buffer in IDEState to
ultimately describe the size of a prepared scatter-gather list.
Even though the AHCI PRDT/SGList can be as large as 256GiB, the
AHCI command header limits transactions to just 4GiB. ATA8-ACS3,
however, defines the largest transaction to be an LBA48 command
that transfers 65,536 sectors. With a 512 byte sector size, this
is just 32MiB.
Since our current state structures use the int type to describe
the size of the buffer, and this state is migrated as int32, we
are limited to describing 2GiB buffer sizes unless we change the
migration protocol.
For this reason, this patch begins to unify the assertions in the
IDE pathways that the scatter-gather list provided by either the
AHCI PRDT or the PCI BMDMA PRDs can only describe, at a maximum,
2GiB. This should be resilient enough unless we need a sector
size that exceeds 32KiB.
Further, the likelihood of any guest operating system actually
attempting to transfer this much data in a single operation is
very slim.
To this end, the IDEState variables have been updated to more
explicitly clarify our maximum supported size. Callers to the
prepare_buf callback have been reworked to understand the new
return code, and all versions of the prepare_buf callback have
been adjusted accordingly.
Lastly, the ahci_populate_sglist helper, relied upon by the
AHCI implementation of .prepare_buf() as well as the PCI
implementation of the callback have had overflow assertions
added to help make clear the reasonings behind the various
type changes.
[Added %d -> %"PRId64" fix John sent because off_pos changed from int to
int64_t.
--Stefan]
Signed-off-by: John Snow <[email protected]>
Reviewed-by: Paolo Bonzini <[email protected]>
Message-id: [email protected]
Signed-off-by: Stefan Hajnoczi <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 ahci_dma_prepare_buf(IDEDMA *dma, int is_write)
{
AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
IDEState *s = &ad->port.ifs[0];
ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset);
s->io_buffer_size = s->sg.size;
DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
return s->io_buffer_size != 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'ide: Correct handling of malformed/short PRDTs
This impacts both BMDMA and AHCI HBA interfaces for IDE.
Currently, we confuse the difference between a PRDT having
"0 bytes" and a PRDT having "0 complete sectors."
When we receive an incomplete sector, inconsistent error checking
leads to an infinite loop wherein the call succeeds, but it
didn't give us enough bytes -- leading us to re-call the
DMA chain over and over again. This leads to, in the BMDMA case,
leaked memory for short PRDTs, and infinite loops and resource
usage in the AHCI case.
The .prepare_buf() callback is reworked to return the number of
bytes that it successfully prepared. 0 is a valid, non-error
answer that means the table was empty and described no bytes.
-1 indicates an error.
Our current implementation uses the io_buffer in IDEState to
ultimately describe the size of a prepared scatter-gather list.
Even though the AHCI PRDT/SGList can be as large as 256GiB, the
AHCI command header limits transactions to just 4GiB. ATA8-ACS3,
however, defines the largest transaction to be an LBA48 command
that transfers 65,536 sectors. With a 512 byte sector size, this
is just 32MiB.
Since our current state structures use the int type to describe
the size of the buffer, and this state is migrated as int32, we
are limited to describing 2GiB buffer sizes unless we change the
migration protocol.
For this reason, this patch begins to unify the assertions in the
IDE pathways that the scatter-gather list provided by either the
AHCI PRDT or the PCI BMDMA PRDs can only describe, at a maximum,
2GiB. This should be resilient enough unless we need a sector
size that exceeds 32KiB.
Further, the likelihood of any guest operating system actually
attempting to transfer this much data in a single operation is
very slim.
To this end, the IDEState variables have been updated to more
explicitly clarify our maximum supported size. Callers to the
prepare_buf callback have been reworked to understand the new
return code, and all versions of the prepare_buf callback have
been adjusted accordingly.
Lastly, the ahci_populate_sglist helper, relied upon by the
AHCI implementation of .prepare_buf() as well as the PCI
implementation of the callback have had overflow assertions
added to help make clear the reasonings behind the various
type changes.
[Added %d -> %"PRId64" fix John sent because off_pos changed from int to
int64_t.
--Stefan]
Signed-off-by: John Snow <[email protected]>
Reviewed-by: Paolo Bonzini <[email protected]>
Message-id: [email protected]
Signed-off-by: Stefan Hajnoczi <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_name_request(enum request_types request_type,
const char *name, const char *domain_name,
struct berval **berval)
{
int ret;
char *fq_name = NULL;
struct passwd pwd;
struct passwd *pwd_result = NULL;
struct group grp;
struct group *grp_result = NULL;
char *sid_str = NULL;
enum sss_id_type id_type;
size_t buf_len;
char *buf = NULL;
struct sss_nss_kv *kv_list = NULL;
ret = asprintf(&fq_name, "%s%c%s", name, SSSD_DOMAIN_SEPARATOR,
domain_name);
if (ret == -1) {
ret = LDAP_OPERATIONS_ERROR;
fq_name = NULL; /* content is undefined according to
asprintf(3) */
goto done;
}
if (request_type == REQ_SIMPLE) {
ret = sss_nss_getsidbyname(fq_name, &sid_str, &id_type);
if (ret != 0) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
ret = pack_ber_sid(sid_str, berval);
} else {
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
goto done;
}
ret = getpwnam_r(fq_name, &pwd, buf, buf_len, &pwd_result);
if (ret != 0) {
/* according to the man page there are a couple of error codes
* which can indicate that the user was not found. To be on the
* safe side we fail back to the group lookup on all errors. */
pwd_result = NULL;
}
if (pwd_result != NULL) {
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
} else { /* no user entry found */
ret = getgrnam_r(fq_name, &grp, buf, buf_len, &grp_result);
if (ret != 0) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (grp_result == NULL) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_GID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP
: RESP_GROUP_MEMBERS),
domain_name, grp.gr_name, grp.gr_gid,
grp.gr_mem, kv_list, berval);
}
}
done:
sss_nss_free_kv(kv_list);
free(fq_name);
free(sid_str);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls
The getXXYYY_r() calls require a buffer to store the variable data of
the passwd and group structs. If the provided buffer is too small ERANGE
is returned and the caller can try with a larger buffer again.
Cmocka/cwrap based unit-tests for get*_r_wrapper() are added.
Resolves https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_sid_request(enum request_types request_type, const char *sid,
struct berval **berval)
{
int ret;
struct passwd pwd;
struct passwd *pwd_result = NULL;
struct group grp;
struct group *grp_result = NULL;
char *domain_name = NULL;
char *fq_name = NULL;
char *object_name = NULL;
char *sep;
size_t buf_len;
char *buf = NULL;
enum sss_id_type id_type;
struct sss_nss_kv *kv_list = NULL;
ret = sss_nss_getnamebysid(sid, &fq_name, &id_type);
if (ret != 0) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
sep = strchr(fq_name, SSSD_DOMAIN_SEPARATOR);
if (sep == NULL) {
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
object_name = strndup(fq_name, (sep - fq_name));
domain_name = strdup(sep + 1);
if (object_name == NULL || domain_name == NULL) {
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
if (request_type == REQ_SIMPLE) {
ret = pack_ber_name(domain_name, object_name, berval);
goto done;
}
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
goto done;
}
switch(id_type) {
case SSS_ID_TYPE_UID:
case SSS_ID_TYPE_BOTH:
ret = getpwnam_r(fq_name, &pwd, buf, buf_len, &pwd_result);
if (ret != 0) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (pwd_result == NULL) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
break;
case SSS_ID_TYPE_GID:
ret = getgrnam_r(fq_name, &grp, buf, buf_len, &grp_result);
if (ret != 0) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (grp_result == NULL) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_GID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP
: RESP_GROUP_MEMBERS),
domain_name, grp.gr_name, grp.gr_gid,
grp.gr_mem, kv_list, berval);
break;
default:
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
done:
sss_nss_free_kv(kv_list);
free(fq_name);
free(object_name);
free(domain_name);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls
The getXXYYY_r() calls require a buffer to store the variable data of
the passwd and group structs. If the provided buffer is too small ERANGE
is returned and the caller can try with a larger buffer again.
Cmocka/cwrap based unit-tests for get*_r_wrapper() are added.
Resolves https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_uid_request(enum request_types request_type, uid_t uid,
const char *domain_name, struct berval **berval)
{
int ret;
struct passwd pwd;
struct passwd *pwd_result = NULL;
char *sid_str = NULL;
enum sss_id_type id_type;
size_t buf_len;
char *buf = NULL;
struct sss_nss_kv *kv_list = NULL;
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
return ret;
}
if (request_type == REQ_SIMPLE) {
ret = sss_nss_getsidbyid(uid, &sid_str, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
ret = pack_ber_sid(sid_str, berval);
} else {
ret = getpwuid_r(uid, &pwd, buf, buf_len, &pwd_result);
if (ret != 0) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (pwd_result == NULL) {
ret = LDAP_NO_SUCH_OBJECT;
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
}
done:
sss_nss_free_kv(kv_list);
free(sid_str);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls
The getXXYYY_r() calls require a buffer to store the variable data of
the passwd and group structs. If the provided buffer is too small ERANGE
is returned and the caller can try with a larger buffer again.
Cmocka/cwrap based unit-tests for get*_r_wrapper() are added.
Resolves https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_uid_request(enum request_types request_type, uid_t uid,
const char *domain_name, struct berval **berval)
{
int ret;
struct passwd pwd;
char *sid_str = NULL;
enum sss_id_type id_type;
size_t buf_len;
char *buf = NULL;
struct sss_nss_kv *kv_list = NULL;
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
return ret;
}
if (request_type == REQ_SIMPLE) {
ret = sss_nss_getsidbyid(uid, &sid_str, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
ret = pack_ber_sid(sid_str, berval);
} else {
ret = getpwuid_r_wrapper(MAX_BUF, uid, &pwd, &buf, &buf_len);
if (ret != 0) {
if (ret == ENOMEM || ret == ERANGE) {
ret = LDAP_OPERATIONS_ERROR;
} else {
ret = LDAP_NO_SUCH_OBJECT;
}
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
}
done:
sss_nss_free_kv(kv_list);
free(sid_str);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable
The get*_r_wrapper() calls expect a maximum buffer size to avoid memory
shortage if too many threads try to allocate buffers e.g. for large
groups. With this patch this size can be configured by setting
ipaExtdomMaxNssBufSize in the plugin config object
cn=ipa_extdom_extop,cn=plugins,cn=config.
Related to https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_sid_request(enum request_types request_type, const char *sid,
struct berval **berval)
{
int ret;
struct passwd pwd;
struct group grp;
char *domain_name = NULL;
char *fq_name = NULL;
char *object_name = NULL;
char *sep;
size_t buf_len;
char *buf = NULL;
enum sss_id_type id_type;
struct sss_nss_kv *kv_list = NULL;
ret = sss_nss_getnamebysid(sid, &fq_name, &id_type);
if (ret != 0) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
sep = strchr(fq_name, SSSD_DOMAIN_SEPARATOR);
if (sep == NULL) {
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
object_name = strndup(fq_name, (sep - fq_name));
domain_name = strdup(sep + 1);
if (object_name == NULL || domain_name == NULL) {
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
if (request_type == REQ_SIMPLE) {
ret = pack_ber_name(domain_name, object_name, berval);
goto done;
}
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
goto done;
}
switch(id_type) {
case SSS_ID_TYPE_UID:
case SSS_ID_TYPE_BOTH:
ret = getpwnam_r_wrapper(MAX_BUF, fq_name, &pwd, &buf, &buf_len);
if (ret != 0) {
if (ret == ENOMEM || ret == ERANGE) {
ret = LDAP_OPERATIONS_ERROR;
} else {
ret = LDAP_NO_SUCH_OBJECT;
}
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
break;
case SSS_ID_TYPE_GID:
ret = getgrnam_r_wrapper(MAX_BUF, fq_name, &grp, &buf, &buf_len);
if (ret != 0) {
if (ret == ENOMEM || ret == ERANGE) {
ret = LDAP_OPERATIONS_ERROR;
} else {
ret = LDAP_NO_SUCH_OBJECT;
}
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_GID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP
: RESP_GROUP_MEMBERS),
domain_name, grp.gr_name, grp.gr_gid,
grp.gr_mem, kv_list, berval);
break;
default:
ret = LDAP_OPERATIONS_ERROR;
goto done;
}
done:
sss_nss_free_kv(kv_list);
free(fq_name);
free(object_name);
free(domain_name);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable
The get*_r_wrapper() calls expect a maximum buffer size to avoid memory
shortage if too many threads try to allocate buffers e.g. for large
groups. With this patch this size can be configured by setting
ipaExtdomMaxNssBufSize in the plugin config object
cn=ipa_extdom_extop,cn=plugins,cn=config.
Related to https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_name_request(enum request_types request_type,
const char *name, const char *domain_name,
struct berval **berval)
{
int ret;
char *fq_name = NULL;
struct passwd pwd;
struct group grp;
char *sid_str = NULL;
enum sss_id_type id_type;
size_t buf_len;
char *buf = NULL;
struct sss_nss_kv *kv_list = NULL;
ret = asprintf(&fq_name, "%s%c%s", name, SSSD_DOMAIN_SEPARATOR,
domain_name);
if (ret == -1) {
ret = LDAP_OPERATIONS_ERROR;
fq_name = NULL; /* content is undefined according to
asprintf(3) */
goto done;
}
if (request_type == REQ_SIMPLE) {
ret = sss_nss_getsidbyname(fq_name, &sid_str, &id_type);
if (ret != 0) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
ret = pack_ber_sid(sid_str, berval);
} else {
ret = get_buffer(&buf_len, &buf);
if (ret != LDAP_SUCCESS) {
goto done;
}
ret = getpwnam_r_wrapper(MAX_BUF, fq_name, &pwd, &buf, &buf_len);
if (ret == 0) {
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_UID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER
: RESP_USER_GROUPLIST),
domain_name, pwd.pw_name, pwd.pw_uid,
pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,
pwd.pw_shell, kv_list, berval);
} else if (ret == ENOMEM || ret == ERANGE) {
ret = LDAP_OPERATIONS_ERROR;
goto done;
} else { /* no user entry found */
/* according to the getpwnam() man page there are a couple of
* error codes which can indicate that the user was not found. To
* be on the safe side we fail back to the group lookup on all
* errors. */
ret = getgrnam_r_wrapper(MAX_BUF, fq_name, &grp, &buf, &buf_len);
if (ret != 0) {
if (ret == ENOMEM || ret == ERANGE) {
ret = LDAP_OPERATIONS_ERROR;
} else {
ret = LDAP_NO_SUCH_OBJECT;
}
goto done;
}
if (request_type == REQ_FULL_WITH_GROUPS) {
ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);
if (ret != 0 || !(id_type == SSS_ID_TYPE_GID
|| id_type == SSS_ID_TYPE_BOTH)) {
if (ret == ENOENT) {
ret = LDAP_NO_SUCH_OBJECT;
} else {
ret = LDAP_OPERATIONS_ERROR;
}
goto done;
}
}
ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP
: RESP_GROUP_MEMBERS),
domain_name, grp.gr_name, grp.gr_gid,
grp.gr_mem, kv_list, berval);
}
}
done:
sss_nss_free_kv(kv_list);
free(fq_name);
free(sid_str);
free(buf);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable
The get*_r_wrapper() calls expect a maximum buffer size to avoid memory
shortage if too many threads try to allocate buffers e.g. for large
groups. With this patch this size can be configured by setting
ipaExtdomMaxNssBufSize in the plugin config object
cn=ipa_extdom_extop,cn=plugins,cn=config.
Related to https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 ipa_extdom_init_ctx(Slapi_PBlock *pb, struct ipa_extdom_ctx **_ctx)
{
struct ipa_extdom_ctx *ctx;
Slapi_Entry *e;
int ret;
ctx = calloc(1, sizeof(struct ipa_extdom_ctx));
if (!ctx) {
return LDAP_OPERATIONS_ERROR;
}
ret = slapi_pblock_get(pb, SLAPI_PLUGIN_IDENTITY, &ctx->plugin_id);
if ((ret != 0) || (NULL == ctx->plugin_id)) {
LOG_FATAL("Could not get identity or identity was NULL\n");
if (ret == 0) {
ret = -1;
}
goto done;
}
slapi_pblock_get(pb, SLAPI_PLUGIN_CONFIG_ENTRY, &e);
if (!e) {
LOG_FATAL("Plugin configuration not found!\n");
ret = -1;
goto done;
}
ctx->base_dn = slapi_entry_attr_get_charptr(e, "nsslapd-basedn");
if (!ctx->base_dn) {
LOG_FATAL("Base DN not found in plugin configuration not found!\n");
ret = -1;
goto done;
}
done:
if (ret) {
free(ctx);
} else {
*_ctx = ctx;
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable
The get*_r_wrapper() calls expect a maximum buffer size to avoid memory
shortage if too many threads try to allocate buffers e.g. for large
groups. With this patch this size can be configured by setting
ipaExtdomMaxNssBufSize in the plugin config object
cn=ipa_extdom_extop,cn=plugins,cn=config.
Related to https://fedorahosted.org/freeipa/ticket/4908
Reviewed-By: Alexander Bokovoy <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
if (len > INT_MAX)
len = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
iov.iov_base = buff;
iov.iov_len = len;
msg.msg_name = NULL;
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg, len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom
Cc: [email protected] # v3.19
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _asn1_ltostr (long v, char *str)
{
long d, r;
char temp[LTOSTR_MAX_SIZE];
int count, k, start;
if (v < 0)
{
str[0] = '-';
start = 1;
v = -v;
}
else
start = 0;
count = 0;
do
{
d = v / 10;
r = v - d * 10;
temp[start + count] = '0' + (char) r;
count++;
v = d;
}
while (v);
for (k = 0; k < count; k++)
str[k + start] = temp[start + count - k - 1];
str[count + start] = 0;
return str;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'increased size of LTOSTR_MAX_SIZE to account for sign and null byte
This address an overflow found by Hanno Böck in DER decoding.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
bool setting_SaveFullCore;
bool setting_CreateCoreBacktrace;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveFullCore");
setting_SaveFullCore = value ? string_to_bool(value) : true;
value = get_map_string_item_or_NULL(settings, "CreateCoreBacktrace");
setting_CreateCoreBacktrace = value ? string_to_bool(value) : true;
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
if (argc == 2 && strcmp(argv[1], "--config-test"))
return test_configuration(setting_SaveFullCore, setting_CreateCoreBacktrace);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %i */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [TID]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
pid_t tid = 0;
if (argv[8])
{
tid = xatoi_positive(argv[8]);
}
char path[PATH_MAX];
char *executable = get_executable(pid);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid); /* may be NULL on error */
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
char *proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid(proc_pid_status);
if (tmp_fsuid < 0)
perror_msg_and_die("Can't parse 'Uid: line' in /proc/%lu/status", (long)pid);
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
{
fsuid = tmp_fsuid;
}
}
/* Open a fd to compat coredump, if requested and is possible */
int user_core_fd = -1;
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
return create_user_core(user_core_fd, pid, ulimit_c);
}
const char *signame = NULL;
if (!signal_is_fatal(signal_no, &signame))
return create_user_core(user_core_fd, pid, ulimit_c); // not a signal we care about
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
return create_user_core(user_core_fd, pid, ulimit_c);
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
return create_user_core(user_core_fd, pid, ulimit_c);
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
return create_user_core(user_core_fd, pid, ulimit_c);
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
return create_user_core(user_core_fd, pid, ulimit_c);
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*/
dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file(source_filename, dest_filename, 0640);
//chown(dest_filename, dd->dd_uid, dd->dd_gid);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE);
IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid));
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE);
IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid));
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE);
IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid));
strcpy(dest_base, FILENAME_OPEN_FDS);
strcpy(source_filename + source_base_ofs, "fd");
if (dump_fd_info(dest_filename, source_filename) == 0)
IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid));
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "abrt-ccpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (setting_SaveBinaryImage)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
if (save_crashing_binary(pid, path, dd->dd_uid, dd->dd_gid))
{
error_msg("Error saving '%s'", path);
goto error_exit;
}
}
off_t core_size = 0;
if (setting_SaveFullCore)
{
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path, user_core_fd);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg("Error writing '%s'", path);
goto error_exit;
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
xchdir(user_pwd);
unlink(core_basename);
}
}
else
{
/* User core is created even if WriteFullCore is off. */
create_user_core(user_core_fd, pid, ulimit_c);
}
/* User core is either written or closed */
user_core_fd = -1;
/*
* ! No other errors should cause removal of the user core !
*/
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path, user_core_fd);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
error_msg("Error saving '%s'", path);
goto error_exit;
}
close(src_fd);
}
}
/* Perform crash-time unwind of the guilty thread. */
if (tid > 0 && setting_CreateCoreBacktrace)
create_core_backtrace(tid, executable, signal_no, dd->dd_dirname);
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
dd = NULL;
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
if (core_size > 0)
log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)",
(long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
return create_user_core(user_core_fd, pid, ulimit_c);
error_exit:
if (dd)
dd_delete(dd);
if (user_core_fd >= 0)
{
xchdir(user_pwd);
unlink(core_basename);
}
xfunc_die();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'ccpp: add support for containers
A process is considered to be containerized when:
- has the 'container' env variable set to some value
- or has the 'container_uuid' env variable set to some value
- or has remounted /
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlTextReaderConstValue(xmlTextReaderPtr reader) {
xmlNodePtr node;
if (reader == NULL)
return(NULL);
if (reader->node == NULL)
return(NULL);
if (reader->curnode != NULL)
node = reader->curnode;
else
node = reader->node;
switch (node->type) {
case XML_NAMESPACE_DECL:
return(((xmlNsPtr) node)->href);
case XML_ATTRIBUTE_NODE:{
xmlAttrPtr attr = (xmlAttrPtr) node;
if ((attr->children != NULL) &&
(attr->children->type == XML_TEXT_NODE) &&
(attr->children->next == NULL))
return(attr->children->content);
else {
if (reader->buffer == NULL) {
reader->buffer = xmlBufCreateSize(100);
if (reader->buffer == NULL) {
xmlGenericError(xmlGenericErrorContext,
"xmlTextReaderSetup : malloc failed\n");
return (NULL);
}
} else
xmlBufEmpty(reader->buffer);
xmlBufGetNodeContent(reader->buffer, node);
return(xmlBufContent(reader->buffer));
}
break;
}
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
return(node->content);
default:
break;
}
return(NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory
One of the operation on the reader could resolve entities
leading to the classic expansion issue. Make sure the
buffer used for xmlreader operation is bounded.
Introduce a new allocation type for the buffers for this effect.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlBufAdd(xmlBufPtr buf, const xmlChar *str, int len) {
unsigned int needSize;
if ((str == NULL) || (buf == NULL) || (buf->error))
return -1;
CHECK_COMPAT(buf)
if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;
if (len < -1) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufAdd: len < 0\n");
#endif
return -1;
}
if (len == 0) return 0;
if (len < 0)
len = xmlStrlen(str);
if (len < 0) return -1;
if (len == 0) return 0;
needSize = buf->use + len + 2;
if (needSize > buf->size){
if (!xmlBufResize(buf, needSize)){
xmlBufMemoryError(buf, "growing buffer");
return XML_ERR_NO_MEMORY;
}
}
memmove(&buf->content[buf->use], str, len*sizeof(xmlChar));
buf->use += len;
buf->content[buf->use] = 0;
UPDATE_COMPAT(buf)
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory
One of the operation on the reader could resolve entities
leading to the classic expansion issue. Make sure the
buffer used for xmlreader operation is bounded.
Introduce a new allocation type for the buffers for this effect.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlBufAddHead(xmlBufPtr buf, const xmlChar *str, int len) {
unsigned int needSize;
if ((buf == NULL) || (buf->error))
return(-1);
CHECK_COMPAT(buf)
if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;
if (str == NULL) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufAddHead: str == NULL\n");
#endif
return -1;
}
if (len < -1) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufAddHead: len < 0\n");
#endif
return -1;
}
if (len == 0) return 0;
if (len < 0)
len = xmlStrlen(str);
if (len <= 0) return -1;
if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
size_t start_buf = buf->content - buf->contentIO;
if (start_buf > (unsigned int) len) {
/*
* We can add it in the space previously shrinked
*/
buf->content -= len;
memmove(&buf->content[0], str, len);
buf->use += len;
buf->size += len;
UPDATE_COMPAT(buf)
return(0);
}
}
needSize = buf->use + len + 2;
if (needSize > buf->size){
if (!xmlBufResize(buf, needSize)){
xmlBufMemoryError(buf, "growing buffer");
return XML_ERR_NO_MEMORY;
}
}
memmove(&buf->content[len], &buf->content[0], buf->use);
memmove(&buf->content[0], str, len);
buf->use += len;
buf->content[buf->use] = 0;
UPDATE_COMPAT(buf)
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory
One of the operation on the reader could resolve entities
leading to the classic expansion issue. Make sure the
buffer used for xmlreader operation is bounded.
Introduce a new allocation type for the buffers for this effect.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlBufSetAllocationScheme(xmlBufPtr buf,
xmlBufferAllocationScheme scheme) {
if ((buf == NULL) || (buf->error != 0)) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufSetAllocationScheme: buf == NULL or in error\n");
#endif
return(-1);
}
if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
(buf->alloc == XML_BUFFER_ALLOC_IO))
return(-1);
if ((scheme == XML_BUFFER_ALLOC_DOUBLEIT) ||
(scheme == XML_BUFFER_ALLOC_EXACT) ||
(scheme == XML_BUFFER_ALLOC_HYBRID) ||
(scheme == XML_BUFFER_ALLOC_IMMUTABLE)) {
buf->alloc = scheme;
if (buf->buffer)
buf->buffer->alloc = scheme;
return(0);
}
/*
* Switching a buffer ALLOC_IO has the side effect of initializing
* the contentIO field with the current content
*/
if (scheme == XML_BUFFER_ALLOC_IO) {
buf->alloc = XML_BUFFER_ALLOC_IO;
buf->contentIO = buf->content;
}
return(-1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory
One of the operation on the reader could resolve entities
leading to the classic expansion issue. Make sure the
buffer used for xmlreader operation is bounded.
Introduce a new allocation type for the buffers for this effect.'</s> |
<s>[INST] Given the following code containing errors, provide 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 dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
fclose(fp);
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: fix symlink race conditions
Fix copy & chown race conditions
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: open file for dump_fd_info with O_EXCL
To avoid possible races.
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %h */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
struct utsname uts;
if (!argv[8]) /* no HOSTNAME? */
{
uname(&uts);
argv[8] = uts.nodename;
}
char path[PATH_MAX];
int src_fd_binary = -1;
char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid); /* may be NULL on error */
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid();
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
{
fsuid = tmp_fsuid;
}
}
/* Open a fd to compat coredump, if requested and is possible */
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
goto create_user_core;
}
const char *signame = NULL;
switch (signal_no)
{
case SIGILL : signame = "ILL" ; break;
case SIGFPE : signame = "FPE" ; break;
case SIGSEGV: signame = "SEGV"; break;
case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access)
case SIGABRT: signame = "ABRT"; break; //usually when abort() was called
// We have real-world reports from users who see buggy programs
// dying with SIGTRAP, uncommented it too:
case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap
// These usually aren't caused by bugs:
//case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard
//case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4)
//case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD)
//case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD)
default: goto create_user_core; // not a signal we care about
}
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
goto create_user_core;
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
goto create_user_core;
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
goto create_user_core;
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
goto create_user_core;
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*/
dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(dest_base, FILENAME_OPEN_FDS);
dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "CCpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (src_fd_binary > 0)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);
if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd_binary);
}
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
dd_delete(dd);
if (user_core_fd >= 0)
{
xchdir(user_pwd);
unlink(core_basename);
}
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error writing '%s'", path);
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
xchdir(user_pwd);
unlink(core_basename);
}
/* Because of #1211835 and #1126850 */
#if 0
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd);
}
}
#endif
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
create_user_core:
if (user_core_fd >= 0)
{
off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);
if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)
{
/* perror first, otherwise unlink may trash errno */
perror_msg("Error writing '%s'", full_core_basename);
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
if (ulimit_c == 0 || core_size > ulimit_c)
{
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: do not read data from root directories
Users are allowed to modify /proc/[pid]/root to any directory by running
their own MOUNT namespace.
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %h */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
struct utsname uts;
if (!argv[8]) /* no HOSTNAME? */
{
uname(&uts);
argv[8] = uts.nodename;
}
char path[PATH_MAX];
int src_fd_binary = -1;
char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid); /* may be NULL on error */
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid();
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
{
fsuid = tmp_fsuid;
}
}
/* Open a fd to compat coredump, if requested and is possible */
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
goto create_user_core;
}
const char *signame = NULL;
switch (signal_no)
{
case SIGILL : signame = "ILL" ; break;
case SIGFPE : signame = "FPE" ; break;
case SIGSEGV: signame = "SEGV"; break;
case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access)
case SIGABRT: signame = "ABRT"; break; //usually when abort() was called
// We have real-world reports from users who see buggy programs
// dying with SIGTRAP, uncommented it too:
case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap
// These usually aren't caused by bugs:
//case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard
//case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4)
//case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD)
//case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD)
default: goto create_user_core; // not a signal we care about
}
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
goto create_user_core;
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
goto create_user_core;
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
goto create_user_core;
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
goto create_user_core;
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*/
dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(dest_base, FILENAME_OPEN_FDS);
dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "CCpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (src_fd_binary > 0)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);
if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd_binary);
}
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
dd_delete(dd);
if (user_core_fd >= 0)
{
xchdir(user_pwd);
unlink(core_basename);
}
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error writing '%s'", path);
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
xchdir(user_pwd);
unlink(core_basename);
}
/* Because of #1211835 and #1126850 */
#if 0
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd);
}
}
#endif
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
create_user_core:
if (user_core_fd >= 0)
{
off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);
if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)
{
/* perror first, otherwise unlink may trash errno */
perror_msg("Error writing '%s'", full_core_basename);
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
if (ulimit_c == 0 || core_size > ulimit_c)
{
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: postpone changing ownership of new dump directories
Florian Weimer <[email protected]>:
Currently, dd_create changes ownership of the directory immediately,
when it is still empty. This means that any operations within the
directory (which happen as the root user) can race with changes to
the directory contents by the user. If you delay changing directory
ownership until all the files have created and written, this is no
longer a problem.
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %h */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
struct utsname uts;
if (!argv[8]) /* no HOSTNAME? */
{
uname(&uts);
argv[8] = uts.nodename;
}
char path[PATH_MAX];
int src_fd_binary = -1;
char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid);
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid();
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
fsuid = tmp_fsuid;
else
{
g_user_core_flags = O_EXCL;
g_need_nonrelative = 1;
}
}
/* Open a fd to compat coredump, if requested and is possible */
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
goto create_user_core;
}
const char *signame = NULL;
switch (signal_no)
{
case SIGILL : signame = "ILL" ; break;
case SIGFPE : signame = "FPE" ; break;
case SIGSEGV: signame = "SEGV"; break;
case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access)
case SIGABRT: signame = "ABRT"; break; //usually when abort() was called
// We have real-world reports from users who see buggy programs
// dying with SIGTRAP, uncommented it too:
case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap
// These usually aren't caused by bugs:
//case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard
//case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4)
//case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD)
//case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD)
default: goto create_user_core; // not a signal we care about
}
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
goto create_user_core;
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
goto create_user_core;
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
goto create_user_core;
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
goto create_user_core;
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*
* dd_create_skeleton() creates a new directory and leaves ownership to
* the current user, hence, we have to call dd_reset_ownership() after the
* directory is populated.
*/
dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(dest_base, FILENAME_OPEN_FDS);
dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "CCpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (src_fd_binary > 0)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);
if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd_binary);
}
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
dd_delete(dd);
if (user_core_fd >= 0)
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error writing '%s'", path);
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
}
/* Because of #1211835 and #1126850 */
#if 0
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd);
}
}
#endif
/* And finally set the right uid and gid */
dd_reset_ownership(dd);
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
create_user_core:
if (user_core_fd >= 0)
{
off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);
if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)
{
/* perror first, otherwise unlink may trash errno */
perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd);
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 1;
}
if (ulimit_c == 0 || core_size > ulimit_c)
{
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 1;
}
log("Saved core dump of pid %lu to %s at %s (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size);
}
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: check for overflow in abrt coredump path creation
This issue was discovered by Florian Weimer of Red Hat Product Security.
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && !ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && !ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'whiteboard: fixup a few reversed tests (GH #446)
This is a follow-up to commit 3a3ec26.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %h */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
struct utsname uts;
if (!argv[8]) /* no HOSTNAME? */
{
uname(&uts);
argv[8] = uts.nodename;
}
char path[PATH_MAX];
int src_fd_binary = -1;
char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid); /* may be NULL on error */
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid();
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
{
fsuid = tmp_fsuid;
}
}
/* Open a fd to compat coredump, if requested and is possible */
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
goto create_user_core;
}
const char *signame = NULL;
switch (signal_no)
{
case SIGILL : signame = "ILL" ; break;
case SIGFPE : signame = "FPE" ; break;
case SIGSEGV: signame = "SEGV"; break;
case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access)
case SIGABRT: signame = "ABRT"; break; //usually when abort() was called
// We have real-world reports from users who see buggy programs
// dying with SIGTRAP, uncommented it too:
case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap
// These usually aren't caused by bugs:
//case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard
//case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4)
//case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD)
//case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD)
default: goto create_user_core; // not a signal we care about
}
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
goto create_user_core;
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
goto create_user_core;
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
goto create_user_core;
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
goto create_user_core;
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*
* dd_create_skeleton() creates a new directory and leaves ownership to
* the current user, hence, we have to call dd_reset_ownership() after the
* directory is populated.
*/
dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(dest_base, FILENAME_OPEN_FDS);
dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "CCpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (src_fd_binary > 0)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);
if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd_binary);
}
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
dd_delete(dd);
if (user_core_fd >= 0)
{
xchdir(user_pwd);
unlink(core_basename);
}
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error writing '%s'", path);
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
xchdir(user_pwd);
unlink(core_basename);
}
/* Because of #1211835 and #1126850 */
#if 0
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd);
}
}
#endif
/* And finally set the right uid and gid */
dd_reset_ownership(dd);
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
create_user_core:
if (user_core_fd >= 0)
{
off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);
if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)
{
/* perror first, otherwise unlink may trash errno */
perror_msg("Error writing '%s'", full_core_basename);
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
if (ulimit_c == 0 || core_size > ulimit_c)
{
xchdir(user_pwd);
unlink(core_basename);
return 1;
}
log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not override existing files by compat cores
Implement all checks used in kernel's do_coredump() and require
non-relative path if suid_dumpable is 2.
Related: #1212818
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 create_or_die(const char *filename)
{
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE);
if (fd >= 0)
{
IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid));
return fd;
}
int sv_errno = errno;
if (dd)
dd_delete(dd);
if (user_core_fd >= 0)
{
xchdir(user_pwd);
unlink(core_basename);
}
errno = sv_errno;
perror_msg_and_die("Can't open '%s'", filename);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not use value of /proc/PID/cwd for chdir
Avoid symlink resolutions.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values)
{
proc_cwd = open_cwd(pid);
if (proc_cwd == NULL)
return -1;
struct passwd* pw = getpwuid(uid);
gid_t gid = pw ? pw->pw_gid : uid;
//log("setting uid: %i gid: %i", uid, gid);
xsetegid(gid);
xseteuid(fsuid);
if (strcmp(core_basename, "core") == 0)
{
/* Mimic "core.PID" if requested */
char buf[] = "0\n";
int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
if (fd >= 0)
{
IGNORE_RESULT(read(fd, buf, sizeof(buf)));
close(fd);
}
if (strcmp(buf, "1\n") == 0)
{
core_basename = xasprintf("%s.%lu", core_basename, (long)pid);
}
}
else
{
/* Expand old core pattern, put expanded name in core_basename */
core_basename = xstrdup(core_basename);
unsigned idx = 0;
while (1)
{
char c = core_basename[idx];
if (!c)
break;
idx++;
if (c != '%')
continue;
/* We just copied %, look at following char and expand %c */
c = core_basename[idx];
unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers;
if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */
{
const char *val = "%";
if (specifier_num > 0) /* not %% */
val = percent_values[specifier_num - 1];
//log("c:'%c'", c);
//log("val:'%s'", val);
/* Replace %c at core_basename[idx] by its value */
idx--;
char *old = core_basename;
core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2);
//log("pos:'%*s|'", idx, "");
//log("new:'%s'", core_basename);
//log("old:'%s'", old);
free(old);
idx += strlen(val);
}
/* else: invalid %c, % is already copied verbatim,
* next loop iteration will copy c */
}
}
if (g_need_nonrelative && core_basename[0] != '/')
{
error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern");
return -1;
}
/* Open (create) compat core file.
* man core:
* There are various circumstances in which a core dump file
* is not produced:
*
* [skipped obvious ones]
* The process does not have permission to write the core file.
* ...if a file with the same name exists and is not writable
* or is not a regular file (e.g., it is a directory or a symbolic link).
*
* A file with the same name already exists, but there is more
* than one hard link to that file.
*
* The file system where the core dump file would be created is full;
* or has run out of inodes; or is mounted read-only;
* or the user has reached their quota for the file system.
*
* The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process
* are set to zero.
* [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?]
*
* The binary being executed by the process does not have
* read permission enabled. [how we can check it here?]
*
* The process is executing a set-user-ID (set-group-ID) program
* that is owned by a user (group) other than the real
* user (group) ID of the process. [TODO?]
* (However, see the description of the prctl(2) PR_SET_DUMPABLE operation,
* and the description of the /proc/sys/fs/suid_dumpable file in proc(5).)
*/
struct stat sb;
errno = 0;
/* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */
int user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */
xsetegid(0);
xseteuid(0);
if (user_core_fd < 0
|| fstat(user_core_fd, &sb) != 0
|| !S_ISREG(sb.st_mode)
|| sb.st_nlink != 1
|| sb.st_uid != fsuid
) {
if (user_core_fd < 0)
perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd);
else
perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid);
return -1;
}
if (ftruncate(user_core_fd, 0) != 0) {
/* perror first, otherwise unlink may trash errno */
perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd);
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
return -1;
}
return user_core_fd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: harden dealing with UID/GID
* Don't fall back to UID 0.
* Use fsgid.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values)
{
proc_cwd = open_cwd(pid);
if (proc_cwd == NULL)
return -1;
errno = 0;
/* http://article.gmane.org/gmane.comp.security.selinux/21842 */
security_context_t newcon;
if (compute_selinux_con_for_new_file(pid, dirfd(proc_cwd), &newcon) < 0)
{
log_notice("Not going to create a user core due to SELinux errors");
return -1;
}
xsetegid(get_fsgid());
xseteuid(fsuid);
if (strcmp(core_basename, "core") == 0)
{
/* Mimic "core.PID" if requested */
char buf[] = "0\n";
int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
if (fd >= 0)
{
IGNORE_RESULT(read(fd, buf, sizeof(buf)));
close(fd);
}
if (strcmp(buf, "1\n") == 0)
{
core_basename = xasprintf("%s.%lu", core_basename, (long)pid);
}
}
else
{
/* Expand old core pattern, put expanded name in core_basename */
core_basename = xstrdup(core_basename);
unsigned idx = 0;
while (1)
{
char c = core_basename[idx];
if (!c)
break;
idx++;
if (c != '%')
continue;
/* We just copied %, look at following char and expand %c */
c = core_basename[idx];
unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers;
if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */
{
const char *val = "%";
if (specifier_num > 0) /* not %% */
val = percent_values[specifier_num - 1];
//log("c:'%c'", c);
//log("val:'%s'", val);
/* Replace %c at core_basename[idx] by its value */
idx--;
char *old = core_basename;
core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2);
//log("pos:'%*s|'", idx, "");
//log("new:'%s'", core_basename);
//log("old:'%s'", old);
free(old);
idx += strlen(val);
}
/* else: invalid %c, % is already copied verbatim,
* next loop iteration will copy c */
}
}
if (g_need_nonrelative && core_basename[0] != '/')
{
error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern");
return -1;
}
/* Open (create) compat core file.
* man core:
* There are various circumstances in which a core dump file
* is not produced:
*
* [skipped obvious ones]
* The process does not have permission to write the core file.
* ...if a file with the same name exists and is not writable
* or is not a regular file (e.g., it is a directory or a symbolic link).
*
* A file with the same name already exists, but there is more
* than one hard link to that file.
*
* The file system where the core dump file would be created is full;
* or has run out of inodes; or is mounted read-only;
* or the user has reached their quota for the file system.
*
* The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process
* are set to zero.
* [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?]
*
* The binary being executed by the process does not have
* read permission enabled. [how we can check it here?]
*
* The process is executing a set-user-ID (set-group-ID) program
* that is owned by a user (group) other than the real
* user (group) ID of the process. [TODO?]
* (However, see the description of the prctl(2) PR_SET_DUMPABLE operation,
* and the description of the /proc/sys/fs/suid_dumpable file in proc(5).)
*/
/* Set SELinux context like kernel when creating core dump file */
if (newcon != NULL && setfscreatecon_raw(newcon) < 0)
{
perror_msg("setfscreatecon_raw(%s)", newcon);
return -1;
}
struct stat sb;
errno = 0;
/* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */
int user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */
if (newcon != NULL && setfscreatecon_raw(NULL) < 0)
{
error_msg("setfscreatecon_raw(NULL)");
goto user_core_fail;
}
xsetegid(0);
xseteuid(0);
if (user_core_fd < 0
|| fstat(user_core_fd, &sb) != 0
|| !S_ISREG(sb.st_mode)
|| sb.st_nlink != 1
|| sb.st_uid != fsuid
) {
if (user_core_fd < 0)
perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd);
else
perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid);
goto user_core_fail;
}
if (ftruncate(user_core_fd, 0) != 0) {
/* perror first, otherwise unlink may trash errno */
perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd);
goto user_core_fail;
}
return user_core_fd;
user_core_fail:
if (user_core_fd >= 0)
{
close(user_core_fd);
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
}
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: revert the UID/GID changes if user core fails
Thanks Florian Weimer <[email protected]>
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dir_has_correct_permissions(dirname))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 400; /* */
}
if (g_settings_privatereports)
{
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
//log("Reading from event fd %d", child_stdout_fd);
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
//log("Started notify, fd %d -> %d", fd, child_stdout_fd);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'daemon: allow only root user to trigger the post-create
There is no reason to allow non-root users to trigger this
functionality. Regular users can create abrt problems only through
abrtd or abrt-dbus and both triggers the post-create.
Other hooks run under root user (CCpp, Koops, VMCore, Xorg).
Related: #1212861
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static gboolean key_value_ok(gchar *key, gchar *value)
{
char *i;
/* check key, it has to be valid filename and will end up in the
* bugzilla */
for (i = key; *i != 0; i++)
{
if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))
return FALSE;
}
/* check value of 'basename', it has to be valid non-hidden directory
* name */
if (strcmp(key, "basename") == 0
|| strcmp(key, FILENAME_TYPE) == 0
)
{
if (!str_is_correct_filename(value))
{
error_msg("Value of '%s' ('%s') is not a valid directory name",
key, value);
return FALSE;
}
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'daemon, dbus: allow only root to create CCpp, Koops, vmcore and xorg
Florian Weimer <[email protected]>:
This prevents users from feeding things that are not actually
coredumps and excerpts from /proc to these analyzers.
For example, it should not be possible to trigger a rule with
“EVENT=post-create analyzer=CCpp” using NewProblem
Related: #1212861
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 save_bt_to_dump_dir(const char *bt, const char *exe, const char *reason)
{
time_t t = time(NULL);
const char *iso_date = iso_date_string(&t);
/* dump should be readable by all if we're run with -x */
uid_t my_euid = (uid_t)-1L;
mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH;
/* and readable only for the owner otherwise */
if (!(g_opts & OPT_x))
{
mode = DEFAULT_DUMP_DIR_MODE;
my_euid = geteuid();
}
pid_t my_pid = getpid();
char base[sizeof("xorg-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3];
sprintf(base, "xorg-%s-%lu-%u", iso_date, (long)my_pid, g_bt_count);
char *path = concat_path_file(debug_dumps_dir, base);
struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode);
if (dd)
{
dd_create_basic_files(dd, /*uid:*/ my_euid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
dd_save_text(dd, FILENAME_ANALYZER, "xorg");
dd_save_text(dd, FILENAME_TYPE, "xorg");
dd_save_text(dd, FILENAME_REASON, reason);
dd_save_text(dd, FILENAME_BACKTRACE, bt);
/*
* Reporters usually need component name to file a bug.
* It is usually derived from executable.
* We _guess_ X server's executable name as a last resort.
* Better ideas?
*/
if (!exe)
{
exe = "/usr/bin/X";
if (access("/usr/bin/Xorg", X_OK) == 0)
exe = "/usr/bin/Xorg";
}
dd_save_text(dd, FILENAME_EXECUTABLE, exe);
dd_close(dd);
notify_new_path(path);
}
free(path);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char** argv)
{
/* Kernel starts us with all fd's closed.
* But it's dangerous:
* fprintf(stderr) can dump messages into random fds, etc.
* Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.
*/
int fd = xopen("/dev/null", O_RDWR);
while (fd < 2)
fd = xdup(fd);
if (fd > 2)
close(fd);
if (argc < 8)
{
/* percent specifier: %s %c %p %u %g %t %e %h */
/* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/
error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]);
}
/* Not needed on 2.6.30.
* At least 2.6.18 has a bug where
* argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..."
* argv[2] = "CORE_SIZE_LIMIT PID ..."
* and so on. Fixing it:
*/
if (strchr(argv[1], ' '))
{
int i;
for (i = 1; argv[i]; i++)
{
strchrnul(argv[i], ' ')[0] = '\0';
}
}
logmode = LOGMODE_JOURNAL;
/* Parse abrt.conf */
load_abrt_conf();
/* ... and plugins/CCpp.conf */
bool setting_MakeCompatCore;
bool setting_SaveBinaryImage;
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("CCpp.conf", settings);
const char *value;
value = get_map_string_item_or_NULL(settings, "MakeCompatCore");
setting_MakeCompatCore = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "SaveBinaryImage");
setting_SaveBinaryImage = value && string_to_bool(value);
value = get_map_string_item_or_NULL(settings, "VerboseLog");
if (value)
g_verbose = xatoi_positive(value);
free_map_string(settings);
}
errno = 0;
const char* signal_str = argv[1];
int signal_no = xatoi_positive(signal_str);
off_t ulimit_c = strtoull(argv[2], NULL, 10);
if (ulimit_c < 0) /* unlimited? */
{
/* set to max possible >0 value */
ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));
}
const char *pid_str = argv[3];
pid_t pid = xatoi_positive(argv[3]);
uid_t uid = xatoi_positive(argv[4]);
if (errno || pid <= 0)
{
perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]);
}
{
char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern");
/* If we have a saved pattern and it's not a "|PROG ARGS" thing... */
if (s && s[0] != '|')
core_basename = s;
else
free(s);
}
struct utsname uts;
if (!argv[8]) /* no HOSTNAME? */
{
uname(&uts);
argv[8] = uts.nodename;
}
char path[PATH_MAX];
int src_fd_binary = -1;
char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);
if (executable && strstr(executable, "/abrt-hook-ccpp"))
{
error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion",
(long)pid, executable);
}
user_pwd = get_cwd(pid);
log_notice("user_pwd:'%s'", user_pwd);
sprintf(path, "/proc/%lu/status", (long)pid);
proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);
uid_t fsuid = uid;
uid_t tmp_fsuid = get_fsuid();
int suid_policy = dump_suid_policy();
if (tmp_fsuid != uid)
{
/* use root for suided apps unless it's explicitly set to UNSAFE */
fsuid = 0;
if (suid_policy == DUMP_SUID_UNSAFE)
fsuid = tmp_fsuid;
else
{
g_user_core_flags = O_EXCL;
g_need_nonrelative = 1;
}
}
/* Open a fd to compat coredump, if requested and is possible */
if (setting_MakeCompatCore && ulimit_c != 0)
/* note: checks "user_pwd == NULL" inside; updates core_basename */
user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);
if (executable == NULL)
{
/* readlink on /proc/$PID/exe failed, don't create abrt dump dir */
error_msg("Can't read /proc/%lu/exe link", (long)pid);
goto create_user_core;
}
const char *signame = NULL;
switch (signal_no)
{
case SIGILL : signame = "ILL" ; break;
case SIGFPE : signame = "FPE" ; break;
case SIGSEGV: signame = "SEGV"; break;
case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access)
case SIGABRT: signame = "ABRT"; break; //usually when abort() was called
// We have real-world reports from users who see buggy programs
// dying with SIGTRAP, uncommented it too:
case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap
// These usually aren't caused by bugs:
//case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard
//case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4)
//case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD)
//case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD)
default: goto create_user_core; // not a signal we care about
}
if (!daemon_is_ok())
{
/* not an error, exit with exit code 0 */
log("abrtd is not running. If it crashed, "
"/proc/sys/kernel/core_pattern contains a stale value, "
"consider resetting it to 'core'"
);
goto create_user_core;
}
if (g_settings_nMaxCrashReportsSize > 0)
{
/* If free space is less than 1/4 of MaxCrashReportsSize... */
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
goto create_user_core;
}
/* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes
* if they happen too often. Else, write new marker value.
*/
snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location);
if (check_recent_crash_file(path, executable))
{
/* It is a repeating crash */
goto create_user_core;
}
const char *last_slash = strrchr(executable, '/');
if (last_slash && strncmp(++last_slash, "abrt", 4) == 0)
{
/* If abrtd/abrt-foo crashes, we don't want to create a _directory_,
* since that can make new copy of abrtd to process it,
* and maybe crash again...
* Unlike dirs, mere files are ignored by abrtd.
*/
if (snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash) >= sizeof(path))
error_msg_and_die("Error saving '%s': truncated long file path", path);
int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);
if (core_size < 0 || fsync(abrt_core_fd) != 0)
{
unlink(path);
/* copyfd_eof logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error saving '%s'", path);
}
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
}
unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new",
g_settings_dump_location, iso_date_string(NULL), (long)pid);
if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP)))
{
goto create_user_core;
}
/* use fsuid instead of uid, so we don't expose any sensitive
* information of suided app in /var/tmp/abrt
*
* dd_create_skeleton() creates a new directory and leaves ownership to
* the current user, hence, we have to call dd_reset_ownership() after the
* directory is populated.
*/
dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0);
if (dd)
{
char *rootdir = get_rootdir(pid);
dd_create_basic_files(dd, fsuid, NULL);
char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3];
int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid);
source_base_ofs -= strlen("smaps");
char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name");
char *dest_base = strrchr(dest_filename, '/') + 1;
// Disabled for now: /proc/PID/smaps tends to be BIG,
// and not much more informative than /proc/PID/maps:
//copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "maps");
strcpy(dest_base, FILENAME_MAPS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "limits");
strcpy(dest_base, FILENAME_LIMITS);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(source_filename + source_base_ofs, "cgroup");
strcpy(dest_base, FILENAME_CGROUP);
copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
strcpy(dest_base, FILENAME_OPEN_FDS);
dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);
free(dest_filename);
dd_save_text(dd, FILENAME_ANALYZER, "CCpp");
dd_save_text(dd, FILENAME_TYPE, "CCpp");
dd_save_text(dd, FILENAME_EXECUTABLE, executable);
dd_save_text(dd, FILENAME_PID, pid_str);
dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);
if (user_pwd)
dd_save_text(dd, FILENAME_PWD, user_pwd);
if (rootdir)
{
if (strcmp(rootdir, "/") != 0)
dd_save_text(dd, FILENAME_ROOTDIR, rootdir);
}
char *reason = xasprintf("%s killed by SIG%s",
last_slash, signame ? signame : signal_str);
dd_save_text(dd, FILENAME_REASON, reason);
free(reason);
char *cmdline = get_cmdline(pid);
dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : "");
free(cmdline);
char *environ = get_environ(pid);
dd_save_text(dd, FILENAME_ENVIRON, environ ? : "");
free(environ);
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
if (fips_enabled)
{
if (strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
free(fips_enabled);
}
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
if (src_fd_binary > 0)
{
strcpy(path + path_len, "/"FILENAME_BINARY);
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);
if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd_binary);
}
strcpy(path + path_len, "/"FILENAME_COREDUMP);
int abrt_core_fd = create_or_die(path);
/* We write both coredumps at once.
* We can't write user coredump first, since it might be truncated
* and thus can't be copied and used as abrt coredump;
* and if we write abrt coredump first and then copy it as user one,
* then we have a race when process exits but coredump does not exist yet:
* $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -
* $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*
* 21631 Segmentation fault (core dumped) ./test
* ls: cannot access core*: No such file or directory <=== BAD
*/
off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);
if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)
{
unlink(path);
dd_delete(dd);
if (user_core_fd >= 0)
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
/* copyfd_sparse logs the error including errno string,
* but it does not log file name */
error_msg_and_die("Error writing '%s'", path);
}
if (user_core_fd >= 0
/* error writing user coredump? */
&& (fsync(user_core_fd) != 0 || close(user_core_fd) != 0
/* user coredump is too big? */
|| (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)
)
) {
/* nuke it (silently) */
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
}
/* Because of #1211835 and #1126850 */
#if 0
/* Save JVM crash log if it exists. (JVM's coredump per se
* is nearly useless for JVM developers)
*/
{
char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
int src_fd = open(java_log, O_RDONLY);
free(java_log);
/* If we couldn't open the error log in /tmp directory we can try to
* read the log from the current directory. It may produce AVC, it
* may produce some error log but all these are expected.
*/
if (src_fd < 0)
{
java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid);
src_fd = open(java_log, O_RDONLY);
free(java_log);
}
if (src_fd >= 0)
{
strcpy(path + path_len, "/hs_err.log");
int dst_fd = create_or_die(path);
off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);
if (close(dst_fd) != 0 || sz < 0)
{
dd_delete(dd);
error_msg_and_die("Error saving '%s'", path);
}
close(src_fd);
}
}
#endif
/* And finally set the right uid and gid */
dd_reset_ownership(dd);
/* We close dumpdir before we start catering for crash storm case.
* Otherwise, delete_dump_dir's from other concurrent
* CCpp's won't be able to delete our dump (their delete_dump_dir
* will wait for us), and we won't be able to delete their dumps.
* Classic deadlock.
*/
dd_close(dd);
path[path_len] = '\0'; /* path now contains only directory name */
char *newpath = xstrndup(path, path_len - (sizeof(".new")-1));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size);
notify_new_path(path);
/* rhbz#539551: "abrt going crazy when crashing process is respawned" */
if (g_settings_nMaxCrashReportsSize > 0)
{
/* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming
* kicks in first, and we don't "fight" with it:
*/
unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;
maxsize |= 63;
trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);
}
free(rootdir);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
}
/* We didn't create abrt dump, but may need to create compat coredump */
create_user_core:
if (user_core_fd >= 0)
{
off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);
if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)
{
/* perror first, otherwise unlink may trash errno */
perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd);
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 1;
}
if (ulimit_c == 0 || core_size > ulimit_c)
{
unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0);
if (proc_cwd != NULL)
closedir(proc_cwd);
return 1;
}
log("Saved core dump of pid %lu to %s at %s (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size);
}
if (proc_cwd != NULL)
closedir(proc_cwd);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ConnectionExists(struct SessionHandle *data,
struct connectdata *needle,
struct connectdata **usethis,
bool *force_reuse)
{
struct connectdata *check;
struct connectdata *chosen = 0;
bool canPipeline = IsPipeliningPossible(data, needle);
bool wantNTLMhttp = ((data->state.authhost.want & CURLAUTH_NTLM) ||
(data->state.authhost.want & CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP) ? TRUE : FALSE;
struct connectbundle *bundle;
*force_reuse = FALSE;
/* We can't pipe if the site is blacklisted */
if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
canPipeline = FALSE;
}
/* Look up the bundle with all the connections to this
particular host */
bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
if(bundle) {
size_t max_pipe_len = Curl_multi_max_pipeline_length(data->multi);
size_t best_pipe_len = max_pipe_len;
struct curl_llist_element *curr;
infof(data, "Found bundle for host %s: %p\n",
needle->host.name, (void *)bundle);
/* We can't pipe if we don't know anything about the server */
if(canPipeline && !bundle->server_supports_pipelining) {
infof(data, "Server doesn't support pipelining\n");
canPipeline = FALSE;
}
curr = bundle->conn_list->head;
while(curr) {
bool match = FALSE;
#if defined(USE_NTLM)
bool credentialsMatch = FALSE;
#endif
size_t pipeLen;
/*
* Note that if we use a HTTP proxy, we check connections to that
* proxy and not to the actual remote server.
*/
check = curr->ptr;
curr = curr->next;
if(disconnect_if_dead(check, data))
continue;
pipeLen = check->send_pipe->size + check->recv_pipe->size;
if(canPipeline) {
/* Make sure the pipe has only GET requests */
struct SessionHandle* sh = gethandleathead(check->send_pipe);
struct SessionHandle* rh = gethandleathead(check->recv_pipe);
if(sh) {
if(!IsPipeliningPossible(sh, check))
continue;
}
else if(rh) {
if(!IsPipeliningPossible(rh, check))
continue;
}
}
else {
if(pipeLen > 0) {
/* can only happen within multi handles, and means that another easy
handle is using this connection */
continue;
}
if(Curl_resolver_asynch()) {
/* ip_addr_str[0] is NUL only if the resolving of the name hasn't
completed yet and until then we don't re-use this connection */
if(!check->ip_addr_str[0]) {
infof(data,
"Connection #%ld is still name resolving, can't reuse\n",
check->connection_id);
continue;
}
}
if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
check->bits.close) {
/* Don't pick a connection that hasn't connected yet or that is going
to get closed. */
infof(data, "Connection #%ld isn't open enough, can't reuse\n",
check->connection_id);
#ifdef DEBUGBUILD
if(check->recv_pipe->size > 0) {
infof(data,
"BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
check->connection_id);
}
#endif
continue;
}
}
if((needle->handler->flags&PROTOPT_SSL) !=
(check->handler->flags&PROTOPT_SSL))
/* don't do mixed SSL and non-SSL connections */
if(!(needle->handler->protocol & check->handler->protocol))
/* except protocols that have been upgraded via TLS */
continue;
if(needle->handler->flags&PROTOPT_SSL) {
if((data->set.ssl.verifypeer != check->verifypeer) ||
(data->set.ssl.verifyhost != check->verifyhost))
continue;
}
if(needle->bits.proxy != check->bits.proxy)
/* don't do mixed proxy and non-proxy connections */
continue;
if(!canPipeline && check->inuse)
/* this request can't be pipelined but the checked connection is
already in use so we skip it */
continue;
if(needle->localdev || needle->localport) {
/* If we are bound to a specific local end (IP+port), we must not
re-use a random other one, although if we didn't ask for a
particular one we can reuse one that was bound.
This comparison is a bit rough and too strict. Since the input
parameters can be specified in numerous ways and still end up the
same it would take a lot of processing to make it really accurate.
Instead, this matching will assume that re-uses of bound connections
will most likely also re-use the exact same binding parameters and
missing out a few edge cases shouldn't hurt anyone very much.
*/
if((check->localport != needle->localport) ||
(check->localportrange != needle->localportrange) ||
!check->localdev ||
!needle->localdev ||
strcmp(check->localdev, needle->localdev))
continue;
}
if((!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) ||
wantNTLMhttp) {
/* This protocol requires credentials per connection or is HTTP+NTLM,
so verify that we're using the same name and password as well */
if(!strequal(needle->user, check->user) ||
!strequal(needle->passwd, check->passwd)) {
/* one of them was different */
continue;
}
#if defined(USE_NTLM)
credentialsMatch = TRUE;
#endif
}
if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
(needle->bits.httpproxy && check->bits.httpproxy &&
needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
(needle->port == check->port))) {
/* The requested connection does not use a HTTP proxy or it uses SSL or
it is a non-SSL protocol tunneled over the same http proxy name and
port number or it is a non-SSL protocol which is allowed to be
upgraded via TLS */
if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
needle->handler->protocol & check->handler->protocol) &&
Curl_raw_equal(needle->host.name, check->host.name) &&
needle->remote_port == check->remote_port) {
if(needle->handler->flags & PROTOPT_SSL) {
/* This is a SSL connection so verify that we're using the same
SSL options as well */
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config)) {
DEBUGF(infof(data,
"Connection #%ld has different SSL parameters, "
"can't reuse\n",
check->connection_id));
continue;
}
else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
DEBUGF(infof(data,
"Connection #%ld has not started SSL connect, "
"can't reuse\n",
check->connection_id));
continue;
}
}
match = TRUE;
}
}
else { /* The requested needle connection is using a proxy,
is the checked one using the same host, port and type? */
if(check->bits.proxy &&
(needle->proxytype == check->proxytype) &&
(needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
needle->port == check->port) {
/* This is the same proxy connection, use it! */
match = TRUE;
}
}
if(match) {
#if defined(USE_NTLM)
/* If we are looking for an HTTP+NTLM connection, check if this is
already authenticating with the right credentials. If not, keep
looking so that we can reuse NTLM connections if
possible. (Especially we must not reuse the same connection if
partway through a handshake!) */
if(wantNTLMhttp) {
if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) {
chosen = check;
/* We must use this connection, no other */
*force_reuse = TRUE;
break;
}
else if(credentialsMatch)
/* this is a backup choice */
chosen = check;
continue;
}
#endif
if(canPipeline) {
/* We can pipeline if we want to. Let's continue looking for
the optimal connection to use, i.e the shortest pipe that is not
blacklisted. */
if(pipeLen == 0) {
/* We have the optimal connection. Let's stop looking. */
chosen = check;
break;
}
/* We can't use the connection if the pipe is full */
if(pipeLen >= max_pipe_len)
continue;
/* We can't use the connection if the pipe is penalized */
if(Curl_pipeline_penalized(data, check))
continue;
if(pipeLen < best_pipe_len) {
/* This connection has a shorter pipe so far. We'll pick this
and continue searching */
chosen = check;
best_pipe_len = pipeLen;
continue;
}
}
else {
/* We have found a connection. Let's stop searching. */
chosen = check;
break;
}
}
}
}
if(chosen) {
*usethis = chosen;
return TRUE; /* yes, we found one to use! */
}
return FALSE; /* no matching connecting exists */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'ConnectionExists: for NTLM re-use, require credentials to match
CVE-2015-3143
Bug: http://curl.haxx.se/docs/adv_20150422A.html
Reported-by: Paras Sethia'</s> |
<s>[INST] Given the following code containing errors, provide 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 char *sanitize_cookie_path(const char *cookie_path)
{
size_t len;
char *new_path = strdup(cookie_path);
if(!new_path)
return NULL;
/* some stupid site sends path attribute with '"'. */
if(new_path[0] == '\"') {
memmove((void *)new_path, (const void *)(new_path + 1), strlen(new_path));
}
if(new_path[strlen(new_path) - 1] == '\"') {
new_path[strlen(new_path) - 1] = 0x0;
}
/* RFC6265 5.2.4 The Path Attribute */
if(new_path[0] != '/') {
/* Let cookie-path be the default-path. */
free(new_path);
new_path = strdup("/");
return new_path;
}
/* convert /hoge/ to /hoge */
len = strlen(new_path);
if(1 < len && new_path[len - 1] == '/') {
new_path[len - 1] = 0x0;
}
return new_path;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'cookie: cookie parser out of boundary memory access
The internal libcurl function called sanitize_cookie_path() that cleans
up the path element as given to it from a remote site or when read from
a file, did not properly validate the input. If given a path that
consisted of a single double-quote, libcurl would index a newly
allocated memory area with index -1 and assign a zero to it, thus
destroying heap memory it wasn't supposed to.
CVE-2015-3145
Bug: http://curl.haxx.se/docs/adv_20150422C.html
Reported-by: Hanno Böck'</s> |
<s>[INST] Given the following code containing errors, provide 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 PacketReader::getLabelFromContent(const vector<uint8_t>& content, uint16_t& frompos, string& ret, int recurs)
{
if(recurs > 1000) // the forward reference-check below should make this test 100% obsolete
throw MOADNSException("Loop");
// it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop
for(;;) {
unsigned char labellen=content.at(frompos++);
if(!labellen) {
if(ret.empty())
ret.append(1,'.');
break;
}
else if((labellen & 0xc0) == 0xc0) {
uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader);
// cout<<"This is an offset, need to go to: "<<offset<<endl;
if(offset >= frompos-2)
throw MOADNSException("forward reference during label decompression");
return getLabelFromContent(content, offset, ret, ++recurs);
}
else if(labellen > 63)
throw MOADNSException("Overly long label during label decompression ("+lexical_cast<string>((unsigned int)labellen)+")");
else {
// XXX FIXME THIS MIGHT BE VERY SLOW!
for(string::size_type n = 0 ; n < labellen; ++n, frompos++) {
if(content.at(frompos)=='.' || content.at(frompos)=='\\') {
ret.append(1, '\\');
ret.append(1, content[frompos]);
}
else if(content.at(frompos)==' ') {
ret+="\\032";
}
else
ret.append(1, content[frompos]);
}
ret.append(1,'.');
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'fix forward reference-check in getLabelFromContent()'</s> |
<s>[INST] Given the following code containing errors, provide 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 php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
} else {
ctx->r = parent_req;
}
return OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #68486 and bug #69218 (segfault in apache2handler with apache 2.4)'</s> |
<s>[INST] Given the following code containing errors, provide 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 php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
char *algo, *data, *digest;
int algo_len, data_len;
zend_bool raw_output = raw_output_default;
const php_hash_ops *ops;
void *context;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &algo, &algo_len, &data, &data_len, &raw_output) == FAILURE) {
return;
}
ops = php_hash_fetch_ops(algo, algo_len);
if (!ops) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo);
RETURN_FALSE;
}
if (isfilename) {
if (CHECK_NULL_PATH(data, data_len)) {
RETURN_FALSE;
}
stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT);
if (!stream) {
/* Stream will report errors opening file */
RETURN_FALSE;
}
}
context = emalloc(ops->context_size);
ops->hash_init(context);
if (isfilename) {
char buf[1024];
int n;
while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
ops->hash_update(context, (unsigned char *) buf, n);
}
php_stream_close(stream);
} else {
ops->hash_update(context, (unsigned char *) data, data_len);
}
digest = emalloc(ops->digest_size + 1);
ops->hash_final((unsigned char *) digest, context);
efree(context);
if (raw_output) {
digest[ops->digest_size] = 0;
RETURN_STRINGL(digest, ops->digest_size, 0);
} else {
char *hex_digest = safe_emalloc(ops->digest_size, 2, 1);
php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size);
hex_digest[2 * ops->digest_size] = 0;
efree(digest);
RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide 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 php_hash_do_hash_hmac(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
char *algo, *data, *digest, *key, *K;
int algo_len, data_len, key_len;
zend_bool raw_output = raw_output_default;
const php_hash_ops *ops;
void *context;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|b", &algo, &algo_len, &data, &data_len,
&key, &key_len, &raw_output) == FAILURE) {
return;
}
ops = php_hash_fetch_ops(algo, algo_len);
if (!ops) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo);
RETURN_FALSE;
}
if (isfilename) {
stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT);
if (!stream) {
/* Stream will report errors opening file */
RETURN_FALSE;
}
}
context = emalloc(ops->context_size);
K = emalloc(ops->block_size);
digest = emalloc(ops->digest_size + 1);
php_hash_hmac_prep_key((unsigned char *) K, ops, context, (unsigned char *) key, key_len);
if (isfilename) {
char buf[1024];
int n;
ops->hash_init(context);
ops->hash_update(context, (unsigned char *) K, ops->block_size);
while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
ops->hash_update(context, (unsigned char *) buf, n);
}
php_stream_close(stream);
ops->hash_final((unsigned char *) digest, context);
} else {
php_hash_hmac_round((unsigned char *) digest, ops, context, (unsigned char *) K, (unsigned char *) data, data_len);
}
php_hash_string_xor_char((unsigned char *) K, (unsigned char *) K, 0x6A, ops->block_size);
php_hash_hmac_round((unsigned char *) digest, ops, context, (unsigned char *) K, (unsigned char *) digest, ops->digest_size);
/* Zero the key */
memset(K, 0, ops->block_size);
efree(K);
efree(context);
if (raw_output) {
digest[ops->digest_size] = 0;
RETURN_STRINGL(digest, ops->digest_size, 0);
} else {
char *hex_digest = safe_emalloc(ops->digest_size, 2, 1);
php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size);
hex_digest[2 * ops->digest_size] = 0;
efree(digest);
RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide 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 PHP_FUNCTION(xmlwriter_open_uri)
{
char *valid_file = NULL;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
char *source;
char resolved_path[MAXPATHLEN + 1];
int source_len;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
ze_xmlwriter_object *ze_obj = NULL;
#endif
#ifndef ZEND_ENGINE_2
xmlOutputBufferPtr out_buffer;
void *ioctx;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) {
return;
}
#ifdef ZEND_ENGINE_2
if (this) {
/* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */
ze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC);
}
#endif
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source");
RETURN_FALSE;
}
valid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to resolve file path");
RETURN_FALSE;
}
/* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given
path is valid and not report out of memory error. Once it is done, remove the
directory check in _xmlwriter_get_valid_file_path */
#ifndef ZEND_ENGINE_2
ioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC);
if (ioctx == NULL) {
RETURN_FALSE;
}
out_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write,
php_xmlwriter_streams_IO_close, ioctx, NULL);
if (out_buffer == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create output buffer");
RETURN_FALSE;
}
ptr = xmlNewTextWriter(out_buffer);
#else
ptr = xmlNewTextWriterFilename(valid_file, 0);
#endif
if (!ptr) {
RETURN_FALSE;
}
intern = emalloc(sizeof(xmlwriter_object));
intern->ptr = ptr;
intern->output = NULL;
#ifndef ZEND_ENGINE_2
intern->uri_output = out_buffer;
#else
if (this) {
if (ze_obj->xmlwriter_ptr) {
xmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC);
}
ze_obj->xmlwriter_ptr = intern;
RETURN_TRUE;
} else
#endif
{
ZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide 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 dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
{
zval *id;
xmlDoc *docp = NULL, *newdoc;
dom_object *intern;
dom_doc_propsptr doc_prop;
char *source;
int source_len, refcount, ret;
long options = 0;
htmlParserCtxtPtr ctxt;
id = getThis();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) {
return;
}
if (!source_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input");
RETURN_FALSE;
}
if (mode == DOM_LOAD_FILE) {
ctxt = htmlCreateFileParserCtxt(source, NULL);
} else {
source_len = xmlStrlen(source);
ctxt = htmlCreateMemoryParserCtxt(source, source_len);
}
if (!ctxt) {
RETURN_FALSE;
}
if (options) {
htmlCtxtUseOptions(ctxt, options);
}
ctxt->vctxt.error = php_libxml_ctx_error;
ctxt->vctxt.warning = php_libxml_ctx_warning;
if (ctxt->sax != NULL) {
ctxt->sax->error = php_libxml_ctx_error;
ctxt->sax->warning = php_libxml_ctx_warning;
}
htmlParseDocument(ctxt);
newdoc = ctxt->myDoc;
htmlFreeParserCtxt(ctxt);
if (!newdoc)
RETURN_FALSE;
if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
if (intern != NULL) {
docp = (xmlDocPtr) dom_object_get_node(intern);
doc_prop = NULL;
if (docp != NULL) {
php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC);
doc_prop = intern->document->doc_props;
intern->document->doc_props = NULL;
refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC);
if (refcount != 0) {
docp->_private = NULL;
}
}
intern->document = NULL;
if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) {
RETURN_FALSE;
}
intern->document->doc_props = doc_prop;
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC);
RETURN_TRUE;
} else {
DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PHP_FUNCTION(stream_resolve_include_path)
{
char *filename, *resolved_path;
int filename_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) {
return;
}
resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC);
if (resolved_path) {
RETURN_STRING(resolved_path, 0);
}
RETURN_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code:
private int
mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines, linecnt, bytecnt;
linecnt = m->str_range;
bytecnt = linecnt * 80;
if (bytecnt == 0) {
bytecnt = 8192;
}
if (bytecnt > nbytes) {
bytecnt = nbytes;
}
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + bytecnt;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + bytecnt;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes) {
file_magerror(ms, "invalid offset %u in mcopy()",
offset);
return -1;
}
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #68819 (Fileinfo on specific file causes spurious OOM and/or segfault)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: htmlParseComment(htmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len;
int size = HTML_PARSER_BUFFER_SIZE;
int q, ql;
int r, rl;
int cur, l;
xmlParserInputState state;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
SHRINK;
SKIP(4);
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
htmlErrMemory(ctxt, "buffer allocation failed\n");
ctxt->instate = state;
return;
}
q = CUR_CHAR(ql);
NEXTL(ql);
r = CUR_CHAR(rl);
NEXTL(rl);
cur = CUR_CHAR(l);
len = 0;
while (IS_CHAR(cur) &&
((cur != '>') ||
(r != '-') || (q != '-'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
htmlErrMemory(ctxt, "growing buffer failed\n");
ctxt->instate = state;
return;
}
buf = tmp;
}
COPY_BUF(ql,buf,len,q);
q = r;
ql = rl;
r = cur;
rl = l;
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (!IS_CHAR(cur)) {
htmlParseErr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n", buf, NULL);
xmlFree(buf);
} else {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->comment(ctxt->userData, buf);
xmlFree(buf);
}
ctxt->instate = state;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix parsing short unclosed comment uninitialized access
For https://bugzilla.gnome.org/show_bug.cgi?id=746048
The HTML parser was too optimistic when processing comments and
didn't check for the end of the stream on the first 2 characters'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static gboolean key_value_ok(gchar *key, gchar *value)
{
char *i;
/* check key, it has to be valid filename and will end up in the
* bugzilla */
for (i = key; *i != 0; i++)
{
if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))
return FALSE;
}
/* check value of 'basename', it has to be valid non-hidden directory
* name */
if (strcmp(key, "basename") == 0
|| strcmp(key, FILENAME_TYPE) == 0
)
{
if (!is_correct_filename(value))
{
error_msg("Value of '%s' ('%s') is not a valid directory name",
key, value);
return FALSE;
}
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'daemon: use libreport's function checking file name
Move the functions to libreport because we need the same functionality
there too.
Related: #1214451
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static gboolean is_correct_filename(const char *value)
{
return printable_str(value) && !strchr(value, '/') && !strchr(value, '.');
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'daemon: use libreport's function checking file name
Move the functions to libreport because we need the same functionality
there too.
Related: #1214451
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)
{
INITIALIZE_LIBREPORT();
char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);
if (!type)
{
error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER);
return NULL;
}
uid_t uid = (uid_t)-1L;
char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);
if (uid_str)
{
char *endptr;
errno = 0;
long val = strtol(uid_str, &endptr, 10);
if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val)
{
error_msg(_("uid value is not valid: '%s'"), uid_str);
return NULL;
}
uid = (uid_t)val;
}
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0)
{
perror_msg("gettimeofday()");
return NULL;
}
char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());
log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid);
struct dump_dir *dd;
if (base_dir_name)
dd = try_dd_create(base_dir_name, problem_id, uid);
else
{
/* Try /var/run/abrt */
dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid);
/* Try $HOME/tmp */
if (!dd)
{
char *home = getenv("HOME");
if (home && home[0])
{
home = concat_path_file(home, "tmp");
/*mkdir(home, 0777); - do we want this? */
dd = try_dd_create(home, problem_id, uid);
free(home);
}
}
//TODO: try user's home dir obtained by getpwuid(getuid())?
/* Try system temporary directory */
if (!dd)
dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);
}
if (!dd) /* try_dd_create() already emitted the error message */
goto ret;
GHashTableIter iter;
char *name;
struct problem_item *value;
g_hash_table_iter_init(&iter, problem_data);
while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))
{
if (value->flags & CD_FLAG_BIN)
{
char *dest = concat_path_file(dd->dd_dirname, name);
log_info("copying '%s' to '%s'", value->content, dest);
off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);
if (copied < 0)
error_msg("Can't copy %s to %s", value->content, dest);
else
log_info("copied %li bytes", (unsigned long)copied);
free(dest);
continue;
}
/* only files should contain '/' and those are handled earlier */
if (name[0] == '.' || strchr(name, '/'))
{
error_msg("Problem data field name contains disallowed chars: '%s'", name);
continue;
}
dd_save_text(dd, name, value->content);
}
/* need to create basic files AFTER we save the pd to dump_dir
* otherwise we can't skip already created files like in case when
* reporting from anaconda where we can't read /etc/{system,redhat}-release
* and os_release is taken from anaconda
*/
dd_create_basic_files(dd, uid, NULL);
problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0';
char* new_path = concat_path_file(base_dir_name, problem_id);
log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path);
dd_rename(dd, new_path);
ret:
free(problem_id);
return dd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues
Test correctness of all accessed dump dir files in all dd* functions.
Before this commit, the callers were allowed to pass strings like
"../../etc/shadow" in the filename argument of all dd* functions.
Related: #1214457
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues
Test correctness of all accessed dump dir files in all dd* functions.
Before this commit, the callers were allowed to pass strings like
"../../etc/shadow" in the filename argument of all dd* functions.
Related: #1214457
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
/* Compat with old abrt dumps. Remove in abrt-2.1 */
if (strcmp(name, "release") == 0)
name = FILENAME_OS_RELEASE;
char *full_path = concat_path_file(dd->dd_dirname, name);
char *ret = load_text_file(full_path, flags);
free(full_path);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues
Test correctness of all accessed dump dir files in all dd* functions.
Before this commit, the callers were allowed to pass strings like
"../../etc/shadow" in the filename argument of all dd* functions.
Related: #1214457
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues
Test correctness of all accessed dump dir files in all dd* functions.
Before this commit, the callers were allowed to pass strings like
"../../etc/shadow" in the filename argument of all dd* functions.
Related: #1214457
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dir_is_in_dump_location(const char *dump_dir_name)
{
unsigned len = strlen(g_settings_dump_location);
if (strncmp(dump_dir_name, g_settings_dump_location, len) == 0
&& dump_dir_name[len] == '/'
/* must not contain "/." anywhere (IOW: disallow ".." component) */
&& !strstr(dump_dir_name + len, "/.")
) {
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir
Move the code from abrt-server to shared library and fix the condition
validating dump dir's path.
As of now, abrt is allowed to process only direct sub-directories of the
dump locations.
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (g_settings_privatereports)
{
struct stat statbuf;
if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
error_msg("Path '%s' isn't directory", dirname);
return 404; /* Not Found */
}
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (!gr)
{
error_msg("Group 'abrt' does not exist");
return 500;
}
if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 403;
}
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
//log("Reading from event fd %d", child_stdout_fd);
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
//log("Started notify, fd %d -> %d", fd, child_stdout_fd);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir
Move the code from abrt-server to shared library and fix the condition
validating dump dir's path.
As of now, abrt is allowed to process only direct sub-directories of the
dump locations.
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 for_each_problem_in_dir(const char *path,
uid_t caller_uid,
int (*callback)(struct dump_dir *dd, void *arg),
void *arg)
{
DIR *dp = opendir(path);
if (!dp)
{
/* We don't want to yell if, say, $XDG_CACHE_DIR/abrt/spool doesn't exist */
//perror_msg("Can't open directory '%s'", path);
return 0;
}
int brk = 0;
struct dirent *dent;
while ((dent = readdir(dp)) != NULL)
{
if (dot_or_dotdot(dent->d_name))
continue; /* skip "." and ".." */
char *full_name = concat_path_file(path, dent->d_name);
if (caller_uid == -1 || dump_dir_accessible_by_uid(full_name, caller_uid))
{
/* Silently ignore *any* errors, not only EACCES.
* We saw "lock file is locked by process PID" error
* when we raced with wizard.
*/
int sv_logmode = logmode;
logmode = 0;
struct dump_dir *dd = dd_opendir(full_name, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES | DD_DONT_WAIT_FOR_LOCK);
logmode = sv_logmode;
if (dd)
{
brk = callback ? callback(dd, arg) : 0;
dd_close(dd);
}
}
free(full_name);
if (brk)
break;
}
closedir(dp);
return brk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'dbus: avoid race-conditions in tests for dum dir availability
Florian Weimer <[email protected]>
dump_dir_accessible_by_uid() is fundamentally insecure because it
opens up a classic time-of-check-time-of-use race between this
function and and dd_opendir().
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
if (!dump_dir_accessible_by_uid(problem_id, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
return NULL;
}
struct dump_dir *dd = dd_opendir(problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'dbus: avoid race-conditions in tests for dum dir availability
Florian Weimer <[email protected]>
dump_dir_accessible_by_uid() is fundamentally insecure because it
opens up a classic time-of-check-time-of-use race between this
function and and dd_opendir().
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_reset_ownership(struct dump_dir *dd)
{
const int r =lchown(dd->dd_dirname, dd->dd_uid, dd->dd_gid);
if (r < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dd->dd_dirname,
(long)dd->dd_uid, (long)dd->dd_gid);
}
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static const char *dd_check(struct dump_dir *dd)
{
unsigned dirname_len = strlen(dd->dd_dirname);
char filename_buf[FILENAME_MAX+1];
strcpy(filename_buf, dd->dd_dirname);
strcpy(filename_buf + dirname_len, "/"FILENAME_TIME);
dd->dd_time = parse_time_file(filename_buf);
if (dd->dd_time < 0)
{
log_warning("Missing file: "FILENAME_TIME);
return FILENAME_TIME;
}
strcpy(filename_buf + dirname_len, "/"FILENAME_TYPE);
dd->dd_type = load_text_file(filename_buf, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!dd->dd_type || (strlen(dd->dd_type) == 0))
{
log_warning("Missing or empty file: "FILENAME_TYPE);
return FILENAME_TYPE;
}
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_delete_item(struct dump_dir *dd, const char *name)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name);
char *path = concat_path_file(dd->dd_dirname, name);
int res = unlink(path);
if (res < 0)
{
if (errno == ENOENT)
errno = res = 0;
else
perror_msg("Can't delete file '%s'", path);
}
free(path);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_close(struct dump_dir *dd)
{
if (!dd)
return;
dd_unlock(dd);
if (dd->next_dir)
{
closedir(dd->next_dir);
/* free(dd->next_dir); - WRONG! */
}
free(dd->dd_type);
free(dd->dd_dirname);
free(dd);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 time_t parse_time_file(const char *filename)
{
/* Open input file, and parse it. */
int fd = open(filename, O_RDONLY | O_NOFOLLOW);
if (fd < 0)
{
VERB2 pwarn_msg("Can't open '%s'", filename);
return -1;
}
/* ~ maximal number of digits for positive time stamp string */
char time_buf[sizeof(time_t) * 3 + 1];
ssize_t rdsz = read(fd, time_buf, sizeof(time_buf));
/* Just reading, so no need to check the returned value. */
close(fd);
if (rdsz == -1)
{
VERB2 pwarn_msg("Can't read from '%s'", filename);
return -1;
}
/* approximate maximal number of digits in timestamp is sizeof(time_t)*3 */
/* buffer has this size + 1 byte for trailing '\0' */
/* if whole size of buffer was read then file is bigger */
/* than string representing maximal time stamp */
if (rdsz == sizeof(time_buf))
{
VERB2 warn_msg("File '%s' is too long to be valid unix "
"time stamp (max size %u)", filename, (int)sizeof(time_buf));
return -1;
}
/* Our tools don't put trailing newline into time file,
* but we allow such format too:
*/
if (rdsz > 0 && time_buf[rdsz - 1] == '\n')
rdsz--;
time_buf[rdsz] = '\0';
/* Note that on some architectures (x32) time_t is "long long" */
errno = 0; /* To distinguish success/failure after call */
char *endptr;
long long val = strtoll(time_buf, &endptr, /* base */ 10);
const long long MAX_TIME_T = (1ULL << (sizeof(time_t)*8 - 1)) - 1;
/* Check for various possible errors */
if (errno
|| (*endptr != '\0')
|| val >= MAX_TIME_T
|| !isdigit_str(time_buf) /* this filters out "-num", " num", "" */
) {
VERB2 pwarn_msg("File '%s' doesn't contain valid unix "
"time stamp ('%s')", filename, time_buf);
return -1;
}
/* If we got here, strtoll() successfully parsed a number */
return val;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot save binary. '%s' is not a valid file name", name);
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 delete_file_dir(const char *dir, bool skip_lock_file)
{
DIR *d = opendir(dir);
if (!d)
{
/* The caller expects us to error out only if the directory
* still exists (not deleted). If directory
* *doesn't exist*, return 0 and clear errno.
*/
if (errno == ENOENT || errno == ENOTDIR)
{
errno = 0;
return 0;
}
return -1;
}
bool unlink_lock_file = false;
struct dirent *dent;
while ((dent = readdir(d)) != NULL)
{
if (dot_or_dotdot(dent->d_name))
continue;
if (skip_lock_file && strcmp(dent->d_name, ".lock") == 0)
{
unlink_lock_file = true;
continue;
}
char *full_path = concat_path_file(dir, dent->d_name);
if (unlink(full_path) == -1 && errno != ENOENT)
{
int err = 0;
if (errno == EISDIR)
{
errno = 0;
err = delete_file_dir(full_path, /*skip_lock_file:*/ false);
}
if (errno || err)
{
perror_msg("Can't remove '%s'", full_path);
free(full_path);
closedir(d);
return -1;
}
}
free(full_path);
}
closedir(d);
/* Here we know for sure that all files/subdirs we found via readdir
* were deleted successfully. If rmdir below fails, we assume someone
* is racing with us and created a new file.
*/
if (unlink_lock_file)
{
char *full_path = concat_path_file(dir, ".lock");
xunlink(full_path);
free(full_path);
unsigned cnt = RMDIR_FAIL_COUNT;
do {
if (rmdir(dir) == 0)
return 0;
/* Someone locked the dir after unlink, but before rmdir.
* This "someone" must be dd_lock().
* It detects this (by seeing that there is no time file)
* and backs off at once. So we need to just retry rmdir,
* with minimal sleep.
*/
usleep(RMDIR_FAIL_USLEEP);
} while (--cnt != 0);
}
int r = rmdir(dir);
if (r)
perror_msg("Can't remove directory '%s'", dir);
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: struct dump_dir *dd_create_skeleton(const char *dir, uid_t uid, mode_t mode, int flags)
{
/* a little trick to copy read bits from file mode to exec bit of dir mode*/
mode_t dir_mode = mode | ((mode & 0444) >> 2);
struct dump_dir *dd = dd_init();
dd->mode = mode;
/* Unlike dd_opendir, can't use realpath: the directory doesn't exist yet,
* realpath will always return NULL. We don't really have to:
* dd_opendir(".") makes sense, dd_create(".") does not.
*/
dir = dd->dd_dirname = rm_trailing_slashes(dir);
const char *last_component = strrchr(dir, '/');
if (last_component)
last_component++;
else
last_component = dir;
if (dot_or_dotdot(last_component))
{
/* dd_create("."), dd_create(".."), dd_create("dir/."),
* dd_create("dir/..") and similar are madness, refuse them.
*/
error_msg("Bad dir name '%s'", dir);
dd_close(dd);
return NULL;
}
/* Was creating it with mode 0700 and user as the owner, but this allows
* the user to replace any file in the directory, changing security-sensitive data
* (e.g. "uid", "analyzer", "executable")
*/
int r;
if ((flags & DD_CREATE_PARENTS))
r = g_mkdir_with_parents(dd->dd_dirname, dir_mode);
else
r = mkdir(dd->dd_dirname, dir_mode);
if (r != 0)
{
perror_msg("Can't create directory '%s'", dir);
dd_close(dd);
return NULL;
}
if (dd_lock(dd, CREATE_LOCK_USLEEP, /*flags:*/ 0) < 0)
{
dd_close(dd);
return NULL;
}
/* mkdir's mode (above) can be affected by umask, fix it */
if (chmod(dir, dir_mode) == -1)
{
perror_msg("Can't change mode of '%s'", dir);
dd_close(dd);
return NULL;
}
dd->dd_uid = (uid_t)-1L;
dd->dd_gid = (gid_t)-1L;
if (uid != (uid_t)-1L)
{
dd->dd_uid = 0;
dd->dd_uid = 0;
#if DUMP_DIR_OWNED_BY_USER > 0
/* Check crashed application's uid */
struct passwd *pw = getpwuid(uid);
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User %lu does not exist, using uid 0", (long)uid);
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (gr)
dd->dd_gid = gr->gr_gid;
else
error_msg("Group 'abrt' does not exist, using gid 0");
#else
/* Get ABRT's user uid */
struct passwd *pw = getpwnam("abrt");
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User 'abrt' does not exist, using uid 0");
/* Get crashed application's gid */
pw = getpwuid(uid);
if (pw)
dd->dd_gid = pw->pw_gid;
else
error_msg("User %lu does not exist, using gid 0", (long)uid);
#endif
}
return dd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: DIR *dd_init_next_file(struct dump_dir *dd)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
if (dd->next_dir)
closedir(dd->next_dir);
dd->next_dir = opendir(dd->dd_dirname);
if (!dd->next_dir)
{
error_msg("Can't open directory '%s'", dd->dd_dirname);
}
return dd->next_dir;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 char *load_text_file(const char *path, unsigned flags)
{
int fd = open(path, O_RDONLY | ((flags & DD_OPEN_FOLLOW) ? 0 : O_NOFOLLOW));
if (fd == -1)
{
if (!(flags & DD_FAIL_QUIETLY_ENOENT))
perror_msg("Can't open file '%s'", path);
return (flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE ? NULL : xstrdup(""));
}
/* Why? Because half a million read syscalls of one byte each isn't fun.
* FILE-based IO buffers reads.
*/
FILE *fp = fdopen(fd, "r");
if (!fp)
die_out_of_memory();
struct strbuf *buf_content = strbuf_new();
int oneline = 0;
int ch;
while ((ch = fgetc(fp)) != EOF)
{
//TODO? \r -> \n?
//TODO? strip trailing spaces/tabs?
if (ch == '\n')
oneline = (oneline << 1) | 1;
if (ch == '\0')
ch = ' ';
if (isspace(ch) || ch >= ' ') /* used !iscntrl, but it failed on unicode */
strbuf_append_char(buf_content, ch);
}
fclose(fp); /* this also closes fd */
char last = oneline != 0 ? buf_content->buf[buf_content->len - 1] : 0;
if (last == '\n')
{
/* If file contains exactly one '\n' and it is at the end, remove it.
* This enables users to use simple "echo blah >file" in order to create
* short string items in dump dirs.
*/
if (oneline == 1)
buf_content->buf[--buf_content->len] = '\0';
}
else /* last != '\n' */
{
/* Last line is unterminated, fix it */
/* Cases: */
/* oneline=0: "qwe" - DONT fix this! */
/* oneline=1: "qwe\nrty" - two lines in fact */
/* oneline>1: "qwe\nrty\uio" */
if (oneline >= 1)
strbuf_append_char(buf_content, '\n');
}
return strbuf_free_nobuf(buf_content);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_get_next_file(struct dump_dir *dd, char **short_name, char **full_name)
{
if (dd->next_dir == NULL)
return 0;
struct dirent *dent;
while ((dent = readdir(dd->next_dir)) != NULL)
{
if (is_regular_file(dent, dd->dd_dirname))
{
if (short_name)
*short_name = xstrdup(dent->d_name);
if (full_name)
*full_name = concat_path_file(dd->dd_dirname, dent->d_name);
return 1;
}
}
closedir(dd->next_dir);
dd->next_dir = NULL;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 save_binary_file(const char *path, const char* data, unsigned size, uid_t uid, gid_t gid, mode_t mode)
{
/* the mode is set by the caller, see dd_create() for security analysis */
unlink(path);
int fd = open(path, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, mode);
if (fd < 0)
{
perror_msg("Can't open file '%s'", path);
return false;
}
if (uid != (uid_t)-1L)
{
if (fchown(fd, uid, gid) == -1)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", path, (long)uid, (long)gid);
}
}
/* O_CREATE in the open() call above causes that the permissions of the
* created file are (mode & ~umask)
*
* This is true only if we did create file. We are not sure we created it
* in this case - it may exist already.
*/
if (fchmod(fd, mode) == -1)
{
perror_msg("Can't change mode of '%s'", path);
}
unsigned r = full_write(fd, data, size);
close(fd);
if (r != size)
{
error_msg("Can't save file '%s'", path);
return false;
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dd_unlock(struct dump_dir *dd)
{
if (dd->locked)
{
dd->locked = 0;
unsigned dirname_len = strlen(dd->dd_dirname);
char lock_buf[dirname_len + sizeof("/.lock")];
strcpy(lock_buf, dd->dd_dirname);
strcpy(lock_buf + dirname_len, "/.lock");
xunlink(lock_buf);
log_info("Unlocked '%s'", lock_buf);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
{
error_msg("Cannot load text. '%s' is not a valid file name", name);
if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))
xfunc_die();
}
/* Compat with old abrt dumps. Remove in abrt-2.1 */
if (strcmp(name, "release") == 0)
name = FILENAME_OS_RELEASE;
char *full_path = concat_path_file(dd->dd_dirname, name);
char *ret = load_text_file(full_path, flags);
free(full_path);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code
Florian Weimer <[email protected]>:
dd_opendir() should keep a file handle (opened with O_DIRECTORY) and
use openat() and similar functions to access files in it.
...
The file system manipulation functions should guard against hard
links (check that link count is <= 1, just as in the user coredump
code in abrt-hook-ccpp), possibly after opening the file
with O_PATH first to avoid side effects on open/close.
Related: #1214745
Signed-off-by: Jakub Filak <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 AbstractSqlStorage::addConnectionToPool()
{
QMutexLocker locker(&_connectionPoolMutex);
// we have to recheck if the connection pool already contains a connection for
// this thread. Since now (after the lock) we can only tell for sure
if (_connectionPool.contains(QThread::currentThread()))
return;
QThread *currentThread = QThread::currentThread();
int connectionId = _nextConnectionId++;
Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
connection->moveToThread(currentThread);
connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
_connectionPool[currentThread] = connection;
QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
db.setDatabaseName(databaseName());
if (!hostName().isEmpty())
db.setHostName(hostName());
if (port() != -1)
db.setPort(port());
if (!userName().isEmpty()) {
db.setUserName(userName());
db.setPassword(password());
}
if (!db.open()) {
quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
quWarning() << "-" << db.lastError().text();
}
else {
if (!initDbSession(db)) {
quWarning() << "Unable to initialize database" << displayName() << "for thread" << QThread::currentThread();
db.close();
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-89'], 'message': 'Execute initDbSession() on DB reconnects
Previously, the initDbSession() function would only be run on the
initial connect. Since the initDbSession() code in PostgreSQL is
used to fix the CVE-2013-4422 SQL Injection bug, this means that
Quassel was still vulnerable to that CVE if the PostgreSQL server
is restarted or the connection is lost at any point while Quassel
is running.
This bug also causes the Qt5 psql timezone fix to stop working
after a reconnect.
The fix is to disable Qt's automatic reconnecting, check the
connection status ourselves, and reconnect if necessary, executing
the initDbSession() function afterward.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request,
krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond, void *arg)
{
krb5_keyblock *armor_key = NULL;
krb5_pa_otp_req *req = NULL;
struct request_state *rs;
krb5_error_code retval;
krb5_data d, plaintext;
char *config;
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
/* Get the FAST armor key. */
armor_key = cb->fast_armor(context, rock);
if (armor_key == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
com_err("otp", retval, "No armor key found when verifying padata");
goto error;
}
/* Decode the request. */
d = make_data(pa->contents, pa->length);
retval = decode_krb5_pa_otp_req(&d, &req);
if (retval != 0) {
com_err("otp", retval, "Unable to decode OTP request");
goto error;
}
/* Decrypt the nonce from the request. */
retval = decrypt_encdata(context, armor_key, req, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to decrypt nonce");
goto error;
}
/* Verify the nonce or timestamp. */
retval = nonce_verify(context, armor_key, &plaintext);
if (retval != 0)
retval = timestamp_verify(context, &plaintext);
krb5_free_data_contents(context, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to verify nonce or timestamp");
goto error;
}
/* Create the request state. */
rs = k5alloc(sizeof(struct request_state), &retval);
if (rs == NULL)
goto error;
rs->arg = arg;
rs->respond = respond;
/* Get the principal's OTP configuration string. */
retval = cb->get_string(context, rock, "otp", &config);
if (retval == 0 && config == NULL)
retval = KRB5_PREAUTH_FAILED;
if (retval != 0) {
free(rs);
goto error;
}
/* Send the request. */
otp_state_verify((otp_state *)moddata, cb->event_context(context, rock),
request->client, config, req, on_response, rs);
cb->free_string(context, rock, config);
k5_free_pa_otp_req(context, req);
return;
error:
k5_free_pa_otp_req(context, req);
(*respond)(arg, retval, NULL, NULL, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
int valid_eku = 0, valid_san = 0;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n");
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n");
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
pkiDebug("pkcs7_signeddata_verify failed\n");
goto cleanup;
}
if (is_signed) {
retval = verify_client_san(context, plgctx, reqctx, request->client,
&valid_san);
if (retval)
goto cleanup;
if (!valid_san) {
pkiDebug("%s: did not find an acceptable SAN in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
retval = verify_client_eku(context, plgctx, reqctx, &valid_eku);
if (retval)
goto cleanup;
if (!valid_eku) {
pkiDebug("%s: did not find an acceptable EKU in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
goto cleanup;
}
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]'</s> |
<s>[INST] Given the following code containing errors, provide 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 dbConnect(char *host, char *user, char *passwd)
{
DBUG_ENTER("dbConnect");
if (verbose)
{
fprintf(stderr, "# Connecting to %s...\n", host ? host : "localhost");
}
mysql_init(&mysql_connection);
if (opt_compress)
mysql_options(&mysql_connection, MYSQL_OPT_COMPRESS, NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
{
mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
}
#endif
if (opt_protocol)
mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
if (opt_bind_addr)
mysql_options(&mysql_connection, MYSQL_OPT_BIND, opt_bind_addr);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);
mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);
mysql_options(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqlcheck");
if (!(sock = mysql_real_connect(&mysql_connection, host, user, passwd,
NULL, opt_mysql_port, opt_mysql_unix_port, 0)))
{
DBerror(&mysql_connection, "when trying to connect");
DBUG_RETURN(1);
}
mysql_connection.reconnect= 1;
DBUG_RETURN(0);
} /* dbConnect */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: init_connection_options(MYSQL *mysql)
{
my_bool handle_expired= (opt_connect_expired_password || !status.batch) ?
TRUE : FALSE;
if (opt_init_command)
mysql_options(mysql, MYSQL_INIT_COMMAND, opt_init_command);
if (opt_connect_timeout)
{
uint timeout= opt_connect_timeout;
mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char*) &timeout);
}
if (opt_bind_addr)
mysql_options(mysql, MYSQL_OPT_BIND, opt_bind_addr);
if (opt_compress)
mysql_options(mysql, MYSQL_OPT_COMPRESS, NullS);
if (!opt_secure_auth)
mysql_options(mysql, MYSQL_SECURE_AUTH, (char *) &opt_secure_auth);
if (using_opt_local_infile)
mysql_options(mysql, MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (opt_use_ssl)
{
mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
}
mysql_options(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
(char*) &opt_ssl_verify_server_cert);
#endif
if (opt_protocol)
mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME, shared_memory_base_name);
#endif
if (safe_updates)
{
char init_command[100];
sprintf(init_command,
"SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%lu,MAX_JOIN_SIZE=%lu",
select_limit, max_join_size);
mysql_options(mysql, MYSQL_INIT_COMMAND, init_command);
}
mysql_set_character_set(mysql, default_charset);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
#if !defined(HAVE_YASSL)
if (opt_server_public_key && *opt_server_public_key)
mysql_options(mysql, MYSQL_SERVER_PUBLIC_KEY, opt_server_public_key);
#endif
if (using_opt_enable_cleartext_plugin)
mysql_options(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*) &opt_enable_cleartext_plugin);
mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysql");
mysql_options(mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, &handle_expired);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: get_one_option(int optid, const struct my_option *opt,
char *argument)
{
my_bool add_option= TRUE;
switch (optid) {
case '?':
printf("%s Ver %s Distrib %s, for %s (%s)\n",
my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
puts("MySQL utility for upgrading databases to new MySQL versions.\n");
my_print_help(my_long_options);
exit(0);
break;
case '#':
DBUG_PUSH(argument ? argument : default_dbug_option);
add_option= FALSE;
debug_check_flag= 1;
break;
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; /* Don't require password */
tty_password= 1;
add_option= FALSE;
if (argument)
{
/* Add password to ds_args before overwriting the arg with x's */
add_one_option(&ds_args, opt, argument);
while (*argument)
*argument++= 'x'; /* Destroy argument */
tty_password= 0;
}
break;
case 't':
my_stpnmov(opt_tmpdir, argument, sizeof(opt_tmpdir));
add_option= FALSE;
break;
case 'k': /* --version-check */
case 'v': /* --verbose */
case 'f': /* --force */
case 's': /* --upgrade-system-tables */
case OPT_WRITE_BINLOG: /* --write-binlog */
add_option= FALSE;
break;
case 'h': /* --host */
case 'W': /* --pipe */
case 'P': /* --port */
case 'S': /* --socket */
case OPT_MYSQL_PROTOCOL: /* --protocol */
case OPT_SHARED_MEMORY_BASE_NAME: /* --shared-memory-base-name */
case OPT_PLUGIN_DIR: /* --plugin-dir */
case OPT_DEFAULT_AUTH: /* --default-auth */
add_one_option(&conn_args, opt, argument);
break;
}
if (add_option)
{
/*
This is an option that is accpted by mysql_upgrade just so
it can be passed on to "mysql" and "mysqlcheck"
Save it in the ds_args string
*/
add_one_option(&ds_args, opt, argument);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 do_connect(struct st_command *command)
{
int con_port= opt_port;
char *con_options;
my_bool con_ssl= 0, con_compress= 0;
my_bool con_pipe= 0, con_shm= 0, con_cleartext_enable= 0;
my_bool con_secure_auth= 1;
struct st_connection* con_slot;
static DYNAMIC_STRING ds_connection_name;
static DYNAMIC_STRING ds_host;
static DYNAMIC_STRING ds_user;
static DYNAMIC_STRING ds_password;
static DYNAMIC_STRING ds_database;
static DYNAMIC_STRING ds_port;
static DYNAMIC_STRING ds_sock;
static DYNAMIC_STRING ds_options;
static DYNAMIC_STRING ds_default_auth;
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
static DYNAMIC_STRING ds_shm;
#endif
const struct command_arg connect_args[] = {
{ "connection name", ARG_STRING, TRUE, &ds_connection_name, "Name of the connection" },
{ "host", ARG_STRING, TRUE, &ds_host, "Host to connect to" },
{ "user", ARG_STRING, FALSE, &ds_user, "User to connect as" },
{ "passsword", ARG_STRING, FALSE, &ds_password, "Password used when connecting" },
{ "database", ARG_STRING, FALSE, &ds_database, "Database to select after connect" },
{ "port", ARG_STRING, FALSE, &ds_port, "Port to connect to" },
{ "socket", ARG_STRING, FALSE, &ds_sock, "Socket to connect with" },
{ "options", ARG_STRING, FALSE, &ds_options, "Options to use while connecting" },
{ "default_auth", ARG_STRING, FALSE, &ds_default_auth, "Default authentication to use" }
};
DBUG_ENTER("do_connect");
DBUG_PRINT("enter",("connect: %s", command->first_argument));
strip_parentheses(command);
check_command_args(command, command->first_argument, connect_args,
sizeof(connect_args)/sizeof(struct command_arg),
',');
/* Port */
if (ds_port.length)
{
con_port= atoi(ds_port.str);
if (con_port == 0)
die("Illegal argument for port: '%s'", ds_port.str);
}
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
/* Shared memory */
init_dynamic_string(&ds_shm, ds_sock.str, 0, 0);
#endif
/* Sock */
if (ds_sock.length)
{
/*
If the socket is specified just as a name without path
append tmpdir in front
*/
if (*ds_sock.str != FN_LIBCHAR)
{
char buff[FN_REFLEN];
fn_format(buff, ds_sock.str, TMPDIR, "", 0);
dynstr_set(&ds_sock, buff);
}
}
else
{
/* No socket specified, use default */
dynstr_set(&ds_sock, unix_sock);
}
DBUG_PRINT("info", ("socket: %s", ds_sock.str));
/* Options */
con_options= ds_options.str;
while (*con_options)
{
char* end;
/* Step past any spaces in beginning of option*/
while (*con_options && my_isspace(charset_info, *con_options))
con_options++;
/* Find end of this option */
end= con_options;
while (*end && !my_isspace(charset_info, *end))
end++;
if (!strncmp(con_options, "SSL", 3))
con_ssl= 1;
else if (!strncmp(con_options, "COMPRESS", 8))
con_compress= 1;
else if (!strncmp(con_options, "PIPE", 4))
con_pipe= 1;
else if (!strncmp(con_options, "SHM", 3))
con_shm= 1;
else if (!strncmp(con_options, "CLEARTEXT", 9))
con_cleartext_enable= 1;
else if (!strncmp(con_options, "SKIPSECUREAUTH",14))
con_secure_auth= 0;
else
die("Illegal option to connect: %.*s",
(int) (end - con_options), con_options);
/* Process next option */
con_options= end;
}
if (find_connection_by_name(ds_connection_name.str))
die("Connection %s already exists", ds_connection_name.str);
if (next_con != connections_end)
con_slot= next_con;
else
{
if (!(con_slot= find_connection_by_name("-closed_connection-")))
die("Connection limit exhausted, you can have max %d connections",
opt_max_connections);
}
#ifdef EMBEDDED_LIBRARY
init_connection_thd(con_slot);
#endif /*EMBEDDED_LIBRARY*/
if (!mysql_init(&con_slot->mysql))
die("Failed on mysql_init()");
if (opt_connect_timeout)
mysql_options(&con_slot->mysql, MYSQL_OPT_CONNECT_TIMEOUT,
(void *) &opt_connect_timeout);
if (opt_compress || con_compress)
mysql_options(&con_slot->mysql, MYSQL_OPT_COMPRESS, NullS);
mysql_options(&con_slot->mysql, MYSQL_OPT_LOCAL_INFILE, 0);
mysql_options(&con_slot->mysql, MYSQL_SET_CHARSET_NAME,
charset_info->csname);
if (opt_charsets_dir)
mysql_options(&con_slot->mysql, MYSQL_SET_CHARSET_DIR,
opt_charsets_dir);
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (opt_use_ssl)
con_ssl= 1;
#endif
if (con_ssl)
{
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
mysql_ssl_set(&con_slot->mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&con_slot->mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(&con_slot->mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
#if MYSQL_VERSION_ID >= 50000
/* Turn on ssl_verify_server_cert only if host is "localhost" */
opt_ssl_verify_server_cert= !strcmp(ds_host.str, "localhost");
mysql_options(&con_slot->mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
&opt_ssl_verify_server_cert);
#endif
#endif
}
if (con_pipe)
{
#if defined(_WIN32) && !defined(EMBEDDED_LIBRARY)
opt_protocol= MYSQL_PROTOCOL_PIPE;
#endif
}
#ifndef EMBEDDED_LIBRARY
if (opt_protocol)
mysql_options(&con_slot->mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);
#endif
if (con_shm)
{
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
uint protocol= MYSQL_PROTOCOL_MEMORY;
if (!ds_shm.length)
die("Missing shared memory base name");
mysql_options(&con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME, ds_shm.str);
mysql_options(&con_slot->mysql, MYSQL_OPT_PROTOCOL, &protocol);
#endif
}
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
else if (shared_memory_base_name)
{
mysql_options(&con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME,
shared_memory_base_name);
}
#endif
/* Use default db name */
if (ds_database.length == 0)
dynstr_set(&ds_database, opt_db);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&con_slot->mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (ds_default_auth.length)
mysql_options(&con_slot->mysql, MYSQL_DEFAULT_AUTH, ds_default_auth.str);
#if !defined(HAVE_YASSL)
/* Set server public_key */
if (opt_server_public_key && *opt_server_public_key)
mysql_options(&con_slot->mysql, MYSQL_SERVER_PUBLIC_KEY,
opt_server_public_key);
#endif
if (con_cleartext_enable)
mysql_options(&con_slot->mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*) &con_cleartext_enable);
if (!con_secure_auth)
mysql_options(&con_slot->mysql, MYSQL_SECURE_AUTH,
(char*) &con_secure_auth);
/* Special database to allow one to connect without a database name */
if (ds_database.length && !strcmp(ds_database.str,"*NO-ONE*"))
dynstr_set(&ds_database, "");
if (connect_n_handle_errors(command, &con_slot->mysql,
ds_host.str,ds_user.str,
ds_password.str, ds_database.str,
con_port, ds_sock.str))
{
DBUG_PRINT("info", ("Inserting connection %s in connection pool",
ds_connection_name.str));
if (!(con_slot->name= my_strdup(PSI_NOT_INSTRUMENTED,
ds_connection_name.str, MYF(MY_WME))))
die("Out of memory");
con_slot->name_len= strlen(con_slot->name);
set_current_connection(con_slot);
if (con_slot == next_con)
next_con++; /* if we used the next_con slot, advance the pointer */
}
dynstr_free(&ds_connection_name);
dynstr_free(&ds_host);
dynstr_free(&ds_user);
dynstr_free(&ds_password);
dynstr_free(&ds_database);
dynstr_free(&ds_port);
dynstr_free(&ds_sock);
dynstr_free(&ds_options);
dynstr_free(&ds_default_auth);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
dynstr_free(&ds_shm);
#endif
DBUG_VOID_RETURN;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 MYSQL *db_connect(char *host, char *database,
char *user, char *passwd)
{
MYSQL *mysql;
if (verbose)
fprintf(stdout, "Connecting to %s\n", host ? host : "localhost");
if (!(mysql= mysql_init(NULL)))
return 0;
if (opt_compress)
mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);
if (opt_local_file)
mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE,
(char*) &opt_local_file);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
{
mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
}
mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
(char*)&opt_ssl_verify_server_cert);
#endif
if (opt_protocol)
mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
if (opt_bind_addr)
mysql_options(mysql,MYSQL_OPT_BIND,opt_bind_addr);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset);
mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqlimport");
if (!(mysql_real_connect(mysql,host,user,passwd,
database,opt_mysql_port,opt_mysql_unix_port,
0)))
{
ignore_errors=0; /* NO RETURN FROM db_error */
db_error(mysql);
}
mysql->reconnect= 0;
if (verbose)
fprintf(stdout, "Selecting database %s\n", database);
if (mysql_select_db(mysql, database))
{
ignore_errors=0;
db_error(mysql);
}
return mysql;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 send_client_reply_packet(MCPVIO_EXT *mpvio,
const uchar *data, int data_len)
{
MYSQL *mysql= mpvio->mysql;
NET *net= &mysql->net;
char *buff, *end;
size_t buff_size;
size_t connect_attrs_len=
(mysql->server_capabilities & CLIENT_CONNECT_ATTRS &&
mysql->options.extension) ?
mysql->options.extension->connection_attributes_length : 0;
DBUG_ASSERT(connect_attrs_len < MAX_CONNECTION_ATTR_STORAGE_LENGTH);
/*
see end= buff+32 below, fixed size of the packet is 32 bytes.
+9 because data is a length encoded binary where meta data size is max 9.
*/
buff_size= 33 + USERNAME_LENGTH + data_len + 9 + NAME_LEN + NAME_LEN + connect_attrs_len + 9;
buff= my_alloca(buff_size);
mysql->client_flag|= mysql->options.client_flag;
mysql->client_flag|= CLIENT_CAPABILITIES;
if (mysql->client_flag & CLIENT_MULTI_STATEMENTS)
mysql->client_flag|= CLIENT_MULTI_RESULTS;
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (mysql->options.ssl_key || mysql->options.ssl_cert ||
mysql->options.ssl_ca || mysql->options.ssl_capath ||
mysql->options.ssl_cipher ||
(mysql->options.extension && mysql->options.extension->ssl_crl) ||
(mysql->options.extension && mysql->options.extension->ssl_crlpath))
mysql->options.use_ssl= 1;
if (mysql->options.use_ssl)
mysql->client_flag|= CLIENT_SSL;
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY*/
if (mpvio->db)
mysql->client_flag|= CLIENT_CONNECT_WITH_DB;
else
mysql->client_flag&= ~CLIENT_CONNECT_WITH_DB;
/* Remove options that server doesn't support */
mysql->client_flag= mysql->client_flag &
(~(CLIENT_COMPRESS | CLIENT_SSL | CLIENT_PROTOCOL_41)
| mysql->server_capabilities);
#ifndef HAVE_COMPRESS
mysql->client_flag&= ~CLIENT_COMPRESS;
#endif
if (mysql->client_flag & CLIENT_PROTOCOL_41)
{
/* 4.1 server and 4.1 client has a 32 byte option flag */
int4store(buff,mysql->client_flag);
int4store(buff+4, net->max_packet_size);
buff[8]= (char) mysql->charset->number;
memset(buff+9, 0, 32-9);
end= buff+32;
}
else
{
int2store(buff, mysql->client_flag);
int3store(buff+2, net->max_packet_size);
end= buff+5;
}
#ifdef HAVE_OPENSSL
if (mysql->client_flag & CLIENT_SSL)
{
/* Do the SSL layering. */
struct st_mysql_options *options= &mysql->options;
struct st_VioSSLFd *ssl_fd;
enum enum_ssl_init_error ssl_init_error;
const char *cert_error;
unsigned long ssl_error;
/*
Send mysql->client_flag, max_packet_size - unencrypted otherwise
the server does not know we want to do SSL
*/
MYSQL_TRACE(SEND_SSL_REQUEST, mysql, (end - buff, (const unsigned char*)buff));
if (my_net_write(net, (uchar*)buff, (size_t) (end-buff)) || net_flush(net))
{
set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
ER(CR_SERVER_LOST_EXTENDED),
"sending connection information to server",
errno);
goto error;
}
MYSQL_TRACE_STAGE(mysql, SSL_NEGOTIATION);
/* Create the VioSSLConnectorFd - init SSL and load certs */
if (!(ssl_fd= new_VioSSLConnectorFd(options->ssl_key,
options->ssl_cert,
options->ssl_ca,
options->ssl_capath,
options->ssl_cipher,
&ssl_init_error,
options->extension ?
options->extension->ssl_crl : NULL,
options->extension ?
options->extension->ssl_crlpath : NULL)))
{
set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
ER(CR_SSL_CONNECTION_ERROR), sslGetErrString(ssl_init_error));
goto error;
}
mysql->connector_fd= (unsigned char *) ssl_fd;
/* Connect to the server */
DBUG_PRINT("info", ("IO layer change in progress..."));
MYSQL_TRACE(SSL_CONNECT, mysql, ());
if (sslconnect(ssl_fd, net->vio,
(long) (mysql->options.connect_timeout), &ssl_error))
{
char buf[512];
ERR_error_string_n(ssl_error, buf, 512);
buf[511]= 0;
set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
ER(CR_SSL_CONNECTION_ERROR),
buf);
goto error;
}
DBUG_PRINT("info", ("IO layer change done!"));
/* Verify server cert */
if ((mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) &&
ssl_verify_server_cert(net->vio, mysql->host, &cert_error))
{
set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
ER(CR_SSL_CONNECTION_ERROR), cert_error);
goto error;
}
MYSQL_TRACE(SSL_CONNECTED, mysql, ());
MYSQL_TRACE_STAGE(mysql, AUTHENTICATE);
}
#endif /* HAVE_OPENSSL */
DBUG_PRINT("info",("Server version = '%s' capabilites: %lu status: %u client_flag: %lu",
mysql->server_version, mysql->server_capabilities,
mysql->server_status, mysql->client_flag));
compile_time_assert(MYSQL_USERNAME_LENGTH == USERNAME_LENGTH);
/* This needs to be changed as it's not useful with big packets */
if (mysql->user[0])
strmake(end, mysql->user, USERNAME_LENGTH);
else
read_user_name(end);
/* We have to handle different version of handshake here */
DBUG_PRINT("info",("user: %s",end));
end= strend(end) + 1;
if (data_len)
{
if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
{
/*
Since the older versions of server do not have
CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA capability,
a check is performed on this before sending auth data.
If lenenc support is not available, the data is sent
in the format of first byte representing the length of
the string followed by the actual string.
*/
if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA)
end= write_length_encoded_string4(end, (char *)(buff + buff_size),
(char *) data,
(char *)(data + data_len));
else
end= write_string(end, (char *)(buff + buff_size),
(char *) data,
(char *)(data + data_len));
if (end == NULL)
goto error;
}
else
{
DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1); /* incl. \0 at the end */
memcpy(end, data, data_len);
end+= data_len;
}
}
else
*end++= 0;
/* Add database if needed */
if (mpvio->db && (mysql->server_capabilities & CLIENT_CONNECT_WITH_DB))
{
end= strmake(end, mpvio->db, NAME_LEN) + 1;
mysql->db= my_strdup(key_memory_MYSQL,
mpvio->db, MYF(MY_WME));
}
if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH)
end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1;
end= (char *) send_client_connect_attrs(mysql, (uchar *) end);
/* Write authentication package */
MYSQL_TRACE(SEND_AUTH_RESPONSE, mysql, (end-buff, (const unsigned char*)buff));
if (my_net_write(net, (uchar*) buff, (size_t) (end-buff)) || net_flush(net))
{
set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
ER(CR_SERVER_LOST_EXTENDED),
"sending authentication information",
errno);
goto error;
}
MYSQL_TRACE(PACKET_SENT, mysql, (end-buff));
my_afree(buff);
return 0;
error:
my_afree(buff);
return 1; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 STDCALL
mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)
{
DBUG_ENTER("mysql_option");
DBUG_PRINT("enter",("option: %d",(int) option));
switch (option) {
case MYSQL_OPT_CONNECT_TIMEOUT:
mysql->options.connect_timeout= *(uint*) arg;
break;
case MYSQL_OPT_READ_TIMEOUT:
mysql->options.read_timeout= *(uint*) arg;
break;
case MYSQL_OPT_WRITE_TIMEOUT:
mysql->options.write_timeout= *(uint*) arg;
break;
case MYSQL_OPT_COMPRESS:
mysql->options.compress= 1; /* Remember for connect */
mysql->options.client_flag|= CLIENT_COMPRESS;
break;
case MYSQL_OPT_NAMED_PIPE: /* This option is depricated */
mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */
break;
case MYSQL_OPT_LOCAL_INFILE: /* Allow LOAD DATA LOCAL ?*/
if (!arg || test(*(uint*) arg))
mysql->options.client_flag|= CLIENT_LOCAL_FILES;
else
mysql->options.client_flag&= ~CLIENT_LOCAL_FILES;
break;
case MYSQL_INIT_COMMAND:
add_init_command(&mysql->options,arg);
break;
case MYSQL_READ_DEFAULT_FILE:
my_free(mysql->options.my_cnf_file);
mysql->options.my_cnf_file=my_strdup(key_memory_mysql_options,
arg,MYF(MY_WME));
break;
case MYSQL_READ_DEFAULT_GROUP:
my_free(mysql->options.my_cnf_group);
mysql->options.my_cnf_group=my_strdup(key_memory_mysql_options,
arg,MYF(MY_WME));
break;
case MYSQL_SET_CHARSET_DIR:
my_free(mysql->options.charset_dir);
mysql->options.charset_dir=my_strdup(key_memory_mysql_options,
arg,MYF(MY_WME));
break;
case MYSQL_SET_CHARSET_NAME:
my_free(mysql->options.charset_name);
mysql->options.charset_name=my_strdup(key_memory_mysql_options,
arg,MYF(MY_WME));
break;
case MYSQL_OPT_PROTOCOL:
mysql->options.protocol= *(uint*) arg;
break;
case MYSQL_SHARED_MEMORY_BASE_NAME:
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (mysql->options.shared_memory_base_name != def_shared_memory_base_name)
my_free(mysql->options.shared_memory_base_name);
mysql->options.shared_memory_base_name=my_strdup(key_memory_mysql_options,
arg,MYF(MY_WME));
#endif
break;
case MYSQL_OPT_USE_REMOTE_CONNECTION:
case MYSQL_OPT_USE_EMBEDDED_CONNECTION:
case MYSQL_OPT_GUESS_CONNECTION:
mysql->options.methods_to_use= option;
break;
case MYSQL_SET_CLIENT_IP:
my_free(mysql->options.ci.client_ip);
mysql->options.ci.client_ip= my_strdup(key_memory_mysql_options,
arg, MYF(MY_WME));
break;
case MYSQL_SECURE_AUTH:
mysql->options.secure_auth= *(my_bool *) arg;
break;
case MYSQL_REPORT_DATA_TRUNCATION:
mysql->options.report_data_truncation= test(*(my_bool *) arg);
break;
case MYSQL_OPT_RECONNECT:
mysql->reconnect= *(my_bool *) arg;
break;
case MYSQL_OPT_BIND:
my_free(mysql->options.ci.bind_address);
mysql->options.ci.bind_address= my_strdup(key_memory_mysql_options,
arg, MYF(MY_WME));
break;
case MYSQL_OPT_SSL_VERIFY_SERVER_CERT:
if (*(my_bool*) arg)
mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT;
else
mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT;
break;
case MYSQL_PLUGIN_DIR:
EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg);
break;
case MYSQL_DEFAULT_AUTH:
EXTENSION_SET_STRING(&mysql->options, default_auth, arg);
break;
case MYSQL_OPT_SSL_KEY: SET_SSL_OPTION(ssl_key, arg); break;
case MYSQL_OPT_SSL_CERT: SET_SSL_OPTION(ssl_cert, arg); break;
case MYSQL_OPT_SSL_CA: SET_SSL_OPTION(ssl_ca, arg); break;
case MYSQL_OPT_SSL_CAPATH: SET_SSL_OPTION(ssl_capath, arg); break;
case MYSQL_OPT_SSL_CIPHER: SET_SSL_OPTION(ssl_cipher, arg); break;
case MYSQL_OPT_SSL_CRL: EXTENSION_SET_SSL_STRING(&mysql->options,
ssl_crl, arg);
break;
case MYSQL_OPT_SSL_CRLPATH: EXTENSION_SET_SSL_STRING(&mysql->options,
ssl_crlpath, arg);
break;
case MYSQL_SERVER_PUBLIC_KEY:
EXTENSION_SET_STRING(&mysql->options, server_public_key_path, arg);
break;
case MYSQL_OPT_CONNECT_ATTR_RESET:
ENSURE_EXTENSIONS_PRESENT(&mysql->options);
if (my_hash_inited(&mysql->options.extension->connection_attributes))
{
my_hash_free(&mysql->options.extension->connection_attributes);
mysql->options.extension->connection_attributes_length= 0;
}
break;
case MYSQL_OPT_CONNECT_ATTR_DELETE:
ENSURE_EXTENSIONS_PRESENT(&mysql->options);
if (my_hash_inited(&mysql->options.extension->connection_attributes))
{
size_t len;
uchar *elt;
len= arg ? strlen(arg) : 0;
if (len)
{
elt= my_hash_search(&mysql->options.extension->connection_attributes,
arg, len);
if (elt)
{
LEX_STRING *attr= (LEX_STRING *) elt;
LEX_STRING *key= attr, *value= attr + 1;
mysql->options.extension->connection_attributes_length-=
get_length_store_length(key->length) + key->length +
get_length_store_length(value->length) + value->length;
my_hash_delete(&mysql->options.extension->connection_attributes,
elt);
}
}
}
break;
case MYSQL_ENABLE_CLEARTEXT_PLUGIN:
ENSURE_EXTENSIONS_PRESENT(&mysql->options);
mysql->options.extension->enable_cleartext_plugin=
(*(my_bool*) arg) ? TRUE : FALSE;
break;
case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS:
if (*(my_bool*) arg)
mysql->options.client_flag|= CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS;
else
mysql->options.client_flag&= ~CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS;
break;
default:
DBUG_RETURN(1);
}
DBUG_RETURN(0); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 connect_to_master(THD* thd, MYSQL* mysql, Master_info* mi,
bool reconnect, bool suppress_warnings)
{
int slave_was_killed= 0;
int last_errno= -2; // impossible error
ulong err_count=0;
char llbuff[22];
char password[MAX_PASSWORD_LENGTH + 1];
int password_size= sizeof(password);
DBUG_ENTER("connect_to_master");
set_slave_max_allowed_packet(thd, mysql);
#ifndef DBUG_OFF
mi->events_until_exit = disconnect_slave_event_count;
#endif
ulong client_flag= CLIENT_REMEMBER_OPTIONS;
if (opt_slave_compressed_protocol)
client_flag=CLIENT_COMPRESS; /* We will use compression */
mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *) &slave_net_timeout);
mysql_options(mysql, MYSQL_OPT_READ_TIMEOUT, (char *) &slave_net_timeout);
if (mi->bind_addr[0])
{
DBUG_PRINT("info",("bind_addr: %s", mi->bind_addr));
mysql_options(mysql, MYSQL_OPT_BIND, mi->bind_addr);
}
#ifdef HAVE_OPENSSL
if (mi->ssl)
{
mysql_ssl_set(mysql,
mi->ssl_key[0]?mi->ssl_key:0,
mi->ssl_cert[0]?mi->ssl_cert:0,
mi->ssl_ca[0]?mi->ssl_ca:0,
mi->ssl_capath[0]?mi->ssl_capath:0,
mi->ssl_cipher[0]?mi->ssl_cipher:0);
mysql_options(mysql, MYSQL_OPT_SSL_CRL,
mi->ssl_crl[0] ? mi->ssl_crl : 0);
mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH,
mi->ssl_crlpath[0] ? mi->ssl_crlpath : 0);
mysql_options(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
&mi->ssl_verify_server_cert);
}
#endif
mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset_info->csname);
/* This one is not strictly needed but we have it here for completeness */
mysql_options(mysql, MYSQL_SET_CHARSET_DIR, (char *) charsets_dir);
if (mi->is_start_plugin_auth_configured())
{
DBUG_PRINT("info", ("Slaving is using MYSQL_DEFAULT_AUTH %s",
mi->get_start_plugin_auth()));
mysql_options(mysql, MYSQL_DEFAULT_AUTH, mi->get_start_plugin_auth());
}
if (mi->is_start_plugin_dir_configured())
{
DBUG_PRINT("info", ("Slaving is using MYSQL_PLUGIN_DIR %s",
mi->get_start_plugin_dir()));
mysql_options(mysql, MYSQL_PLUGIN_DIR, mi->get_start_plugin_dir());
}
/* Set MYSQL_PLUGIN_DIR in case master asks for an external authentication plugin */
else if (opt_plugin_dir_ptr && *opt_plugin_dir_ptr)
mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir_ptr);
if (!mi->is_start_user_configured())
sql_print_warning("%s", ER(ER_INSECURE_CHANGE_MASTER));
if (mi->get_password(password, &password_size))
{
mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR,
ER(ER_SLAVE_FATAL_ERROR),
"Unable to configure password when attempting to "
"connect to the master server. Connection attempt "
"terminated.");
DBUG_RETURN(1);
}
const char* user= mi->get_user();
if (user == NULL || user[0] == 0)
{
mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR,
ER(ER_SLAVE_FATAL_ERROR),
"Invalid (empty) username when attempting to "
"connect to the master server. Connection attempt "
"terminated.");
DBUG_RETURN(1);
}
while (!(slave_was_killed = io_slave_killed(thd,mi))
&& (reconnect ? mysql_reconnect(mysql) != 0 :
mysql_real_connect(mysql, mi->host, user,
password, 0, mi->port, 0, client_flag) == 0))
{
/*
SHOW SLAVE STATUS will display the number of retries which
would be real retry counts instead of mi->retry_count for
each connection attempt by 'Last_IO_Error' entry.
*/
last_errno=mysql_errno(mysql);
suppress_warnings= 0;
mi->report(ERROR_LEVEL, last_errno,
"error %s to master '%s@%s:%d'"
" - retry-time: %d retries: %lu",
(reconnect ? "reconnecting" : "connecting"),
mi->get_user(), mi->host, mi->port,
mi->connect_retry, err_count + 1);
/*
By default we try forever. The reason is that failure will trigger
master election, so if the user did not set mi->retry_count we
do not want to have election triggered on the first failure to
connect
*/
if (++err_count == mi->retry_count)
{
slave_was_killed=1;
break;
}
slave_sleep(thd, mi->connect_retry, io_slave_killed, mi);
}
if (!slave_was_killed)
{
mi->clear_error(); // clear possible left over reconnect error
if (reconnect)
{
if (!suppress_warnings)
sql_print_information("Slave: connected to master '%s@%s:%d',\
replication resumed in log '%s' at position %s", mi->get_user(),
mi->host, mi->port,
mi->get_io_rpl_log_name(),
llstr(mi->get_master_log_pos(),llbuff));
}
else
{
query_logger.general_log_print(thd, COM_CONNECT_OUT, "%s@%s:%d",
mi->get_user(), mi->host, mi->port);
}
thd->set_active_vio(mysql->net.vio);
}
mysql->reconnect= 1;
DBUG_PRINT("exit",("slave_was_killed: %d", slave_was_killed));
DBUG_RETURN(slave_was_killed);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption
# Changed the meaning of the --ssl=1 option of all client binaries
to mean force ssl, not try ssl and fail over to eunecrypted
# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()
option to specify that an ssl connection is required.
# Added a new macro SSL_SET_OPTIONS() to the client
SSL handling headers that sets all the relevant SSL options at
once.
# Revamped all of the current native clients to use the new macro
# Removed some Windows line endings.
# Added proper handling of the new option into the ssl helper
headers.
# If SSL is mandatory assume that the media is secure enough
for the sha256 plugin to do unencrypted password exchange even
before establishing a connection.
# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is
specified.
# updated test cases that require a non-default cipher to spawn
a mysql command line tool binary since mysqltest has no support
for specifying ciphers.
# updated the replication slave connection code to always enforce
SSL if any of the SSL config options is present.
# test cases added and updated.
# added a mysql_get_option() API to return mysql_options()
values. Used the new API inside the sha256 plugin.
# Fixed compilation warnings because of unused variables.
# Fixed test failures (mysql_ssl and bug13115401)
# Fixed whitespace issues.
# Fully implemented the mysql_get_option() function.
# Added a test case for mysql_get_option()
# fixed some trailing whitespace issues
# fixed some uint/int warnings in mysql_client_test.c
# removed shared memory option from non-windows get_options
tests
# moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s> |
<s>[INST] Given the following code containing errors, provide 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 connect_n_handle_errors(struct st_command *command,
MYSQL* con, const char* host,
const char* user, const char* pass,
const char* db, int port, const char* sock)
{
DYNAMIC_STRING *ds;
int failed_attempts= 0;
ds= &ds_res;
/* Only log if an error is expected */
if (command->expected_errors.count > 0 &&
!disable_query_log)
{
/*
Log the connect to result log
*/
dynstr_append_mem(ds, "connect(", 8);
replace_dynstr_append(ds, host);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append(ds, user);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append(ds, pass);
dynstr_append_mem(ds, ",", 1);
if (db)
replace_dynstr_append(ds, db);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append_uint(ds, port);
dynstr_append_mem(ds, ",", 1);
if (sock)
replace_dynstr_append(ds, sock);
dynstr_append_mem(ds, ")", 1);
dynstr_append_mem(ds, delimiter, delimiter_length);
dynstr_append_mem(ds, "\n", 1);
}
/* Simlified logging if enabled */
if (!disable_connect_log && !disable_query_log)
{
replace_dynstr_append(ds, command->query);
dynstr_append_mem(ds, ";\n", 2);
}
while (!mysql_real_connect(con, host, user, pass, db, port, sock ? sock: 0,
CLIENT_MULTI_STATEMENTS))
{
/*
If we have used up all our connections check whether this
is expected (by --error). If so, handle the error right away.
Otherwise, give it some extra time to rule out race-conditions.
If extra-time doesn't help, we have an unexpected error and
must abort -- just proceeding to handle_error() when second
and third chances are used up will handle that for us.
There are various user-limits of which only max_user_connections
and max_connections_per_hour apply at connect time. For the
the second to create a race in our logic, we'd need a limits
test that runs without a FLUSH for longer than an hour, so we'll
stay clear of trying to work out which exact user-limit was
exceeded.
*/
if (((mysql_errno(con) == ER_TOO_MANY_USER_CONNECTIONS) ||
(mysql_errno(con) == ER_USER_LIMIT_REACHED)) &&
(failed_attempts++ < opt_max_connect_retries))
{
int i;
i= match_expected_error(command, mysql_errno(con), mysql_sqlstate(con));
if (i >= 0)
goto do_handle_error; /* expected error, handle */
my_sleep(connection_retry_sleep); /* unexpected error, wait */
continue; /* and give it 1 more chance */
}
do_handle_error:
var_set_errno(mysql_errno(con));
handle_error(command, mysql_errno(con), mysql_error(con),
mysql_sqlstate(con), ds);
return 0; /* Not connected */
}
var_set_errno(0);
handle_no_error(command);
revert_properties();
return 1; /* Connected */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char **argv)
{
int error;
my_bool first_argument_uses_wildcards=0;
char *wild;
MYSQL mysql;
MY_INIT(argv[0]);
if (load_defaults("my",load_default_groups,&argc,&argv))
exit(1);
get_options(&argc,&argv);
wild=0;
if (argc)
{
char *pos= argv[argc-1], *to;
for (to= pos ; *pos ; pos++, to++)
{
switch (*pos) {
case '*':
*pos= '%';
first_argument_uses_wildcards= 1;
break;
case '?':
*pos= '_';
first_argument_uses_wildcards= 1;
break;
case '%':
case '_':
first_argument_uses_wildcards= 1;
break;
case '\\':
pos++;
default: break;
}
*to= *pos;
}
*to= *pos; /* just to copy a '\0' if '\\' was used */
}
if (first_argument_uses_wildcards)
wild= argv[--argc];
else if (argc == 3) /* We only want one field */
wild= argv[--argc];
if (argc > 2)
{
fprintf(stderr,"%s: Too many arguments\n",my_progname);
exit(1);
}
mysql_init(&mysql);
if (opt_compress)
mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
(char*)&opt_ssl_verify_server_cert);
#endif
if (opt_protocol)
mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
if (using_opt_enable_cleartext_plugin)
mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*)&opt_enable_cleartext_plugin);
if (!(mysql_real_connect(&mysql,host,user,opt_password,
(first_argument_uses_wildcards) ? "" :
argv[0],opt_mysql_port,opt_mysql_unix_port,
0)))
{
fprintf(stderr,"%s: %s\n",my_progname,mysql_error(&mysql));
exit(1);
}
mysql.reconnect= 1;
switch (argc) {
case 0: error=list_dbs(&mysql,wild); break;
case 1:
if (opt_status)
error=list_table_status(&mysql,argv[0],wild);
else
error=list_tables(&mysql,argv[0],wild);
break;
default:
if (opt_status && ! wild)
error=list_table_status(&mysql,argv[0],argv[1]);
else
error=list_fields(&mysql,argv[0],argv[1],wild);
break;
}
mysql_close(&mysql); /* Close & free connection */
my_free(opt_password);
#ifdef HAVE_SMEM
my_free(shared_memory_base_name);
#endif
my_end(my_end_arg);
exit(error ? 1 : 0);
return 0; /* No compiler warnings */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sql_real_connect(char *host,char *database,char *user,char *password,
uint silent)
{
if (connected)
{
connected= 0;
mysql_close(&mysql);
}
mysql_init(&mysql);
if (opt_init_command)
mysql_options(&mysql, MYSQL_INIT_COMMAND, opt_init_command);
if (opt_connect_timeout)
{
uint timeout=opt_connect_timeout;
mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,
(char*) &timeout);
}
if (opt_compress)
mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
if (opt_secure_auth)
mysql_options(&mysql, MYSQL_SECURE_AUTH, (char *) &opt_secure_auth);
if (using_opt_local_infile)
mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (opt_use_ssl)
mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
(char*)&opt_ssl_verify_server_cert);
#endif
if (opt_protocol)
mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (safe_updates)
{
char init_command[100];
sprintf(init_command,
"SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%lu,MAX_JOIN_SIZE=%lu",
select_limit,max_join_size);
mysql_options(&mysql, MYSQL_INIT_COMMAND, init_command);
}
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
if (using_opt_enable_cleartext_plugin)
mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*) &opt_enable_cleartext_plugin);
if (!mysql_real_connect(&mysql, host, user, password,
database, opt_mysql_port, opt_mysql_unix_port,
connect_flag | CLIENT_MULTI_STATEMENTS))
{
if (!silent ||
(mysql_errno(&mysql) != CR_CONN_HOST_ERROR &&
mysql_errno(&mysql) != CR_CONNECTION_ERROR))
{
(void) put_error(&mysql);
(void) fflush(stdout);
return ignore_errors ? -1 : 1; // Abort
}
return -1; // Retryable
}
charset_info= mysql.charset;
connected=1;
#ifndef EMBEDDED_LIBRARY
mysql.reconnect= debug_info_flag; // We want to know if this happens
#else
mysql.reconnect= 1;
#endif
#ifdef HAVE_READLINE
build_completion_hash(opt_rehash, 1);
#endif
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide 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 dbConnect(char *host, char *user, char *passwd)
{
DBUG_ENTER("dbConnect");
if (verbose)
{
fprintf(stderr, "# Connecting to %s...\n", host ? host : "localhost");
}
mysql_init(&mysql_connection);
if (opt_compress)
mysql_options(&mysql_connection, MYSQL_OPT_COMPRESS, NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
#endif
if (opt_protocol)
mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);
if (using_opt_enable_cleartext_plugin)
mysql_options(&mysql_connection, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char *) &opt_enable_cleartext_plugin);
mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);
if (!(sock = mysql_real_connect(&mysql_connection, host, user, passwd,
NULL, opt_mysql_port, opt_mysql_unix_port, 0)))
{
DBerror(&mysql_connection, "when trying to connect");
return 1;
}
mysql_connection.reconnect= 1;
return 0;
} /* dbConnect */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char **argv)
{
MYSQL mysql;
option_string *eptr;
MY_INIT(argv[0]);
if (load_defaults("my",load_default_groups,&argc,&argv))
{
my_end(0);
exit(1);
}
defaults_argv=argv;
if (get_options(&argc,&argv))
{
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
/* Seed the random number generator if we will be using it. */
if (auto_generate_sql)
srandom((uint)time(NULL));
/* globals? Yes, so we only have to run strlen once */
delimiter_length= strlen(delimiter);
if (argc > 2)
{
fprintf(stderr,"%s: Too many arguments\n",my_progname);
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
mysql_init(&mysql);
if (opt_compress)
mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
#endif
if (opt_protocol)
mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
if (using_opt_enable_cleartext_plugin)
mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*) &opt_enable_cleartext_plugin);
if (!opt_only_print)
{
if (!(mysql_real_connect(&mysql, host, user, opt_password,
NULL, opt_mysql_port,
opt_mysql_unix_port, connect_flags)))
{
fprintf(stderr,"%s: Error when connecting to server: %s\n",
my_progname,mysql_error(&mysql));
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
}
pthread_mutex_init(&counter_mutex, NULL);
pthread_cond_init(&count_threshhold, NULL);
pthread_mutex_init(&sleeper_mutex, NULL);
pthread_cond_init(&sleep_threshhold, NULL);
/* Main iterations loop */
eptr= engine_options;
do
{
/* For the final stage we run whatever queries we were asked to run */
uint *current;
if (verbose >= 2)
printf("Starting Concurrency Test\n");
if (*concurrency)
{
for (current= concurrency; current && *current; current++)
concurrency_loop(&mysql, *current, eptr);
}
else
{
uint infinite= 1;
do {
concurrency_loop(&mysql, infinite, eptr);
}
while (infinite++);
}
if (!opt_preserve)
drop_schema(&mysql, create_schema_string);
} while (eptr ? (eptr= eptr->next) : 0);
pthread_mutex_destroy(&counter_mutex);
pthread_cond_destroy(&count_threshhold);
pthread_mutex_destroy(&sleeper_mutex);
pthread_cond_destroy(&sleep_threshhold);
if (!opt_only_print)
mysql_close(&mysql); /* Close & free connection */
/* now free all the strings we created */
my_free(opt_password);
my_free(concurrency);
statement_cleanup(create_statements);
statement_cleanup(query_statements);
statement_cleanup(pre_statements);
statement_cleanup(post_statements);
option_cleanup(engine_options);
#ifdef HAVE_SMEM
my_free(shared_memory_base_name);
#endif
free_defaults(defaults_argv);
my_end(my_end_arg);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sig_handler handle_sigint(int sig)
{
char kill_buffer[40];
MYSQL *kill_mysql= NULL;
/* terminate if no query being executed, or we already tried interrupting */
/* terminate if no query being executed, or we already tried interrupting */
if (!executing_query || (interrupted_query == 2))
{
tee_fprintf(stdout, "Ctrl-C -- exit!\n");
goto err;
}
kill_mysql= mysql_init(kill_mysql);
if (!mysql_real_connect(kill_mysql,current_host, current_user, opt_password,
"", opt_mysql_port, opt_mysql_unix_port,0))
{
tee_fprintf(stdout, "Ctrl-C -- sorry, cannot connect to server to kill query, giving up ...\n");
goto err;
}
interrupted_query++;
/* mysqld < 5 does not understand KILL QUERY, skip to KILL CONNECTION */
if ((interrupted_query == 1) && (mysql_get_server_version(&mysql) < 50000))
interrupted_query= 2;
/* kill_buffer is always big enough because max length of %lu is 15 */
sprintf(kill_buffer, "KILL %s%lu",
(interrupted_query == 1) ? "QUERY " : "",
mysql_thread_id(&mysql));
tee_fprintf(stdout, "Ctrl-C -- sending \"%s\" to server ...\n", kill_buffer);
mysql_real_query(kill_mysql, kill_buffer, (uint) strlen(kill_buffer));
mysql_close(kill_mysql);
tee_fprintf(stdout, "Ctrl-C -- query aborted.\n");
return;
err:
#ifdef _WIN32
/*
When SIGINT is raised on Windows, the OS creates a new thread to handle the
interrupt. Once that thread completes, the main thread continues running
only to find that it's resources have already been free'd when the sigint
handler called mysql_end().
*/
mysql_thread_end();
return;
#else
mysql_end(sig);
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s> |
<s>[INST] Given the following code containing errors, provide 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 ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'ipv4: Missing sk_nulls_node_init() in ping_unhash().
If we don't do that, then the poison value is left in the ->pprev
backlink.
This can cause crashes if we do a disconnect, followed by a connect().
Tested-by: Linus Torvalds <[email protected]>
Reported-by: Wen Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: set_lenIV(char *line)
{
char *p = strstr(line, "/lenIV ");
/* Allow lenIV to be negative. Thanks to Tom Kacvinsky <[email protected]> */
if (p && (isdigit(p[7]) || p[7] == '+' || p[7] == '-')) {
lenIV = atoi(p + 7);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: set_cs_start(char *line)
{
char *p, *q, *r;
if ((p = strstr(line, "string currentfile"))) {
/* enforce presence of `readstring' -- 5/29/99 */
if (!strstr(line, "readstring"))
return;
/* locate the name of the charstring start command */
*p = '\0'; /* damage line[] */
q = strrchr(line, '/');
if (q) {
r = cs_start;
++q;
while (!isspace(*q) && *q != '{')
*r++ = *q++;
*r = '\0';
}
*p = 's'; /* repair line[] */
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: t1mac_output_ascii(char *s, int len)
{
if (blocktyp == POST_BINARY) {
output_current_post();
blocktyp = POST_ASCII;
}
/* Mac line endings */
if (len > 0 && s[len-1] == '\n')
s[len-1] = '\r';
t1mac_output_data((byte *)s, len);
if (strncmp(s, "/FontName", 9) == 0) {
for (s += 9; isspace(*s); s++) ;
if (*s == '/') {
const char *t = ++s;
while (*t && !isspace(*t)) t++;
free(font_name);
font_name = (char *)malloc(t - s + 1);
memcpy(font_name, s, t - s);
font_name[t - s] = 0;
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char *argv[])
{
char *p, *q, *r;
Clp_Parser *clp =
Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
program_name = Clp_ProgramName(clp);
/* interpret command line arguments using CLP */
while (1) {
int opt = Clp_Next(clp);
switch (opt) {
case BLOCK_LEN_OPT:
blocklen = clp->val.i;
break;
output_file:
case OUTPUT_OPT:
if (ofp)
fatal_error("output file already specified");
if (strcmp(clp->vstr, "-") == 0)
ofp = stdout;
else if (!(ofp = fopen(clp->vstr, "w")))
fatal_error("%s: %s", clp->vstr, strerror(errno));
break;
case PFB_OPT:
pfb = 1;
break;
case PFA_OPT:
pfb = 0;
break;
case HELP_OPT:
usage();
exit(0);
break;
case VERSION_OPT:
printf("t1asm (LCDF t1utils) %s\n", VERSION);
printf("Copyright (C) 1992-2010 I. Lee Hetherington, Eddie Kohler et al.\n\
This is free software; see the source for copying conditions.\n\
There is NO warranty, not even for merchantability or fitness for a\n\
particular purpose.\n");
exit(0);
break;
case Clp_NotOption:
if (ifp && ofp)
fatal_error("too many arguments");
else if (ifp)
goto output_file;
if (strcmp(clp->vstr, "-") == 0)
ifp = stdin;
else if (!(ifp = fopen(clp->vstr, "r")))
fatal_error("%s: %s", clp->vstr, strerror(errno));
break;
case Clp_Done:
goto done;
case Clp_BadOption:
short_usage();
exit(1);
break;
}
}
done:
if (!pfb) {
if (blocklen == -1)
blocklen = 64;
else if (blocklen < 8) {
blocklen = 8;
error("warning: line length raised to %d", blocklen);
} else if (blocklen > 1024) {
blocklen = 1024;
error("warning: line length lowered to %d", blocklen);
}
}
if (!ifp) ifp = stdin;
if (!ofp) ofp = stdout;
if (pfb)
init_pfb_writer(&w, blocklen, ofp);
#if defined(_MSDOS) || defined(_WIN32)
/* If we are processing a PFB (binary) output */
/* file, we must set its file mode to binary. */
if (pfb)
_setmode(_fileno(ofp), _O_BINARY);
#endif
/* Finally, we loop until no more input. Some special things to look for are
the `currentfile eexec' line, the beginning of the `/Subrs' or
`/CharStrings' definition, the definition of `/lenIV', and the definition
of the charstring start command which has `...string currentfile...' in
it.
Being careful: Check with `/Subrs' and `/CharStrings' to see that a
number follows the token -- otherwise, the token is probably nested in a
subroutine a la Adobe Jenson, and we shouldn't pay attention to it.
Bugs: Occurrence of `/Subrs 9' in a comment will fool t1asm.
Thanks to Tom Kacvinsky <[email protected]> who reported that some fonts come
without /Subrs sections and provided a patch. */
while (!feof(ifp) && !ferror(ifp)) {
t1utils_getline();
if (!ever_active) {
if (strncmp(line, "currentfile eexec", 17) == 0 && isspace(line[17])) {
/* Allow arbitrary whitespace after "currentfile eexec".
Thanks to Tom Kacvinsky <[email protected]> for reporting this.
Note: strlen("currentfile eexec") == 17. */
for (p = line + 18; isspace(*p); p++)
;
eexec_start(p);
continue;
} else if (strncmp(line, "/lenIV", 6) == 0) {
lenIV = atoi(line + 6);
} else if ((p = strstr(line, "string currentfile"))
&& strstr(line, "readstring")) { /* enforce `readstring' */
/* locate the name of the charstring start command */
*p = '\0'; /* damage line[] */
q = strrchr(line, '/');
if (q) {
r = cs_start;
++q;
while (!isspace(*q) && *q != '{')
*r++ = *q++;
*r = '\0';
}
*p = 's'; /* repair line[] */
}
}
if (!active) {
if ((p = strstr(line, "/Subrs")) && isdigit(p[7]))
ever_active = active = 1;
else if ((p = strstr(line, "/CharStrings")) && isdigit(p[13]))
ever_active = active = 1;
}
if ((p = strstr(line, "currentfile closefile"))) {
/* 2/14/99 -- happy Valentine's day! -- don't look for `mark
currentfile closefile'; the `mark' might be on a different line */
/* 1/3/2002 -- happy new year! -- Luc Devroye reports a failure with
some printers when `currentfile closefile' is followed by space */
p += sizeof("currentfile closefile") - 1;
for (q = p; isspace(*q) && *q != '\n'; q++)
/* nada */;
if (q == p && !*q)
error("warning: `currentfile closefile' line too long");
else if (q != p) {
if (*q != '\n')
error("text after `currentfile closefile' ignored");
*p++ = '\n';
*p++ = '\0';
}
eexec_string(line);
break;
}
eexec_string(line);
/* output line data */
if (start_charstring) {
if (!cs_start[0])
fatal_error("couldn't find charstring start command");
parse_charstring();
}
}
/* Handle remaining PostScript after the eexec section */
if (in_eexec)
eexec_end();
/* There may be additional code. */
while (!feof(ifp) && !ferror(ifp)) {
t1utils_getline();
eexec_string(line);
}
if (pfb)
pfb_writer_end(&w);
/* the end! */
if (!ever_active)
error("warning: no charstrings found in input file");
fclose(ifp);
fclose(ofp);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.'</s> |
<s>[INST] Given the following code containing errors, provide 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 is_integer(char *string)
{
if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') {
while (*++string && isdigit(*string))
; /* deliberately empty */
if (!*string)
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.'</s> |
<s>[INST] Given the following code containing errors, provide 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 perf_callchain_user_64(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long sp, next_sp;
unsigned long next_ip;
unsigned long lr;
long level = 0;
struct signal_frame_64 __user *sigframe;
unsigned long __user *fp, *uregs;
next_ip = perf_instruction_pointer(regs);
lr = regs->link;
sp = regs->gpr[1];
perf_callchain_store(entry, next_ip);
for (;;) {
fp = (unsigned long __user *) sp;
if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp))
return;
if (level > 0 && read_user_stack_64(&fp[2], &next_ip))
return;
/*
* Note: the next_sp - sp >= signal frame size check
* is true when next_sp < sp, which can happen when
* transitioning from an alternate signal stack to the
* normal stack.
*/
if (next_sp - sp >= sizeof(struct signal_frame_64) &&
(is_sigreturn_64_address(next_ip, sp) ||
(level <= 1 && is_sigreturn_64_address(lr, sp))) &&
sane_signal_64_frame(sp)) {
/*
* This looks like an signal frame
*/
sigframe = (struct signal_frame_64 __user *) sp;
uregs = sigframe->uc.uc_mcontext.gp_regs;
if (read_user_stack_64(&uregs[PT_NIP], &next_ip) ||
read_user_stack_64(&uregs[PT_LNK], &lr) ||
read_user_stack_64(&uregs[PT_R1], &sp))
return;
level = 0;
perf_callchain_store(entry, PERF_CONTEXT_USER);
perf_callchain_store(entry, next_ip);
continue;
}
if (level == 0)
next_ip = lr;
perf_callchain_store(entry, next_ip);
++level;
sp = next_sp;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH
We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH
(currently 127), but we forgot to do the same for 64bit backtraces.
Cc: [email protected]
Signed-off-by: Anton Blanchard <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide 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 fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction)
{
FDrive *cur_drv = get_cur_drv(fdctrl);
if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) {
/* Command parameters done */
if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) {
fdctrl->fifo[0] = fdctrl->fifo[1];
fdctrl->fifo[2] = 0;
fdctrl->fifo[3] = 0;
fdctrl_set_fifo(fdctrl, 4);
} else {
fdctrl_reset_fifo(fdctrl);
}
} else if (fdctrl->data_len > 7) {
/* ERROR */
fdctrl->fifo[0] = 0x80 |
(cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
fdctrl_set_fifo(fdctrl, 1);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'fdc: force the fifo access to be in bounds of the allocated buffer
During processing of certain commands such as FD_CMD_READ_ID and
FD_CMD_DRIVE_SPECIFICATION_COMMAND the fifo memory access could
get out of bounds leading to memory corruption with values coming
from the guest.
Fix this by making sure that the index is always bounded by the
allocated memory.
This is CVE-2015-3456.
Signed-off-by: Petr Matousek <[email protected]>
Reviewed-by: John Snow <[email protected]>
Signed-off-by: John Snow <[email protected]>'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.