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: Perl_my_setenv(pTHX_ const char *nam, const char *val)
{
dVAR;
char *envstr;
const int nlen = strlen(nam);
int vlen;
if (!val) {
val = "";
}
vlen = strlen(val);
Newx(envstr, nlen+vlen+2, char);
my_setenv_format(envstr, nam, nlen, val, vlen);
(void)PerlEnv_putenv(envstr);
Safefree(envstr);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-703', 'CWE-787'], 'message': 'Perl_my_setenv(); handle integer wrap
RT #133204
Wean this function off int/I32 and onto UV/Size_t.
Also, replace all malloc-ish calls with a wrapper that does
overflow checks,
In particular, it was doing (nlen + vlen + 2) which could wrap when
the combined length of the environment variable name and value
exceeded around 0x7fffffff.
The wrapper check function is probably overkill, but belt and braces...
NB this function has several variant parts, #ifdef'ed by platform
type; I have blindly changed the parts that aren't compiled under linux.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: main(
int argc,
char ** argv)
{
#ifdef GNUTAR
int i;
char *e;
char *dbf;
char *cmdline;
GPtrArray *array = g_ptr_array_new();
gchar **strings;
char **new_argv;
char **env;
#endif
if (argc > 1 && argv[1] && g_str_equal(argv[1], "--version")) {
printf("runtar-%s\n", VERSION);
return (0);
}
/*
* Configure program for internationalization:
* 1) Only set the message locale for now.
* 2) Set textdomain for all amanda related programs to "amanda"
* We don't want to be forced to support dozens of message catalogs.
*/
setlocale(LC_MESSAGES, "C");
textdomain("amanda");
safe_fd(-1, 0);
safe_cd();
set_pname("runtar");
/* Don't die when child closes pipe */
signal(SIGPIPE, SIG_IGN);
dbopen(DBG_SUBDIR_CLIENT);
config_init(CONFIG_INIT_CLIENT|CONFIG_INIT_GLOBAL, NULL);
if (argc < 3) {
error(_("Need at least 3 arguments\n"));
/*NOTREACHED*/
}
dbprintf(_("version %s\n"), VERSION);
if (!g_str_equal(argv[3], "--create")) {
error(_("Can only be used to create tar archives\n"));
/*NOTREACHED*/
}
#ifndef GNUTAR
g_fprintf(stderr,_("gnutar not available on this system.\n"));
dbprintf(_("%s: gnutar not available on this system.\n"), argv[0]);
dbclose();
return 1;
#else
/*
* Print out version information for tar.
*/
do {
FILE * version_file;
char version_buf[80];
if ((version_file = popen(GNUTAR " --version 2>&1", "r")) != NULL) {
if (fgets(version_buf, (int)sizeof(version_buf), version_file) != NULL) {
dbprintf(_(GNUTAR " version: %s\n"), version_buf);
} else {
if (ferror(version_file)) {
dbprintf(_(GNUTAR " version: Read failure: %s\n"), strerror(errno));
} else {
dbprintf(_(GNUTAR " version: Read failure; EOF\n"));
}
}
} else {
dbprintf(_(GNUTAR " version: unavailable: %s\n"), strerror(errno));
}
} while(0);
#ifdef WANT_SETUID_CLIENT
check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
if (!become_root()) {
error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname());
/*NOTREACHED*/
}
#else
check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif
/* skip argv[0] */
argc--;
argv++;
dbprintf(_("config: %s\n"), argv[0]);
if (!g_str_equal(argv[0], "NOCONFIG"))
dbrename(argv[0], DBG_SUBDIR_CLIENT);
argc--;
argv++;
new_argv = g_new0(char *, argc+1);
new_argv[0] = g_strdup_printf("%s", argv[0]);
g_ptr_array_add(array, g_strdup(GNUTAR));
for (i = 1; argv[i]; i++) {
g_ptr_array_add(array, quote_string(argv[i]));
new_argv[i] = g_strdup_printf("%s", argv[i]);
}
g_ptr_array_add(array, NULL);
strings = (gchar **)g_ptr_array_free(array, FALSE);
cmdline = g_strjoinv(" ", strings);
g_strfreev(strings);
dbprintf(_("running: %s\n"), cmdline);
amfree(cmdline);
dbf = dbfn();
if (dbf) {
dbf = g_strdup(dbf);
}
dbclose();
env = safe_env();
execve(GNUTAR, new_argv, env);
free_env(env);
e = strerror(errno);
dbreopen(dbf, "more");
amfree(dbf);
dbprintf(_("execve of %s failed (%s)\n"), GNUTAR, e);
dbclose();
g_fprintf(stderr, _("runtar: could not exec %s: %s\n"), GNUTAR, e);
return 1;
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* client-src/runtar.c: Filter tar arguments
* installcheck/runtar.pl: Check runtar errorr
* installcheck/Makefile.am: Add runtar.pl
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6479 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amstar_backup(
application_argument_t *argument)
{
int dumpin;
char *cmd = NULL;
char *qdisk;
char line[32768];
amregex_t *rp;
off_t dump_size = -1;
char *type;
char startchr;
GPtrArray *argv_ptr;
int starpid;
int dataf = 1;
int mesgf = 3;
int indexf = 4;
int outf;
FILE *mesgstream;
FILE *indexstream = NULL;
FILE *outstream;
int level;
regex_t regex_root;
regex_t regex_dir;
regex_t regex_file;
regex_t regex_special;
regex_t regex_symbolic;
regex_t regex_hard;
mesgstream = fdopen(mesgf, "w");
if (!mesgstream) {
error(_("error mesgstream(%d): %s\n"), mesgf, strerror(errno));
}
if (!argument->level) {
fprintf(mesgstream, "? No level argument\n");
error(_("No level argument"));
}
if (!argument->dle.disk) {
fprintf(mesgstream, "? No disk argument\n");
error(_("No disk argument"));
}
if (!argument->dle.device) {
fprintf(mesgstream, "? No device argument\n");
error(_("No device argument"));
}
if (!check_exec_for_suid(star_path, FALSE)) {
fprintf(mesgstream, "? '%s' binary is not secure", star_path);
error("'%s' binary is not secure", star_path);
}
if (argument->dle.include_list &&
argument->dle.include_list->nb_element >= 0) {
fprintf(mesgstream, "? include-list not supported for backup\n");
}
level = GPOINTER_TO_INT(argument->level->data);
qdisk = quote_string(argument->dle.disk);
argv_ptr = amstar_build_argv(argument, level, CMD_BACKUP, mesgstream);
cmd = g_strdup(star_path);
starpid = pipespawnv(cmd, STDIN_PIPE|STDERR_PIPE, 1,
&dumpin, &dataf, &outf, (char **)argv_ptr->pdata);
g_ptr_array_free_full(argv_ptr);
/* close the write ends of the pipes */
aclose(dumpin);
aclose(dataf);
if (argument->dle.create_index) {
indexstream = fdopen(indexf, "w");
if (!indexstream) {
error(_("error indexstream(%d): %s\n"), indexf, strerror(errno));
}
}
outstream = fdopen(outf, "r");
if (!outstream) {
error(_("error outstream(%d): %s\n"), outf, strerror(errno));
}
regcomp(®ex_root, "^a \\.\\/ directory$", REG_EXTENDED|REG_NEWLINE);
regcomp(®ex_dir, "^a (.*) directory$", REG_EXTENDED|REG_NEWLINE);
regcomp(®ex_file, "^a (.*) (.*) bytes", REG_EXTENDED|REG_NEWLINE);
regcomp(®ex_special, "^a (.*) special", REG_EXTENDED|REG_NEWLINE);
regcomp(®ex_symbolic, "^a (.*) symbolic", REG_EXTENDED|REG_NEWLINE);
regcomp(®ex_hard, "^a (.*) link to", REG_EXTENDED|REG_NEWLINE);
while ((fgets(line, sizeof(line), outstream)) != NULL) {
regmatch_t regmatch[3];
if (strlen(line) > 0 && line[strlen(line)-1] == '\n') {
/* remove trailling \n */
line[strlen(line)-1] = '\0';
}
if (regexec(®ex_root, line, 1, regmatch, 0) == 0) {
if (argument->dle.create_index)
fprintf(indexstream, "%s\n", "/");
continue;
}
if (regexec(®ex_dir, line, 3, regmatch, 0) == 0) {
if (argument->dle.create_index && regmatch[1].rm_so == 2) {
line[regmatch[1].rm_eo]='\0';
fprintf(indexstream, "/%s\n", &line[regmatch[1].rm_so]);
}
continue;
}
if (regexec(®ex_file, line, 3, regmatch, 0) == 0 ||
regexec(®ex_special, line, 3, regmatch, 0) == 0 ||
regexec(®ex_symbolic, line, 3, regmatch, 0) == 0 ||
regexec(®ex_hard, line, 3, regmatch, 0) == 0) {
if (argument->dle.create_index && regmatch[1].rm_so == 2) {
line[regmatch[1].rm_eo]='\0';
fprintf(indexstream, "/%s\n", &line[regmatch[1].rm_so]);
}
continue;
}
for (rp = re_table; rp->regex != NULL; rp++) {
if (match(rp->regex, line)) {
break;
}
}
if (rp->typ == DMP_SIZE) {
dump_size = (off_t)((the_num(line, rp->field)* rp->scale+1023.0)/1024.0);
}
switch (rp->typ) {
case DMP_IGNORE:
continue;
case DMP_NORMAL:
type = "normal";
startchr = '|';
break;
case DMP_STRANGE:
type = "strange";
startchr = '?';
break;
case DMP_SIZE:
type = "size";
startchr = '|';
break;
case DMP_ERROR:
type = "error";
startchr = '?';
break;
default:
type = "unknown";
startchr = '!';
break;
}
dbprintf("%3d: %7s(%c): %s\n", rp->srcline, type, startchr, line);
fprintf(mesgstream,"%c %s\n", startchr, line);
}
fclose(outstream);
regfree(®ex_root);
regfree(®ex_dir);
regfree(®ex_file);
regfree(®ex_special);
regfree(®ex_symbolic);
regfree(®ex_hard);
dbprintf(_("gnutar: %s: pid %ld\n"), cmd, (long)starpid);
dbprintf("sendbackup: size %lld\n", (long long)dump_size);
fprintf(mesgstream, "sendbackup: size %lld\n", (long long)dump_size);
fclose(mesgstream);
if (argument->dle.create_index)
fclose(indexstream);
amfree(qdisk);
amfree(cmd);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,
application-src/amstar.c: Filter option from COMMAND-OPTIONS
* common-src/ammessage.c: Add message.
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amgtar_selfcheck(
application_argument_t *argument)
{
if (argument->dle.disk) {
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700000, MSG_INFO, 3,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
}
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700001, MSG_INFO, 4,
"version", VERSION,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
amgtar_build_exinclude(&argument->dle, 1, NULL, NULL, NULL, NULL);
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700004, MSG_INFO, 3,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
if (gnutar_path) {
message_t *message;
if ((message = check_exec_for_suid_message(gnutar_path))) {
delete_message(print_message(message));
} else {
message = print_message(check_file_message(gnutar_path, X_OK));
if (message && message_get_severity(message) <= MSG_INFO) {
char *gtar_version;
GPtrArray *argv_ptr = g_ptr_array_new();
g_ptr_array_add(argv_ptr, gnutar_path);
g_ptr_array_add(argv_ptr, "--version");
g_ptr_array_add(argv_ptr, NULL);
gtar_version = get_first_line(argv_ptr);
if (gtar_version) {
char *gv;
for (gv = gtar_version; *gv && !g_ascii_isdigit(*gv); gv++);
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700002, MSG_INFO, 4,
"gtar-version", gv,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
} else {
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700003, MSG_ERROR, 4,
"gtar-path", gnutar_path,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
}
g_ptr_array_free(argv_ptr, TRUE);
amfree(gtar_version);
}
if (message)
delete_message(message);
}
} else {
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700005, MSG_ERROR, 3,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
}
if (gnutar_listdir && strlen(gnutar_listdir) == 0)
gnutar_listdir = NULL;
if (gnutar_listdir) {
delete_message(print_message(check_dir_message(gnutar_listdir, R_OK|W_OK)));
} else {
delete_message(print_message(build_message(
AMANDA_FILE, __LINE__, 3700006, MSG_ERROR, 3,
"disk", argument->dle.disk,
"device", argument->dle.device,
"hostname", argument->host)));
}
set_root_privs(1);
if (gnutar_directory) {
delete_message(print_message(check_dir_message(gnutar_directory, R_OK)));
} else if (argument->dle.device) {
delete_message(print_message(check_dir_message(argument->dle.device, R_OK)));
}
if (argument->calcsize) {
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
delete_message(print_message(check_exec_for_suid_message(calcsize)));
delete_message(print_message(check_file_message(calcsize, X_OK)));
delete_message(print_message(check_suid_message(calcsize)));
amfree(calcsize);
}
set_root_privs(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,
application-src/amstar.c: Filter option from COMMAND-OPTIONS
* common-src/ammessage.c: Add message.
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ambsdtar_estimate(
application_argument_t *argument)
{
char *incrname = NULL;
GPtrArray *argv_ptr;
char *cmd = NULL;
int nullfd = -1;
int pipefd = -1;
FILE *dumpout = NULL;
off_t size = -1;
char line[32768];
char *errmsg = NULL;
char *qerrmsg = NULL;
char *qdisk = NULL;
amwait_t wait_status;
int tarpid;
amregex_t *rp;
times_t start_time;
int level;
GSList *levels;
char *file_exclude = NULL;
char *file_include = NULL;
GString *strbuf;
if (!argument->level) {
fprintf(stderr, "ERROR No level argument\n");
error(_("No level argument"));
}
if (!argument->dle.disk) {
fprintf(stderr, "ERROR No disk argument\n");
error(_("No disk argument"));
}
if (!argument->dle.device) {
fprintf(stderr, "ERROR No device argument\n");
error(_("No device argument"));
}
if (argument->calcsize) {
char *dirname;
int nb_exclude;
int nb_include;
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
if (!check_exec_for_suid(calcsize, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", calcsize);
goto common_error;
return;
}
if (bsdtar_directory) {
dirname = bsdtar_directory;
} else {
dirname = argument->dle.device;
}
ambsdtar_build_exinclude(&argument->dle, 1,
&nb_exclude, &file_exclude,
&nb_include, &file_include);
run_calcsize(argument->config, "BSDTAR", argument->dle.disk, dirname,
argument->level, file_exclude, file_include);
if (argument->verbose == 0) {
if (file_exclude)
unlink(file_exclude);
if (file_include)
unlink(file_include);
}
amfree(file_exclude);
amfree(file_include);
amfree(qdisk);
return;
}
if (!bsdtar_path) {
errmsg = g_strdup(_("BSDTAR-PATH not defined"));
goto common_error;
}
if (!check_exec_for_suid(bsdtar_path, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", bsdtar_path);
goto common_error;
}
if (!state_dir) {
errmsg = g_strdup(_("STATE-DIR not defined"));
goto common_error;
}
qdisk = quote_string(argument->dle.disk);
for (levels = argument->level; levels != NULL; levels = levels->next) {
char *timestamps;
level = GPOINTER_TO_INT(levels->data);
timestamps = ambsdtar_get_timestamps(argument, level, stdout, CMD_ESTIMATE);
cmd = g_strdup(bsdtar_path);
argv_ptr = ambsdtar_build_argv(argument, timestamps, &file_exclude,
&file_include, CMD_ESTIMATE);
amfree(timestamps);
start_time = curclock();
if ((nullfd = open("/dev/null", O_RDWR)) == -1) {
errmsg = g_strdup_printf(_("Cannot access /dev/null : %s"),
strerror(errno));
goto common_exit;
}
tarpid = pipespawnv(cmd, STDERR_PIPE, 1,
&nullfd, &nullfd, &pipefd,
(char **)argv_ptr->pdata);
dumpout = fdopen(pipefd,"r");
if (!dumpout) {
error(_("Can't fdopen: %s"), strerror(errno));
/*NOTREACHED*/
}
size = (off_t)-1;
while (size < 0 && (fgets(line, sizeof(line), dumpout) != NULL)) {
if (strlen(line) > 0 && line[strlen(line)-1] == '\n') {
/* remove trailling \n */
line[strlen(line)-1] = '\0';
}
if (line[0] == '\0')
continue;
g_debug("%s", line);
/* check for size match */
/*@ignore@*/
for(rp = re_table; rp->regex != NULL; rp++) {
if(match(rp->regex, line)) {
if (rp->typ == DMP_SIZE) {
off_t blocksize = gblocksize;
size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);
if(size < 0.0)
size = 1.0; /* found on NeXT -- sigh */
if (!blocksize) {
blocksize = 20;
}
blocksize /= 2;
size = (size+blocksize-1) / blocksize;
size *= blocksize;
}
break;
}
}
/*@end@*/
}
while (fgets(line, sizeof(line), dumpout) != NULL) {
g_debug("%s", line);
}
g_debug(".....");
g_debug(_("estimate time for %s level %d: %s"),
qdisk,
level,
walltime_str(timessub(curclock(), start_time)));
if(size == (off_t)-1) {
errmsg = g_strdup_printf(_("no size line match in %s output"), cmd);
g_debug(_("%s for %s"), errmsg, qdisk);
g_debug(".....");
} else if(size == (off_t)0 && argument->level == 0) {
g_debug(_("possible %s problem -- is \"%s\" really empty?"),
cmd, argument->dle.disk);
g_debug(".....");
}
g_debug(_("estimate size for %s level %d: %lld KB"),
qdisk,
level,
(long long)size);
(void)kill(-tarpid, SIGTERM);
g_debug(_("waiting for %s \"%s\" child"), cmd, qdisk);
waitpid(tarpid, &wait_status, 0);
if (WIFSIGNALED(wait_status)) {
strbuf = g_string_new(errmsg);
g_string_append_printf(strbuf, "%s terminated with signal %d: see %s",
cmd, WTERMSIG(wait_status), dbfn());
g_free(errmsg);
errmsg = g_string_free(strbuf, FALSE);
exit_status = 1;
} else if (WIFEXITED(wait_status)) {
if (exit_value[WEXITSTATUS(wait_status)] == 1) {
strbuf = g_string_new(errmsg);
g_string_append_printf(strbuf, "%s exited with status %d: see %s",
cmd, WEXITSTATUS(wait_status), dbfn());
g_free(errmsg);
errmsg = g_string_free(strbuf, FALSE);
exit_status = 1;
} else {
/* Normal exit */
}
} else {
errmsg = g_strdup_printf(_("%s got bad exit: see %s"),
cmd, dbfn());
exit_status = 1;
}
g_debug(_("after %s %s wait"), cmd, qdisk);
common_exit:
if (errmsg) {
g_debug("%s", errmsg);
fprintf(stdout, "ERROR %s\n", errmsg);
amfree(errmsg);
}
if (argument->verbose == 0) {
if (file_exclude)
unlink(file_exclude);
if (file_include)
unlink(file_include);
}
g_ptr_array_free_full(argv_ptr);
amfree(cmd);
amfree(incrname);
aclose(nullfd);
afclose(dumpout);
fprintf(stdout, "%d %lld 1\n", level, (long long)size);
}
amfree(qdisk);
amfree(file_exclude);
amfree(file_include);
amfree(errmsg);
amfree(qerrmsg);
amfree(incrname);
return;
common_error:
qerrmsg = quote_string(errmsg);
amfree(qdisk);
g_debug("%s", errmsg);
fprintf(stdout, "ERROR %s\n", qerrmsg);
exit_status = 1;
amfree(file_exclude);
amfree(file_include);
amfree(errmsg);
amfree(qerrmsg);
amfree(incrname);
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,
application-src/amstar.c: Filter option from COMMAND-OPTIONS
* common-src/ammessage.c: Add message.
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amstar_selfcheck(
application_argument_t *argument)
{
if (argument->dle.disk) {
char *qdisk = quote_string(argument->dle.disk);
fprintf(stdout, "OK disk %s\n", qdisk);
amfree(qdisk);
}
fprintf(stdout, "OK amstar version %s\n", VERSION);
fprintf(stdout, "OK amstar\n");
if (argument->dle.device) {
char *qdevice = quote_string(argument->dle.device);
fprintf(stdout, "OK %s\n", qdevice);
amfree(qdevice);
}
if (star_directory) {
char *qdirectory = quote_string(star_directory);
fprintf(stdout, "OK %s\n", qdirectory);
amfree(qdirectory);
}
if (((argument->dle.include_list &&
argument->dle.include_list->nb_element >= 0) ||
(argument->dle.include_file &&
argument->dle.include_file->nb_element >= 0)) &&
((argument->dle.exclude_list &&
argument->dle.exclude_list->nb_element >= 0) ||
(argument->dle.exclude_file &&
argument->dle.exclude_file->nb_element >= 0))) {
fprintf(stdout, "ERROR Can't use include and exclude simultaneously\n");
}
if (!star_path) {
fprintf(stdout, "ERROR STAR-PATH not defined\n");
} else {
if (check_file(star_path, X_OK)) {
if (check_exec_for_suid(star_path, TRUE)) {
char *star_version;
GPtrArray *argv_ptr = g_ptr_array_new();
g_ptr_array_add(argv_ptr, star_path);
g_ptr_array_add(argv_ptr, "--version");
g_ptr_array_add(argv_ptr, NULL);
star_version = get_first_line(argv_ptr);
if (star_version) {
char *sv, *sv1;
for (sv = star_version; *sv && !g_ascii_isdigit(*sv); sv++);
for (sv1 = sv; *sv1 && *sv1 != ' '; sv1++);
*sv1 = '\0';
printf("OK amstar star-version %s\n", sv);
} else {
printf(_("ERROR [Can't get %s version]\n"), star_path);
}
g_ptr_array_free(argv_ptr, TRUE);
amfree(star_version);
}
}
}
if (argument->calcsize) {
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
check_exec_for_suid(calcsize, TRUE);
check_file(calcsize, X_OK);
check_suid(calcsize);
amfree(calcsize);
}
{
char *amandates_file;
amandates_file = getconf_str(CNF_AMANDATES);
check_file(amandates_file, R_OK|W_OK);
}
set_root_privs(1);
if (argument->dle.device) {
check_dir(argument->dle.device, R_OK);
}
set_root_privs(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,
application-src/amstar.c: Filter option from COMMAND-OPTIONS
* common-src/ammessage.c: Add message.
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amgtar_estimate(
application_argument_t *argument)
{
char *incrname = NULL;
GPtrArray *argv_ptr;
char *cmd = NULL;
int nullfd = -1;
int pipefd = -1;
FILE *dumpout = NULL;
off_t size = -1;
char line[32768];
char *errmsg = NULL;
char *qerrmsg = NULL;
char *qdisk = NULL;
amwait_t wait_status;
int tarpid;
amregex_t *rp;
times_t start_time;
int level;
GSList *levels;
char *file_exclude = NULL;
char *file_include = NULL;
GString *strbuf;
if (!argument->level) {
fprintf(stderr, "ERROR No level argument\n");
error(_("No level argument"));
}
if (!argument->dle.disk) {
fprintf(stderr, "ERROR No disk argument\n");
error(_("No disk argument"));
}
if (!argument->dle.device) {
fprintf(stderr, "ERROR No device argument\n");
error(_("No device argument"));
}
if (argument->calcsize) {
char *dirname;
int nb_exclude;
int nb_include;
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
if (!check_exec_for_suid(calcsize, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", calcsize);
g_free(calcsize);
goto common_error;
}
g_free(calcsize);
if (gnutar_directory) {
dirname = gnutar_directory;
} else {
dirname = argument->dle.device;
}
amgtar_build_exinclude(&argument->dle, 1,
&nb_exclude, &file_exclude,
&nb_include, &file_include);
run_calcsize(argument->config, "GNUTAR", argument->dle.disk, dirname,
argument->level, file_exclude, file_include);
if (argument->verbose == 0) {
if (file_exclude)
unlink(file_exclude);
if (file_include)
unlink(file_include);
}
amfree(file_exclude);
amfree(file_include);
return;
}
if (!gnutar_path) {
errmsg = g_strdup(_("GNUTAR-PATH not defined"));
goto common_error;
}
if (!gnutar_listdir) {
errmsg = g_strdup(_("GNUTAR-LISTDIR not defined"));
goto common_error;
}
if (!check_exec_for_suid(gnutar_path, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", gnutar_path);
goto common_error;
}
qdisk = quote_string(argument->dle.disk);
for (levels = argument->level; levels != NULL; levels = levels->next) {
level = GPOINTER_TO_INT(levels->data);
incrname = amgtar_get_incrname(argument, level, stdout, CMD_ESTIMATE);
cmd = g_strdup(gnutar_path);
argv_ptr = amgtar_build_argv(argument, incrname, &file_exclude,
&file_include, CMD_ESTIMATE);
start_time = curclock();
if ((nullfd = open("/dev/null", O_RDWR)) == -1) {
errmsg = g_strdup_printf(_("Cannot access /dev/null : %s"),
strerror(errno));
goto common_exit;
}
tarpid = pipespawnv(cmd, STDERR_PIPE, 1,
&nullfd, &nullfd, &pipefd,
(char **)argv_ptr->pdata);
dumpout = fdopen(pipefd,"r");
if (!dumpout) {
error(_("Can't fdopen: %s"), strerror(errno));
/*NOTREACHED*/
}
size = (off_t)-1;
while (size < 0 && (fgets(line, sizeof(line), dumpout) != NULL)) {
if (strlen(line) > 0 && line[strlen(line)-1] == '\n') {
/* remove trailling \n */
line[strlen(line)-1] = '\0';
}
if (line[0] == '\0')
continue;
dbprintf("%s\n", line);
/* check for size match */
/*@ignore@*/
for(rp = re_table; rp->regex != NULL; rp++) {
if(match(rp->regex, line)) {
if (rp->typ == DMP_SIZE) {
size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);
if(size < 0.0)
size = 1.0; /* found on NeXT -- sigh */
}
break;
}
}
/*@end@*/
}
while (fgets(line, sizeof(line), dumpout) != NULL) {
dbprintf("%s", line);
}
dbprintf(".....\n");
dbprintf(_("estimate time for %s level %d: %s\n"),
qdisk,
level,
walltime_str(timessub(curclock(), start_time)));
if(size == (off_t)-1) {
errmsg = g_strdup_printf(_("no size line match in %s output"), cmd);
dbprintf(_("%s for %s\n"), errmsg, qdisk);
dbprintf(".....\n");
} else if(size == (off_t)0 && argument->level == 0) {
dbprintf(_("possible %s problem -- is \"%s\" really empty?\n"),
cmd, argument->dle.disk);
dbprintf(".....\n");
}
dbprintf(_("estimate size for %s level %d: %lld KB\n"),
qdisk,
level,
(long long)size);
(void)kill(-tarpid, SIGTERM);
dbprintf(_("waiting for %s \"%s\" child\n"), cmd, qdisk);
waitpid(tarpid, &wait_status, 0);
if (WIFSIGNALED(wait_status)) {
strbuf = g_string_new(errmsg);
g_string_append_printf(strbuf, "%s terminated with signal %d: see %s",
cmd, WTERMSIG(wait_status), dbfn());
g_free(errmsg);
errmsg = g_string_free(strbuf, FALSE);
} else if (WIFEXITED(wait_status)) {
if (exit_value[WEXITSTATUS(wait_status)] == 1) {
strbuf = g_string_new(errmsg);
g_string_append_printf(strbuf, "%s exited with status %d: see %s",
cmd, WEXITSTATUS(wait_status), dbfn());
g_free(errmsg);
errmsg = g_string_free(strbuf, FALSE);
} else {
/* Normal exit */
}
} else {
errmsg = g_strdup_printf(_("%s got bad exit: see %s"),
cmd, dbfn());
}
dbprintf(_("after %s %s wait\n"), cmd, qdisk);
common_exit:
if (errmsg) {
dbprintf("%s", errmsg);
fprintf(stdout, "ERROR %s\n", errmsg);
amfree(errmsg);
}
unlink(incrname);
if (argument->verbose == 0) {
if (file_exclude)
unlink(file_exclude);
if (file_include)
unlink(file_include);
}
g_ptr_array_free_full(argv_ptr);
amfree(cmd);
amfree(incrname);
aclose(nullfd);
afclose(dumpout);
fprintf(stdout, "%d %lld 1\n", level, (long long)size);
}
amfree(qdisk);
amfree(file_exclude);
amfree(file_include);
amfree(errmsg);
amfree(qerrmsg);
amfree(incrname);
return;
common_error:
qerrmsg = quote_string(errmsg);
amfree(qdisk);
dbprintf("%s", errmsg);
fprintf(stdout, "ERROR %s\n", qerrmsg);
amfree(file_exclude);
amfree(file_include);
amfree(errmsg);
amfree(qerrmsg);
amfree(incrname);
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,
application-src/amstar.c: Filter option from COMMAND-OPTIONS
* common-src/ammessage.c: Add message.
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: check_exec_for_suid(
char *filename,
gboolean verbose)
{
struct stat stat_buf;
char *quoted = quote_string(filename);
if(!stat(filename, &stat_buf)) {
char *copy_filename;
char *s;
if (stat_buf.st_uid != 0 ) {
if (verbose)
g_printf(_("ERROR [%s is not owned by root]\n"), quoted);
g_debug("Error: %s is not owned by root", quoted);
amfree(quoted);
return FALSE;
}
if (stat_buf.st_mode & S_IWOTH) {
if (verbose)
g_printf(_("ERROR [%s is writable by everyone]\n"), quoted);
g_debug("Error: %s is writable by everyone", quoted);
amfree(quoted);
return FALSE;
}
if (stat_buf.st_mode & S_IWGRP) {
if (verbose)
g_printf(_("ERROR [%s is writable by the group]\n"), quoted);
g_debug("Error: %s is writable by the group", quoted);
amfree(quoted);
return FALSE;
}
copy_filename = g_strdup(filename);
if ((s = strchr(copy_filename, '/'))) {
*s = '\0';
if (*copy_filename && !check_exec_for_suid(copy_filename, verbose)) {
amfree(quoted);
amfree(copy_filename);
return FALSE;
}
}
amfree(copy_filename);
}
else {
if (verbose)
g_printf(_("ERROR [can not stat %s: %s]\n"), quoted, strerror(errno));
g_debug("Error: can not stat %s: %s", quoted, strerror(errno));
amfree(quoted);
return FALSE;
}
amfree(quoted);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amstar_selfcheck(
application_argument_t *argument)
{
char *option;
if (argument->dle.disk) {
char *qdisk = quote_string(argument->dle.disk);
fprintf(stdout, "OK disk %s\n", qdisk);
amfree(qdisk);
}
fprintf(stdout, "OK amstar version %s\n", VERSION);
fprintf(stdout, "OK amstar\n");
if (argument->dle.device) {
char *qdevice = quote_string(argument->dle.device);
fprintf(stdout, "OK %s\n", qdevice);
amfree(qdevice);
}
if (star_directory) {
char *qdirectory = quote_string(star_directory);
fprintf(stdout, "OK %s\n", qdirectory);
amfree(qdirectory);
}
if (((argument->dle.include_list &&
argument->dle.include_list->nb_element >= 0) ||
(argument->dle.include_file &&
argument->dle.include_file->nb_element >= 0)) &&
((argument->dle.exclude_list &&
argument->dle.exclude_list->nb_element >= 0) ||
(argument->dle.exclude_file &&
argument->dle.exclude_file->nb_element >= 0))) {
fprintf(stdout, "ERROR Can't use include and exclude simultaneously\n");
}
if ((option = validate_command_options(argument))) {
fprintf(stdout, "ERROR Invalid '%s' COMMAND-OPTIONS\n", option);
}
if (!star_path) {
fprintf(stdout, "ERROR STAR-PATH not defined\n");
} else {
if (check_file(star_path, X_OK)) {
if (check_exec_for_suid(star_path, TRUE)) {
char *star_version;
GPtrArray *argv_ptr = g_ptr_array_new();
g_ptr_array_add(argv_ptr, star_path);
g_ptr_array_add(argv_ptr, "--version");
g_ptr_array_add(argv_ptr, NULL);
star_version = get_first_line(argv_ptr);
if (star_version) {
char *sv, *sv1;
for (sv = star_version; *sv && !g_ascii_isdigit(*sv); sv++);
for (sv1 = sv; *sv1 && *sv1 != ' '; sv1++);
*sv1 = '\0';
printf("OK amstar star-version %s\n", sv);
} else {
printf(_("ERROR [Can't get %s version]\n"), star_path);
}
g_ptr_array_free(argv_ptr, TRUE);
amfree(star_version);
}
}
}
if (argument->calcsize) {
char *calcsize = vstralloc(amlibexecdir, "/", "calcsize", NULL);
check_exec_for_suid(calcsize, TRUE);
check_file(calcsize, X_OK);
check_suid(calcsize);
amfree(calcsize);
}
{
char *amandates_file;
amandates_file = getconf_str(CNF_AMANDATES);
check_file(amandates_file, R_OK|W_OK);
}
set_root_privs(1);
if (argument->dle.device) {
check_dir(argument->dle.device, R_OK);
}
set_root_privs(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amgtar_restore(
application_argument_t *argument)
{
char *cmd;
GPtrArray *argv_ptr = g_ptr_array_new();
char **env;
int j;
char *e;
char *include_filename = NULL;
char *exclude_filename = NULL;
if (!gnutar_path) {
error(_("GNUTAR-PATH not defined"));
}
if (!check_exec_for_suid(gnutar_path, FALSE)) {
error("'%s' binary is not secure", gnutar_path);
}
cmd = stralloc(gnutar_path);
g_ptr_array_add(argv_ptr, stralloc(gnutar_path));
g_ptr_array_add(argv_ptr, stralloc("--numeric-owner"));
if (gnutar_no_unquote)
g_ptr_array_add(argv_ptr, stralloc("--no-unquote"));
if (gnutar_acls)
g_ptr_array_add(argv_ptr, stralloc("--acls"));
if (gnutar_selinux)
g_ptr_array_add(argv_ptr, stralloc("--selinux"));
if (gnutar_xattrs)
g_ptr_array_add(argv_ptr, stralloc("--xattrs"));
/* ignore trailing zero blocks on input (this was the default until tar-1.21) */
if (argument->ignore_zeros) {
g_ptr_array_add(argv_ptr, stralloc("--ignore-zeros"));
}
if (argument->tar_blocksize) {
g_ptr_array_add(argv_ptr, stralloc("--blocking-factor"));
g_ptr_array_add(argv_ptr, stralloc(argument->tar_blocksize));
}
g_ptr_array_add(argv_ptr, stralloc("-xpGvf"));
g_ptr_array_add(argv_ptr, stralloc("-"));
if (gnutar_directory) {
struct stat stat_buf;
if(stat(gnutar_directory, &stat_buf) != 0) {
fprintf(stderr,"can not stat directory %s: %s\n", gnutar_directory, strerror(errno));
exit(1);
}
if (!S_ISDIR(stat_buf.st_mode)) {
fprintf(stderr,"%s is not a directory\n", gnutar_directory);
exit(1);
}
if (access(gnutar_directory, W_OK) != 0) {
fprintf(stderr, "Can't write to %s: %s\n", gnutar_directory, strerror(errno));
exit(1);
}
g_ptr_array_add(argv_ptr, stralloc("--directory"));
g_ptr_array_add(argv_ptr, stralloc(gnutar_directory));
}
g_ptr_array_add(argv_ptr, stralloc("--wildcards"));
if (argument->dle.exclude_list &&
argument->dle.exclude_list->nb_element == 1) {
FILE *exclude;
char *sdisk;
int in_argv;
int entry_in_exclude = 0;
char line[2*PATH_MAX];
FILE *exclude_list;
if (argument->dle.disk) {
sdisk = sanitise_filename(argument->dle.disk);
} else {
sdisk = g_strdup_printf("no_dle-%d", (int)getpid());
}
exclude_filename= vstralloc(AMANDA_TMPDIR, "/", "exclude-", sdisk, NULL);
exclude_list = fopen(argument->dle.exclude_list->first->name, "r");
exclude = fopen(exclude_filename, "w");
while (fgets(line, 2*PATH_MAX, exclude_list)) {
char *escaped;
line[strlen(line)-1] = '\0'; /* remove '\n' */
escaped = escape_tar_glob(line, &in_argv);
if (in_argv) {
g_ptr_array_add(argv_ptr, "--exclude");
g_ptr_array_add(argv_ptr, escaped);
} else {
fprintf(exclude,"%s\n", escaped);
entry_in_exclude++;
amfree(escaped);
}
}
fclose(exclude);
g_ptr_array_add(argv_ptr, stralloc("--exclude-from"));
g_ptr_array_add(argv_ptr, exclude_filename);
}
if (argument->exclude_list_glob) {
g_ptr_array_add(argv_ptr, stralloc("--exclude-from"));
g_ptr_array_add(argv_ptr, stralloc(argument->exclude_list_glob));
}
{
GPtrArray *argv_include = g_ptr_array_new();
FILE *include;
char *sdisk;
int in_argv;
guint i;
int entry_in_include = 0;
if (argument->dle.disk) {
sdisk = sanitise_filename(argument->dle.disk);
} else {
sdisk = g_strdup_printf("no_dle-%d", (int)getpid());
}
include_filename = vstralloc(AMANDA_TMPDIR, "/", "include-", sdisk, NULL);
include = fopen(include_filename, "w");
if (argument->dle.include_list &&
argument->dle.include_list->nb_element == 1) {
char line[2*PATH_MAX];
FILE *include_list = fopen(argument->dle.include_list->first->name, "r");
while (fgets(line, 2*PATH_MAX, include_list)) {
char *escaped;
line[strlen(line)-1] = '\0'; /* remove '\n' */
escaped = escape_tar_glob(line, &in_argv);
if (in_argv) {
g_ptr_array_add(argv_include, escaped);
} else {
fprintf(include,"%s\n", escaped);
entry_in_include++;
amfree(escaped);
}
}
}
for (j=1; j< argument->argc; j++) {
char *escaped = escape_tar_glob(argument->argv[j], &in_argv);
if (in_argv) {
g_ptr_array_add(argv_include, escaped);
} else {
fprintf(include,"%s\n", escaped);
entry_in_include++;
amfree(escaped);
}
}
fclose(include);
if (entry_in_include) {
g_ptr_array_add(argv_ptr, stralloc("--files-from"));
g_ptr_array_add(argv_ptr, include_filename);
}
if (argument->include_list_glob) {
g_ptr_array_add(argv_ptr, stralloc("--files-from"));
g_ptr_array_add(argv_ptr, stralloc(argument->include_list_glob));
}
for (i = 0; i < argv_include->len; i++) {
g_ptr_array_add(argv_ptr, (char *)g_ptr_array_index(argv_include,i));
}
}
g_ptr_array_add(argv_ptr, NULL);
debug_executing(argv_ptr);
env = safe_env();
become_root();
execve(cmd, (char **)argv_ptr->pdata, env);
e = strerror(errno);
error(_("error [exec %s: %s]"), cmd, e);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GPtrArray *amgtar_build_argv(
application_argument_t *argument,
char *incrname,
char **file_exclude,
char **file_include,
int command)
{
int nb_exclude;
int nb_include;
char *dirname;
char tmppath[PATH_MAX];
GPtrArray *argv_ptr = g_ptr_array_new();
GSList *copt;
check_no_check_device();
amgtar_build_exinclude(&argument->dle, 1,
&nb_exclude, file_exclude,
&nb_include, file_include);
if (gnutar_directory) {
dirname = gnutar_directory;
} else {
dirname = argument->dle.device;
}
g_ptr_array_add(argv_ptr, stralloc(gnutar_path));
g_ptr_array_add(argv_ptr, stralloc("--create"));
if (command == CMD_BACKUP && argument->dle.create_index)
g_ptr_array_add(argv_ptr, stralloc("--verbose"));
g_ptr_array_add(argv_ptr, stralloc("--file"));
if (command == CMD_ESTIMATE) {
g_ptr_array_add(argv_ptr, stralloc("/dev/null"));
} else {
g_ptr_array_add(argv_ptr, stralloc("-"));
}
if (gnutar_no_unquote)
g_ptr_array_add(argv_ptr, stralloc("--no-unquote"));
g_ptr_array_add(argv_ptr, stralloc("--directory"));
canonicalize_pathname(dirname, tmppath);
g_ptr_array_add(argv_ptr, stralloc(tmppath));
if (gnutar_onefilesystem)
g_ptr_array_add(argv_ptr, stralloc("--one-file-system"));
if (gnutar_atimepreserve)
g_ptr_array_add(argv_ptr, stralloc("--atime-preserve=system"));
if (!gnutar_checkdevice)
g_ptr_array_add(argv_ptr, stralloc("--no-check-device"));
if (gnutar_acls)
g_ptr_array_add(argv_ptr, stralloc("--acls"));
if (gnutar_selinux)
g_ptr_array_add(argv_ptr, stralloc("--selinux"));
if (gnutar_xattrs)
g_ptr_array_add(argv_ptr, stralloc("--xattrs"));
g_ptr_array_add(argv_ptr, stralloc("--listed-incremental"));
g_ptr_array_add(argv_ptr, stralloc(incrname));
if (gnutar_sparse) {
if (!gnutar_sparse_set) {
char *gtar_version;
char *minor_version;
char *sminor_version;
char *gv;
int major;
int minor;
GPtrArray *version_ptr = g_ptr_array_new();
g_ptr_array_add(version_ptr, gnutar_path);
g_ptr_array_add(version_ptr, "--version");
g_ptr_array_add(version_ptr, NULL);
gtar_version = get_first_line(version_ptr);
if (gtar_version) {
for (gv = gtar_version; *gv && !g_ascii_isdigit(*gv); gv++);
minor_version = index(gtar_version, '.');
if (minor_version) {
*minor_version++ = '\0';
sminor_version = index(minor_version, '.');
if (sminor_version) {
*sminor_version = '\0';
}
major = atoi(gv);
minor = atoi(minor_version);
if (major < 1 ||
(major == 1 && minor < 28)) {
gnutar_sparse = 0;
}
}
}
g_ptr_array_free(version_ptr, TRUE);
amfree(gtar_version);
}
if (gnutar_sparse) {
g_ptr_array_add(argv_ptr, g_strdup("--sparse"));
}
}
if (argument->tar_blocksize) {
g_ptr_array_add(argv_ptr, stralloc("--blocking-factor"));
g_ptr_array_add(argv_ptr, stralloc(argument->tar_blocksize));
}
g_ptr_array_add(argv_ptr, stralloc("--ignore-failed-read"));
g_ptr_array_add(argv_ptr, stralloc("--totals"));
for (copt = argument->command_options; copt != NULL; copt = copt->next) {
g_ptr_array_add(argv_ptr, stralloc((char *)copt->data));
}
if (*file_exclude) {
g_ptr_array_add(argv_ptr, stralloc("--exclude-from"));
g_ptr_array_add(argv_ptr, stralloc(*file_exclude));
}
if (*file_include) {
g_ptr_array_add(argv_ptr, stralloc("--files-from"));
g_ptr_array_add(argv_ptr, stralloc(*file_include));
}
else {
g_ptr_array_add(argv_ptr, stralloc("."));
}
g_ptr_array_add(argv_ptr, NULL);
return(argv_ptr);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: main(
int argc,
char ** argv)
{
char *line = NULL;
char *qdisk = NULL;
char *qamdevice = NULL;
char *optstr = NULL;
char *err_extra = NULL;
char *s, *fp;
int ch;
dle_t *dle;
int level;
GSList *errlist;
am_level_t *alevel;
if (argc > 1 && argv && argv[1] && g_str_equal(argv[1], "--version")) {
printf("selfcheck-%s\n", VERSION);
return (0);
}
/* initialize */
/*
* Configure program for internationalization:
* 1) Only set the message locale for now.
* 2) Set textdomain for all amanda related programs to "amanda"
* We don't want to be forced to support dozens of message catalogs.
*/
setlocale(LC_MESSAGES, "C");
textdomain("amanda");
safe_fd(-1, 0);
openbsd_fd_inform();
safe_cd();
set_pname("selfcheck");
/* Don't die when child closes pipe */
signal(SIGPIPE, SIG_IGN);
add_amanda_log_handler(amanda_log_stderr);
add_amanda_log_handler(amanda_log_syslog);
dbopen(DBG_SUBDIR_CLIENT);
startclock();
dbprintf(_("version %s\n"), VERSION);
g_printf("OK version %s\n", VERSION);
print_platform();
if(argc > 2 && strcmp(argv[1], "amandad") == 0) {
amandad_auth = stralloc(argv[2]);
}
config_init(CONFIG_INIT_CLIENT, NULL);
/* (check for config errors comes later) */
check_running_as(RUNNING_AS_CLIENT_LOGIN);
our_features = am_init_feature_set();
our_feature_string = am_feature_to_string(our_features);
/* handle all service requests */
/*@ignore@*/
for(; (line = agets(stdin)) != NULL; free(line)) {
/*@end@*/
if (line[0] == '\0')
continue;
if(strncmp_const(line, "OPTIONS ") == 0) {
g_options = parse_g_options(line+8, 1);
if(!g_options->hostname) {
g_options->hostname = alloc(MAX_HOSTNAME_LENGTH+1);
gethostname(g_options->hostname, MAX_HOSTNAME_LENGTH);
g_options->hostname[MAX_HOSTNAME_LENGTH] = '\0';
}
g_printf("OPTIONS ");
if(am_has_feature(g_options->features, fe_rep_options_features)) {
g_printf("features=%s;", our_feature_string);
}
if(am_has_feature(g_options->features, fe_rep_options_hostname)) {
g_printf("hostname=%s;", g_options->hostname);
}
g_printf("\n");
fflush(stdout);
if (g_options->config) {
/* overlay this configuration on the existing (nameless) configuration */
config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
g_options->config);
dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
}
/* check for any config errors now */
if (config_errors(&errlist) >= CFGERR_ERRORS) {
char *errstr = config_errors_to_error_string(errlist);
g_printf("%s\n", errstr);
dbclose();
return 1;
}
if (am_has_feature(g_options->features, fe_req_xml)) {
break;
}
continue;
}
dle = alloc_dle();
s = line;
ch = *s++;
skip_whitespace(s, ch); /* find program name */
if (ch == '\0') {
goto err; /* no program */
}
dle->program = s - 1;
skip_non_whitespace(s, ch);
s[-1] = '\0'; /* terminate the program name */
dle->program_is_application_api = 0;
if(strcmp(dle->program,"APPLICATION")==0) {
dle->program_is_application_api = 1;
skip_whitespace(s, ch); /* find dumper name */
if (ch == '\0') {
goto err; /* no program */
}
dle->program = s - 1;
skip_non_whitespace(s, ch);
s[-1] = '\0'; /* terminate the program name */
}
if(strncmp_const(dle->program, "CALCSIZE") == 0) {
skip_whitespace(s, ch); /* find program name */
if (ch == '\0') {
goto err; /* no program */
}
dle->program = s - 1;
skip_non_whitespace(s, ch);
s[-1] = '\0';
dle->estimatelist = g_slist_append(dle->estimatelist,
GINT_TO_POINTER(ES_CALCSIZE));
}
else {
dle->estimatelist = g_slist_append(dle->estimatelist,
GINT_TO_POINTER(ES_CLIENT));
}
skip_whitespace(s, ch); /* find disk name */
if (ch == '\0') {
goto err; /* no disk */
}
qdisk = s - 1;
skip_quoted_string(s, ch);
s[-1] = '\0'; /* terminate the disk name */
dle->disk = unquote_string(qdisk);
skip_whitespace(s, ch); /* find the device or level */
if (ch == '\0') {
goto err; /* no device or level */
}
if(!isdigit((int)s[-1])) {
fp = s - 1;
skip_quoted_string(s, ch);
s[-1] = '\0'; /* terminate the device */
qamdevice = stralloc(fp);
dle->device = unquote_string(qamdevice);
skip_whitespace(s, ch); /* find level number */
}
else {
dle->device = stralloc(dle->disk);
qamdevice = stralloc(qdisk);
}
/* find level number */
if (ch == '\0' || sscanf(s - 1, "%d", &level) != 1) {
goto err; /* bad level */
}
alevel = g_new0(am_level_t, 1);
alevel->level = level;
dle->levellist = g_slist_append(dle->levellist, alevel);
skip_integer(s, ch);
skip_whitespace(s, ch);
if (ch && strncmp_const_skip(s - 1, "OPTIONS ", s, ch) == 0) {
skip_whitespace(s, ch); /* find the option string */
if(ch == '\0') {
goto err; /* bad options string */
}
optstr = s - 1;
skip_quoted_string(s, ch);
s[-1] = '\0'; /* terminate the options */
parse_options(optstr, dle, g_options->features, 1);
/*@ignore@*/
check_options(dle);
check_disk(dle);
/*@end@*/
} else if (ch == '\0') {
/* check all since no option */
need_samba=1;
need_rundump=1;
need_dump=1;
need_restore=1;
need_vdump=1;
need_vrestore=1;
need_xfsdump=1;
need_xfsrestore=1;
need_vxdump=1;
need_vxrestore=1;
need_runtar=1;
need_gnutar=1;
need_compress_path=1;
need_calcsize=1;
need_global_check=1;
/*@ignore@*/
check_disk(dle);
/*@end@*/
} else {
goto err; /* bad syntax */
}
amfree(qamdevice);
}
if (g_options == NULL) {
g_printf(_("ERROR [Missing OPTIONS line in selfcheck input]\n"));
error(_("Missing OPTIONS line in selfcheck input\n"));
/*NOTREACHED*/
}
if (am_has_feature(g_options->features, fe_req_xml)) {
char *errmsg = NULL;
dle_t *dles, *dle, *dle_next;
dles = amxml_parse_node_FILE(stdin, &errmsg);
if (errmsg) {
err_extra = errmsg;
goto err;
}
if (merge_dles_properties(dles, 1) == 0) {
goto checkoverall;
}
for (dle = dles; dle != NULL; dle = dle->next) {
run_client_scripts(EXECUTE_ON_PRE_HOST_AMCHECK, g_options, dle,
stdout);
}
for (dle = dles; dle != NULL; dle = dle->next) {
check_options(dle);
run_client_scripts(EXECUTE_ON_PRE_DLE_AMCHECK, g_options, dle,
stdout);
check_disk(dle);
run_client_scripts(EXECUTE_ON_POST_DLE_AMCHECK, g_options, dle,
stdout);
}
for (dle = dles; dle != NULL; dle = dle->next) {
run_client_scripts(EXECUTE_ON_POST_HOST_AMCHECK, g_options, dle,
stdout);
}
for (dle = dles; dle != NULL; dle = dle_next) {
dle_next = dle->next;
free_dle(dle);
}
}
checkoverall:
check_overall();
amfree(line);
amfree(our_feature_string);
am_release_feature_set(our_features);
our_features = NULL;
free_g_options(g_options);
dbclose();
return 0;
err:
if (err_extra) {
g_printf(_("ERROR [FORMAT ERROR IN REQUEST PACKET %s]\n"), err_extra);
dbprintf(_("REQ packet is bogus: %s\n"), err_extra);
} else {
g_printf(_("ERROR [FORMAT ERROR IN REQUEST PACKET]\n"));
dbprintf(_("REQ packet is bogus\n"));
}
dbclose();
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amstar_estimate(
application_argument_t *argument)
{
GPtrArray *argv_ptr;
char *cmd = NULL;
int nullfd;
int pipefd;
FILE *dumpout = NULL;
off_t size = -1;
char line[32768];
char *errmsg = NULL;
char *qerrmsg;
char *qdisk;
amwait_t wait_status;
int starpid;
amregex_t *rp;
times_t start_time;
int level = 0;
GSList *levels = NULL;
char *option;
if (!argument->level) {
fprintf(stderr, "ERROR No level argument\n");
error(_("No level argument"));
}
if (!argument->dle.disk) {
fprintf(stderr, "ERROR No disk argument\n");
error(_("No disk argument"));
}
if (!argument->dle.device) {
fprintf(stderr, "ERROR No device argument\n");
error(_("No device argument"));
}
if (argument->dle.include_list &&
argument->dle.include_list->nb_element >= 0) {
fprintf(stderr, "ERROR include-list not supported for backup\n");
}
if (check_device(argument) == 0) {
return;
}
if ((option = validate_command_options(argument))) {
fprintf(stderr, "ERROR Invalid '%s' COMMAND-OPTIONS\n", option);
error("Invalid '%s' COMMAND-OPTIONS", option);
}
qdisk = quote_string(argument->dle.disk);
if (argument->calcsize) {
char *dirname;
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
if (!check_exec_for_suid(calcsize, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", calcsize);
goto common_error;
return;
}
if (star_directory) {
dirname = star_directory;
} else {
dirname = argument->dle.device;
}
run_calcsize(argument->config, "STAR", argument->dle.disk, dirname,
argument->level, NULL, NULL);
return;
}
if (!star_path) {
errmsg = vstrallocf(_("STAR-PATH not defined"));
goto common_error;
}
if (!check_exec_for_suid(star_path, FALSE)) {
errmsg = g_strdup_printf("'%s' binary is not secure", star_path);
goto common_error;
}
cmd = stralloc(star_path);
start_time = curclock();
for (levels = argument->level; levels != NULL; levels = levels->next) {
level = GPOINTER_TO_INT(levels->data);
argv_ptr = amstar_build_argv(argument, level, CMD_ESTIMATE, NULL);
if ((nullfd = open("/dev/null", O_RDWR)) == -1) {
errmsg = vstrallocf(_("Cannot access /dev/null : %s"),
strerror(errno));
goto common_error;
}
starpid = pipespawnv(cmd, STDERR_PIPE, 1,
&nullfd, &nullfd, &pipefd,
(char **)argv_ptr->pdata);
dumpout = fdopen(pipefd,"r");
if (!dumpout) {
errmsg = vstrallocf(_("Can't fdopen: %s"), strerror(errno));
goto common_error;
}
size = (off_t)-1;
while (size < 0 && (fgets(line, sizeof(line), dumpout)) != NULL) {
if (line[strlen(line)-1] == '\n') /* remove trailling \n */
line[strlen(line)-1] = '\0';
if (line[0] == '\0')
continue;
dbprintf("%s\n", line);
/* check for size match */
/*@ignore@*/
for(rp = re_table; rp->regex != NULL; rp++) {
if(match(rp->regex, line)) {
if (rp->typ == DMP_SIZE) {
size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);
if(size < 0.0)
size = 1.0; /* found on NeXT -- sigh */
}
break;
}
}
/*@end@*/
}
while ((fgets(line, sizeof(line), dumpout)) != NULL) {
dbprintf("%s", line);
}
dbprintf(".....\n");
dbprintf(_("estimate time for %s level %d: %s\n"),
qdisk,
level,
walltime_str(timessub(curclock(), start_time)));
if(size == (off_t)-1) {
errmsg = vstrallocf(_("no size line match in %s output"),
cmd);
dbprintf(_("%s for %s\n"), errmsg, qdisk);
dbprintf(".....\n");
} else if(size == (off_t)0 && argument->level == 0) {
dbprintf(_("possible %s problem -- is \"%s\" really empty?\n"),
cmd, argument->dle.disk);
dbprintf(".....\n");
}
dbprintf(_("estimate size for %s level %d: %lld KB\n"),
qdisk,
level,
(long long)size);
kill(-starpid, SIGTERM);
dbprintf(_("waiting for %s \"%s\" child\n"), cmd, qdisk);
waitpid(starpid, &wait_status, 0);
if (WIFSIGNALED(wait_status)) {
errmsg = vstrallocf(_("%s terminated with signal %d: see %s"),
cmd, WTERMSIG(wait_status), dbfn());
} else if (WIFEXITED(wait_status)) {
if (WEXITSTATUS(wait_status) != 0) {
errmsg = vstrallocf(_("%s exited with status %d: see %s"),
cmd, WEXITSTATUS(wait_status), dbfn());
} else {
/* Normal exit */
}
} else {
errmsg = vstrallocf(_("%s got bad exit: see %s"), cmd, dbfn());
}
dbprintf(_("after %s %s wait\n"), cmd, qdisk);
g_ptr_array_free_full(argv_ptr);
aclose(nullfd);
afclose(dumpout);
fprintf(stdout, "%d %lld 1\n", level, (long long)size);
}
amfree(qdisk);
amfree(cmd);
return;
common_error:
dbprintf("%s\n", errmsg);
qerrmsg = quote_string(errmsg);
amfree(qdisk);
dbprintf("%s", errmsg);
fprintf(stdout, "ERROR %s\n", qerrmsg);
amfree(errmsg);
amfree(qerrmsg);
amfree(cmd);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ambsdtar_selfcheck(
application_argument_t *argument)
{
char *option;
if (argument->dle.disk) {
char *qdisk = quote_string(argument->dle.disk);
fprintf(stdout, "OK disk %s\n", qdisk);
amfree(qdisk);
}
printf("OK ambsdtar version %s\n", VERSION);
ambsdtar_build_exinclude(&argument->dle, 1, NULL, NULL, NULL, NULL);
printf("OK ambsdtar\n");
if ((option = validate_command_options(argument))) {
fprintf(stdout, "ERROR Invalid '%s' COMMAND-OPTIONS\n", option);
}
if (bsdtar_path) {
if (check_file(bsdtar_path, X_OK)) {
if (check_exec_for_suid(bsdtar_path, TRUE)) {
char *bsdtar_version;
GPtrArray *argv_ptr = g_ptr_array_new();
g_ptr_array_add(argv_ptr, bsdtar_path);
g_ptr_array_add(argv_ptr, "--version");
g_ptr_array_add(argv_ptr, NULL);
bsdtar_version = get_first_line(argv_ptr);
if (bsdtar_version) {
char *tv, *bv;
for (tv = bsdtar_version; *tv && !g_ascii_isdigit(*tv); tv++);
for (bv = tv; *bv && *bv != ' '; bv++);
if (*bv) *bv = '\0';
printf("OK ambsdtar bsdtar-version %s\n", tv);
} else {
printf(_("ERROR [Can't get %s version]\n"), bsdtar_path);
}
g_ptr_array_free(argv_ptr, TRUE);
amfree(bsdtar_version);
}
}
} else {
printf(_("ERROR [BSDTAR program not available]\n"));
}
set_root_privs(1);
if (state_dir && strlen(state_dir) == 0)
state_dir = NULL;
if (state_dir) {
check_dir(state_dir, R_OK|W_OK);
} else {
printf(_("ERROR [No STATE-DIR]\n"));
}
if (bsdtar_directory) {
check_dir(bsdtar_directory, R_OK);
} else if (argument->dle.device) {
check_dir(argument->dle.device, R_OK);
}
if (argument->calcsize) {
char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
check_exec_for_suid(calcsize, TRUE);
check_file(calcsize, X_OK);
check_suid(calcsize);
amfree(calcsize);
}
set_root_privs(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: main(
int argc,
char ** argv)
{
#ifdef GNUTAR
int i;
char *e;
char *dbf;
char *cmdline;
#endif
int good_option;
if (argc > 1 && argv && argv[1] && g_str_equal(argv[1], "--version")) {
printf("runtar-%s\n", VERSION);
return (0);
}
/*
* Configure program for internationalization:
* 1) Only set the message locale for now.
* 2) Set textdomain for all amanda related programs to "amanda"
* We don't want to be forced to support dozens of message catalogs.
*/
setlocale(LC_MESSAGES, "C");
textdomain("amanda");
safe_fd(-1, 0);
safe_cd();
set_pname("runtar");
/* Don't die when child closes pipe */
signal(SIGPIPE, SIG_IGN);
dbopen(DBG_SUBDIR_CLIENT);
config_init(CONFIG_INIT_CLIENT, NULL);
if (argc < 3) {
error(_("Need at least 3 arguments\n"));
/*NOTREACHED*/
}
dbprintf(_("version %s\n"), VERSION);
if (strcmp(argv[3], "--create") != 0) {
error(_("Can only be used to create tar archives\n"));
/*NOTREACHED*/
}
#ifndef GNUTAR
g_fprintf(stderr,_("gnutar not available on this system.\n"));
dbprintf(_("%s: gnutar not available on this system.\n"), argv[0]);
dbclose();
return 1;
#else
/*
* Print out version information for tar.
*/
do {
FILE * version_file;
char version_buf[80];
if ((version_file = popen(GNUTAR " --version 2>&1", "r")) != NULL) {
if (fgets(version_buf, (int)sizeof(version_buf), version_file) != NULL) {
dbprintf(_(GNUTAR " version: %s\n"), version_buf);
} else {
if (ferror(version_file)) {
dbprintf(_(GNUTAR " version: Read failure: %s\n"), strerror(errno));
} else {
dbprintf(_(GNUTAR " version: Read failure; EOF\n"));
}
}
} else {
dbprintf(_(GNUTAR " version: unavailable: %s\n"), strerror(errno));
}
} while(0);
#ifdef WANT_SETUID_CLIENT
check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
if (!become_root()) {
error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname());
/*NOTREACHED*/
}
#else
check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif
/* skip argv[0] */
argc--;
argv++;
dbprintf(_("config: %s\n"), argv[0]);
if (strcmp(argv[0], "NOCONFIG") != 0)
dbrename(argv[0], DBG_SUBDIR_CLIENT);
argc--;
argv++;
if (!check_exec_for_suid(GNUTAR, TRUE)) {
dbclose();
exit(1);
}
cmdline = stralloc(GNUTAR);
good_option = 0;
for (i = 1; argv[i]; i++) {
char *quoted;
if (good_option <= 0) {
if (g_str_has_prefix(argv[i],"--rsh-command") ||
g_str_has_prefix(argv[i],"--to-command") ||
g_str_has_prefix(argv[i],"--info-script") ||
g_str_has_prefix(argv[i],"--new-volume-script") ||
g_str_has_prefix(argv[i],"--rmt-command") ||
g_str_has_prefix(argv[i],"--use-compress-program")) {
/* Filter potential malicious option */
good_option = 0;
} else if (g_str_has_prefix(argv[i],"--create") ||
g_str_has_prefix(argv[i],"--totals") ||
g_str_has_prefix(argv[i],"--dereference") ||
g_str_has_prefix(argv[i],"--no-recursion") ||
g_str_has_prefix(argv[i],"--one-file-system") ||
g_str_has_prefix(argv[i],"--incremental") ||
g_str_has_prefix(argv[i],"--atime-preserve") ||
g_str_has_prefix(argv[i],"--sparse") ||
g_str_has_prefix(argv[i],"--ignore-failed-read") ||
g_str_has_prefix(argv[i],"--numeric-owner")) {
/* Accept theses options */
good_option++;
} else if (g_str_has_prefix(argv[i],"--blocking-factor") ||
g_str_has_prefix(argv[i],"--file") ||
g_str_has_prefix(argv[i],"--directory") ||
g_str_has_prefix(argv[i],"--exclude") ||
g_str_has_prefix(argv[i],"--transform") ||
g_str_has_prefix(argv[i],"--listed-incremental") ||
g_str_has_prefix(argv[i],"--newer") ||
g_str_has_prefix(argv[i],"--exclude-from") ||
g_str_has_prefix(argv[i],"--files-from")) {
/* Accept theses options with the following argument */
good_option += 2;
} else if (argv[i][0] != '-') {
good_option++;
}
}
if (good_option <= 0) {
error("error [%s invalid option: %s]", get_pname(), argv[i]);
}
good_option--;
quoted = quote_string(argv[i]);
cmdline = vstrextend(&cmdline, " ", quoted, NULL);
amfree(quoted);
}
dbprintf(_("running: %s\n"), cmdline);
amfree(cmdline);
dbf = dbfn();
if (dbf) {
dbf = stralloc(dbf);
}
dbclose();
execve(GNUTAR, argv, safe_env());
e = strerror(errno);
dbreopen(dbf, "more");
amfree(dbf);
dbprintf(_("execve of %s failed (%s)\n"), GNUTAR, e);
dbclose();
g_fprintf(stderr, _("runtar: could not exec %s: %s\n"), GNUTAR, e);
return 1;
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: amgtar_selfcheck(
application_argument_t *argument)
{
char *option;
if (argument->dle.disk) {
char *qdisk = quote_string(argument->dle.disk);
fprintf(stdout, "OK disk %s\n", qdisk);
amfree(qdisk);
}
printf("OK amgtar version %s\n", VERSION);
amgtar_build_exinclude(&argument->dle, 1, NULL, NULL, NULL, NULL);
printf("OK amgtar\n");
if ((option = validate_command_options(argument))) {
fprintf(stdout, "ERROR [Invalid '%s' COMMAND-OPTIONS\n", option);
}
if (gnutar_path) {
if (check_file(gnutar_path, X_OK) &&
check_exec_for_suid(gnutar_path, TRUE)) {
char *gtar_version;
GPtrArray *argv_ptr = g_ptr_array_new();
g_ptr_array_add(argv_ptr, gnutar_path);
g_ptr_array_add(argv_ptr, "--version");
g_ptr_array_add(argv_ptr, NULL);
gtar_version = get_first_line(argv_ptr);
if (gtar_version) {
char *gv;
for (gv = gtar_version; *gv && !g_ascii_isdigit(*gv); gv++);
printf("OK amgtar gtar-version %s\n", gv);
} else {
printf(_("ERROR [Can't get %s version]\n"), gnutar_path);
}
g_ptr_array_free(argv_ptr, TRUE);
amfree(gtar_version);
}
} else {
printf(_("ERROR [GNUTAR program not available]\n"));
}
if (gnutar_listdir && strlen(gnutar_listdir) == 0)
gnutar_listdir = NULL;
if (gnutar_listdir) {
check_dir(gnutar_listdir, R_OK|W_OK);
} else {
printf(_("ERROR [No GNUTAR-LISTDIR]\n"));
}
set_root_privs(1);
if (gnutar_directory) {
check_dir(gnutar_directory, R_OK);
} else if (argument->dle.device) {
check_dir(argument->dle.device, R_OK);
}
if (argument->calcsize) {
char *calcsize = vstralloc(amlibexecdir, "/", "calcsize", NULL);
check_file(calcsize, X_OK);
check_suid(calcsize);
check_exec_for_suid(calcsize, TRUE);
amfree(calcsize);
}
set_root_privs(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file
git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t driver_override_store(struct device *_dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct amba_device *dev = to_amba_device(_dev);
char *driver_override, *old, *cp;
if (count > PATH_MAX)
return -EINVAL;
driver_override = kstrndup(buf, count, GFP_KERNEL);
if (!driver_override)
return -ENOMEM;
cp = strchr(driver_override, '\n');
if (cp)
*cp = '\0';
device_lock(_dev);
old = dev->driver_override;
if (strlen(driver_override)) {
dev->driver_override = driver_override;
} else {
kfree(driver_override);
dev->driver_override = NULL;
}
device_unlock(_dev);
kfree(old);
return count;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'ARM: amba: Don't read past the end of sysfs "driver_override" buffer
When printing the driver_override parameter when it is 4095 and 4094
bytes long, the printing code would access invalid memory because we
need count + 1 bytes for printing.
Cfr. commits 4efe874aace57dba ("PCI: Don't read past the end of sysfs
"driver_override" buffer") and bf563b01c2895a4b ("driver core: platform:
Don't read past the end of "driver_override" buffer").
Fixes: 3cf385713460eb2b ("ARM: 8256/1: driver coamba: add device binding path 'driver_override'")
Signed-off-by: Geert Uytterhoeven <[email protected]>
Reviewed-by: Todd Kjos <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 PsdImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Exiv2::PsdImage::readMetadata: Reading Photoshop file " << io_->path() << "\n";
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isPsdType(*io_, false))
{
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAnImage, "Photoshop");
}
clearMetadata();
/*
The Photoshop header goes as follows -- all numbers are in big-endian byte order:
offset length name description
====== ======= ========= =========
0 4 bytes signature always '8BPS'
4 2 bytes version always equal to 1
6 6 bytes reserved must be zero
12 2 bytes channels number of channels in the image, including alpha channels (1 to 24)
14 4 bytes rows the height of the image in pixels
18 4 bytes columns the width of the image in pixels
22 2 bytes depth the number of bits per channel
24 2 bytes mode the color mode of the file; Supported values are: Bitmap=0; Grayscale=1; Indexed=2; RGB=3; CMYK=4; Multichannel=7; Duotone=8; Lab=9
*/
byte buf[26];
if (io_->read(buf, 26) != 26)
{
throw Error(kerNotAnImage, "Photoshop");
}
pixelWidth_ = getLong(buf + 18, bigEndian);
pixelHeight_ = getLong(buf + 14, bigEndian);
// immediately following the image header is the color mode data section,
// the first four bytes of which specify the byte size of the whole section
if (io_->read(buf, 4) != 4)
{
throw Error(kerNotAnImage, "Photoshop");
}
// skip it
uint32_t colorDataLength = getULong(buf, bigEndian);
if (io_->seek(colorDataLength, BasicIo::cur))
{
throw Error(kerNotAnImage, "Photoshop");
}
// after the color data section, comes a list of resource blocks, preceded by the total byte size
if (io_->read(buf, 4) != 4)
{
throw Error(kerNotAnImage, "Photoshop");
}
uint32_t resourcesLength = getULong(buf, bigEndian);
while (resourcesLength > 0)
{
if (io_->read(buf, 8) != 8)
{
throw Error(kerNotAnImage, "Photoshop");
}
if (!Photoshop::isIrb(buf, 4))
{
break; // bad resource type
}
uint16_t resourceId = getUShort(buf + 4, bigEndian);
uint32_t resourceNameLength = buf[6] & ~1;
// skip the resource name, plus any padding
io_->seek(resourceNameLength, BasicIo::cur);
// read resource size
if (io_->read(buf, 4) != 4)
{
throw Error(kerNotAnImage, "Photoshop");
}
uint32_t resourceSize = getULong(buf, bigEndian);
uint32_t curOffset = io_->tell();
#ifdef DEBUG
std::cerr << std::hex << "resourceId: " << resourceId << std::dec << " length: " << resourceSize << std::hex << "\n";
#endif
readResourceBlock(resourceId, resourceSize);
resourceSize = (resourceSize + 1) & ~1; // pad to even
io_->seek(curOffset + resourceSize, BasicIo::beg);
resourcesLength -= (12 + resourceNameLength + resourceSize);
}
} // PsdImage::readMetadata ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'PSD: Use Safe::add for preventing overflows in PSD files'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char *argv[]) {
GooString *fileName;
UnicodeMap *uMap;
GooString *ownerPW, *userPW;
PDFDoc *doc;
char uBuf[8];
char path[1024];
char *p;
bool ok;
int exitCode;
GooList *embeddedFiles = nullptr;
int nFiles, nPages, n, i, j;
FileSpec *fileSpec;
Page *page;
Annots *annots;
Annot *annot;
const GooString *s1;
Unicode u;
bool isUnicode;
Win32Console win32Console(&argc, &argv);
exitCode = 99;
// parse args
ok = parseArgs(argDesc, &argc, argv);
if ((doList ? 1 : 0) +
((saveNum != 0) ? 1 : 0) +
(saveAll ? 1 : 0) != 1) {
ok = false;
}
if (!ok || argc != 2 || printVersion || printHelp) {
fprintf(stderr, "pdfdetach version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfdetach", "<PDF-file>", argDesc);
}
goto err0;
}
fileName = new GooString(argv[1]);
// read config file
globalParams = new GlobalParams();
if (textEncName[0]) {
globalParams->setTextEncoding(textEncName);
}
// get mapping to output encoding
if (!(uMap = globalParams->getTextEncoding())) {
error(errConfig, -1, "Couldn't get text encoding");
delete fileName;
goto err1;
}
// open PDF file
if (ownerPassword[0] != '\001') {
ownerPW = new GooString(ownerPassword);
} else {
ownerPW = nullptr;
}
if (userPassword[0] != '\001') {
userPW = new GooString(userPassword);
} else {
userPW = nullptr;
}
doc = PDFDocFactory().createPDFDoc(*fileName, ownerPW, userPW);
if (userPW) {
delete userPW;
}
if (ownerPW) {
delete ownerPW;
}
if (!doc->isOk()) {
exitCode = 1;
goto err2;
}
embeddedFiles = new GooList();
for (i = 0; i < doc->getCatalog()->numEmbeddedFiles(); ++i)
embeddedFiles->push_back(doc->getCatalog()->embeddedFile(i));
nPages = doc->getCatalog()->getNumPages();
for (i = 0; i < nPages; ++i) {
page = doc->getCatalog()->getPage(i + 1);
if (!page)
continue;
annots = page->getAnnots();
if (!annots)
break;
for (j = 0; j < annots->getNumAnnots(); ++j) {
annot = annots->getAnnot(j);
if (annot->getType() != Annot::typeFileAttachment)
continue;
embeddedFiles->push_back(new FileSpec(static_cast<AnnotFileAttachment *>(annot)->getFile()));
}
}
nFiles = embeddedFiles->getLength();
// list embedded files
if (doList) {
printf("%d embedded files\n", nFiles);
for (i = 0; i < nFiles; ++i) {
fileSpec = static_cast<FileSpec *>(embeddedFiles->get(i));
printf("%d: ", i+1);
s1 = fileSpec->getFileName();
if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {
isUnicode = true;
j = 2;
} else {
isUnicode = false;
j = 0;
}
while (j < fileSpec->getFileName()->getLength()) {
if (isUnicode) {
u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);
j += 2;
} else {
u = pdfDocEncoding[s1->getChar(j) & 0xff];
++j;
}
n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));
fwrite(uBuf, 1, n, stdout);
}
fputc('\n', stdout);
}
// save all embedded files
} else if (saveAll) {
for (i = 0; i < nFiles; ++i) {
fileSpec = static_cast<FileSpec *>(embeddedFiles->get(i));
if (savePath[0]) {
n = strlen(savePath);
if (n > (int)sizeof(path) - 2) {
n = sizeof(path) - 2;
}
memcpy(path, savePath, n);
path[n] = '/';
p = path + n + 1;
} else {
p = path;
}
s1 = fileSpec->getFileName();
if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {
isUnicode = true;
j = 2;
} else {
isUnicode = false;
j = 0;
}
while (j < fileSpec->getFileName()->getLength()) {
if (isUnicode) {
u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);
j += 2;
} else {
u = pdfDocEncoding[s1->getChar(j) & 0xff];
++j;
}
n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));
if (p + n >= path + sizeof(path))
break;
memcpy(p, uBuf, n);
p += n;
}
*p = '\0';
auto *embFile = fileSpec->getEmbeddedFile();
if (!embFile || !embFile->isOk()) {
exitCode = 3;
goto err2;
}
if (!embFile->save(path)) {
error(errIO, -1, "Error saving embedded file as '{0:s}'", p);
exitCode = 2;
goto err2;
}
}
// save an embedded file
} else {
if (saveNum < 1 || saveNum > nFiles) {
error(errCommandLine, -1, "Invalid file number");
goto err2;
}
fileSpec = static_cast<FileSpec *>(embeddedFiles->get(saveNum - 1));
if (savePath[0]) {
p = savePath;
} else {
p = path;
s1 = fileSpec->getFileName();
if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {
isUnicode = true;
j = 2;
} else {
isUnicode = false;
j = 0;
}
while (j < fileSpec->getFileName()->getLength()) {
if (isUnicode) {
u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);
j += 2;
} else {
u = pdfDocEncoding[s1->getChar(j) & 0xff];
++j;
}
n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));
if (p + n >= path + sizeof(path))
break;
memcpy(p, uBuf, n);
p += n;
}
*p = '\0';
p = path;
}
auto *embFile = fileSpec->getEmbeddedFile();
if (!embFile || !embFile->isOk()) {
exitCode = 3;
goto err2;
}
if (!embFile->save(p)) {
error(errIO, -1, "Error saving embedded file as '{0:s}'", p);
exitCode = 2;
goto err2;
}
}
exitCode = 0;
// clean up
err2:
if (embeddedFiles)
deleteGooList<FileSpec>(embeddedFiles);
uMap->decRefCnt();
delete doc;
err1:
delete globalParams;
err0:
return exitCode;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'pdfdetach: Check for valid file name of embedded file before using it to determine save path.
Closes #660'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: poppler_document_get_attachments (PopplerDocument *document)
{
Catalog *catalog;
int n_files, i;
GList *retval = nullptr;
g_return_val_if_fail (POPPLER_IS_DOCUMENT (document), NULL);
catalog = document->doc->getCatalog ();
if (catalog == nullptr || ! catalog->isOk ())
return nullptr;
n_files = catalog->numEmbeddedFiles ();
for (i = 0; i < n_files; i++)
{
PopplerAttachment *attachment;
FileSpec *emb_file;
emb_file = catalog->embeddedFile (i);
if (!emb_file->isOk () || !emb_file->getEmbeddedFile()->isOk()) {
delete emb_file;
continue;
}
attachment = _poppler_attachment_new (emb_file);
delete emb_file;
retval = g_list_prepend (retval, attachment);
}
return g_list_reverse (retval);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix crash on missing embedded file
Check whether an embedded file is actually present in the PDF
and show warning in that case.
https://bugs.freedesktop.org/show_bug.cgi?id=106137
https://gitlab.freedesktop.org/poppler/poppler/issues/236'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: vrrp_tfile_end_handler(void)
{
vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);
struct stat statb;
FILE *tf;
int ret;
if (!tfile->file_path) {
report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname);
free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);
return;
}
if (track_file_init == TRACK_FILE_NO_INIT)
return;
ret = stat(tfile->file_path, &statb);
if (!ret) {
if (track_file_init == TRACK_FILE_CREATE) {
/* The file exists */
return;
}
if ((statb.st_mode & S_IFMT) != S_IFREG) {
/* It is not a regular file */
report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname);
return;
}
/* Don't overwrite a file on reload */
if (reload)
return;
}
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
/* Write the value to the file */
if ((tf = fopen(tfile->file_path, "w"))) {
fprintf(tf, "%d\n", track_file_init_value);
fclose(tf);
}
else
report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: dump_keywords(vector_t *keydump, int level, FILE *fp)
{
unsigned int i;
keyword_t *keyword_vec;
char file_name[21];
if (!level) {
snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid());
fp = fopen(file_name, "w");
if (!fp)
return;
}
for (i = 0; i < vector_size(keydump); i++) {
keyword_vec = vector_slot(keydump, i);
fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled");
if (keyword_vec->sub)
dump_keywords(keyword_vec->sub, level + 1, fp);
}
if (!level)
fclose(fp);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: vrrp_print_json(void)
{
FILE *file;
element e;
struct json_object *array;
if (LIST_ISEMPTY(vrrp_data->vrrp))
return;
file = fopen ("/tmp/keepalived.json","w");
if (!file) {
log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)",
errno, strerror(errno));
return;
}
array = json_object_new_array();
for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {
struct json_object *instance_json, *json_stats, *json_data,
*vips, *evips, *track_ifp, *track_script;
#ifdef _HAVE_FIB_ROUTING_
struct json_object *vroutes, *vrules;
#endif
element f;
vrrp_t *vrrp = ELEMENT_DATA(e);
instance_json = json_object_new_object();
json_stats = json_object_new_object();
json_data = json_object_new_object();
vips = json_object_new_array();
evips = json_object_new_array();
track_ifp = json_object_new_array();
track_script = json_object_new_array();
#ifdef _HAVE_FIB_ROUTING_
vroutes = json_object_new_array();
vrules = json_object_new_array();
#endif
// Dump data to json
json_object_object_add(json_data, "iname",
json_object_new_string(vrrp->iname));
json_object_object_add(json_data, "dont_track_primary",
json_object_new_int(vrrp->dont_track_primary));
json_object_object_add(json_data, "skip_check_adv_addr",
json_object_new_int(vrrp->skip_check_adv_addr));
json_object_object_add(json_data, "strict_mode",
json_object_new_int((int)vrrp->strict_mode));
#ifdef _HAVE_VRRP_VMAC_
json_object_object_add(json_data, "vmac_ifname",
json_object_new_string(vrrp->vmac_ifname));
#endif
// Tracked interfaces are stored in a list
if (!LIST_ISEMPTY(vrrp->track_ifp)) {
for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) {
interface_t *ifp = ELEMENT_DATA(f);
json_object_array_add(track_ifp,
json_object_new_string(ifp->ifname));
}
}
json_object_object_add(json_data, "track_ifp", track_ifp);
// Tracked scripts also
if (!LIST_ISEMPTY(vrrp->track_script)) {
for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) {
tracked_sc_t *tsc = ELEMENT_DATA(f);
vrrp_script_t *vscript = tsc->scr;
json_object_array_add(track_script,
json_object_new_string(cmd_str(&vscript->script)));
}
}
json_object_object_add(json_data, "track_script", track_script);
json_object_object_add(json_data, "ifp_ifname",
json_object_new_string(vrrp->ifp->ifname));
json_object_object_add(json_data, "master_priority",
json_object_new_int(vrrp->master_priority));
json_object_object_add(json_data, "last_transition",
json_object_new_double(timeval_to_double(&vrrp->last_transition)));
json_object_object_add(json_data, "garp_delay",
json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "garp_refresh",
json_object_new_int((int)vrrp->garp_refresh.tv_sec));
json_object_object_add(json_data, "garp_rep",
json_object_new_int((int)vrrp->garp_rep));
json_object_object_add(json_data, "garp_refresh_rep",
json_object_new_int((int)vrrp->garp_refresh_rep));
json_object_object_add(json_data, "garp_lower_prio_delay",
json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ)));
json_object_object_add(json_data, "garp_lower_prio_rep",
json_object_new_int((int)vrrp->garp_lower_prio_rep));
json_object_object_add(json_data, "lower_prio_no_advert",
json_object_new_int((int)vrrp->lower_prio_no_advert));
json_object_object_add(json_data, "higher_prio_send_advert",
json_object_new_int((int)vrrp->higher_prio_send_advert));
json_object_object_add(json_data, "vrid",
json_object_new_int(vrrp->vrid));
json_object_object_add(json_data, "base_priority",
json_object_new_int(vrrp->base_priority));
json_object_object_add(json_data, "effective_priority",
json_object_new_int(vrrp->effective_priority));
json_object_object_add(json_data, "vipset",
json_object_new_boolean(vrrp->vipset));
//Virtual IPs are stored in a list
if (!LIST_ISEMPTY(vrrp->vip)) {
for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) {
ip_address_t *vip = ELEMENT_DATA(f);
char ipaddr[INET6_ADDRSTRLEN];
inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr),
ipaddr, INET6_ADDRSTRLEN);
json_object_array_add(vips,
json_object_new_string(ipaddr));
}
}
json_object_object_add(json_data, "vips", vips);
//External VIPs are also stored in a list
if (!LIST_ISEMPTY(vrrp->evip)) {
for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) {
ip_address_t *evip = ELEMENT_DATA(f);
char ipaddr[INET6_ADDRSTRLEN];
inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr),
ipaddr, INET6_ADDRSTRLEN);
json_object_array_add(evips,
json_object_new_string(ipaddr));
}
}
json_object_object_add(json_data, "evips", evips);
json_object_object_add(json_data, "promote_secondaries",
json_object_new_boolean(vrrp->promote_secondaries));
#ifdef _HAVE_FIB_ROUTING_
// Dump vroutes
if (!LIST_ISEMPTY(vrrp->vroutes)) {
for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) {
ip_route_t *route = ELEMENT_DATA(f);
char *buf = MALLOC(ROUTE_BUF_SIZE);
format_iproute(route, buf, ROUTE_BUF_SIZE);
json_object_array_add(vroutes,
json_object_new_string(buf));
}
}
json_object_object_add(json_data, "vroutes", vroutes);
// Dump vrules
if (!LIST_ISEMPTY(vrrp->vrules)) {
for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) {
ip_rule_t *rule = ELEMENT_DATA(f);
char *buf = MALLOC(RULE_BUF_SIZE);
format_iprule(rule, buf, RULE_BUF_SIZE);
json_object_array_add(vrules,
json_object_new_string(buf));
}
}
json_object_object_add(json_data, "vrules", vrules);
#endif
json_object_object_add(json_data, "adver_int",
json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "master_adver_int",
json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "accept",
json_object_new_int((int)vrrp->accept));
json_object_object_add(json_data, "nopreempt",
json_object_new_boolean(vrrp->nopreempt));
json_object_object_add(json_data, "preempt_delay",
json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ)));
json_object_object_add(json_data, "state",
json_object_new_int(vrrp->state));
json_object_object_add(json_data, "wantstate",
json_object_new_int(vrrp->wantstate));
json_object_object_add(json_data, "version",
json_object_new_int(vrrp->version));
if (vrrp->script_backup)
json_object_object_add(json_data, "script_backup",
json_object_new_string(cmd_str(vrrp->script_backup)));
if (vrrp->script_master)
json_object_object_add(json_data, "script_master",
json_object_new_string(cmd_str(vrrp->script_master)));
if (vrrp->script_fault)
json_object_object_add(json_data, "script_fault",
json_object_new_string(cmd_str(vrrp->script_fault)));
if (vrrp->script_stop)
json_object_object_add(json_data, "script_stop",
json_object_new_string(cmd_str(vrrp->script_stop)));
if (vrrp->script)
json_object_object_add(json_data, "script",
json_object_new_string(cmd_str(vrrp->script)));
if (vrrp->script_master_rx_lower_pri)
json_object_object_add(json_data, "script_master_rx_lower_pri",
json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri)));
json_object_object_add(json_data, "smtp_alert",
json_object_new_boolean(vrrp->smtp_alert));
#ifdef _WITH_VRRP_AUTH_
if (vrrp->auth_type) {
json_object_object_add(json_data, "auth_type",
json_object_new_int(vrrp->auth_type));
if (vrrp->auth_type != VRRP_AUTH_AH) {
char auth_data[sizeof(vrrp->auth_data) + 1];
memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data));
auth_data[sizeof(vrrp->auth_data)] = '\0';
json_object_object_add(json_data, "auth_data",
json_object_new_string(auth_data));
}
}
else
json_object_object_add(json_data, "auth_type",
json_object_new_int(0));
#endif
// Dump stats to json
json_object_object_add(json_stats, "advert_rcvd",
json_object_new_int64((int64_t)vrrp->stats->advert_rcvd));
json_object_object_add(json_stats, "advert_sent",
json_object_new_int64(vrrp->stats->advert_sent));
json_object_object_add(json_stats, "become_master",
json_object_new_int64(vrrp->stats->become_master));
json_object_object_add(json_stats, "release_master",
json_object_new_int64(vrrp->stats->release_master));
json_object_object_add(json_stats, "packet_len_err",
json_object_new_int64((int64_t)vrrp->stats->packet_len_err));
json_object_object_add(json_stats, "advert_interval_err",
json_object_new_int64((int64_t)vrrp->stats->advert_interval_err));
json_object_object_add(json_stats, "ip_ttl_err",
json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err));
json_object_object_add(json_stats, "invalid_type_rcvd",
json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd));
json_object_object_add(json_stats, "addr_list_err",
json_object_new_int64((int64_t)vrrp->stats->addr_list_err));
json_object_object_add(json_stats, "invalid_authtype",
json_object_new_int64(vrrp->stats->invalid_authtype));
#ifdef _WITH_VRRP_AUTH_
json_object_object_add(json_stats, "authtype_mismatch",
json_object_new_int64(vrrp->stats->authtype_mismatch));
json_object_object_add(json_stats, "auth_failure",
json_object_new_int64(vrrp->stats->auth_failure));
#endif
json_object_object_add(json_stats, "pri_zero_rcvd",
json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd));
json_object_object_add(json_stats, "pri_zero_sent",
json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent));
// Add both json_data and json_stats to main instance_json
json_object_object_add(instance_json, "data", json_data);
json_object_object_add(instance_json, "stats", json_stats);
// Add instance_json to main array
json_object_array_add(array, instance_json);
}
fprintf(file, "%s", json_object_to_json_string(array));
fclose(file);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: vrrp_print_data(void)
{
FILE *file = fopen (dump_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
dump_file, errno, strerror(errno));
return;
}
dump_data_vrrp(file);
fclose(file);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: dump_threads(void)
{
FILE *fp;
char time_buf[26];
element e;
vrrp_t *vrrp;
char *file_name;
file_name = make_file_name("/tmp/thread_dump.dat",
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
fp = fopen(file_name, "a");
FREE(file_name);
set_time_now();
ctime_r(&time_now.tv_sec, time_buf);
fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec);
dump_thread_data(master, fp);
fprintf(fp, "alloc = %lu\n", master->alloc);
fprintf(fp, "\n");
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
ctime_r(&vrrp->sands.tv_sec, time_buf);
fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec,
vrrp->state == VRRP_STATE_INIT ? "INIT" :
vrrp->state == VRRP_STATE_BACK ? "BACKUP" :
vrrp->state == VRRP_STATE_MAST ? "MASTER" :
vrrp->state == VRRP_STATE_FAULT ? "FAULT" :
vrrp->state == VRRP_STATE_STOP ? "STOP" :
vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown");
}
fclose(fp);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: vrrp_print_stats(void)
{
FILE *file;
file = fopen (stats_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
stats_file, errno, strerror(errno));
return;
}
list l = vrrp_data->vrrp;
element e;
vrrp_t *vrrp;
for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) {
vrrp = ELEMENT_DATA(e);
fprintf(file, "VRRP Instance: %s\n", vrrp->iname);
fprintf(file, " Advertisements:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd);
fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent);
fprintf(file, " Became master: %d\n", vrrp->stats->become_master);
fprintf(file, " Released master: %d\n",
vrrp->stats->release_master);
fprintf(file, " Packet Errors:\n");
fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err);
fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err);
fprintf(file, " Invalid Type: %" PRIu64 "\n",
vrrp->stats->invalid_type_rcvd);
fprintf(file, " Advertisement Interval: %" PRIu64 "\n",
vrrp->stats->advert_interval_err);
fprintf(file, " Address List: %" PRIu64 "\n",
vrrp->stats->addr_list_err);
fprintf(file, " Authentication Errors:\n");
fprintf(file, " Invalid Type: %d\n",
vrrp->stats->invalid_authtype);
#ifdef _WITH_VRRP_AUTH_
fprintf(file, " Type Mismatch: %d\n",
vrrp->stats->authtype_mismatch);
fprintf(file, " Failure: %d\n",
vrrp->stats->auth_failure);
#endif
fprintf(file, " Priority Zero:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd);
fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent);
}
fclose(file);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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: smtp_log_to_file(smtp_t *smtp)
{
FILE *fp = fopen("/tmp/smtp-alert.log", "a");
time_t now;
struct tm tm;
char time_buf[25];
int time_buf_len;
time(&now);
localtime_r(&now, &tm);
time_buf_len = strftime(time_buf, sizeof time_buf, "%a %b %e %X %Y", &tm);
fprintf(fp, "%s: %s -> %s\n"
"%*sSubject: %s\n"
"%*sBody: %s\n\n",
time_buf, global_data->email_from, smtp->email_to,
time_buf_len - 7, "", smtp->subject,
time_buf_len - 7, "", smtp->body);
fclose(fp);
free_smtp_all(smtp);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[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_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fix compile warning introduced in commit c6247a9
Commit c6247a9 - "Add command line and configuration option to set umask"
introduced a compile warning, although the code would have worked OK.
Signed-off-by: Quentin Armitage <[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: parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndDRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[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: usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[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: mem_log_init(const char* prog_name, const char *banner)
{
size_t log_name_len;
char *log_name;
if (__test_bit(LOG_CONSOLE_BIT, &debug)) {
log_op = stderr;
return;
}
if (log_op)
fclose(log_op);
log_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1; /* "/tmp/" + prog_name + "_mem." + PID + ".log" + '\0" */
log_name = malloc(log_name_len);
if (!log_name) {
log_message(LOG_INFO, "Unable to malloc log file name");
log_op = stderr;
return;
}
snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid());
log_op = fopen_safe(log_name, "a");
if (log_op == NULL) {
log_message(LOG_INFO, "Unable to open %s for appending", log_name);
log_op = stderr;
}
else {
int fd = fileno(log_op);
/* We don't want any children to inherit the log file */
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
/* Make the log output line buffered. This was to ensure that
* children didn't inherit the buffer, but the CLOEXEC above
* should resolve that. */
setlinebuf(log_op);
fprintf(log_op, "\n");
}
free(log_name);
terminate_banner = banner;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'When opening files for write, ensure files can only be read by root
Issue #1048 referred to CVE-2018-19046 regarding files used for
debugging purposes could potentially be read by non root users.
This commit ensures that such log files cannot be opened by non root
users.
Signed-off-by: Quentin Armitage <[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: start_check_child(void)
{
#ifndef _DEBUG_
pid_t pid;
char *syslog_ident;
/* Initialize child process */
if (log_file_name)
flush_log_file();
pid = fork();
if (pid < 0) {
log_message(LOG_INFO, "Healthcheck child process: fork error(%s)"
, strerror(errno));
return -1;
} else if (pid) {
checkers_child = pid;
log_message(LOG_INFO, "Starting Healthcheck child process, pid=%d"
, pid);
/* Start respawning thread */
thread_add_child(master, check_respawn_thread, NULL,
pid, TIMER_NEVER);
return 0;
}
prctl(PR_SET_PDEATHSIG, SIGTERM);
prog_type = PROG_TYPE_CHECKER;
initialise_debug_options();
#ifdef _WITH_BFD_
/* Close the write end of the BFD checker event notification pipe */
close(bfd_checker_event_pipe[1]);
#ifdef _WITH_VRRP_
close(bfd_vrrp_event_pipe[0]);
close(bfd_vrrp_event_pipe[1]);
#endif
#endif
if ((global_data->instance_name
#if HAVE_DECL_CLONE_NEWNET
|| global_data->network_namespace
#endif
) &&
(check_syslog_ident = make_syslog_ident(PROG_CHECK)))
syslog_ident = check_syslog_ident;
else
syslog_ident = PROG_CHECK;
/* Opening local CHECK syslog channel */
if (!__test_bit(NO_SYSLOG_BIT, &debug))
openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0)
, (log_facility==LOG_DAEMON) ? LOG_LOCAL2 : log_facility);
if (log_file_name)
open_log_file(log_file_name,
"check",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
#ifdef _MEM_CHECK_
mem_log_init(PROG_CHECK, "Healthcheck child process");
#endif
free_parent_mallocs_startup(true);
/* Clear any child finder functions set in parent */
set_child_finder_name(NULL);
/* Child process part, write pidfile */
if (!pidfile_write(checkers_pidfile, getpid())) {
log_message(LOG_INFO, "Healthcheck child process: cannot write pidfile");
exit(KEEPALIVED_EXIT_FATAL);
}
/* Create the new master thread */
thread_destroy_master(master); /* This destroys any residual settings from the parent */
master = thread_make_master();
#endif
/* If last process died during a reload, we can get there and we
* don't want to loop again, because we're not reloading anymore.
*/
UNSET_RELOAD;
#ifndef _DEBUG_
/* Signal handling initialization */
check_signal_init();
#endif
/* Start Healthcheck daemon */
start_check(NULL, NULL);
#ifdef _DEBUG_
return 0;
#endif
#ifdef THREAD_DUMP
register_check_thread_addresses();
#endif
/* Launch the scheduling I/O multiplexer */
launch_thread_scheduler(master);
/* Finish healthchecker daemon process */
if (two_phase_terminate)
checker_terminate_phase2();
else
stop_check(KEEPALIVED_EXIT_OK);
#ifdef THREAD_DUMP
deregister_thread_addresses();
#endif
/* unreachable */
exit(KEEPALIVED_EXIT_OK);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: keepalived_main(int argc, char **argv)
{
bool report_stopped = true;
struct utsname uname_buf;
char *end;
int exit_code = KEEPALIVED_EXIT_OK;
/* Ensure time_now is set. We then don't have to check anywhere
* else if it is set. */
set_time_now();
/* Save command line options in case need to log them later */
save_cmd_line_options(argc, argv);
/* Init debugging level */
debug = 0;
/* We are the parent process */
#ifndef _DEBUG_
prog_type = PROG_TYPE_PARENT;
#endif
/* Initialise daemon_mode */
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
/* Set default file creation mask */
umask(022);
/* Open log with default settings so we can log initially */
openlog(PACKAGE_NAME, LOG_PID, log_facility);
#ifdef _MEM_CHECK_
mem_log_init(PACKAGE_NAME, "Parent process");
#endif
/* Some functionality depends on kernel version, so get the version here */
if (uname(&uname_buf))
log_message(LOG_INFO, "Unable to get uname() information - error %d", errno);
else {
os_major = (unsigned)strtoul(uname_buf.release, &end, 10);
if (*end != '.')
os_major = 0;
else {
os_minor = (unsigned)strtoul(end + 1, &end, 10);
if (*end != '.')
os_major = 0;
else {
if (!isdigit(end[1]))
os_major = 0;
else
os_release = (unsigned)strtoul(end + 1, &end, 10);
}
}
if (!os_major)
log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release);
/* config_id defaults to hostname */
if (!config_id) {
end = strchrnul(uname_buf.nodename, '.');
config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1);
strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename));
config_id[end - uname_buf.nodename] = '\0';
}
}
/*
* Parse command line and set debug level.
* bits 0..7 reserved by main.c
*/
if (parse_cmdline(argc, argv)) {
closelog();
if (!__test_bit(NO_SYSLOG_BIT, &debug))
openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility);
}
if (__test_bit(LOG_CONSOLE_BIT, &debug))
enable_console_log();
#ifdef GIT_COMMIT
log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT);
#else
log_message(LOG_INFO, "Starting %s", version_string);
#endif
/* Handle any core file requirements */
core_dump_init();
if (os_major) {
if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) {
/* keepalived was build for a later kernel version */
log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff,
uname_buf.sysname, uname_buf.release, uname_buf.version);
} else {
/* keepalived was build for a later kernel version */
log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)",
uname_buf.sysname, uname_buf.release, uname_buf.version,
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
}
}
#ifndef _DEBUG_
log_command_line(0);
#endif
/* Check we can read the configuration file(s).
NOTE: the working directory will be / if we
forked, but will be the current working directory
when keepalived was run if we haven't forked.
This means that if any config file names are not
absolute file names, the behaviour will be different
depending on whether we forked or not. */
if (!check_conf_file(conf_file)) {
if (__test_bit(CONFIG_TEST_BIT, &debug))
config_test_exit();
exit_code = KEEPALIVED_EXIT_NO_CONFIG;
goto end;
}
global_data = alloc_global_data();
global_data->umask = umask_val;
read_config_file();
init_global_data(global_data, NULL);
#if HAVE_DECL_CLONE_NEWNET
if (override_namespace) {
if (global_data->network_namespace) {
log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace);
FREE(global_data->network_namespace);
}
global_data->network_namespace = override_namespace;
override_namespace = NULL;
}
#endif
if (!__test_bit(CONFIG_TEST_BIT, &debug) &&
(global_data->instance_name
#if HAVE_DECL_CLONE_NEWNET
|| global_data->network_namespace
#endif
)) {
if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) {
log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident);
closelog();
openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility);
}
else
log_message(LOG_INFO, "Unable to change syslog ident");
use_pid_dir = true;
open_log_file(log_file_name,
NULL,
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
}
/* Initialise pointer to child finding function */
set_child_finder_name(find_keepalived_child_name);
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
if (use_pid_dir) {
/* Create the directory for pid files */
create_pid_dir();
}
}
#if HAVE_DECL_CLONE_NEWNET
if (global_data->network_namespace) {
if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) {
log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace);
goto end;
}
}
#endif
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
if (global_data->instance_name) {
if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION)))
free_main_pidfile = true;
#ifdef _WITH_LVS_
if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION)))
free_checkers_pidfile = true;
#endif
#ifdef _WITH_VRRP_
if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION)))
free_vrrp_pidfile = true;
#endif
#ifdef _WITH_BFD_
if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION)))
free_bfd_pidfile = true;
#endif
}
if (use_pid_dir) {
if (!main_pidfile)
main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION;
#ifdef _WITH_LVS_
if (!checkers_pidfile)
checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION;
#endif
#ifdef _WITH_VRRP_
if (!vrrp_pidfile)
vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION;
#endif
#ifdef _WITH_BFD_
if (!bfd_pidfile)
bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION;
#endif
}
else
{
if (!main_pidfile)
main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION;
#ifdef _WITH_LVS_
if (!checkers_pidfile)
checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION;
#endif
#ifdef _WITH_VRRP_
if (!vrrp_pidfile)
vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION;
#endif
#ifdef _WITH_BFD_
if (!bfd_pidfile)
bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION;
#endif
}
/* Check if keepalived is already running */
if (keepalived_running(daemon_mode)) {
log_message(LOG_INFO, "daemon is already running");
report_stopped = false;
goto end;
}
}
/* daemonize process */
if (!__test_bit(DONT_FORK_BIT, &debug) &&
xdaemon(false, false, true) > 0) {
closelog();
FREE_PTR(config_id);
FREE_PTR(orig_core_dump_pattern);
close_std_fd();
exit(0);
}
#ifdef _MEM_CHECK_
enable_mem_log_termination();
#endif
if (__test_bit(CONFIG_TEST_BIT, &debug)) {
validate_config();
config_test_exit();
}
/* write the father's pidfile */
if (!pidfile_write(main_pidfile, getpid()))
goto end;
/* Create the master thread */
master = thread_make_master();
/* Signal handling initialization */
signal_init();
/* Init daemon */
if (!start_keepalived())
log_message(LOG_INFO, "Warning - keepalived has no configuration to run");
initialise_debug_options();
#ifdef THREAD_DUMP
register_parent_thread_addresses();
#endif
/* Launch the scheduling I/O multiplexer */
launch_thread_scheduler(master);
/* Finish daemon process */
stop_keepalived();
#ifdef THREAD_DUMP
deregister_thread_addresses();
#endif
/*
* Reached when terminate signal catched.
* finally return from system
*/
end:
if (report_stopped) {
#ifdef GIT_COMMIT
log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT);
#else
log_message(LOG_INFO, "Stopped %s", version_string);
#endif
}
#if HAVE_DECL_CLONE_NEWNET
if (global_data && global_data->network_namespace)
clear_namespaces();
#endif
if (use_pid_dir)
remove_pid_dir();
/* Restore original core_pattern if necessary */
if (orig_core_dump_pattern)
update_core_dump_pattern(orig_core_dump_pattern);
free_parent_mallocs_startup(false);
free_parent_mallocs_exit();
free_global_data(global_data);
closelog();
#ifndef _MEM_CHECK_LOG_
FREE_PTR(syslog_ident);
#else
if (syslog_ident)
free(syslog_ident);
#endif
close_std_fd();
exit(exit_code);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: system_call_script(thread_master_t *m, int (*func) (thread_t *), void * arg, unsigned long timer, notify_script_t* script)
{
pid_t pid;
/* Daemonization to not degrade our scheduling timer */
if (log_file_name)
flush_log_file();
pid = local_fork();
if (pid < 0) {
/* fork error */
log_message(LOG_INFO, "Failed fork process");
return -1;
}
if (pid) {
/* parent process */
thread_add_child(m, func, arg, pid, timer);
return 0;
}
/* Child process */
#ifdef _MEM_CHECK_
skip_mem_dump();
#endif
system_call(script);
exit(0); /* Script errors aren't server errors */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: fork_exec(char **argv)
{
pid_t pid;
int status;
struct sigaction act, old_act;
int res = 0;
act.sa_handler = SIG_DFL;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, &old_act);
if (log_file_name)
flush_log_file();
pid = local_fork();
if (pid < 0)
res = -1;
else if (pid == 0) {
/* Child */
set_std_fd(false);
signal_handler_script();
execvp(*argv, argv);
exit(EXIT_FAILURE);
} else {
/* Parent */
while (waitpid(pid, &status, 0) != pid);
if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS)
res = -1;
}
sigaction(SIGCHLD, &old_act, NULL);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: vrrp_terminate_phase2(int exit_status)
{
struct rusage usage;
#ifdef _NETLINK_TIMERS_
if (do_netlink_timers)
report_and_clear_netlink_timers("Starting shutdown instances");
#endif
if (!__test_bit(DONT_RELEASE_VRRP_BIT, &debug))
shutdown_vrrp_instances();
#ifdef _NETLINK_TIMERS_
if (do_netlink_timers)
report_and_clear_netlink_timers("Completed shutdown instances");
#endif
#if defined _WITH_SNMP_RFC || defined _WITH_SNMP_VRRP_
if (
#ifdef _WITH_SNMP_RFC_
global_data->enable_snmp_vrrp ||
#endif
#ifdef _WITH_SNMP_RFCV2_
global_data->enable_snmp_rfcv2 ||
#endif
#ifdef _WITH_SNMP_RFCV3_
global_data->enable_snmp_rfcv3 ||
#endif
false)
vrrp_snmp_agent_close();
#endif
#ifdef _WITH_LVS_
if (vrrp_ipvs_needed()) {
/* Clean ipvs related */
ipvs_stop();
}
#endif
kernel_netlink_close_cmd();
thread_destroy_master(master);
master = NULL;
gratuitous_arp_close();
ndisc_close();
#ifdef _WITH_DBUS_
if (global_data->enable_dbus)
dbus_stop();
#endif
if (global_data->vrrp_notify_fifo.fd != -1)
notify_fifo_close(&global_data->notify_fifo, &global_data->vrrp_notify_fifo);
free_global_data(global_data);
free_vrrp_data(vrrp_data);
free_vrrp_buffer();
free_interface_queue();
free_parent_mallocs_exit();
/*
* Reached when terminate signal catched.
* finally return to parent process.
*/
if (__test_bit(LOG_DETAIL_BIT, &debug)) {
getrusage(RUSAGE_SELF, &usage);
log_message(LOG_INFO, "Stopped - used %ld.%6.6ld user time, %ld.%6.6ld system time", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
}
else
log_message(LOG_INFO, "Stopped");
if (log_file_name)
close_log_file();
closelog();
#ifndef _MEM_CHECK_LOG_
FREE_PTR(vrrp_syslog_ident);
#else
if (vrrp_syslog_ident)
free(vrrp_syslog_ident);
#endif
close_std_fd();
/* Stop daemon */
pidfile_rm(vrrp_pidfile);
exit(exit_status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: start_bfd_child(void)
{
#ifndef _DEBUG_
pid_t pid;
int ret;
char *syslog_ident;
/* Initialize child process */
if (log_file_name)
flush_log_file();
pid = fork();
if (pid < 0) {
log_message(LOG_INFO, "BFD child process: fork error(%m)");
return -1;
} else if (pid) {
bfd_child = pid;
log_message(LOG_INFO, "Starting BFD child process, pid=%d",
pid);
/* Start respawning thread */
thread_add_child(master, bfd_respawn_thread, NULL,
pid, TIMER_NEVER);
return 0;
}
prctl(PR_SET_PDEATHSIG, SIGTERM);
prog_type = PROG_TYPE_BFD;
/* Close the read end of the event notification pipes */
#ifdef _WITH_VRRP_
close(bfd_vrrp_event_pipe[0]);
#endif
#ifdef _WITH_LVS_
close(bfd_checker_event_pipe[0]);
#endif
initialise_debug_options();
if ((global_data->instance_name
#if HAVE_DECL_CLONE_NEWNET
|| global_data->network_namespace
#endif
) &&
(bfd_syslog_ident = make_syslog_ident(PROG_BFD)))
syslog_ident = bfd_syslog_ident;
else
syslog_ident = PROG_BFD;
/* Opening local BFD syslog channel */
if (!__test_bit(NO_SYSLOG_BIT, &debug))
openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0)
, (log_facility==LOG_DAEMON) ? LOG_LOCAL2 : log_facility);
if (log_file_name)
open_log_file(log_file_name,
"bfd",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
#ifdef _MEM_CHECK_
mem_log_init(PROG_BFD, "BFD child process");
#endif
free_parent_mallocs_startup(true);
/* Clear any child finder functions set in parent */
set_child_finder_name(NULL);
/* Child process part, write pidfile */
if (!pidfile_write(bfd_pidfile, getpid())) {
/* Fatal error */
log_message(LOG_INFO,
"BFD child process: cannot write pidfile");
exit(0);
}
/* Create the new master thread */
thread_destroy_master(master);
master = thread_make_master();
/* change to / dir */
ret = chdir("/");
if (ret < 0) {
log_message(LOG_INFO, "BFD child process: error chdir");
}
/* Set mask */
umask(0);
#endif
/* If last process died during a reload, we can get there and we
* don't want to loop again, because we're not reloading anymore.
*/
UNSET_RELOAD;
#ifndef _DEBUG_
/* Signal handling initialization */
bfd_signal_init();
#endif
/* Start BFD daemon */
start_bfd(NULL);
#ifdef _DEBUG_
return 0;
#else
#ifdef THREAD_DUMP
register_bfd_thread_addresses();
#endif
/* Launch the scheduling I/O multiplexer */
launch_thread_scheduler(master);
#ifdef THREAD_DUMP
deregister_thread_addresses();
#endif
/* Finish BFD daemon process */
stop_bfd(EXIT_SUCCESS);
/* unreachable */
exit(EXIT_SUCCESS);
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: start_vrrp_child(void)
{
#ifndef _DEBUG_
pid_t pid;
char *syslog_ident;
/* Initialize child process */
if (log_file_name)
flush_log_file();
pid = fork();
if (pid < 0) {
log_message(LOG_INFO, "VRRP child process: fork error(%s)"
, strerror(errno));
return -1;
} else if (pid) {
vrrp_child = pid;
log_message(LOG_INFO, "Starting VRRP child process, pid=%d"
, pid);
/* Start respawning thread */
thread_add_child(master, vrrp_respawn_thread, NULL,
pid, TIMER_NEVER);
return 0;
}
prctl(PR_SET_PDEATHSIG, SIGTERM);
#ifdef _WITH_PERF_
if (perf_run == PERF_ALL)
run_perf("vrrp", global_data->network_namespace, global_data->instance_name);
#endif
prog_type = PROG_TYPE_VRRP;
initialise_debug_options();
#ifdef _WITH_BFD_
/* Close the write end of the BFD vrrp event notification pipe */
close(bfd_vrrp_event_pipe[1]);
#ifdef _WITH_LVS_
close(bfd_checker_event_pipe[0]);
close(bfd_checker_event_pipe[1]);
#endif
#endif
/* Opening local VRRP syslog channel */
if ((global_data->instance_name
#if HAVE_DECL_CLONE_NEWNET
|| global_data->network_namespace
#endif
) &&
(vrrp_syslog_ident = make_syslog_ident(PROG_VRRP)))
syslog_ident = vrrp_syslog_ident;
else
syslog_ident = PROG_VRRP;
if (!__test_bit(NO_SYSLOG_BIT, &debug))
openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0)
, (log_facility==LOG_DAEMON) ? LOG_LOCAL1 : log_facility);
if (log_file_name)
open_log_file(log_file_name,
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
#ifdef _MEM_CHECK_
mem_log_init(PROG_VRRP, "VRRP Child process");
#endif
free_parent_mallocs_startup(true);
/* Clear any child finder functions set in parent */
set_child_finder_name(NULL);
/* Child process part, write pidfile */
if (!pidfile_write(vrrp_pidfile, getpid())) {
/* Fatal error */
log_message(LOG_INFO, "VRRP child process: cannot write pidfile");
exit(0);
}
#ifdef _VRRP_FD_DEBUG_
if (do_vrrp_fd_debug)
set_extra_threads_debug(dump_vrrp_fd);
#endif
/* Create the new master thread */
thread_destroy_master(master); /* This destroys any residual settings from the parent */
master = thread_make_master();
#endif
/* If last process died during a reload, we can get there and we
* don't want to loop again, because we're not reloading anymore.
*/
UNSET_RELOAD;
#ifndef _DEBUG_
/* Signal handling initialization */
vrrp_signal_init();
#endif
/* Start VRRP daemon */
start_vrrp(NULL);
#ifdef _DEBUG_
return 0;
#endif
#ifdef THREAD_DUMP
register_vrrp_thread_addresses();
#endif
#ifdef _WITH_PERF_
if (perf_run == PERF_RUN)
run_perf("vrrp", global_data->network_namespace, global_data->instance_name);
#endif
/* Launch the scheduling I/O multiplexer */
launch_thread_scheduler(master);
#ifdef THREAD_DUMP
deregister_thread_addresses();
#endif
/* Finish VRRP daemon process */
vrrp_terminate_phase2(EXIT_SUCCESS);
/* unreachable */
exit(EXIT_SUCCESS);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default
If a non privileged user creates /tmp/keepalived.log and has it open
for read (e.g. tail -f), then even though keepalived will change the
owner to root and remove all read/write permissions from non owners,
the application which already has the file open will be able to read
the added log entries.
Accordingly, opening a file in append mode is disabled by default, and
only enabled if --enable-smtp-alert-debug or --enable-log-file (which
are debugging options and unset by default) are enabled.
This should further alleviate security concerns related to CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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: FILE *fopen_safe(const char *path, const char *mode)
{
int fd;
FILE *file;
int flags = O_NOFOLLOW | O_CREAT;
int sav_errno;
if (mode[0] == 'r')
return fopen(path, mode);
if ((mode[0] != 'a' && mode[0] != 'w') ||
(mode[1] &&
(mode[1] != '+' || mode[2]))) {
errno = EINVAL;
return NULL;
}
if (mode[0] == 'w')
flags |= O_TRUNC;
else
flags |= O_APPEND;
if (mode[1])
flags |= O_RDWR;
else
flags |= O_WRONLY;
if (mode[0] == 'w') {
/* Ensure that any existing file isn't currently opened for read by a non-privileged user.
* We do this by unlinking the file, so that the open() below will create a new file. */
if (unlink(path) && errno != ENOENT) {
log_message(LOG_INFO, "Failed to remove existing file '%s' prior to write", path);
return NULL;
}
}
else {
/* Only allow append mode if debugging features requiring append are enabled. Since we
* can't unlink the file, there may be a non privileged user who already has the file open
* for read (e.g. tail -f). If these debug option aren't enabled, there is no potential
* security risk. */
#ifndef ENABLE_LOG_FILE_APPEND
log_message(LOG_INFO, "BUG - shouldn't be opening file for append with current build options");
errno = EINVAL;
return NULL;
#endif
}
fd = open(path, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd == -1)
return NULL;
/* Change file ownership to root */
if (fchown(fd, 0, 0)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file ownership of %s- errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
/* Set file mode to rw------- */
if (fchmod(fd, S_IRUSR | S_IWUSR)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file permission of %s - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
file = fdopen (fd, "w");
if (!file) {
sav_errno = errno;
log_message(LOG_INFO, "fdopen(\"%s\") failed - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
return file;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Make sure a non privileged user cannot read keepalived file output
Ensure that when a file such as /tmp/keepalived.data is wriiten,
no non privileged can have a previous version of that file already
open, thereby allowing them to read the data.
This should fully resolve CVE-2018-19046.
Signed-off-by: Quentin Armitage <[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 URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team'</s> |
<s>[INST] Given the following code containing errors, provide 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 URI_FUNC(ResetUri)(URI_TYPE(Uri) * uri) {
memset(uri, 0, sizeof(URI_TYPE(Uri)));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'ResetUri: Protect against NULL'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: wav_read_header (SF_PRIVATE *psf, int *blockalign, int *framesperblock)
{ WAVLIKE_PRIVATE *wpriv ;
WAV_FMT *wav_fmt ;
FACT_CHUNK fact_chunk ;
uint32_t marker, chunk_size = 0, RIFFsize = 0, done = 0 ;
int parsestage = 0, error, format = 0 ;
if (psf->is_pipe == 0 && psf->filelength > SF_PLATFORM_S64 (0xffffffff))
psf_log_printf (psf, "Warning : filelength > 0xffffffff. This is bad!!!!\n") ;
if ((wpriv = psf->container_data) == NULL)
return SFE_INTERNAL ;
wav_fmt = &wpriv->wav_fmt ;
/* Set position to start of file to begin reading header. */
psf_binheader_readf (psf, "pmj", 0, &marker, -4) ;
psf->header.indx = 0 ;
/* RIFX signifies big-endian format for all header and data to prevent
** lots of code copying here, we'll set the psf->rwf_endian flag once here,
** and never specify endian-ness for all other header ops/
*/
psf->rwf_endian = (marker == RIFF_MARKER) ? SF_ENDIAN_LITTLE : SF_ENDIAN_BIG ;
while (! done)
{ size_t jump = chunk_size & 1 ;
marker = chunk_size = 0 ;
psf_binheader_readf (psf, "jm4", jump, &marker, &chunk_size) ;
if (marker == 0)
{ sf_count_t pos = psf_ftell (psf) ;
psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
break ;
} ;
psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
switch (marker)
{ case RIFF_MARKER :
case RIFX_MARKER :
if (parsestage)
return SFE_WAV_NO_RIFF ;
parsestage |= HAVE_RIFF ;
RIFFsize = chunk_size ;
if (psf->fileoffset > 0 && psf->filelength > RIFFsize + 8)
{ /* Set file length. */
psf->filelength = RIFFsize + 8 ;
if (marker == RIFF_MARKER)
psf_log_printf (psf, "RIFF : %u\n", RIFFsize) ;
else
psf_log_printf (psf, "RIFX : %u\n", RIFFsize) ;
}
else if (psf->filelength < RIFFsize + 2 * SIGNED_SIZEOF (marker))
{ if (marker == RIFF_MARKER)
psf_log_printf (psf, "RIFF : %u (should be %D)\n", RIFFsize, psf->filelength - 2 * SIGNED_SIZEOF (marker)) ;
else
psf_log_printf (psf, "RIFX : %u (should be %D)\n", RIFFsize, psf->filelength - 2 * SIGNED_SIZEOF (marker)) ;
RIFFsize = psf->filelength - 2 * SIGNED_SIZEOF (RIFFsize) ;
}
else
{ if (marker == RIFF_MARKER)
psf_log_printf (psf, "RIFF : %u\n", RIFFsize) ;
else
psf_log_printf (psf, "RIFX : %u\n", RIFFsize) ;
} ;
psf_binheader_readf (psf, "m", &marker) ;
if (marker != WAVE_MARKER)
return SFE_WAV_NO_WAVE ;
parsestage |= HAVE_WAVE ;
psf_log_printf (psf, "WAVE\n") ;
chunk_size = 0 ;
break ;
case fmt_MARKER :
if ((parsestage & (HAVE_RIFF | HAVE_WAVE)) != (HAVE_RIFF | HAVE_WAVE))
return SFE_WAV_NO_FMT ;
/* If this file has a SECOND fmt chunk, I don't want to know about it. */
if (parsestage & HAVE_fmt)
break ;
parsestage |= HAVE_fmt ;
psf_log_printf (psf, "fmt : %d\n", chunk_size) ;
if ((error = wavlike_read_fmt_chunk (psf, chunk_size)))
return error ;
format = wav_fmt->format ;
break ;
case data_MARKER :
if ((parsestage & (HAVE_RIFF | HAVE_WAVE | HAVE_fmt)) != (HAVE_RIFF | HAVE_WAVE | HAVE_fmt))
return SFE_WAV_NO_DATA ;
if (psf->file.mode == SFM_RDWR && (parsestage & HAVE_other) != 0)
return SFE_RDWR_BAD_HEADER ;
parsestage |= HAVE_data ;
psf->datalength = chunk_size ;
if (psf->datalength & 1)
psf_log_printf (psf, "*** 'data' chunk should be an even number of bytes in length.\n") ;
psf->dataoffset = psf_ftell (psf) ;
if (psf->dataoffset > 0)
{ if (chunk_size == 0 && RIFFsize == 8 && psf->filelength > 44)
{ psf_log_printf (psf, "*** Looks like a WAV file which wasn't closed properly. Fixing it.\n") ;
psf->datalength = psf->filelength - psf->dataoffset ;
} ;
if (psf->datalength > psf->filelength - psf->dataoffset)
{ psf_log_printf (psf, "data : %D (should be %D)\n", psf->datalength, psf->filelength - psf->dataoffset) ;
psf->datalength = psf->filelength - psf->dataoffset ;
}
else
psf_log_printf (psf, "data : %D\n", psf->datalength) ;
/* Only set dataend if there really is data at the end. */
if (psf->datalength + psf->dataoffset < psf->filelength)
psf->dataend = psf->datalength + psf->dataoffset ;
psf->datalength += chunk_size & 1 ;
chunk_size = 0 ;
} ;
if (! psf->sf.seekable || psf->dataoffset < 0)
break ;
/* Seek past data and continue reading header. */
psf_fseek (psf, psf->datalength, SEEK_CUR) ;
if (psf_ftell (psf) != psf->datalength + psf->dataoffset)
psf_log_printf (psf, "*** psf_fseek past end error ***\n") ;
break ;
case fact_MARKER :
if ((parsestage & (HAVE_RIFF | HAVE_WAVE)) != (HAVE_RIFF | HAVE_WAVE))
return SFE_WAV_BAD_FACT ;
parsestage |= HAVE_fact ;
if ((parsestage & HAVE_fmt) != HAVE_fmt)
psf_log_printf (psf, "*** Should have 'fmt ' chunk before 'fact'\n") ;
psf_binheader_readf (psf, "4", & (fact_chunk.frames)) ;
if (chunk_size > SIGNED_SIZEOF (fact_chunk))
psf_binheader_readf (psf, "j", (int) (chunk_size - SIGNED_SIZEOF (fact_chunk))) ;
if (chunk_size)
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
else
psf_log_printf (psf, "%M : %u (should not be zero)\n", marker, chunk_size) ;
psf_log_printf (psf, " frames : %d\n", fact_chunk.frames) ;
break ;
case PEAK_MARKER :
if ((parsestage & (HAVE_RIFF | HAVE_WAVE | HAVE_fmt)) != (HAVE_RIFF | HAVE_WAVE | HAVE_fmt))
return SFE_WAV_PEAK_B4_FMT ;
parsestage |= HAVE_PEAK ;
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
if ((error = wavlike_read_peak_chunk (psf, chunk_size)) != 0)
return error ;
psf->peak_info->peak_loc = ((parsestage & HAVE_data) == 0) ? SF_PEAK_START : SF_PEAK_END ;
break ;
case cue_MARKER :
parsestage |= HAVE_other ;
{ uint32_t thisread, bytesread, cue_count, position, offset ;
int id, chunk_id, chunk_start, block_start, cue_index ;
bytesread = psf_binheader_readf (psf, "4", &cue_count) ;
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
if (cue_count > 1000)
{ psf_log_printf (psf, " Count : %u (skipping)\n", cue_count) ;
psf_binheader_readf (psf, "j", (cue_count > 20 ? 20 : cue_count) * 24) ;
break ;
} ;
psf_log_printf (psf, " Count : %d\n", cue_count) ;
if ((psf->cues = psf_cues_alloc (cue_count)) == NULL)
return SFE_MALLOC_FAILED ;
cue_index = 0 ;
while (cue_count)
{
if ((thisread = psf_binheader_readf (psf, "e44m444", &id, &position, &chunk_id, &chunk_start, &block_start, &offset)) == 0)
break ;
bytesread += thisread ;
psf_log_printf (psf, " Cue ID : %2d"
" Pos : %5u Chunk : %M"
" Chk Start : %d Blk Start : %d"
" Offset : %5d\n",
id, position, chunk_id, chunk_start, block_start, offset) ;
psf->cues->cue_points [cue_index].indx = id ;
psf->cues->cue_points [cue_index].position = position ;
psf->cues->cue_points [cue_index].fcc_chunk = chunk_id ;
psf->cues->cue_points [cue_index].chunk_start = chunk_start ;
psf->cues->cue_points [cue_index].block_start = block_start ;
psf->cues->cue_points [cue_index].sample_offset = offset ;
psf->cues->cue_points [cue_index].name [0] = '\0' ;
cue_count -- ;
cue_index ++ ;
} ;
if (bytesread != chunk_size)
{ psf_log_printf (psf, "**** Chunk size weirdness (%d != %d)\n", chunk_size, bytesread) ;
psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
} ;
} ;
break ;
case smpl_MARKER :
parsestage |= HAVE_other ;
psf_log_printf (psf, "smpl : %u\n", chunk_size) ;
if ((error = wav_read_smpl_chunk (psf, chunk_size)))
return error ;
break ;
case acid_MARKER :
parsestage |= HAVE_other ;
psf_log_printf (psf, "acid : %u\n", chunk_size) ;
if ((error = wav_read_acid_chunk (psf, chunk_size)))
return error ;
break ;
case INFO_MARKER :
case LIST_MARKER :
parsestage |= HAVE_other ;
if ((error = wavlike_subchunk_parse (psf, marker, chunk_size)) != 0)
return error ;
break ;
case bext_MARKER :
/*
The 'bext' chunk can actually be updated, so don't need to set this.
parsestage |= HAVE_other ;
*/
if ((error = wavlike_read_bext_chunk (psf, chunk_size)))
return error ;
break ;
case PAD_MARKER :
/*
We can eat into a 'PAD ' chunk if we need to.
parsestage |= HAVE_other ;
*/
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
case cart_MARKER:
if ((error = wavlike_read_cart_chunk (psf, chunk_size)))
return error ;
break ;
case iXML_MARKER : /* See http://en.wikipedia.org/wiki/IXML */
case strc_MARKER : /* Multiple of 32 bytes. */
case afsp_MARKER :
case clm_MARKER :
case elmo_MARKER :
case levl_MARKER :
case plst_MARKER :
case minf_MARKER :
case elm1_MARKER :
case regn_MARKER :
case ovwf_MARKER :
case inst_MARKER :
case AFAn_MARKER :
case umid_MARKER :
case SyLp_MARKER :
case Cr8r_MARKER :
case JUNK_MARKER :
case PMX_MARKER :
case DISP_MARKER :
case MEXT_MARKER :
case FLLR_MARKER :
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
default :
if (chunk_size >= 0xffff0000)
{ done = SF_TRUE ;
psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
break ;
} ;
if (psf_isprint ((marker >> 24) & 0xFF) && psf_isprint ((marker >> 16) & 0xFF)
&& psf_isprint ((marker >> 8) & 0xFF) && psf_isprint (marker & 0xFF))
{ psf_log_printf (psf, "*** %M : %u (unknown marker)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
if (psf_ftell (psf) & 0x03)
{ psf_log_printf (psf, " Unknown chunk marker at position %D. Resynching.\n", psf_ftell (psf) - 8) ;
psf_binheader_readf (psf, "j", -3) ;
/* File is too messed up so we prevent editing in RDWR mode here. */
parsestage |= HAVE_other ;
break ;
} ;
psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D. Exiting parser.\n", marker, psf_ftell (psf) - 8) ;
done = SF_TRUE ;
break ;
} ; /* switch (marker) */
if (chunk_size >= psf->filelength)
{ psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
break ;
} ;
if (! psf->sf.seekable && (parsestage & HAVE_data))
break ;
if (psf_ftell (psf) >= psf->filelength - SIGNED_SIZEOF (chunk_size))
{ psf_log_printf (psf, "End\n") ;
break ;
} ;
} ; /* while (1) */
if (psf->dataoffset <= 0)
return SFE_WAV_NO_DATA ;
if (psf->sf.channels < 1)
return SFE_CHANNEL_COUNT_ZERO ;
if (psf->sf.channels >= SF_MAX_CHANNELS)
return SFE_CHANNEL_COUNT ;
if (format != WAVE_FORMAT_PCM && (parsestage & HAVE_fact) == 0)
psf_log_printf (psf, "**** All non-PCM format files should have a 'fact' chunk.\n") ;
/* WAVs can be little or big endian */
psf->endian = psf->rwf_endian ;
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
if (psf->is_pipe == 0)
{ /*
** Check for 'wvpk' at the start of the DATA section. Not able to
** handle this.
*/
psf_binheader_readf (psf, "4", &marker) ;
if (marker == wvpk_MARKER || marker == OggS_MARKER)
return SFE_WAV_WVPK_DATA ;
} ;
/* Seek to start of DATA section. */
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
if (psf->blockwidth)
{ if (psf->filelength - psf->dataoffset < psf->datalength)
psf->sf.frames = (psf->filelength - psf->dataoffset) / psf->blockwidth ;
else
psf->sf.frames = psf->datalength / psf->blockwidth ;
} ;
switch (format)
{ case WAVE_FORMAT_EXTENSIBLE :
if (psf->sf.format == (SF_FORMAT_WAVEX | SF_FORMAT_MS_ADPCM))
{ *blockalign = wav_fmt->msadpcm.blockalign ;
*framesperblock = wav_fmt->msadpcm.samplesperblock ;
} ;
break ;
case WAVE_FORMAT_NMS_VBXADPCM :
*blockalign = wav_fmt->min.blockalign ;
*framesperblock = 160 ;
switch (wav_fmt->min.bitwidth)
{ case 2 :
psf->sf.format = SF_FORMAT_WAV | SF_FORMAT_NMS_ADPCM_16 ;
break ;
case 3 :
psf->sf.format = SF_FORMAT_WAV | SF_FORMAT_NMS_ADPCM_24 ;
break ;
case 4 :
psf->sf.format = SF_FORMAT_WAV | SF_FORMAT_NMS_ADPCM_32 ;
break ;
default :
return SFE_UNIMPLEMENTED ;
}
break ;
case WAVE_FORMAT_PCM :
psf->sf.format = SF_FORMAT_WAV | u_bitwidth_to_subformat (psf->bytewidth * 8) ;
break ;
case WAVE_FORMAT_MULAW :
case IBM_FORMAT_MULAW :
psf->sf.format = (SF_FORMAT_WAV | SF_FORMAT_ULAW) ;
break ;
case WAVE_FORMAT_ALAW :
case IBM_FORMAT_ALAW :
psf->sf.format = (SF_FORMAT_WAV | SF_FORMAT_ALAW) ;
break ;
case WAVE_FORMAT_MS_ADPCM :
psf->sf.format = (SF_FORMAT_WAV | SF_FORMAT_MS_ADPCM) ;
*blockalign = wav_fmt->msadpcm.blockalign ;
*framesperblock = wav_fmt->msadpcm.samplesperblock ;
break ;
case WAVE_FORMAT_IMA_ADPCM :
psf->sf.format = (SF_FORMAT_WAV | SF_FORMAT_IMA_ADPCM) ;
*blockalign = wav_fmt->ima.blockalign ;
*framesperblock = wav_fmt->ima.samplesperblock ;
break ;
case WAVE_FORMAT_GSM610 :
psf->sf.format = (SF_FORMAT_WAV | SF_FORMAT_GSM610) ;
break ;
case WAVE_FORMAT_IEEE_FLOAT :
psf->sf.format = SF_FORMAT_WAV ;
psf->sf.format |= (psf->bytewidth == 8) ? SF_FORMAT_DOUBLE : SF_FORMAT_FLOAT ;
break ;
case WAVE_FORMAT_G721_ADPCM :
psf->sf.format = SF_FORMAT_WAV | SF_FORMAT_G721_32 ;
break ;
default : return SFE_UNIMPLEMENTED ;
} ;
if (wpriv->fmt_is_broken)
wavlike_analyze (psf) ;
/* Only set the format endian-ness if its non-standard big-endian. */
if (psf->endian == SF_ENDIAN_BIG)
psf->sf.format |= SF_ENDIAN_BIG ;
return 0 ;
} /* wav_read_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug
The code was allowing files to be written with a channel count of exactly
`SF_MAX_CHANNELS` but was failing to read some file formats with the same
channel count.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rf64_read_header (SF_PRIVATE *psf, int *blockalign, int *framesperblock)
{ WAVLIKE_PRIVATE *wpriv ;
WAV_FMT *wav_fmt ;
sf_count_t riff_size = 0, frame_count = 0, ds64_datalength = 0 ;
uint32_t marks [2], marker, chunk_size, parsestage = 0 ;
int error, done = 0, format = 0 ;
if ((wpriv = psf->container_data) == NULL)
return SFE_INTERNAL ;
wav_fmt = &wpriv->wav_fmt ;
/* Set position to start of file to begin reading header. */
psf_binheader_readf (psf, "pmmm", 0, &marker, marks, marks + 1) ;
if (marker != RF64_MARKER || marks [1] != WAVE_MARKER)
return SFE_RF64_NOT_RF64 ;
if (marks [0] == FFFF_MARKER)
psf_log_printf (psf, "%M\n %M\n", RF64_MARKER, WAVE_MARKER) ;
else
psf_log_printf (psf, "%M : 0x%x (should be 0xFFFFFFFF)\n %M\n", RF64_MARKER, WAVE_MARKER) ;
while (NOT (done))
{
marker = chunk_size = 0 ;
psf_binheader_readf (psf, "em4", &marker, &chunk_size) ;
if (marker == 0)
{ sf_count_t pos = psf_ftell (psf) ;
psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
break ;
} ;
psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
switch (marker)
{ case ds64_MARKER :
if (parsestage & HAVE_ds64)
{ psf_log_printf (psf, "*** Second 'ds64' chunk?\n") ;
break ;
} ;
{ unsigned int table_len, bytesread ;
/* Read ds64 sizes (3 8-byte words). */
bytesread = psf_binheader_readf (psf, "888", &riff_size, &ds64_datalength, &frame_count) ;
/* Read table length. */
bytesread += psf_binheader_readf (psf, "4", &table_len) ;
/* Skip table for now. (this was "table_len + 4", why?) */
bytesread += psf_binheader_readf (psf, "j", table_len) ;
if (chunk_size == bytesread)
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
else if (chunk_size >= bytesread + 4)
{ unsigned int next ;
psf_binheader_readf (psf, "m", &next) ;
if (next == fmt_MARKER)
{ psf_log_printf (psf, "%M : %u (should be %u)\n", marker, chunk_size, bytesread) ;
psf_binheader_readf (psf, "j", -4) ;
}
else
{ psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size - bytesread - 4) ;
} ;
} ;
if (psf->filelength != riff_size + 8)
psf_log_printf (psf, " Riff size : %D (should be %D)\n", riff_size, psf->filelength - 8) ;
else
psf_log_printf (psf, " Riff size : %D\n", riff_size) ;
psf_log_printf (psf, " Data size : %D\n", ds64_datalength) ;
psf_log_printf (psf, " Frames : %D\n", frame_count) ;
psf_log_printf (psf, " Table length : %u\n", table_len) ;
} ;
parsestage |= HAVE_ds64 ;
break ;
case fmt_MARKER:
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
if ((error = wavlike_read_fmt_chunk (psf, chunk_size)) != 0)
return error ;
format = wav_fmt->format ;
parsestage |= HAVE_fmt ;
break ;
case bext_MARKER :
if ((error = wavlike_read_bext_chunk (psf, chunk_size)) != 0)
return error ;
parsestage |= HAVE_bext ;
break ;
case cart_MARKER :
if ((error = wavlike_read_cart_chunk (psf, chunk_size)) != 0)
return error ;
parsestage |= HAVE_cart ;
break ;
case INFO_MARKER :
case LIST_MARKER :
if ((error = wavlike_subchunk_parse (psf, marker, chunk_size)) != 0)
return error ;
parsestage |= HAVE_other ;
break ;
case PEAK_MARKER :
if ((parsestage & (HAVE_ds64 | HAVE_fmt)) != (HAVE_ds64 | HAVE_fmt))
return SFE_RF64_PEAK_B4_FMT ;
parsestage |= HAVE_PEAK ;
psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ;
if ((error = wavlike_read_peak_chunk (psf, chunk_size)) != 0)
return error ;
psf->peak_info->peak_loc = ((parsestage & HAVE_data) == 0) ? SF_PEAK_START : SF_PEAK_END ;
break ;
case data_MARKER :
/* see wav for more sophisticated parsing -> implement state machine with parsestage */
if (HAVE_CHUNK (HAVE_ds64))
{ if (chunk_size == 0xffffffff)
psf_log_printf (psf, "%M : 0x%x\n", marker, chunk_size) ;
else
psf_log_printf (psf, "%M : 0x%x (should be 0xffffffff\n", marker, chunk_size) ;
psf->datalength = ds64_datalength ;
}
else
{ if (chunk_size == 0xffffffff)
{ psf_log_printf (psf, "%M : 0x%x\n", marker, chunk_size) ;
psf_log_printf (psf, " *** Data length not specified no 'ds64' chunk.\n") ;
}
else
{ psf_log_printf (psf, "%M : 0x%x\n**** Weird, RF64 file without a 'ds64' chunk and no valid 'data' size.\n", marker, chunk_size) ;
psf->datalength = chunk_size ;
} ;
} ;
psf->dataoffset = psf_ftell (psf) ;
if (psf->dataoffset > 0)
{ if (chunk_size == 0 && riff_size == 8 && psf->filelength > 44)
{ psf_log_printf (psf, " *** Looks like a WAV file which wasn't closed properly. Fixing it.\n") ;
psf->datalength = psf->filelength - psf->dataoffset ;
} ;
/* Only set dataend if there really is data at the end. */
if (psf->datalength + psf->dataoffset < psf->filelength)
psf->dataend = psf->datalength + psf->dataoffset ;
if (NOT (psf->sf.seekable) || psf->dataoffset < 0)
break ;
/* Seek past data and continue reading header. */
psf_fseek (psf, psf->datalength, SEEK_CUR) ;
if (psf_ftell (psf) != psf->datalength + psf->dataoffset)
psf_log_printf (psf, " *** psf_fseek past end error ***\n") ;
} ;
break ;
case JUNK_MARKER :
case PAD_MARKER :
psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
default :
if (chunk_size >= 0xffff0000)
{ psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
done = SF_TRUE ;
break ;
} ;
if (isprint ((marker >> 24) & 0xFF) && isprint ((marker >> 16) & 0xFF)
&& isprint ((marker >> 8) & 0xFF) && isprint (marker & 0xFF))
{ psf_log_printf (psf, "*** %M : %d (unknown marker)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
if (psf_ftell (psf) & 0x03)
{ psf_log_printf (psf, " Unknown chunk marker at position 0x%x. Resynching.\n", chunk_size - 4) ;
psf_binheader_readf (psf, "j", -3) ;
break ;
} ;
psf_log_printf (psf, "*** Unknown chunk marker (0x%X) at position 0x%X. Exiting parser.\n", marker, psf_ftell (psf) - 4) ;
done = SF_TRUE ;
break ;
} ; /* switch (marker) */
/* The 'data' chunk, a chunk size of 0xffffffff means that the 'data' chunk size
** is actually given by the ds64_datalength field.
*/
if (marker != data_MARKER && chunk_size >= psf->filelength)
{ psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
break ;
} ;
if (psf_ftell (psf) >= psf->filelength - SIGNED_SIZEOF (marker))
{ psf_log_printf (psf, "End\n") ;
break ;
} ;
} ;
if (psf->dataoffset <= 0)
return SFE_RF64_NO_DATA ;
if (psf->sf.channels < 1)
return SFE_CHANNEL_COUNT_ZERO ;
if (psf->sf.channels >= SF_MAX_CHANNELS)
return SFE_CHANNEL_COUNT ;
/* WAVs can be little or big endian */
psf->endian = psf->rwf_endian ;
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
if (psf->is_pipe == 0)
{ /*
** Check for 'wvpk' at the start of the DATA section. Not able to
** handle this.
*/
psf_binheader_readf (psf, "4", &marker) ;
if (marker == wvpk_MARKER || marker == OggS_MARKER)
return SFE_WAV_WVPK_DATA ;
} ;
/* Seek to start of DATA section. */
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
if (psf->blockwidth)
{ if (psf->filelength - psf->dataoffset < psf->datalength)
psf->sf.frames = (psf->filelength - psf->dataoffset) / psf->blockwidth ;
else
psf->sf.frames = psf->datalength / psf->blockwidth ;
} ;
if (frame_count != psf->sf.frames)
psf_log_printf (psf, "*** Calculated frame count %d does not match value from 'ds64' chunk of %d.\n", psf->sf.frames, frame_count) ;
switch (format)
{
case WAVE_FORMAT_EXTENSIBLE :
/* with WAVE_FORMAT_EXTENSIBLE the psf->sf.format field is already set. We just have to set the major to rf64 */
psf->sf.format = (psf->sf.format & ~SF_FORMAT_TYPEMASK) | SF_FORMAT_RF64 ;
if (psf->sf.format == (SF_FORMAT_WAVEX | SF_FORMAT_MS_ADPCM))
{ *blockalign = wav_fmt->msadpcm.blockalign ;
*framesperblock = wav_fmt->msadpcm.samplesperblock ;
} ;
break ;
case WAVE_FORMAT_PCM :
psf->sf.format = SF_FORMAT_RF64 | u_bitwidth_to_subformat (psf->bytewidth * 8) ;
break ;
case WAVE_FORMAT_MULAW :
case IBM_FORMAT_MULAW :
psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_ULAW) ;
break ;
case WAVE_FORMAT_ALAW :
case IBM_FORMAT_ALAW :
psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_ALAW) ;
break ;
case WAVE_FORMAT_MS_ADPCM :
psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_MS_ADPCM) ;
*blockalign = wav_fmt->msadpcm.blockalign ;
*framesperblock = wav_fmt->msadpcm.samplesperblock ;
break ;
case WAVE_FORMAT_IMA_ADPCM :
psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_IMA_ADPCM) ;
*blockalign = wav_fmt->ima.blockalign ;
*framesperblock = wav_fmt->ima.samplesperblock ;
break ;
case WAVE_FORMAT_GSM610 :
psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_GSM610) ;
break ;
case WAVE_FORMAT_IEEE_FLOAT :
psf->sf.format = SF_FORMAT_RF64 ;
psf->sf.format |= (psf->bytewidth == 8) ? SF_FORMAT_DOUBLE : SF_FORMAT_FLOAT ;
break ;
case WAVE_FORMAT_G721_ADPCM :
psf->sf.format = SF_FORMAT_RF64 | SF_FORMAT_G721_32 ;
break ;
default : return SFE_UNIMPLEMENTED ;
} ;
if (wpriv->fmt_is_broken)
wavlike_analyze (psf) ;
/* Only set the format endian-ness if its non-standard big-endian. */
if (psf->endian == SF_ENDIAN_BIG)
psf->sf.format |= SF_ENDIAN_BIG ;
return 0 ;
} /* rf64_read_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug
The code was allowing files to be written with a channel count of exactly
`SF_MAX_CHANNELS` but was failing to read some file formats with the same
channel count.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
{ SSND_CHUNK ssnd_fmt ;
AIFF_PRIVATE *paiff ;
BUF_UNION ubuf ;
uint32_t chunk_size = 0, FORMsize, SSNDsize, bytesread, mark_count = 0 ;
int k, found_chunk = 0, done = 0, error = 0 ;
char *cptr ;
int instr_found = 0, mark_found = 0 ;
if (psf->filelength > SF_PLATFORM_S64 (0xffffffff))
psf_log_printf (psf, "Warning : filelength > 0xffffffff. This is bad!!!!\n") ;
if ((paiff = psf->container_data) == NULL)
return SFE_INTERNAL ;
paiff->comm_offset = 0 ;
paiff->ssnd_offset = 0 ;
/* Set position to start of file to begin reading header. */
psf_binheader_readf (psf, "p", 0) ;
memset (comm_fmt, 0, sizeof (COMM_CHUNK)) ;
/* Until recently AIF* file were all BIG endian. */
psf->endian = SF_ENDIAN_BIG ;
/* AIFF files can apparently have their chunks in any order. However, they
** must have a FORM chunk. Approach here is to read all the chunks one by
** one and then check for the mandatory chunks at the end.
*/
while (! done)
{ unsigned marker ;
size_t jump = chunk_size & 1 ;
marker = chunk_size = 0 ;
psf_binheader_readf (psf, "Ejm4", jump, &marker, &chunk_size) ;
if (marker == 0)
{ sf_count_t pos = psf_ftell (psf) ;
psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
break ;
} ;
if (psf->file.mode == SFM_RDWR && (found_chunk & HAVE_SSND))
return SFE_AIFF_RW_SSND_NOT_LAST ;
psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
switch (marker)
{ case FORM_MARKER :
if (found_chunk)
return SFE_AIFF_NO_FORM ;
FORMsize = chunk_size ;
found_chunk |= HAVE_FORM ;
psf_binheader_readf (psf, "m", &marker) ;
switch (marker)
{ case AIFC_MARKER :
case AIFF_MARKER :
found_chunk |= (marker == AIFC_MARKER) ? (HAVE_AIFC | HAVE_AIFF) : HAVE_AIFF ;
break ;
default :
break ;
} ;
if (psf->fileoffset > 0 && psf->filelength > FORMsize + 8)
{ /* Set file length. */
psf->filelength = FORMsize + 8 ;
psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
}
else if (FORMsize != psf->filelength - 2 * SIGNED_SIZEOF (chunk_size))
{ chunk_size = psf->filelength - 2 * sizeof (chunk_size) ;
psf_log_printf (psf, "FORM : %u (should be %u)\n %M\n", FORMsize, chunk_size, marker) ;
FORMsize = chunk_size ;
}
else
psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
/* Set this to 0, so we don't jump a byte when parsing the next marker. */
chunk_size = 0 ;
break ;
case COMM_MARKER :
paiff->comm_offset = psf_ftell (psf) - 8 ;
chunk_size += chunk_size & 1 ;
comm_fmt->size = chunk_size ;
if ((error = aiff_read_comm_chunk (psf, comm_fmt)) != 0)
return error ;
found_chunk |= HAVE_COMM ;
break ;
case PEAK_MARKER :
/* Must have COMM chunk before PEAK chunk. */
if ((found_chunk & (HAVE_FORM | HAVE_AIFF | HAVE_COMM)) != (HAVE_FORM | HAVE_AIFF | HAVE_COMM))
return SFE_AIFF_PEAK_B4_COMM ;
psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ;
if (chunk_size != AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))
{ psf_binheader_readf (psf, "j", chunk_size) ;
psf_log_printf (psf, "*** File PEAK chunk too big.\n") ;
return SFE_WAV_BAD_PEAK ;
} ;
if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
return SFE_MALLOC_FAILED ;
/* read in rest of PEAK chunk. */
psf_binheader_readf (psf, "E44", &(psf->peak_info->version), &(psf->peak_info->timestamp)) ;
if (psf->peak_info->version != 1)
psf_log_printf (psf, " version : %d *** (should be version 1)\n", psf->peak_info->version) ;
else
psf_log_printf (psf, " version : %d\n", psf->peak_info->version) ;
psf_log_printf (psf, " time stamp : %d\n", psf->peak_info->timestamp) ;
psf_log_printf (psf, " Ch Position Value\n") ;
cptr = ubuf.cbuf ;
for (k = 0 ; k < psf->sf.channels ; k++)
{ float value ;
uint32_t position ;
psf_binheader_readf (psf, "Ef4", &value, &position) ;
psf->peak_info->peaks [k].value = value ;
psf->peak_info->peaks [k].position = position ;
snprintf (cptr, sizeof (ubuf.scbuf), " %2d %-12" PRId64 " %g\n",
k, psf->peak_info->peaks [k].position, psf->peak_info->peaks [k].value) ;
cptr [sizeof (ubuf.scbuf) - 1] = 0 ;
psf_log_printf (psf, "%s", cptr) ;
} ;
psf->peak_info->peak_loc = ((found_chunk & HAVE_SSND) == 0) ? SF_PEAK_START : SF_PEAK_END ;
break ;
case SSND_MARKER :
if ((found_chunk & HAVE_AIFC) && (found_chunk & HAVE_FVER) == 0)
psf_log_printf (psf, "*** Valid AIFC files should have an FVER chunk.\n") ;
paiff->ssnd_offset = psf_ftell (psf) - 8 ;
SSNDsize = chunk_size ;
psf_binheader_readf (psf, "E44", &(ssnd_fmt.offset), &(ssnd_fmt.blocksize)) ;
psf->datalength = SSNDsize - sizeof (ssnd_fmt) ;
psf->dataoffset = psf_ftell (psf) ;
if (psf->datalength > psf->filelength - psf->dataoffset || psf->datalength < 0)
{ psf_log_printf (psf, " SSND : %u (should be %D)\n", SSNDsize, psf->filelength - psf->dataoffset + sizeof (SSND_CHUNK)) ;
psf->datalength = psf->filelength - psf->dataoffset ;
}
else
psf_log_printf (psf, " SSND : %u\n", SSNDsize) ;
if (ssnd_fmt.offset == 0 || psf->dataoffset + ssnd_fmt.offset == ssnd_fmt.blocksize)
{ psf_log_printf (psf, " Offset : %u\n", ssnd_fmt.offset) ;
psf_log_printf (psf, " Block Size : %u\n", ssnd_fmt.blocksize) ;
psf->dataoffset += ssnd_fmt.offset ;
psf->datalength -= ssnd_fmt.offset ;
}
else
{ psf_log_printf (psf, " Offset : %u\n", ssnd_fmt.offset) ;
psf_log_printf (psf, " Block Size : %u ???\n", ssnd_fmt.blocksize) ;
psf->dataoffset += ssnd_fmt.offset ;
psf->datalength -= ssnd_fmt.offset ;
} ;
/* Only set dataend if there really is data at the end. */
if (psf->datalength + psf->dataoffset < psf->filelength)
psf->dataend = psf->datalength + psf->dataoffset ;
found_chunk |= HAVE_SSND ;
if (! psf->sf.seekable)
break ;
/* Seek to end of SSND chunk. */
psf_fseek (psf, psf->dataoffset + psf->datalength, SEEK_SET) ;
break ;
case c_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf))
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_sanitize_string (cptr, chunk_size) ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_COPYRIGHT, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case AUTH_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_ARTIST, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case COMT_MARKER :
{ uint16_t count, id, len ;
uint32_t timestamp, bytes ;
if (chunk_size == 0)
break ;
bytes = chunk_size ;
bytes -= psf_binheader_readf (psf, "E2", &count) ;
psf_log_printf (psf, " %M : %d\n count : %d\n", marker, chunk_size, count) ;
for (k = 0 ; k < count ; k++)
{ bytes -= psf_binheader_readf (psf, "E422", ×tamp, &id, &len) ;
psf_log_printf (psf, " time : 0x%x\n marker : %x\n length : %d\n", timestamp, id, len) ;
if (len + 1 > SIGNED_SIZEOF (ubuf.scbuf))
{ psf_log_printf (psf, "\nError : string length (%d) too big.\n", len) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
bytes -= psf_binheader_readf (psf, "b", cptr, len) ;
cptr [len] = 0 ;
psf_log_printf (psf, " string : %s\n", cptr) ;
} ;
if (bytes > 0)
psf_binheader_readf (psf, "j", bytes) ;
} ;
break ;
case APPL_MARKER :
{ unsigned appl_marker ;
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
{ psf_log_printf (psf, " %M : %u (too big, skipping)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
break ;
} ;
if (chunk_size < 4)
{ psf_log_printf (psf, " %M : %d (too small, skipping)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
break ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "mb", &appl_marker, cptr, chunk_size + (chunk_size & 1) - 4) ;
cptr [chunk_size] = 0 ;
for (k = 0 ; k < (int) chunk_size ; k++)
if (! psf_isprint (cptr [k]))
{ cptr [k] = 0 ;
break ;
} ;
psf_log_printf (psf, " %M : %d\n AppSig : %M\n Name : %s\n", marker, chunk_size, appl_marker, cptr) ;
psf_store_string (psf, SF_STR_SOFTWARE, cptr) ;
chunk_size += chunk_size & 1 ;
} ;
break ;
case NAME_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_TITLE, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case ANNO_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_COMMENT, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case INST_MARKER :
if (chunk_size != SIZEOF_INST_CHUNK)
{ psf_log_printf (psf, " %M : %d (should be %d)\n", marker, chunk_size, SIZEOF_INST_CHUNK) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
{ uint8_t bytes [6] ;
int16_t gain ;
if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
return SFE_MALLOC_FAILED ;
psf_binheader_readf (psf, "b", bytes, 6) ;
psf_log_printf (psf, " Base Note : %u\n Detune : %u\n"
" Low Note : %u\n High Note : %u\n"
" Low Vel. : %u\n High Vel. : %u\n",
bytes [0], bytes [1], bytes [2], bytes [3], bytes [4], bytes [5]) ;
psf->instrument->basenote = bytes [0] ;
psf->instrument->detune = bytes [1] ;
psf->instrument->key_lo = bytes [2] ;
psf->instrument->key_hi = bytes [3] ;
psf->instrument->velocity_lo = bytes [4] ;
psf->instrument->velocity_hi = bytes [5] ;
psf_binheader_readf (psf, "E2", &gain) ;
psf->instrument->gain = gain ;
psf_log_printf (psf, " Gain (dB) : %d\n", gain) ;
} ;
{ int16_t mode ; /* 0 - no loop, 1 - forward looping, 2 - backward looping */
const char *loop_mode ;
uint16_t begin, end ;
psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
loop_mode = get_loop_mode_str (mode) ;
mode = get_loop_mode (mode) ;
if (mode == SF_LOOP_NONE)
{ psf->instrument->loop_count = 0 ;
psf->instrument->loops [0].mode = SF_LOOP_NONE ;
}
else
{ psf->instrument->loop_count = 1 ;
psf->instrument->loops [0].mode = SF_LOOP_FORWARD ;
psf->instrument->loops [0].start = begin ;
psf->instrument->loops [0].end = end ;
psf->instrument->loops [0].count = 0 ;
} ;
psf_log_printf (psf, " Sustain\n mode : %d => %s\n begin : %u\n end : %u\n",
mode, loop_mode, begin, end) ;
psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
loop_mode = get_loop_mode_str (mode) ;
mode = get_loop_mode (mode) ;
if (mode == SF_LOOP_NONE)
psf->instrument->loops [1].mode = SF_LOOP_NONE ;
else
{ psf->instrument->loop_count += 1 ;
psf->instrument->loops [1].mode = SF_LOOP_FORWARD ;
psf->instrument->loops [1].start = begin ;
psf->instrument->loops [1].end = end ;
psf->instrument->loops [1].count = 0 ;
} ;
psf_log_printf (psf, " Release\n mode : %d => %s\n begin : %u\n end : %u\n",
mode, loop_mode, begin, end) ;
} ;
instr_found++ ;
break ;
case basc_MARKER :
psf_log_printf (psf, " basc : %u\n", chunk_size) ;
if ((error = aiff_read_basc_chunk (psf, chunk_size)))
return error ;
break ;
case MARK_MARKER :
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
{ uint16_t mark_id, n = 0 ;
uint32_t position ;
bytesread = psf_binheader_readf (psf, "E2", &n) ;
mark_count = n ;
psf_log_printf (psf, " Count : %u\n", mark_count) ;
if (paiff->markstr != NULL)
{ psf_log_printf (psf, "*** Second MARK chunk found. Throwing away the first.\n") ;
free (paiff->markstr) ;
} ;
paiff->markstr = calloc (mark_count, sizeof (MARK_ID_POS)) ;
if (paiff->markstr == NULL)
return SFE_MALLOC_FAILED ;
if (mark_count > 1000)
{ psf_log_printf (psf, " More than 1000 markers, skipping!\n") ;
psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
break ;
} ;
if ((psf->cues = psf_cues_alloc (mark_count)) == NULL)
return SFE_MALLOC_FAILED ;
for (n = 0 ; n < mark_count && bytesread < chunk_size ; n++)
{ uint32_t pstr_len ;
uint8_t ch ;
bytesread += psf_binheader_readf (psf, "E241", &mark_id, &position, &ch) ;
psf_log_printf (psf, " Mark ID : %u\n Position : %u\n", mark_id, position) ;
psf->cues->cue_points [n].indx = mark_id ;
psf->cues->cue_points [n].position = 0 ;
psf->cues->cue_points [n].fcc_chunk = MAKE_MARKER ('d', 'a', 't', 'a') ; /* always data */
psf->cues->cue_points [n].chunk_start = 0 ;
psf->cues->cue_points [n].block_start = 0 ;
psf->cues->cue_points [n].sample_offset = position ;
pstr_len = (ch & 1) ? ch : ch + 1 ;
if (pstr_len < sizeof (ubuf.scbuf) - 1)
{ bytesread += psf_binheader_readf (psf, "b", ubuf.scbuf, pstr_len) ;
ubuf.scbuf [pstr_len] = 0 ;
}
else
{ uint32_t read_len = pstr_len - (sizeof (ubuf.scbuf) - 1) ;
bytesread += psf_binheader_readf (psf, "bj", ubuf.scbuf, read_len, pstr_len - read_len) ;
ubuf.scbuf [sizeof (ubuf.scbuf) - 1] = 0 ;
}
psf_log_printf (psf, " Name : %s\n", ubuf.scbuf) ;
psf_strlcpy (psf->cues->cue_points [n].name, sizeof (psf->cues->cue_points [n].name), ubuf.cbuf) ;
paiff->markstr [n].markerID = mark_id ;
paiff->markstr [n].position = position ;
/*
** TODO if ubuf.scbuf is equal to
** either Beg_loop, Beg loop or beg loop and spam
** if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
** return SFE_MALLOC_FAILED ;
*/
} ;
} ;
mark_found++ ;
psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
break ;
case FVER_MARKER :
found_chunk |= HAVE_FVER ;
/* Falls through. */
case SFX_MARKER :
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
case NONE_MARKER :
/* Fix for broken AIFC files with incorrect COMM chunk length. */
chunk_size = (chunk_size >> 24) - 3 ;
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
break ;
case CHAN_MARKER :
if (chunk_size < 12)
{ psf_log_printf (psf, " %M : %d (should be >= 12)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
}
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
if ((error = aiff_read_chanmap (psf, chunk_size)))
return error ;
break ;
default :
if (chunk_size >= 0xffff0000)
{ done = SF_TRUE ;
psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
break ;
} ;
if (psf_isprint ((marker >> 24) & 0xFF) && psf_isprint ((marker >> 16) & 0xFF)
&& psf_isprint ((marker >> 8) & 0xFF) && psf_isprint (marker & 0xFF))
{ psf_log_printf (psf, " %M : %u (unknown marker)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
if (psf_ftell (psf) & 0x03)
{ psf_log_printf (psf, " Unknown chunk marker at position %D. Resynching.\n", psf_ftell (psf) - 8) ;
psf_binheader_readf (psf, "j", -3) ;
break ;
} ;
psf_log_printf (psf, "*** Unknown chunk marker %X at position %D. Exiting parser.\n", marker, psf_ftell (psf)) ;
done = SF_TRUE ;
break ;
} ; /* switch (marker) */
if (chunk_size >= psf->filelength)
{ psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
break ;
} ;
if ((! psf->sf.seekable) && (found_chunk & HAVE_SSND))
break ;
if (psf_ftell (psf) >= psf->filelength - (2 * SIGNED_SIZEOF (int32_t)))
break ;
} ; /* while (1) */
if (instr_found && mark_found)
{ int ji, str_index ;
/* Next loop will convert markers to loop positions for internal handling */
for (ji = 0 ; ji < psf->instrument->loop_count ; ji ++)
{ if (ji < ARRAY_LEN (psf->instrument->loops))
{ psf->instrument->loops [ji].start = marker_to_position (paiff->markstr, psf->instrument->loops [ji].start, mark_count) ;
psf->instrument->loops [ji].end = marker_to_position (paiff->markstr, psf->instrument->loops [ji].end, mark_count) ;
psf->instrument->loops [ji].mode = SF_LOOP_FORWARD ;
} ;
} ;
/* The markers that correspond to loop positions can now be removed from cues struct */
if (psf->cues->cue_count > (uint32_t) (psf->instrument->loop_count * 2))
{ uint32_t j ;
for (j = 0 ; j < psf->cues->cue_count - (uint32_t) (psf->instrument->loop_count * 2) ; j ++)
{ /* This simply copies the information in cues above loop positions and writes it at current count instead */
psf->cues->cue_points [j].indx = psf->cues->cue_points [j + psf->instrument->loop_count * 2].indx ;
psf->cues->cue_points [j].position = psf->cues->cue_points [j + psf->instrument->loop_count * 2].position ;
psf->cues->cue_points [j].fcc_chunk = psf->cues->cue_points [j + psf->instrument->loop_count * 2].fcc_chunk ;
psf->cues->cue_points [j].chunk_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].chunk_start ;
psf->cues->cue_points [j].block_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].block_start ;
psf->cues->cue_points [j].sample_offset = psf->cues->cue_points [j + psf->instrument->loop_count * 2].sample_offset ;
for (str_index = 0 ; str_index < 256 ; str_index++)
psf->cues->cue_points [j].name [str_index] = psf->cues->cue_points [j + psf->instrument->loop_count * 2].name [str_index] ;
} ;
psf->cues->cue_count -= psf->instrument->loop_count * 2 ;
} else
{ /* All the cues were in fact loop positions so we can actually remove the cues altogether */
free (psf->cues) ;
psf->cues = NULL ;
}
} ;
if (psf->sf.channels < 1)
return SFE_CHANNEL_COUNT_ZERO ;
if (psf->sf.channels >= SF_MAX_CHANNELS)
return SFE_CHANNEL_COUNT ;
if (! (found_chunk & HAVE_FORM))
return SFE_AIFF_NO_FORM ;
if (! (found_chunk & HAVE_AIFF))
return SFE_AIFF_COMM_NO_FORM ;
if (! (found_chunk & HAVE_COMM))
return SFE_AIFF_SSND_NO_COMM ;
if (! psf->dataoffset)
return SFE_AIFF_NO_DATA ;
return 0 ;
} /* aiff_read_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug
The code was allowing files to be written with a channel count of exactly
`SF_MAX_CHANNELS` but was failing to read some file formats with the same
channel count.'</s> |
<s>[INST] Given the following code containing errors, provide 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 HashTable *com_properties_get(zval *object)
{
/* TODO: use type-info to get all the names and values ?
* DANGER: if we do that, there is a strong possibility for
* infinite recursion when the hash is displayed via var_dump().
* Perhaps it is best to leave it un-implemented.
*/
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-502'], 'message': 'Fix #77177: Serializing or unserializing COM objects crashes
Firstly, we avoid returning NULL from the get_property handler, but
instead return an empty HashTable, which already prevents the crashes.
Secondly, since (de-)serialization obviously makes no sense for COM,
DOTNET and VARIANT objects (at least with the current implementation),
we prohibit it right away.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int read_record_hdr(int ifd, void *buffer, struct record_header *record_hdr,
struct file_header *file_hdr, int arch_64, int endian_mismatch,
int oneof)
{
int rc;
if ((rc = sa_fread(ifd, buffer, (size_t) file_hdr->rec_size, SOFT_SIZE, oneof)) != 0)
/* End of sa data file */
return rc;
/* Remap record header structure to that expected by current version */
remap_struct(rec_types_nr, file_hdr->rec_types_nr, buffer,
file_hdr->rec_size, RECORD_HEADER_SIZE);
memcpy(record_hdr, buffer, RECORD_HEADER_SIZE);
/* Normalize endianness */
if (endian_mismatch) {
swap_struct(rec_types_nr, record_hdr, arch_64);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues
Check args before calling memmove() and memset() in remap_struct()
function to avoid out of bound reads which would possibly lead to
unknown code execution and/or sadf command crash.
Signed-off-by: Sebastien GODARD <[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 check_file_actlst(int *ifd, char *dfile, struct activity *act[],
struct file_magic *file_magic, struct file_header *file_hdr,
struct file_activity **file_actlst, unsigned int id_seq[],
int ignore, int *endian_mismatch, int *arch_64)
{
int i, j, k, p;
struct file_activity *fal;
void *buffer = NULL;
/* Open sa data file and read its magic structure */
if (sa_open_read_magic(ifd, dfile, file_magic, ignore, endian_mismatch, TRUE) < 0)
/*
* Not current sysstat's format.
* Return now so that sadf -H can display at least
* file's version and magic number.
*/
return;
/*
* We know now that we have a *compatible* sysstat datafile format
* (correct FORMAT_MAGIC value), and in this case, we should have
* checked header_size value. Anyway, with a corrupted datafile,
* this may not be the case. So check again.
*/
if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||
(file_magic->header_size > MAX_FILE_HEADER_SIZE)) {
#ifdef DEBUG
fprintf(stderr, "%s: header_size=%u\n",
__FUNCTION__, file_magic->header_size);
#endif
goto format_error;
}
/* Allocate buffer for file_header structure */
SREALLOC(buffer, char, file_magic->header_size);
/* Read sa data file standard header and allocate activity list */
sa_fread(*ifd, buffer, (size_t) file_magic->header_size, HARD_SIZE, UEOF_STOP);
/*
* Data file header size (file_magic->header_size) may be greater or
* smaller than FILE_HEADER_SIZE. Remap the fields of the file header
* then copy its contents to the expected structure.
*/
remap_struct(hdr_types_nr, file_magic->hdr_types_nr, buffer,
file_magic->header_size, FILE_HEADER_SIZE);
memcpy(file_hdr, buffer, FILE_HEADER_SIZE);
free(buffer);
buffer = NULL;
/* Tell that data come from a 64 bit machine */
*arch_64 = (file_hdr->sa_sizeof_long == SIZEOF_LONG_64BIT);
/* Normalize endianness for file_hdr structure */
if (*endian_mismatch) {
swap_struct(hdr_types_nr, file_hdr, *arch_64);
}
/*
* Sanity checks.
* NB: Compare against MAX_NR_ACT and not NR_ACT because
* we are maybe reading a datafile from a future sysstat version
* with more activities than known today.
*/
if ((file_hdr->sa_act_nr > MAX_NR_ACT) ||
(file_hdr->act_size > MAX_FILE_ACTIVITY_SIZE) ||
(file_hdr->rec_size > MAX_RECORD_HEADER_SIZE) ||
(MAP_SIZE(file_hdr->act_types_nr) > file_hdr->act_size) ||
(MAP_SIZE(file_hdr->rec_types_nr) > file_hdr->rec_size)) {
#ifdef DEBUG
fprintf(stderr, "%s: sa_act_nr=%d act_size=%u rec_size=%u map_size(act)=%u map_size(rec)=%u\n",
__FUNCTION__, file_hdr->sa_act_nr, file_hdr->act_size, file_hdr->rec_size,
MAP_SIZE(file_hdr->act_types_nr), MAP_SIZE(file_hdr->rec_types_nr));
#endif
/* Maybe a "false positive" sysstat datafile? */
goto format_error;
}
SREALLOC(buffer, char, file_hdr->act_size);
SREALLOC(*file_actlst, struct file_activity, FILE_ACTIVITY_SIZE * file_hdr->sa_act_nr);
fal = *file_actlst;
/* Read activity list */
j = 0;
for (i = 0; i < file_hdr->sa_act_nr; i++, fal++) {
/* Read current file_activity structure from file */
sa_fread(*ifd, buffer, (size_t) file_hdr->act_size, HARD_SIZE, UEOF_STOP);
/*
* Data file_activity size (file_hdr->act_size) may be greater or
* smaller than FILE_ACTIVITY_SIZE. Remap the fields of the file's structure
* then copy its contents to the expected structure.
*/
remap_struct(act_types_nr, file_hdr->act_types_nr, buffer,
file_hdr->act_size, FILE_ACTIVITY_SIZE);
memcpy(fal, buffer, FILE_ACTIVITY_SIZE);
/* Normalize endianness for file_activity structures */
if (*endian_mismatch) {
swap_struct(act_types_nr, fal, *arch_64);
}
/*
* Every activity, known or unknown, should have
* at least one item and sub-item.
* Also check that the number of items and sub-items
* doesn't exceed a max value. This is necessary
* because we will use @nr and @nr2 to
* allocate memory to read the file contents. So we
* must make sure the file is not corrupted.
* NB: Another check will be made below for known
* activities which have each a specific max value.
*/
if ((fal->nr < 1) || (fal->nr2 < 1) ||
(fal->nr > NR_MAX) || (fal->nr2 > NR2_MAX)) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d nr=%d nr2=%d\n",
__FUNCTION__, fal->id, fal->nr, fal->nr2);
#endif
goto format_error;
}
if ((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0)
/* Unknown activity */
continue;
if (act[p]->magic != fal->magic) {
/* Bad magical number */
if (ignore) {
/*
* This is how sadf -H knows that this
* activity has an unknown format.
*/
act[p]->magic = ACTIVITY_MAGIC_UNKNOWN;
}
else
continue;
}
/* Check max value for known activities */
if (fal->nr > act[p]->nr_max) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d nr=%d nr_max=%d\n",
__FUNCTION__, fal->id, fal->nr, act[p]->nr_max);
#endif
goto format_error;
}
/*
* Number of fields of each type ("long long", or "long"
* or "int") composing the structure with statistics may
* only increase with new sysstat versions. Here, we may
* be reading a file created by current sysstat version,
* or by an older or a newer version.
*/
if (!(((fal->types_nr[0] >= act[p]->gtypes_nr[0]) &&
(fal->types_nr[1] >= act[p]->gtypes_nr[1]) &&
(fal->types_nr[2] >= act[p]->gtypes_nr[2]))
||
((fal->types_nr[0] <= act[p]->gtypes_nr[0]) &&
(fal->types_nr[1] <= act[p]->gtypes_nr[1]) &&
(fal->types_nr[2] <= act[p]->gtypes_nr[2]))) && !ignore) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d file=%d,%d,%d activity=%d,%d,%d\n",
__FUNCTION__, fal->id, fal->types_nr[0], fal->types_nr[1], fal->types_nr[2],
act[p]->gtypes_nr[0], act[p]->gtypes_nr[1], act[p]->gtypes_nr[2]);
#endif
goto format_error;
}
if (MAP_SIZE(fal->types_nr) > fal->size) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d size=%u map_size=%u\n",
__FUNCTION__, fal->id, fal->size, MAP_SIZE(fal->types_nr));
#endif
goto format_error;
}
for (k = 0; k < 3; k++) {
act[p]->ftypes_nr[k] = fal->types_nr[k];
}
if (fal->size > act[p]->msize) {
act[p]->msize = fal->size;
}
act[p]->nr_ini = fal->nr;
act[p]->nr2 = fal->nr2;
act[p]->fsize = fal->size;
/*
* This is a known activity with a known format
* (magical number). Only such activities will be displayed.
* (Well, this may also be an unknown format if we have entered sadf -H.)
*/
id_seq[j++] = fal->id;
}
while (j < NR_ACT) {
id_seq[j++] = 0;
}
free(buffer);
/* Check that at least one activity selected by the user is available in file */
for (i = 0; i < NR_ACT; i++) {
if (!IS_SELECTED(act[i]->options))
continue;
/* Here is a selected activity: Does it exist in file? */
fal = *file_actlst;
for (j = 0; j < file_hdr->sa_act_nr; j++, fal++) {
if (act[i]->id == fal->id)
break;
}
if (j == file_hdr->sa_act_nr) {
/* No: Unselect it */
act[i]->options &= ~AO_SELECTED;
}
}
/*
* None of selected activities exist in file: Abort.
* NB: Error is ignored if we only want to display
* datafile header (sadf -H).
*/
if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES) && !ignore) {
fprintf(stderr, _("Requested activities not available in file %s\n"),
dfile);
close(*ifd);
exit(1);
}
return;
format_error:
if (buffer) {
free(buffer);
}
handle_invalid_sa_file(*ifd, file_magic, dfile, 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues
Check args before calling memmove() and memset() in remap_struct()
function to avoid out of bound reads which would possibly lead to
unknown code execution and/or sadf command crash.
Signed-off-by: Sebastien GODARD <[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 read_file_stat_bunch(struct activity *act[], int curr, int ifd, int act_nr,
struct file_activity *file_actlst, int endian_mismatch,
int arch_64, char *dfile, struct file_magic *file_magic,
int oneof)
{
int i, j, p;
struct file_activity *fal = file_actlst;
off_t offset;
__nr_t nr_value;
for (i = 0; i < act_nr; i++, fal++) {
/* Read __nr_t value preceding statistics structures if it exists */
if (fal->has_nr) {
nr_value = read_nr_value(ifd, dfile, file_magic,
endian_mismatch, arch_64, FALSE);
}
else {
nr_value = fal->nr;
}
if (nr_value > NR_MAX) {
#ifdef DEBUG
fprintf(stderr, "%s: Value=%d Max=%d\n", __FUNCTION__, nr_value, NR_MAX);
#endif
handle_invalid_sa_file(ifd, file_magic, dfile, 0);
}
if (((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0) ||
(act[p]->magic != fal->magic)) {
/*
* Ignore current activity in file, which is unknown to
* current sysstat version or has an unknown format.
*/
if (nr_value) {
offset = (off_t) fal->size * (off_t) nr_value * (off_t) fal->nr2;
if (lseek(ifd, offset, SEEK_CUR) < offset) {
close(ifd);
perror("lseek");
if (oneof == UEOF_CONT)
return 2;
exit(2);
}
}
continue;
}
if (nr_value > act[p]->nr_max) {
#ifdef DEBUG
fprintf(stderr, "%s: %s: Value=%d Max=%d\n",
__FUNCTION__, act[p]->name, nr_value, act[p]->nr_max);
#endif
handle_invalid_sa_file(ifd, file_magic, dfile, 0);
}
act[p]->nr[curr] = nr_value;
/* Reallocate buffers if needed */
if (nr_value > act[p]->nr_allocated) {
reallocate_all_buffers(act[p], nr_value);
}
/*
* For persistent activities, we must make sure that no statistics
* from a previous iteration remain, especially if the number
* of structures read is smaller than @nr_ini.
*/
if (HAS_PERSISTENT_VALUES(act[p]->options)) {
memset(act[p]->buf[curr], 0,
(size_t) act[p]->msize * (size_t) act[p]->nr_ini * (size_t) act[p]->nr2);
}
/* OK, this is a known activity: Read the stats structures */
if ((nr_value > 0) &&
((nr_value > 1) || (act[p]->nr2 > 1)) &&
(act[p]->msize > act[p]->fsize)) {
for (j = 0; j < (nr_value * act[p]->nr2); j++) {
if (sa_fread(ifd, (char *) act[p]->buf[curr] + j * act[p]->msize,
(size_t) act[p]->fsize, HARD_SIZE, oneof) > 0)
/* Unexpected EOF */
return 2;
}
}
else if (nr_value > 0) {
/*
* Note: If msize was smaller than fsize,
* then it has been set to fsize in check_file_actlst().
*/
if (sa_fread(ifd, act[p]->buf[curr],
(size_t) act[p]->fsize * (size_t) nr_value * (size_t) act[p]->nr2,
HARD_SIZE, oneof) > 0)
/* Unexpected EOF */
return 2;
}
else {
/* nr_value == 0: Nothing to read */
continue;
}
/* Normalize endianness for current activity's structures */
if (endian_mismatch) {
for (j = 0; j < (nr_value * act[p]->nr2); j++) {
swap_struct(act[p]->ftypes_nr, (char *) act[p]->buf[curr] + j * act[p]->msize,
arch_64);
}
}
/* Remap structure's fields to those known by current sysstat version */
for (j = 0; j < (nr_value * act[p]->nr2); j++) {
remap_struct(act[p]->gtypes_nr, act[p]->ftypes_nr,
(char *) act[p]->buf[curr] + j * act[p]->msize,
act[p]->fsize, act[p]->msize);
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues
Check args before calling memmove() and memset() in remap_struct()
function to avoid out of bound reads which would possibly lead to
unknown code execution and/or sadf command crash.
Signed-off-by: Sebastien GODARD <[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 remap_struct(unsigned int gtypes_nr[], unsigned int ftypes_nr[],
void *ps, unsigned int f_size, unsigned int g_size)
{
int d;
/* Sanity check */
if (MAP_SIZE(ftypes_nr) > f_size)
return;
/* Remap [unsigned] long fields */
d = gtypes_nr[0] - ftypes_nr[0];
if (d) {
memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH,
((char *) ps) + ftypes_nr[0] * ULL_ALIGNMENT_WIDTH,
MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH,
g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH));
if (d > 0) {
memset(((char *) ps) + ftypes_nr[0] * ULL_ALIGNMENT_WIDTH,
0, d * ULL_ALIGNMENT_WIDTH);
}
}
/* Remap [unsigned] int fields */
d = gtypes_nr[1] - ftypes_nr[1];
if (d) {
memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ gtypes_nr[1] * UL_ALIGNMENT_WIDTH,
((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ ftypes_nr[1] * UL_ALIGNMENT_WIDTH,
MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH
- ftypes_nr[1] * UL_ALIGNMENT_WIDTH,
g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
- gtypes_nr[1] * UL_ALIGNMENT_WIDTH));
if (d > 0) {
memset(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ ftypes_nr[1] * UL_ALIGNMENT_WIDTH,
0, d * UL_ALIGNMENT_WIDTH);
}
}
/* Remap possible fields (like strings of chars) following int fields */
d = gtypes_nr[2] - ftypes_nr[2];
if (d) {
memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ gtypes_nr[1] * UL_ALIGNMENT_WIDTH
+ gtypes_nr[2] * U_ALIGNMENT_WIDTH,
((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ gtypes_nr[1] * UL_ALIGNMENT_WIDTH
+ ftypes_nr[2] * U_ALIGNMENT_WIDTH,
MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH
- ftypes_nr[1] * UL_ALIGNMENT_WIDTH
- ftypes_nr[2] * U_ALIGNMENT_WIDTH,
g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
- gtypes_nr[1] * UL_ALIGNMENT_WIDTH
- gtypes_nr[2] * U_ALIGNMENT_WIDTH));
if (d > 0) {
memset(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
+ gtypes_nr[1] * UL_ALIGNMENT_WIDTH
+ ftypes_nr[2] * U_ALIGNMENT_WIDTH,
0, d * U_ALIGNMENT_WIDTH);
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues
Check args before calling memmove() and memset() in remap_struct()
function to avoid out of bound reads which would possibly lead to
unknown code execution and/or sadf command crash.
Signed-off-by: Sebastien GODARD <[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 gather_pid_metadata(
char* context[_CONTEXT_MAX],
char **comm_fallback,
struct iovec *iovec, size_t *n_iovec) {
/* We need 27 empty slots in iovec!
*
* Note that if we fail on oom later on, we do not roll-back changes to the iovec structure. (It remains valid,
* with the first n_iovec fields initialized.) */
uid_t owner_uid;
pid_t pid;
char *t;
const char *p;
int r, signo;
r = parse_pid(context[CONTEXT_PID], &pid);
if (r < 0)
return log_error_errno(r, "Failed to parse PID \"%s\": %m", context[CONTEXT_PID]);
r = get_process_comm(pid, &context[CONTEXT_COMM]);
if (r < 0) {
log_warning_errno(r, "Failed to get COMM, falling back to the command line: %m");
context[CONTEXT_COMM] = strv_join(comm_fallback, " ");
if (!context[CONTEXT_COMM])
return log_oom();
}
r = get_process_exe(pid, &context[CONTEXT_EXE]);
if (r < 0)
log_warning_errno(r, "Failed to get EXE, ignoring: %m");
if (cg_pid_get_unit(pid, &context[CONTEXT_UNIT]) >= 0) {
if (!is_journald_crash((const char**) context)) {
/* OK, now we know it's not the journal, hence we can make use of it now. */
log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
log_open();
}
/* If this is PID 1 disable coredump collection, we'll unlikely be able to process it later on. */
if (is_pid1_crash((const char**) context)) {
log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
disable_coredumps();
}
set_iovec_field(iovec, n_iovec, "COREDUMP_UNIT=", context[CONTEXT_UNIT]);
}
if (cg_pid_get_user_unit(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_USER_UNIT=", t);
/* The next few are mandatory */
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_PID=", context[CONTEXT_PID]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_UID=", context[CONTEXT_UID]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_GID=", context[CONTEXT_GID]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_SIGNAL=", context[CONTEXT_SIGNAL]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_RLIMIT=", context[CONTEXT_RLIMIT]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_HOSTNAME=", context[CONTEXT_HOSTNAME]))
return log_oom();
if (!set_iovec_field(iovec, n_iovec, "COREDUMP_COMM=", context[CONTEXT_COMM]))
return log_oom();
if (context[CONTEXT_EXE] &&
!set_iovec_field(iovec, n_iovec, "COREDUMP_EXE=", context[CONTEXT_EXE]))
return log_oom();
if (sd_pid_get_session(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_SESSION=", t);
if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
r = asprintf(&t, "COREDUMP_OWNER_UID=" UID_FMT, owner_uid);
if (r > 0)
iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(t);
}
if (sd_pid_get_slice(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_SLICE=", t);
if (get_process_cmdline(pid, 0, false, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_CMDLINE=", t);
if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_CGROUP=", t);
if (compose_open_fds(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_OPEN_FDS=", t);
p = procfs_file_alloca(pid, "status");
if (read_full_file(p, &t, NULL) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_PROC_STATUS=", t);
p = procfs_file_alloca(pid, "maps");
if (read_full_file(p, &t, NULL) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_PROC_MAPS=", t);
p = procfs_file_alloca(pid, "limits");
if (read_full_file(p, &t, NULL) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_PROC_LIMITS=", t);
p = procfs_file_alloca(pid, "cgroup");
if (read_full_file(p, &t, NULL) >=0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_PROC_CGROUP=", t);
p = procfs_file_alloca(pid, "mountinfo");
if (read_full_file(p, &t, NULL) >=0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_PROC_MOUNTINFO=", t);
if (get_process_cwd(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_CWD=", t);
if (get_process_root(pid, &t) >= 0) {
bool proc_self_root_is_slash;
proc_self_root_is_slash = strcmp(t, "/") == 0;
set_iovec_field_free(iovec, n_iovec, "COREDUMP_ROOT=", t);
/* If the process' root is "/", then there is a chance it has
* mounted own root and hence being containerized. */
if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_CONTAINER_CMDLINE=", t);
}
if (get_process_environ(pid, &t) >= 0)
set_iovec_field_free(iovec, n_iovec, "COREDUMP_ENVIRON=", t);
t = strjoin("COREDUMP_TIMESTAMP=", context[CONTEXT_TIMESTAMP], "000000");
if (t)
iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(t);
if (safe_atoi(context[CONTEXT_SIGNAL], &signo) >= 0 && SIGNAL_VALID(signo))
set_iovec_field(iovec, n_iovec, "COREDUMP_SIGNAL_NAME=SIG", signal_to_string(signo));
return 0; /* we successfully acquired all metadata */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack
This fixes a crash where we would read the commandline, whose length is under
control of the sending program, and then crash when trying to create a stack
allocation for it.
CVE-2018-16864
https://bugzilla.redhat.com/show_bug.cgi?id=1653855
The message actually doesn't get written to disk, because
journal_file_append_entry() returns -E2BIG.'</s> |
<s>[INST] Given the following code containing errors, provide 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 dispatch_message_real(
Server *s,
struct iovec *iovec, size_t n, size_t m,
const ClientContext *c,
const struct timeval *tv,
int priority,
pid_t object_pid) {
char source_time[sizeof("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)];
uid_t journal_uid;
ClientContext *o;
assert(s);
assert(iovec);
assert(n > 0);
assert(n +
N_IOVEC_META_FIELDS +
(pid_is_valid(object_pid) ? N_IOVEC_OBJECT_FIELDS : 0) +
client_context_extra_fields_n_iovec(c) <= m);
if (c) {
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->pid, pid_t, pid_is_valid, PID_FMT, "_PID");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->uid, uid_t, uid_is_valid, UID_FMT, "_UID");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->gid, gid_t, gid_is_valid, GID_FMT, "_GID");
IOVEC_ADD_STRING_FIELD(iovec, n, c->comm, "_COMM");
IOVEC_ADD_STRING_FIELD(iovec, n, c->exe, "_EXE");
IOVEC_ADD_STRING_FIELD(iovec, n, c->cmdline, "_CMDLINE");
IOVEC_ADD_STRING_FIELD(iovec, n, c->capeff, "_CAP_EFFECTIVE");
IOVEC_ADD_SIZED_FIELD(iovec, n, c->label, c->label_size, "_SELINUX_CONTEXT");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "_AUDIT_SESSION");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->loginuid, uid_t, uid_is_valid, UID_FMT, "_AUDIT_LOGINUID");
IOVEC_ADD_STRING_FIELD(iovec, n, c->cgroup, "_SYSTEMD_CGROUP");
IOVEC_ADD_STRING_FIELD(iovec, n, c->session, "_SYSTEMD_SESSION");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->owner_uid, uid_t, uid_is_valid, UID_FMT, "_SYSTEMD_OWNER_UID");
IOVEC_ADD_STRING_FIELD(iovec, n, c->unit, "_SYSTEMD_UNIT");
IOVEC_ADD_STRING_FIELD(iovec, n, c->user_unit, "_SYSTEMD_USER_UNIT");
IOVEC_ADD_STRING_FIELD(iovec, n, c->slice, "_SYSTEMD_SLICE");
IOVEC_ADD_STRING_FIELD(iovec, n, c->user_slice, "_SYSTEMD_USER_SLICE");
IOVEC_ADD_ID128_FIELD(iovec, n, c->invocation_id, "_SYSTEMD_INVOCATION_ID");
if (c->extra_fields_n_iovec > 0) {
memcpy(iovec + n, c->extra_fields_iovec, c->extra_fields_n_iovec * sizeof(struct iovec));
n += c->extra_fields_n_iovec;
}
}
assert(n <= m);
if (pid_is_valid(object_pid) && client_context_get(s, object_pid, NULL, NULL, 0, NULL, &o) >= 0) {
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->pid, pid_t, pid_is_valid, PID_FMT, "OBJECT_PID");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_UID");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->gid, gid_t, gid_is_valid, GID_FMT, "OBJECT_GID");
IOVEC_ADD_STRING_FIELD(iovec, n, o->comm, "OBJECT_COMM");
IOVEC_ADD_STRING_FIELD(iovec, n, o->exe, "OBJECT_EXE");
IOVEC_ADD_STRING_FIELD(iovec, n, o->cmdline, "OBJECT_CMDLINE");
IOVEC_ADD_STRING_FIELD(iovec, n, o->capeff, "OBJECT_CAP_EFFECTIVE");
IOVEC_ADD_SIZED_FIELD(iovec, n, o->label, o->label_size, "OBJECT_SELINUX_CONTEXT");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "OBJECT_AUDIT_SESSION");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->loginuid, uid_t, uid_is_valid, UID_FMT, "OBJECT_AUDIT_LOGINUID");
IOVEC_ADD_STRING_FIELD(iovec, n, o->cgroup, "OBJECT_SYSTEMD_CGROUP");
IOVEC_ADD_STRING_FIELD(iovec, n, o->session, "OBJECT_SYSTEMD_SESSION");
IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->owner_uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_SYSTEMD_OWNER_UID");
IOVEC_ADD_STRING_FIELD(iovec, n, o->unit, "OBJECT_SYSTEMD_UNIT");
IOVEC_ADD_STRING_FIELD(iovec, n, o->user_unit, "OBJECT_SYSTEMD_USER_UNIT");
IOVEC_ADD_STRING_FIELD(iovec, n, o->slice, "OBJECT_SYSTEMD_SLICE");
IOVEC_ADD_STRING_FIELD(iovec, n, o->user_slice, "OBJECT_SYSTEMD_USER_SLICE");
IOVEC_ADD_ID128_FIELD(iovec, n, o->invocation_id, "OBJECT_SYSTEMD_INVOCATION_ID=");
}
assert(n <= m);
if (tv) {
sprintf(source_time, "_SOURCE_REALTIME_TIMESTAMP=" USEC_FMT, timeval_load(tv));
iovec[n++] = IOVEC_MAKE_STRING(source_time);
}
/* Note that strictly speaking storing the boot id here is
* redundant since the entry includes this in-line
* anyway. However, we need this indexed, too. */
if (!isempty(s->boot_id_field))
iovec[n++] = IOVEC_MAKE_STRING(s->boot_id_field);
if (!isempty(s->machine_id_field))
iovec[n++] = IOVEC_MAKE_STRING(s->machine_id_field);
if (!isempty(s->hostname_field))
iovec[n++] = IOVEC_MAKE_STRING(s->hostname_field);
assert(n <= m);
if (s->split_mode == SPLIT_UID && c && uid_is_valid(c->uid))
/* Split up strictly by (non-root) UID */
journal_uid = c->uid;
else if (s->split_mode == SPLIT_LOGIN && c && c->uid > 0 && uid_is_valid(c->owner_uid))
/* Split up by login UIDs. We do this only if the
* realuid is not root, in order not to accidentally
* leak privileged information to the user that is
* logged by a privileged process that is part of an
* unprivileged session. */
journal_uid = c->owner_uid;
else
journal_uid = 0;
write_to_journal(s, journal_uid, iovec, n, priority); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack
This fixes a crash where we would read the commandline, whose length is under
control of the sending program, and then crash when trying to create a stack
allocation for it.
CVE-2018-16864
https://bugzilla.redhat.com/show_bug.cgi?id=1653855
The message actually doesn't get written to disk, because
journal_file_append_entry() returns -E2BIG.'</s> |
<s>[INST] Given the following code containing errors, provide 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 get_line(JournalImporter *imp, char **line, size_t *size) {
ssize_t n;
char *c = NULL;
assert(imp);
assert(imp->state == IMPORTER_STATE_LINE);
assert(imp->offset <= imp->filled);
assert(imp->filled <= imp->size);
assert(!imp->buf || imp->size > 0);
assert(imp->fd >= 0);
for (;;) {
if (imp->buf) {
size_t start = MAX(imp->scanned, imp->offset);
c = memchr(imp->buf + start, '\n',
imp->filled - start);
if (c != NULL)
break;
}
imp->scanned = imp->filled;
if (imp->scanned >= DATA_SIZE_MAX)
return log_error_errno(SYNTHETIC_ERRNO(E2BIG),
"Entry is bigger than %u bytes.",
DATA_SIZE_MAX);
if (imp->passive_fd)
/* we have to wait for some data to come to us */
return -EAGAIN;
/* We know that imp->filled is at most DATA_SIZE_MAX, so if
we reallocate it, we'll increase the size at least a bit. */
assert_cc(DATA_SIZE_MAX < ENTRY_SIZE_MAX);
if (imp->size - imp->filled < LINE_CHUNK &&
!realloc_buffer(imp, MIN(imp->filled + LINE_CHUNK, ENTRY_SIZE_MAX)))
return log_oom();
assert(imp->buf);
assert(imp->size - imp->filled >= LINE_CHUNK ||
imp->size == ENTRY_SIZE_MAX);
n = read(imp->fd,
imp->buf + imp->filled,
imp->size - imp->filled);
if (n < 0) {
if (errno != EAGAIN)
log_error_errno(errno, "read(%d, ..., %zu): %m",
imp->fd,
imp->size - imp->filled);
return -errno;
} else if (n == 0)
return 0;
imp->filled += n;
}
*line = imp->buf + imp->offset;
*size = c + 1 - imp->buf - imp->offset;
imp->offset += *size;
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'journal-remote: set a limit on the number of fields in a message
Existing use of E2BIG is replaced with ENOBUFS (entry too long), and E2BIG is
reused for the new error condition (too many fields).
This matches the change done for systemd-journald, hence forming the second
part of the fix for CVE-2018-16865
(https://bugzilla.redhat.com/show_bug.cgi?id=1653861).'</s> |
<s>[INST] Given the following code containing errors, provide 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 process_http_upload(
struct MHD_Connection *connection,
const char *upload_data,
size_t *upload_data_size,
RemoteSource *source) {
bool finished = false;
size_t remaining;
int r;
assert(source);
log_trace("%s: connection %p, %zu bytes",
__func__, connection, *upload_data_size);
if (*upload_data_size) {
log_trace("Received %zu bytes", *upload_data_size);
r = journal_importer_push_data(&source->importer,
upload_data, *upload_data_size);
if (r < 0)
return mhd_respond_oom(connection);
*upload_data_size = 0;
} else
finished = true;
for (;;) {
r = process_source(source,
journal_remote_server_global->compress,
journal_remote_server_global->seal);
if (r == -EAGAIN)
break;
if (r < 0) {
if (r == -E2BIG)
log_warning_errno(r, "Entry is too above maximum of %u, aborting connection %p.",
DATA_SIZE_MAX, connection);
else
log_warning_errno(r, "Failed to process data, aborting connection %p: %m",
connection);
return MHD_NO;
}
}
if (!finished)
return MHD_YES;
/* The upload is finished */
remaining = journal_importer_bytes_remaining(&source->importer);
if (remaining > 0) {
log_warning("Premature EOF byte. %zu bytes lost.", remaining);
return mhd_respondf(connection,
0, MHD_HTTP_EXPECTATION_FAILED,
"Premature EOF. %zu bytes of trailing data not processed.",
remaining);
}
return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.");
}; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'journal-remote: set a limit on the number of fields in a message
Existing use of E2BIG is replaced with ENOBUFS (entry too long), and E2BIG is
reused for the new error condition (too many fields).
This matches the change done for systemd-journald, hence forming the second
part of the fix for CVE-2018-16865
(https://bugzilla.redhat.com/show_bug.cgi?id=1653861).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: size_t syslog_parse_identifier(const char **buf, char **identifier, char **pid) {
const char *p;
char *t;
size_t l, e;
assert(buf);
assert(identifier);
assert(pid);
p = *buf;
p += strspn(p, WHITESPACE);
l = strcspn(p, WHITESPACE);
if (l <= 0 ||
p[l-1] != ':')
return 0;
e = l;
l--;
if (p[l-1] == ']') {
size_t k = l-1;
for (;;) {
if (p[k] == '[') {
t = strndup(p+k+1, l-k-2);
if (t)
*pid = t;
l = k;
break;
}
if (k == 0)
break;
k--;
}
}
t = strndup(p, l);
if (t)
*identifier = t;
if (strchr(WHITESPACE, p[e]))
e++;
*buf = p + e;
return e;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'journal: fix syslog_parse_identifier()
Fixes #9829.'</s> |
<s>[INST] Given the following code containing errors, provide 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 test_syslog_parse_identifier(const char* str,
const char *ident, const char*pid, int ret) {
const char *buf = str;
_cleanup_free_ char *ident2 = NULL, *pid2 = NULL;
int ret2;
ret2 = syslog_parse_identifier(&buf, &ident2, &pid2);
assert_se(ret == ret2);
assert_se(ident == ident2 || streq_ptr(ident, ident2));
assert_se(pid == pid2 || streq_ptr(pid, pid2));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'journal: fix syslog_parse_identifier()
Fixes #9829.'</s> |
<s>[INST] Given the following code containing errors, provide 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 test_syslog_parse_identifier(const char *str,
const char *ident, const char *pid, int ret) {
const char *buf = str;
_cleanup_free_ char *ident2 = NULL, *pid2 = NULL;
int ret2;
ret2 = syslog_parse_identifier(&buf, &ident2, &pid2);
assert_se(ret == ret2);
assert_se(ident == ident2 || streq_ptr(ident, ident2));
assert_se(pid == pid2 || streq_ptr(pid, pid2));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'journal: do not remove multiple spaces after identifier in syslog message
Single space is used as separator.
C.f. discussions in #156.
Fixes #9839 introduced by a6aadf4ae0bae185dc4c414d492a4a781c80ffe5.'</s> |
<s>[INST] Given the following code containing errors, provide 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_MINIT_FUNCTION(imap)
{
unsigned long sa_all = SA_MESSAGES | SA_RECENT | SA_UNSEEN | SA_UIDNEXT | SA_UIDVALIDITY;
#ifndef PHP_WIN32
mail_link(&unixdriver); /* link in the unix driver */
mail_link(&mhdriver); /* link in the mh driver */
/* mail_link(&mxdriver); */ /* According to c-client docs (internal.txt) this shouldn't be used. */
mail_link(&mmdfdriver); /* link in the mmdf driver */
mail_link(&newsdriver); /* link in the news driver */
mail_link(&philedriver); /* link in the phile driver */
#endif
mail_link(&imapdriver); /* link in the imap driver */
mail_link(&nntpdriver); /* link in the nntp driver */
mail_link(&pop3driver); /* link in the pop3 driver */
mail_link(&mbxdriver); /* link in the mbx driver */
mail_link(&tenexdriver); /* link in the tenex driver */
mail_link(&mtxdriver); /* link in the mtx driver */
mail_link(&dummydriver); /* link in the dummy driver */
#ifndef PHP_WIN32
auth_link(&auth_log); /* link in the log authenticator */
auth_link(&auth_md5); /* link in the cram-md5 authenticator */
#if HAVE_IMAP_KRB && defined(HAVE_IMAP_AUTH_GSS)
auth_link(&auth_gss); /* link in the gss authenticator */
#endif
auth_link(&auth_pla); /* link in the plain authenticator */
#endif
#ifdef HAVE_IMAP_SSL
ssl_onceonlyinit ();
#endif
/* lets allow NIL */
REGISTER_LONG_CONSTANT("NIL", NIL, CONST_PERSISTENT | CONST_CS);
/* plug in our gets */
mail_parameters(NIL, SET_GETS, (void *) NIL);
/* set default timeout values */
mail_parameters(NIL, SET_OPENTIMEOUT, (void *) FG(default_socket_timeout));
mail_parameters(NIL, SET_READTIMEOUT, (void *) FG(default_socket_timeout));
mail_parameters(NIL, SET_WRITETIMEOUT, (void *) FG(default_socket_timeout));
mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) FG(default_socket_timeout));
/* timeout constants */
REGISTER_LONG_CONSTANT("IMAP_OPENTIMEOUT", 1, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("IMAP_READTIMEOUT", 2, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("IMAP_WRITETIMEOUT", 3, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("IMAP_CLOSETIMEOUT", 4, CONST_PERSISTENT | CONST_CS);
/* Open Options */
REGISTER_LONG_CONSTANT("OP_DEBUG", OP_DEBUG, CONST_PERSISTENT | CONST_CS);
/* debug protocol negotiations */
REGISTER_LONG_CONSTANT("OP_READONLY", OP_READONLY, CONST_PERSISTENT | CONST_CS);
/* read-only open */
REGISTER_LONG_CONSTANT("OP_ANONYMOUS", OP_ANONYMOUS, CONST_PERSISTENT | CONST_CS);
/* anonymous open of newsgroup */
REGISTER_LONG_CONSTANT("OP_SHORTCACHE", OP_SHORTCACHE, CONST_PERSISTENT | CONST_CS);
/* short (elt-only) caching */
REGISTER_LONG_CONSTANT("OP_SILENT", OP_SILENT, CONST_PERSISTENT | CONST_CS);
/* don't pass up events (internal use) */
REGISTER_LONG_CONSTANT("OP_PROTOTYPE", OP_PROTOTYPE, CONST_PERSISTENT | CONST_CS);
/* return driver prototype */
REGISTER_LONG_CONSTANT("OP_HALFOPEN", OP_HALFOPEN, CONST_PERSISTENT | CONST_CS);
/* half-open (IMAP connect but no select) */
REGISTER_LONG_CONSTANT("OP_EXPUNGE", OP_EXPUNGE, CONST_PERSISTENT | CONST_CS);
/* silently expunge recycle stream */
REGISTER_LONG_CONSTANT("OP_SECURE", OP_SECURE, CONST_PERSISTENT | CONST_CS);
/* don't do non-secure authentication */
/*
PHP re-assigns CL_EXPUNGE a custom value that can be used as part of the imap_open() bitfield
because it seems like a good idea to be able to indicate that the mailbox should be
automatically expunged during imap_open in case the script get interrupted and it doesn't get
to the imap_close() where this option is normally placed. If the c-client library adds other
options and the value for this one conflicts, simply make PHP_EXPUNGE higher at the top of
this file
*/
REGISTER_LONG_CONSTANT("CL_EXPUNGE", PHP_EXPUNGE, CONST_PERSISTENT | CONST_CS);
/* expunge silently */
/* Fetch options */
REGISTER_LONG_CONSTANT("FT_UID", FT_UID, CONST_PERSISTENT | CONST_CS);
/* argument is a UID */
REGISTER_LONG_CONSTANT("FT_PEEK", FT_PEEK, CONST_PERSISTENT | CONST_CS);
/* peek at data */
REGISTER_LONG_CONSTANT("FT_NOT", FT_NOT, CONST_PERSISTENT | CONST_CS);
/* NOT flag for header lines fetch */
REGISTER_LONG_CONSTANT("FT_INTERNAL", FT_INTERNAL, CONST_PERSISTENT | CONST_CS);
/* text can be internal strings */
REGISTER_LONG_CONSTANT("FT_PREFETCHTEXT", FT_PREFETCHTEXT, CONST_PERSISTENT | CONST_CS);
/* IMAP prefetch text when fetching header */
/* Flagging options */
REGISTER_LONG_CONSTANT("ST_UID", ST_UID, CONST_PERSISTENT | CONST_CS);
/* argument is a UID sequence */
REGISTER_LONG_CONSTANT("ST_SILENT", ST_SILENT, CONST_PERSISTENT | CONST_CS);
/* don't return results */
REGISTER_LONG_CONSTANT("ST_SET", ST_SET, CONST_PERSISTENT | CONST_CS);
/* set vs. clear */
/* Copy options */
REGISTER_LONG_CONSTANT("CP_UID", CP_UID, CONST_PERSISTENT | CONST_CS);
/* argument is a UID sequence */
REGISTER_LONG_CONSTANT("CP_MOVE", CP_MOVE, CONST_PERSISTENT | CONST_CS);
/* delete from source after copying */
/* Search/sort options */
REGISTER_LONG_CONSTANT("SE_UID", SE_UID, CONST_PERSISTENT | CONST_CS);
/* return UID */
REGISTER_LONG_CONSTANT("SE_FREE", SE_FREE, CONST_PERSISTENT | CONST_CS);
/* free search program after finished */
REGISTER_LONG_CONSTANT("SE_NOPREFETCH", SE_NOPREFETCH, CONST_PERSISTENT | CONST_CS);
/* no search prefetching */
REGISTER_LONG_CONSTANT("SO_FREE", SO_FREE, CONST_PERSISTENT | CONST_CS);
/* free sort program after finished */
REGISTER_LONG_CONSTANT("SO_NOSERVER", SO_NOSERVER, CONST_PERSISTENT | CONST_CS);
/* don't do server-based sort */
/* Status options */
REGISTER_LONG_CONSTANT("SA_MESSAGES", SA_MESSAGES , CONST_PERSISTENT | CONST_CS);
/* number of messages */
REGISTER_LONG_CONSTANT("SA_RECENT", SA_RECENT, CONST_PERSISTENT | CONST_CS);
/* number of recent messages */
REGISTER_LONG_CONSTANT("SA_UNSEEN", SA_UNSEEN , CONST_PERSISTENT | CONST_CS);
/* number of unseen messages */
REGISTER_LONG_CONSTANT("SA_UIDNEXT", SA_UIDNEXT, CONST_PERSISTENT | CONST_CS);
/* next UID to be assigned */
REGISTER_LONG_CONSTANT("SA_UIDVALIDITY", SA_UIDVALIDITY , CONST_PERSISTENT | CONST_CS);
/* UID validity value */
REGISTER_LONG_CONSTANT("SA_ALL", sa_all, CONST_PERSISTENT | CONST_CS);
/* get all status information */
/* Bits for mm_list() and mm_lsub() */
REGISTER_LONG_CONSTANT("LATT_NOINFERIORS", LATT_NOINFERIORS , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("LATT_NOSELECT", LATT_NOSELECT, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("LATT_MARKED", LATT_MARKED, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("LATT_UNMARKED", LATT_UNMARKED , CONST_PERSISTENT | CONST_CS);
#ifdef LATT_REFERRAL
REGISTER_LONG_CONSTANT("LATT_REFERRAL", LATT_REFERRAL, CONST_PERSISTENT | CONST_CS);
#endif
#ifdef LATT_HASCHILDREN
REGISTER_LONG_CONSTANT("LATT_HASCHILDREN", LATT_HASCHILDREN, CONST_PERSISTENT | CONST_CS);
#endif
#ifdef LATT_HASNOCHILDREN
REGISTER_LONG_CONSTANT("LATT_HASNOCHILDREN", LATT_HASNOCHILDREN, CONST_PERSISTENT | CONST_CS);
#endif
/* Sort functions */
REGISTER_LONG_CONSTANT("SORTDATE", SORTDATE , CONST_PERSISTENT | CONST_CS);
/* date */
REGISTER_LONG_CONSTANT("SORTARRIVAL", SORTARRIVAL , CONST_PERSISTENT | CONST_CS);
/* arrival date */
REGISTER_LONG_CONSTANT("SORTFROM", SORTFROM , CONST_PERSISTENT | CONST_CS);
/* from */
REGISTER_LONG_CONSTANT("SORTSUBJECT", SORTSUBJECT , CONST_PERSISTENT | CONST_CS);
/* subject */
REGISTER_LONG_CONSTANT("SORTTO", SORTTO , CONST_PERSISTENT | CONST_CS);
/* to */
REGISTER_LONG_CONSTANT("SORTCC", SORTCC , CONST_PERSISTENT | CONST_CS);
/* cc */
REGISTER_LONG_CONSTANT("SORTSIZE", SORTSIZE , CONST_PERSISTENT | CONST_CS);
/* size */
REGISTER_LONG_CONSTANT("TYPETEXT", TYPETEXT , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEMULTIPART", TYPEMULTIPART , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEMESSAGE", TYPEMESSAGE , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEAPPLICATION", TYPEAPPLICATION , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEAUDIO", TYPEAUDIO , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEIMAGE", TYPEIMAGE , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEVIDEO", TYPEVIDEO , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEMODEL", TYPEMODEL , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("TYPEOTHER", TYPEOTHER , CONST_PERSISTENT | CONST_CS);
/*
TYPETEXT unformatted text
TYPEMULTIPART multiple part
TYPEMESSAGE encapsulated message
TYPEAPPLICATION application data
TYPEAUDIO audio
TYPEIMAGE static image (GIF, JPEG, etc.)
TYPEVIDEO video
TYPEMODEL model
TYPEOTHER unknown
*/
REGISTER_LONG_CONSTANT("ENC7BIT", ENC7BIT , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("ENC8BIT", ENC8BIT , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("ENCBINARY", ENCBINARY , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("ENCBASE64", ENCBASE64, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("ENCQUOTEDPRINTABLE", ENCQUOTEDPRINTABLE , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("ENCOTHER", ENCOTHER , CONST_PERSISTENT | CONST_CS);
/*
ENC7BIT 7 bit SMTP semantic data
ENC8BIT 8 bit SMTP semantic data
ENCBINARY 8 bit binary data
ENCBASE64 base-64 encoded data
ENCQUOTEDPRINTABLE human-readable 8-as-7 bit data
ENCOTHER unknown
*/
REGISTER_LONG_CONSTANT("IMAP_GC_ELT", GC_ELT , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("IMAP_GC_ENV", GC_ENV , CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("IMAP_GC_TEXTS", GC_TEXTS , CONST_PERSISTENT | CONST_CS);
/*
GC_ELT message cache elements
GC_ENV ENVELOPEs and BODYs
GC_TEXTS texts
*/
le_imap = zend_register_list_destructors_ex(mail_close_it, NULL, "imap", module_number);
return SUCCESS; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-88'], 'message': 'Disable rsh/ssh functionality in imap by default (bug #77153)'</s> |
<s>[INST] Given the following code containing errors, provide 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 seticc(i_ctx_t * i_ctx_p, int ncomps, ref *ICCdict, float *range_buff)
{
int code, k;
gs_color_space * pcs;
ref * pstrmval;
stream * s = 0L;
cmm_profile_t *picc_profile = NULL;
int i, expected = 0;
ref * pnameval;
static const char *const icc_std_profile_names[] = {
GSICC_STANDARD_PROFILES
};
static const char *const icc_std_profile_keys[] = {
GSICC_STANDARD_PROFILES_KEYS
};
/* verify the DataSource entry */
if (dict_find_string(ICCdict, "DataSource", &pstrmval) <= 0)
return_error(gs_error_undefined);
check_read_file(i_ctx_p, s, pstrmval);
/* build the color space object */
code = gs_cspace_build_ICC(&pcs, NULL, gs_gstate_memory(igs));
if (code < 0)
return gs_rethrow(code, "building color space object");
/* For now, dump the profile into a buffer
and obtain handle from the buffer when we need it.
We may want to change this later.
This depends to some degree on what the CMS is capable of doing.
I don't want to get bogged down on stream I/O at this point.
Note also, if we are going to be putting these into the clist we will
want to have this buffer. */
/* Check if we have the /Name entry. This is used to associate with
specs that have enumerated types to indicate sRGB sGray etc */
if (dict_find_string(ICCdict, "Name", &pnameval) > 0){
uint size = r_size(pnameval);
char *str = (char *)gs_alloc_bytes(gs_gstate_memory(igs), size+1, "seticc");
memcpy(str, (const char *)pnameval->value.bytes, size);
str[size] = 0;
/* Compare this to the standard profile names */
for (k = 0; k < GSICC_NUMBER_STANDARD_PROFILES; k++) {
if ( strcmp( str, icc_std_profile_keys[k] ) == 0 ) {
picc_profile = gsicc_get_profile_handle_file(icc_std_profile_names[k],
strlen(icc_std_profile_names[k]), gs_gstate_memory(igs));
break;
}
}
gs_free_object(gs_gstate_memory(igs), str, "seticc");
} else {
picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0);
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
/* We have to get the profile handle due to the fact that we need to know
if it has a data space that is CIELAB */
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
}
if (picc_profile == NULL || picc_profile->profile_handle == NULL) {
/* Free up everything, the profile is not valid. We will end up going
ahead and using a default based upon the number of components */
rc_decrement(picc_profile,"seticc");
rc_decrement(pcs,"seticc");
return -1;
}
code = gsicc_set_gscs_profile(pcs, picc_profile, gs_gstate_memory(igs));
if (code < 0) {
rc_decrement(picc_profile,"seticc");
rc_decrement(pcs,"seticc");
return code;
}
picc_profile->num_comps = ncomps;
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
case gsNAMED: /* Silence warnings */
case gsUNDEFINED: /* Silence warnings */
break;
}
if (!expected || ncomps != expected) {
rc_decrement(picc_profile,"seticc");
rc_decrement(pcs,"seticc");
return_error(gs_error_rangecheck);
}
/* Lets go ahead and get the hash code and check if we match one of the default spaces */
/* Later we may want to delay this, but for now lets go ahead and do it */
gsicc_init_hash_cs(picc_profile, igs);
/* Set the range according to the data type that is associated with the
ICC input color type. Occasionally, we will run into CIELAB to CIELAB
profiles for spot colors in PDF documents. These spot colors are typically described
as separation colors with tint transforms that go from a tint value
to a linear mapping between the CIELAB white point and the CIELAB tint
color. This results in a CIELAB value that we need to use to fill. We
need to detect this to make sure we do the proper scaling of the data. For
CIELAB images in PDF, the source is always normal 8 or 16 bit encoded data
in the range from 0 to 255 or 0 to 65535. In that case, there should not
be any encoding and decoding to CIELAB. The PDF content will not include
an ICC profile but will set the color space to \Lab. In this case, we use
our seticc_lab operation to install the LAB to LAB profile, but we detect
that we did that through the use of the is_lab flag in the profile descriptor.
When then avoid the CIELAB encode and decode */
if (picc_profile->data_cs == gsCIELAB) {
/* If the input space to this profile is CIELAB, then we need to adjust the limits */
/* See ICC spec ICC.1:2004-10 Section 6.3.4.2 and 6.4. I don't believe we need to
worry about CIEXYZ profiles or any of the other odds ones. Need to check that though
at some point. */
picc_profile->Range.ranges[0].rmin = 0.0;
picc_profile->Range.ranges[0].rmax = 100.0;
picc_profile->Range.ranges[1].rmin = -128.0;
picc_profile->Range.ranges[1].rmax = 127.0;
picc_profile->Range.ranges[2].rmin = -128.0;
picc_profile->Range.ranges[2].rmax = 127.0;
picc_profile->islab = true;
} else {
for (i = 0; i < ncomps; i++) {
picc_profile->Range.ranges[i].rmin = range_buff[2 * i];
picc_profile->Range.ranges[i].rmax = range_buff[2 * i + 1];
}
}
/* Now see if we are in an overide situation. We have to wait until now
in case this is an LAB profile which we will not overide */
if (gs_currentoverrideicc(igs) && picc_profile->data_cs != gsCIELAB) {
/* Free up the profile structure */
switch( picc_profile->data_cs ) {
case gsRGB:
pcs->cmm_icc_profile_data = igs->icc_manager->default_rgb;
break;
case gsGRAY:
pcs->cmm_icc_profile_data = igs->icc_manager->default_gray;
break;
case gsCMYK:
pcs->cmm_icc_profile_data = igs->icc_manager->default_cmyk;
break;
default:
break;
}
/* Have one increment from the color space. Having these tied
together is not really correct. Need to fix that. ToDo. MJV */
rc_adjust(picc_profile, -2, "seticc");
rc_increment(pcs->cmm_icc_profile_data);
}
/* Set the color space. We are done. No joint cache here... */
code = gs_setcolorspace(igs, pcs);
/* The context has taken a reference to the colorspace. We no longer need
* ours, so drop it. */
rc_decrement_only(pcs, "seticc");
/* In this case, we already have a ref count of 2 on the icc profile
one for when it was created and one for when it was set. We really
only want one here so adjust */
rc_decrement(picc_profile,"seticc");
/* Remove the ICC dict from the stack */
pop(1);
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'Bug #700169 - unchecked type
Bug #700169 "Type confusion in setcolorspace"
In seticc() we extract "Name" from a dictionary, if it succeeds we then
use it as a string, without checking the type to see if it is in fact
a string.
Add a check on the type, and add a couple to check that 'N' is an integer
in a few places too.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
return_error(gs_error_undefined);
check_read_file(i_ctx_p, s, pstrmval);
picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0);
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'Bug #700169 - unchecked type
Bug #700169 "Type confusion in setcolorspace"
In seticc() we extract "Name" from a dictionary, if it succeeds we then
use it as a string, without checking the type to see if it is in fact
a string.
Add a check on the type, and add a couple to check that 'N' is an integer
in a few places too.'</s> |
<s>[INST] Given the following code containing errors, provide 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 iccompareproc(i_ctx_t *i_ctx_p, ref *space, ref *testspace)
{
int code1, code2;
ref ICCdict1, ICCdict2, *tempref1, *tempref2;
int buff_size;
code1 = array_get(imemory, space, 1, &ICCdict1);
if (code1 < 0)
return 0;
code2 = array_get(imemory, testspace, 1, &ICCdict2);
if (code2 < 0)
return 0;
/* As a quick check see if current is same as new */
if (ICCdict1.value.bytes == ICCdict2.value.bytes)
return 1;
/* Need to check all the various parts */
code1 = dict_find_string(&ICCdict1, "N", &tempref1);
code2 = dict_find_string(&ICCdict2, "N", &tempref2);
if (code1 != code2)
return 0;
if (tempref1->value.intval != tempref2->value.intval)
return 0;
if (!comparedictkey(i_ctx_p, &ICCdict1, &ICCdict2, (char *)"Range"))
return 0;
code1 = dict_find_string(&ICCdict1, "DataSource", &tempref1);
if (code1 <= 0)
return 0;
code2 = dict_find_string(&ICCdict2, "DataSource", &tempref2);
if (code2 <= 0)
return 0;
if (r_size(tempref1) != r_size(tempref2))
return 0;
buff_size = r_size(tempref1);
if (memcmp(tempref1->value.const_bytes, tempref2->value.const_bytes, buff_size) == 0)
return 1;
else
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide 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 iccdomain(i_ctx_t * i_ctx_p, ref *space, float *ptr)
{
int components, i, code = 0;
ref *tempref, ICCdict, valref;
code = array_get(imemory, space, 1, &ICCdict);
if (code < 0)
return code;
code = dict_find_string(&ICCdict, "N", &tempref);
if (code < 0)
return code;
if (code == 0)
return gs_note_error(gs_error_undefined);
components = tempref->value.intval;
code = dict_find_string(&ICCdict, "Range", &tempref);
if (code > 0 && !r_has_type(tempref, t_null)) {
for (i=0;i<components * 2;i++) {
code = array_get(imemory, tempref, i, &valref);
if (code < 0)
return code;
if (r_has_type(&valref, t_integer))
ptr[i * 2] = (float)valref.value.intval;
else
ptr[i * 2] = valref.value.realval;
}
} else {
for (i=0;i<components;i++) {
ptr[i * 2] = 0;
ptr[(i * 2) + 1] = 1;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide 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 comparedictkey(i_ctx_t * i_ctx_p, ref *CIEdict1, ref *CIEdict2, char *key)
{
int code, code1;
ref *tempref1, *tempref2;
code = dict_find_string(CIEdict1, key, &tempref1);
code1 = dict_find_string(CIEdict2, key, &tempref2);
if (code != code1)
return 0;
if (code <= 0)
return 1;
if (r_type(tempref1) != r_type(tempref2))
return 0;
if (r_type(tempref1) == t_null)
return 1;
return comparearrays(i_ctx_p, tempref1, tempref2);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide 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 iccrange(i_ctx_t * i_ctx_p, ref *space, float *ptr)
{
int components, i, code = 0;
ref *tempref, ICCdict, valref;
code = array_get(imemory, space, 1, &ICCdict);
if (code < 0)
return code;
code = dict_find_string(&ICCdict, "N", &tempref);
if (code < 0)
return code;
if (code == 0)
return gs_note_error(gs_error_undefined);
components = tempref->value.intval;
code = dict_find_string(&ICCdict, "Range", &tempref);
if (code > 0 && !r_has_type(tempref, t_null)) {
for (i=0;i<components * 2;i++) {
code = array_get(imemory, tempref, i, &valref);
if (code < 0)
return code;
if (r_has_type(&valref, t_integer))
ptr[i] = (float)valref.value.intval;
else
ptr[i] = (float)valref.value.realval;
}
} else {
for (i=0;i<components;i++) {
ptr[i * 2] = 0;
ptr[(i * 2) + 1] = 1;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide 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 iccalternatespace(i_ctx_t * i_ctx_p, ref *space, ref **r, int *CIESubst)
{
int components, code = 0;
ref *tempref, ICCdict;
if (!r_is_array(space))
return_error(gs_error_typecheck);
/* Validate parameters, check we have enough operands */
if (r_size(space) != 2)
return_error(gs_error_rangecheck);
code = array_get(imemory, space, 1, &ICCdict);
if (code < 0)
return code;
code = dict_find_string(&ICCdict, "N", &tempref);
if (code < 0)
return code;
if (code == 0)
return gs_note_error(gs_error_undefined);
components = tempref->value.intval;
code = dict_find_string(&ICCdict, "Alternate", &tempref);
if (code > 0 && !r_has_type(tempref, t_null)) {
*r = tempref;
} else {
switch (components) {
case 1:
code = name_enter_string(imemory, "DeviceGray", *r);
break;
case 3:
code = name_enter_string(imemory, "DeviceRGB", *r);
break;
case 4:
code = name_enter_string(imemory, "DeviceCMYK", *r);
break;
default:
return_error(gs_error_rangecheck);
}
}
*CIESubst = 1;
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: z_jpx_decode(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
ref *sop = NULL;
ref *csname = NULL;
stream_jpxd_state state;
/* it's our responsibility to call set_defaults() */
state.memory = imemory->non_gc_memory;
if (s_jpxd_template.set_defaults)
(*s_jpxd_template.set_defaults)((stream_state *)&state);
if (r_has_type(op, t_dictionary)) {
check_dict_read(*op);
if ( dict_find_string(op, "Alpha", &sop) > 0) {
check_type(*sop, t_boolean);
if (sop->value.boolval)
state.alpha = true;
}
if ( dict_find_string(op, "ColorSpace", &sop) > 0) {
/* parse the value */
if (r_is_array(sop)) {
/* assume it's the first array element */
csname = sop->value.refs;
} else if (r_has_type(sop,t_name)) {
/* use the name directly */
csname = sop;
} else {
dmprintf(imemory, "warning: JPX ColorSpace value is an unhandled type!\n");
}
if (csname != NULL) {
ref sref;
/* get a reference to the name's string value */
name_string_ref(imemory, csname, &sref);
/* request raw index values if the colorspace is /Indexed */
if (!ISTRCMP(&sref, "Indexed"))
state.colorspace = gs_jpx_cs_indexed;
/* tell the filter what output we want for other spaces */
else if (!ISTRCMP(&sref, "DeviceGray"))
state.colorspace = gs_jpx_cs_gray;
else if (!ISTRCMP(&sref, "DeviceRGB"))
state.colorspace = gs_jpx_cs_rgb;
else if (!ISTRCMP(&sref, "DeviceCMYK"))
state.colorspace = gs_jpx_cs_cmyk;
else if (!ISTRCMP(&sref, "ICCBased")) {
/* The second array element should be the profile's
stream dict */
ref *csdict = sop->value.refs + 1;
ref *nref;
ref altname;
if (r_is_array(sop) && (r_size(sop) > 1) &&
r_has_type(csdict, t_dictionary)) {
check_dict_read(*csdict);
/* try to look up the alternate space */
if (dict_find_string(csdict, "Alternate", &nref) > 0) {
name_string_ref(imemory, csname, &altname);
if (!ISTRCMP(&altname, "DeviceGray"))
state.colorspace = gs_jpx_cs_gray;
else if (!ISTRCMP(&altname, "DeviceRGB"))
state.colorspace = gs_jpx_cs_rgb;
else if (!ISTRCMP(&altname, "DeviceCMYK"))
state.colorspace = gs_jpx_cs_cmyk;
}
/* else guess based on the number of components */
if (state.colorspace == gs_jpx_cs_unset &&
dict_find_string(csdict, "N", &nref) > 0) {
if_debug1m('w', imemory, "[w] JPX image has an external %"PRIpsint
" channel colorspace\n", nref->value.intval);
switch (nref->value.intval) {
case 1: state.colorspace = gs_jpx_cs_gray;
break;
case 3: state.colorspace = gs_jpx_cs_rgb;
break;
case 4: state.colorspace = gs_jpx_cs_cmyk;
break;
}
}
}
}
} else {
if_debug0m('w', imemory, "[w] Couldn't read JPX ColorSpace key!\n");
}
}
}
/* we pass npop=0, since we've no arguments left to consume */
/* we pass 0 instead of the usual rspace(sop) which will allocate storage
for filter state from the same memory pool as the stream it's coding.
this causes no trouble because we maintain no pointers */
return filter_read(i_ctx_p, 0, &s_jpxd_template,
(stream_state *) & state, 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zbuildfont0(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
gs_type0_data data;
ref fdepvector;
ref *pprefenc;
gs_font_type0 *pfont;
font_data *pdata;
ref save_FID;
int i;
int code = 0;
check_type(*op, t_dictionary);
{
ref *pfmaptype;
ref *pfdepvector;
if (dict_find_string(op, "FMapType", &pfmaptype) <= 0 ||
!r_has_type(pfmaptype, t_integer) ||
pfmaptype->value.intval < (int)fmap_type_min ||
pfmaptype->value.intval > (int)fmap_type_max ||
dict_find_string(op, "FDepVector", &pfdepvector) <= 0 ||
!r_is_array(pfdepvector)
)
return_error(gs_error_invalidfont);
data.FMapType = (fmap_type) pfmaptype->value.intval;
/*
* Adding elements below could cause the font dictionary to be
* resized, which would invalidate pfdepvector.
*/
fdepvector = *pfdepvector;
}
/* Check that every element of the FDepVector is a font. */
data.fdep_size = r_size(&fdepvector);
for (i = 0; i < data.fdep_size; i++) {
ref fdep;
gs_font *psub;
array_get(imemory, &fdepvector, i, &fdep);
if ((code = font_param(&fdep, &psub)) < 0)
return code;
/*
* Check the inheritance rules. Allowed configurations
* (paths from root font) are defined by the regular
* expression:
* (shift | double_escape escape* | escape*)
* non_modal* non_composite
*/
if (psub->FontType == ft_composite) {
const gs_font_type0 *const psub0 = (const gs_font_type0 *)psub;
fmap_type fmt = psub0->data.FMapType;
if (fmt == fmap_double_escape ||
fmt == fmap_shift ||
(fmt == fmap_escape &&
!(data.FMapType == fmap_escape ||
data.FMapType == fmap_double_escape))
)
return_error(gs_error_invalidfont);
}
}
switch (data.FMapType) {
case fmap_escape:
case fmap_double_escape: /* need EscChar */
code = ensure_char_entry(i_ctx_p, op, "EscChar", &data.EscChar, 255);
break;
case fmap_shift: /* need ShiftIn & ShiftOut */
code = ensure_char_entry(i_ctx_p, op, "ShiftIn", &data.ShiftIn, 15);
if (code >= 0)
code = ensure_char_entry(i_ctx_p, op, "ShiftOut", &data.ShiftOut, 14);
break;
case fmap_SubsVector: /* need SubsVector */
{
ref *psubsvector;
uint svsize;
if (dict_find_string(op, "SubsVector", &psubsvector) <= 0 ||
!r_has_type(psubsvector, t_string) ||
(svsize = r_size(psubsvector)) == 0 ||
(data.subs_width = (int)*psubsvector->value.bytes + 1) > 4 ||
(svsize - 1) % data.subs_width != 0
)
return_error(gs_error_invalidfont);
data.subs_size = (svsize - 1) / data.subs_width;
data.SubsVector.data = psubsvector->value.bytes + 1;
data.SubsVector.size = svsize - 1;
} break;
case fmap_CMap: /* need CMap */
code = ztype0_get_cmap(&data.CMap, (const ref *)&fdepvector,
(const ref *)op, imemory);
break;
default:
;
}
if (code < 0)
return code;
/*
* Save the old FID in case we have to back out.
* build_gs_font will return an error if there is a FID entry
* but it doesn't reference a valid font.
*/
{
ref *pfid;
if (dict_find_string(op, "FID", &pfid) <= 0)
make_null(&save_FID);
else
save_FID = *pfid;
}
{
build_proc_refs build;
code = build_proc_name_refs(imemory, &build,
"%Type0BuildChar", "%Type0BuildGlyph");
if (code < 0)
return code;
code = build_gs_font(i_ctx_p, op, (gs_font **) & pfont,
ft_composite, &st_gs_font_type0, &build,
bf_options_none);
}
if (code != 0)
return code;
/* Fill in the rest of the basic font data. */
pfont->procs.init_fstack = gs_type0_init_fstack;
pfont->procs.define_font = ztype0_define_font;
pfont->procs.make_font = ztype0_make_font;
pfont->procs.next_char_glyph = gs_type0_next_char_glyph;
pfont->procs.decode_glyph = gs_font_map_glyph_to_unicode; /* PDF needs. */
if (dict_find_string(op, "PrefEnc", &pprefenc) <= 0) {
ref nul;
make_null_new(&nul);
if ((code = idict_put_string(op, "PrefEnc", &nul)) < 0)
goto fail;
}
get_GlyphNames2Unicode(i_ctx_p, (gs_font *)pfont, op);
/* Fill in the font data */
pdata = pfont_data(pfont);
data.encoding_size = r_size(&pdata->Encoding);
/*
* Adobe interpreters apparently require that Encoding.size >= subs_size
* +1 (not sure whether the +1 only applies if the sum of the range
* sizes is less than the size of the code space). The gs library
* doesn't require this -- it only gives an error if a show operation
* actually would reference beyond the end of the Encoding -- so we
* check this here rather than in the library.
*/
if (data.FMapType == fmap_SubsVector) {
if (data.subs_size >= r_size(&pdata->Encoding)) {
code = gs_note_error(gs_error_rangecheck);
goto fail;
}
}
data.Encoding =
(uint *) ialloc_byte_array(data.encoding_size, sizeof(uint),
"buildfont0(Encoding)");
if (data.Encoding == 0) {
code = gs_note_error(gs_error_VMerror);
goto fail;
}
/* Fill in the encoding vector, checking to make sure that */
/* each element is an integer between 0 and fdep_size-1. */
for (i = 0; i < data.encoding_size; i++) {
ref enc;
array_get(imemory, &pdata->Encoding, i, &enc);
if (!r_has_type(&enc, t_integer)) {
code = gs_note_error(gs_error_typecheck);
goto fail;
}
if ((ulong) enc.value.intval >= data.fdep_size) {
code = gs_note_error(gs_error_rangecheck);
goto fail;
}
data.Encoding[i] = (uint) enc.value.intval;
}
data.FDepVector =
ialloc_struct_array(data.fdep_size, gs_font *,
&st_gs_font_ptr_element,
"buildfont0(FDepVector)");
if (data.FDepVector == 0) {
code = gs_note_error(gs_error_VMerror);
goto fail;
}
for (i = 0; i < data.fdep_size; i++) {
ref fdep;
ref *pfid;
array_get(pfont->memory, &fdepvector, i, &fdep);
/* The lookup can't fail, because of the pre-check above. */
dict_find_string(&fdep, "FID", &pfid);
data.FDepVector[i] = r_ptr(pfid, gs_font);
}
pfont->data = data;
code = define_gs_font(i_ctx_p, (gs_font *) pfont);
if (code >= 0)
return code;
fail:
/*
* Undo the insertion of the FID entry in the dictionary. Note that
* some allocations (Encoding, FDepVector) are not undone.
*/
if (r_has_type(&save_FID, t_null)) {
ref rnfid;
name_enter_string(pfont->memory, "FID", &rnfid);
idict_undef(op, &rnfid);
} else
idict_put_string(op, "FID", &save_FID);
gs_free_object(pfont->memory, pfont, "buildfont0(font)");
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zfont_info(gs_font *font, const gs_point *pscale, int members,
gs_font_info_t *info)
{
int code = gs_default_font_info(font, pscale, members &
~(FONT_INFO_COPYRIGHT | FONT_INFO_NOTICE |
FONT_INFO_FAMILY_NAME | FONT_INFO_FULL_NAME),
info);
const ref *pfdict;
ref *pfontinfo, *pvalue;
if (code < 0)
return code;
pfdict = &pfont_data(font)->dict;
if (dict_find_string(pfdict, "FontInfo", &pfontinfo) <= 0 ||
!r_has_type(pfontinfo, t_dictionary))
return 0;
if ((members & FONT_INFO_COPYRIGHT) &&
zfont_info_has(pfontinfo, "Copyright", &info->Copyright))
info->members |= FONT_INFO_COPYRIGHT;
if ((members & FONT_INFO_NOTICE) &&
zfont_info_has(pfontinfo, "Notice", &info->Notice))
info->members |= FONT_INFO_NOTICE;
if ((members & FONT_INFO_FAMILY_NAME) &&
zfont_info_has(pfontinfo, "FamilyName", &info->FamilyName))
info->members |= FONT_INFO_FAMILY_NAME;
if ((members & FONT_INFO_FULL_NAME) &&
zfont_info_has(pfontinfo, "FullName", &info->FullName))
info->members |= FONT_INFO_FULL_NAME;
if ((members & FONT_INFO_EMBEDDING_RIGHTS)
&& (dict_find_string(pfontinfo, "FSType", &pvalue) > 0)) {
info->EmbeddingRights = pvalue->value.intval;
info->members |= FONT_INFO_EMBEDDING_RIGHTS;
}
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking
These were 'probably' safe anyway, since they mostly treat the objects
as integers without checking, which at least can't result in a crash.
Nevertheless, we ought to check.
The return from comparedictkeys could be wrong if one of the keys had
a value which was not an array, it could incorrectly decide the two
were in fact the same.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nfsd4_verify_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
stateid_t *src_stateid, struct file **src,
stateid_t *dst_stateid, struct file **dst)
{
__be32 status;
status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->save_fh,
src_stateid, RD_STATE, src, NULL);
if (status) {
dprintk("NFSD: %s: couldn't process src stateid!\n", __func__);
goto out;
}
status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh,
dst_stateid, WR_STATE, dst, NULL);
if (status) {
dprintk("NFSD: %s: couldn't process dst stateid!\n", __func__);
goto out_put_src;
}
/* fix up for NFS-specific error code */
if (!S_ISREG(file_inode(*src)->i_mode) ||
!S_ISREG(file_inode(*dst)->i_mode)) {
status = nfserr_wrong_type;
goto out_put_dst;
}
out:
return status;
out_put_dst:
fput(*dst);
out_put_src:
fput(*src);
goto out;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'nfsd: COPY and CLONE operations require the saved filehandle to be set
Make sure we have a saved filehandle, otherwise we'll oops with a null
pointer dereference in nfs4_preprocess_stateid_op().
Signed-off-by: Scott Mayhew <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[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 iccompareproc(i_ctx_t *i_ctx_p, ref *space, ref *testspace)
{
int code1, code2;
ref ICCdict1, ICCdict2, *tempref1, *tempref2;
int buff_size;
code1 = array_get(imemory, space, 1, &ICCdict1);
if (code1 < 0)
return 0;
code2 = array_get(imemory, testspace, 1, &ICCdict2);
if (code2 < 0)
return 0;
/* As a quick check see if current is same as new */
if (ICCdict1.value.bytes == ICCdict2.value.bytes)
return 1;
/* Need to check all the various parts */
code1 = dict_find_string(&ICCdict1, "N", &tempref1);
code2 = dict_find_string(&ICCdict2, "N", &tempref2);
if (code1 != code2)
return 0;
if (tempref1->value.intval != tempref2->value.intval)
return 0;
if (!comparedictkey(i_ctx_p, &ICCdict1, &ICCdict2, (char *)"Range"))
return 0;
code1 = dict_find_string(&ICCdict1, "DataSource", &tempref1);
if (code1 <= 0)
return 0;
code2 = dict_find_string(&ICCdict2, "DataSource", &tempref2);
if (code2 <= 0)
return 0;
if (r_size(tempref1) != r_size(tempref2))
return 0;
buff_size = r_size(tempref1);
if (memcmp(tempref1->value.const_bytes, tempref2->value.const_bytes, buff_size) == 0)
return 1;
else
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - check the Implementation of a Pattern before use
Bug #700141 "Type confusion in setpattern"
As the bug thread says, we were not checking that the Implementation
of a pattern dictionary was a structure type, leading to a crash when
we tried to treat it as one.
Here we make the st_pattern1_instance and st_pattern2_instance
structures public definitions and in zsetcolor we check the object
stored under the Implementation key in the supplied dictionary to see if
its a t_struct or t_astruct type, and if it is that its a
st_pattern1_instance or st_pattern2_instance structure.
If either check fails we throw a typecheck error.
We need to make the st_pattern1_instance and st_pattern2_instance
definitions public as they are defined in the graphics library and we
need to check in the interpreter.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs)
{
gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern;
gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace;
int code;
uchar k, num_comps;
pinst->saved->overprint_mode = pgs->overprint_mode;
pinst->saved->overprint = pgs->overprint;
num_comps = pgs->device->color_info.num_components;
for (k = 0; k < num_comps; k++) {
pgs->color_component_map.color_map[k] =
pinst->saved->color_component_map.color_map[k];
}
code = pcs->type->set_overprint(pcs, pgs);
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - check the Implementation of a Pattern before use
Bug #700141 "Type confusion in setpattern"
As the bug thread says, we were not checking that the Implementation
of a pattern dictionary was a structure type, leading to a crash when
we tried to treat it as one.
Here we make the st_pattern1_instance and st_pattern2_instance
structures public definitions and in zsetcolor we check the object
stored under the Implementation key in the supplied dictionary to see if
its a t_struct or t_astruct type, and if it is that its a
st_pattern1_instance or st_pattern2_instance structure.
If either check fails we throw a typecheck error.
We need to make the st_pattern1_instance and st_pattern2_instance
definitions public as they are defined in the graphics library and we
need to check in the interpreter.'</s> |
<s>[INST] Given the following code containing errors, provide 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 sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
{
struct sock *newsk;
bool is_charged = true;
newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family);
if (newsk != NULL) {
struct sk_filter *filter;
sock_copy(newsk, sk);
/* SANITY */
if (likely(newsk->sk_net_refcnt))
get_net(sock_net(newsk));
sk_node_init(&newsk->sk_node);
sock_lock_init(newsk);
bh_lock_sock(newsk);
newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
newsk->sk_backlog.len = 0;
atomic_set(&newsk->sk_rmem_alloc, 0);
/*
* sk_wmem_alloc set to one (see sk_free() and sock_wfree())
*/
refcount_set(&newsk->sk_wmem_alloc, 1);
atomic_set(&newsk->sk_omem_alloc, 0);
sk_init_common(newsk);
newsk->sk_dst_cache = NULL;
newsk->sk_dst_pending_confirm = 0;
newsk->sk_wmem_queued = 0;
newsk->sk_forward_alloc = 0;
atomic_set(&newsk->sk_drops, 0);
newsk->sk_send_head = NULL;
newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
atomic_set(&newsk->sk_zckey, 0);
sock_reset_flag(newsk, SOCK_DONE);
filter = rcu_dereference_protected(newsk->sk_filter, 1);
if (filter != NULL)
/* though it's an empty new sock, the charging may fail
* if sysctl_optmem_max was changed between creation of
* original socket and cloning
*/
is_charged = sk_filter_charge(newsk, filter);
if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
/* We need to make sure that we don't uncharge the new
* socket if we couldn't charge it in the first place
* as otherwise we uncharge the parent's filter.
*/
if (!is_charged)
RCU_INIT_POINTER(newsk->sk_filter, NULL);
sk_free_unlock_clone(newsk);
newsk = NULL;
goto out;
}
RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
newsk->sk_err = 0;
newsk->sk_err_soft = 0;
newsk->sk_priority = 0;
newsk->sk_incoming_cpu = raw_smp_processor_id();
atomic64_set(&newsk->sk_cookie, 0);
mem_cgroup_sk_alloc(newsk);
cgroup_sk_alloc(&newsk->sk_cgrp_data);
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
refcount_set(&newsk->sk_refcnt, 2);
/*
* Increment the counter in the same struct proto as the master
* sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
* is the same as sk->sk_prot->socks, as this field was copied
* with memcpy).
*
* This _changes_ the previous behaviour, where
* tcp_create_openreq_child always was incrementing the
* equivalent to tcp_prot->socks (inet_sock_nr), so this have
* to be taken into account in all callers. -acme
*/
sk_refcnt_debug_inc(newsk);
sk_set_socket(newsk, NULL);
newsk->sk_wq = NULL;
if (newsk->sk_prot->sockets_allocated)
sk_sockets_allocated_inc(newsk);
if (sock_needs_netstamp(sk) &&
newsk->sk_flags & SK_FLAGS_TIMESTAMP)
net_enable_timestamp();
}
out:
return newsk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-704'], 'message': 'net: Set sk_prot_creator when cloning sockets to the right proto
sk->sk_prot and sk->sk_prot_creator can differ when the app uses
IPV6_ADDRFORM (transforming an IPv6-socket to an IPv4-one).
Which is why sk_prot_creator is there to make sure that sk_prot_free()
does the kmem_cache_free() on the right kmem_cache slab.
Now, if such a socket gets transformed back to a listening socket (using
connect() with AF_UNSPEC) we will allocate an IPv4 tcp_sock through
sk_clone_lock() when a new connection comes in. But sk_prot_creator will
still point to the IPv6 kmem_cache (as everything got copied in
sk_clone_lock()). When freeing, we will thus put this
memory back into the IPv6 kmem_cache although it was allocated in the
IPv4 cache. I have seen memory corruption happening because of this.
With slub-debugging and MEMCG_KMEM enabled this gives the warning
"cache_from_obj: Wrong slab cache. TCPv6 but object is from TCP"
A C-program to trigger this:
void main(void)
{
int fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
int new_fd, newest_fd, client_fd;
struct sockaddr_in6 bind_addr;
struct sockaddr_in bind_addr4, client_addr1, client_addr2;
struct sockaddr unsp;
int val;
memset(&bind_addr, 0, sizeof(bind_addr));
bind_addr.sin6_family = AF_INET6;
bind_addr.sin6_port = ntohs(42424);
memset(&client_addr1, 0, sizeof(client_addr1));
client_addr1.sin_family = AF_INET;
client_addr1.sin_port = ntohs(42424);
client_addr1.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&client_addr2, 0, sizeof(client_addr2));
client_addr2.sin_family = AF_INET;
client_addr2.sin_port = ntohs(42421);
client_addr2.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&unsp, 0, sizeof(unsp));
unsp.sa_family = AF_UNSPEC;
bind(fd, (struct sockaddr *)&bind_addr, sizeof(bind_addr));
listen(fd, 5);
client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(client_fd, (struct sockaddr *)&client_addr1, sizeof(client_addr1));
new_fd = accept(fd, NULL, NULL);
close(fd);
val = AF_INET;
setsockopt(new_fd, SOL_IPV6, IPV6_ADDRFORM, &val, sizeof(val));
connect(new_fd, &unsp, sizeof(unsp));
memset(&bind_addr4, 0, sizeof(bind_addr4));
bind_addr4.sin_family = AF_INET;
bind_addr4.sin_port = ntohs(42421);
bind(new_fd, (struct sockaddr *)&bind_addr4, sizeof(bind_addr4));
listen(new_fd, 5);
client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(client_fd, (struct sockaddr *)&client_addr2, sizeof(client_addr2));
newest_fd = accept(new_fd, NULL, NULL);
close(new_fd);
close(client_fd);
close(new_fd);
}
As far as I can see, this bug has been there since the beginning of the
git-days.
Signed-off-by: Christoph Paasch <[email protected]>
Reviewed-by: Eric Dumazet <[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: static void handle_rx(struct vhost_net *net)
{
struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
struct vhost_virtqueue *vq = &nvq->vq;
unsigned uninitialized_var(in), log;
struct vhost_log *vq_log;
struct msghdr msg = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_control = NULL, /* FIXME: get and handle RX aux data. */
.msg_controllen = 0,
.msg_flags = MSG_DONTWAIT,
};
struct virtio_net_hdr hdr = {
.flags = 0,
.gso_type = VIRTIO_NET_HDR_GSO_NONE
};
size_t total_len = 0;
int err, mergeable;
s16 headcount;
size_t vhost_hlen, sock_hlen;
size_t vhost_len, sock_len;
struct socket *sock;
struct iov_iter fixup;
__virtio16 num_buffers;
mutex_lock(&vq->mutex);
sock = vq->private_data;
if (!sock)
goto out;
if (!vq_iotlb_prefetch(vq))
goto out;
vhost_disable_notify(&net->dev, vq);
vhost_net_disable_vq(net, vq);
vhost_hlen = nvq->vhost_hlen;
sock_hlen = nvq->sock_hlen;
vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
vq->log : NULL;
mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
while ((sock_len = vhost_net_rx_peek_head_len(net, sock->sk))) {
sock_len += sock_hlen;
vhost_len = sock_len + vhost_hlen;
headcount = get_rx_bufs(vq, vq->heads, vhost_len,
&in, vq_log, &log,
likely(mergeable) ? UIO_MAXIOV : 1);
/* On error, stop handling until the next kick. */
if (unlikely(headcount < 0))
goto out;
/* OK, now we need to know about added descriptors. */
if (!headcount) {
if (unlikely(vhost_enable_notify(&net->dev, vq))) {
/* They have slipped one in as we were
* doing that: check again. */
vhost_disable_notify(&net->dev, vq);
continue;
}
/* Nothing new? Wait for eventfd to tell us
* they refilled. */
goto out;
}
if (nvq->rx_ring)
msg.msg_control = vhost_net_buf_consume(&nvq->rxq);
/* On overrun, truncate and discard */
if (unlikely(headcount > UIO_MAXIOV)) {
iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
err = sock->ops->recvmsg(sock, &msg,
1, MSG_DONTWAIT | MSG_TRUNC);
pr_debug("Discarded rx packet: len %zd\n", sock_len);
continue;
}
/* We don't need to be notified again. */
iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
fixup = msg.msg_iter;
if (unlikely((vhost_hlen))) {
/* We will supply the header ourselves
* TODO: support TSO.
*/
iov_iter_advance(&msg.msg_iter, vhost_hlen);
}
err = sock->ops->recvmsg(sock, &msg,
sock_len, MSG_DONTWAIT | MSG_TRUNC);
/* Userspace might have consumed the packet meanwhile:
* it's not supposed to do this usually, but might be hard
* to prevent. Discard data we got (if any) and keep going. */
if (unlikely(err != sock_len)) {
pr_debug("Discarded rx packet: "
" len %d, expected %zd\n", err, sock_len);
vhost_discard_vq_desc(vq, headcount);
continue;
}
/* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
if (unlikely(vhost_hlen)) {
if (copy_to_iter(&hdr, sizeof(hdr),
&fixup) != sizeof(hdr)) {
vq_err(vq, "Unable to write vnet_hdr "
"at addr %p\n", vq->iov->iov_base);
goto out;
}
} else {
/* Header came from socket; we'll need to patch
* ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
*/
iov_iter_advance(&fixup, sizeof(hdr));
}
/* TODO: Should check and handle checksum. */
num_buffers = cpu_to_vhost16(vq, headcount);
if (likely(mergeable) &&
copy_to_iter(&num_buffers, sizeof num_buffers,
&fixup) != sizeof num_buffers) {
vq_err(vq, "Failed num_buffers write");
vhost_discard_vq_desc(vq, headcount);
goto out;
}
vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
headcount);
if (unlikely(vq_log))
vhost_log_write(vq, vq_log, log, vhost_len);
total_len += vhost_len;
if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
vhost_poll_queue(&vq->poll);
goto out;
}
}
vhost_net_enable_vq(net, vq);
out:
mutex_unlock(&vq->mutex);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'vhost_net: batch used ring update in rx
This patch tries to batched used ring update during RX. This is pretty
fit for the case when guest is much faster (e.g dpdk based
backend). In this case, used ring is almost empty:
- we may get serious cache line misses/contending on both used ring
and used idx.
- at most 1 packet could be dequeued at one time, batching in guest
does not make much effect.
Update used ring in a batch can help since guest won't access the used
ring until used idx was advanced for several descriptors and since we
advance used ring for every N packets, guest will only need to access
used idx for every N packet since it can cache the used idx. To have a
better interaction for both batch dequeuing and dpdk batching,
VHOST_RX_BATCH was used as the maximum number of descriptors that
could be batched.
Test were done between two machines with 2.40GHz Intel(R) Xeon(R) CPU
E5-2630 connected back to back through ixgbe. Traffic were generated
on one remote ixgbe through MoonGen and measure the RX pps through
testpmd in guest when do xdp_redirect_map from local ixgbe to
tap. RX pps were increased from 3.05 Mpps to 4.00 Mpps (about 31%
improvement).
One possible concern for this is the implications for TCP (especially
latency sensitive workload). Result[1] does not show obvious changes
for most of the netperf test (RR, TX, and RX). And we do get some
improvements for RX on some specific size.
Guest RX:
size/sessions/+thu%/+normalize%
64/ 1/ +2%/ +2%
64/ 2/ +2%/ -1%
64/ 4/ +1%/ +1%
64/ 8/ 0%/ 0%
256/ 1/ +6%/ -3%
256/ 2/ -3%/ +2%
256/ 4/ +11%/ +11%
256/ 8/ 0%/ 0%
512/ 1/ +4%/ 0%
512/ 2/ +2%/ +2%
512/ 4/ 0%/ -1%
512/ 8/ -8%/ -8%
1024/ 1/ -7%/ -17%
1024/ 2/ -8%/ -7%
1024/ 4/ +1%/ 0%
1024/ 8/ 0%/ 0%
2048/ 1/ +30%/ +14%
2048/ 2/ +46%/ +40%
2048/ 4/ 0%/ 0%
2048/ 8/ 0%/ 0%
4096/ 1/ +23%/ +22%
4096/ 2/ +26%/ +23%
4096/ 4/ 0%/ +1%
4096/ 8/ 0%/ 0%
16384/ 1/ -2%/ -3%
16384/ 2/ +1%/ -4%
16384/ 4/ -1%/ -3%
16384/ 8/ 0%/ -1%
65535/ 1/ +15%/ +7%
65535/ 2/ +4%/ +7%
65535/ 4/ 0%/ +1%
65535/ 8/ 0%/ 0%
TCP_RR:
size/sessions/+thu%/+normalize%
1/ 1/ 0%/ +1%
1/ 25/ +2%/ +1%
1/ 50/ +4%/ +1%
64/ 1/ 0%/ -4%
64/ 25/ +2%/ +1%
64/ 50/ 0%/ -1%
256/ 1/ 0%/ 0%
256/ 25/ 0%/ 0%
256/ 50/ +4%/ +2%
Guest TX:
size/sessions/+thu%/+normalize%
64/ 1/ +4%/ -2%
64/ 2/ -6%/ -5%
64/ 4/ +3%/ +6%
64/ 8/ 0%/ +3%
256/ 1/ +15%/ +16%
256/ 2/ +11%/ +12%
256/ 4/ +1%/ 0%
256/ 8/ +5%/ +5%
512/ 1/ -1%/ -6%
512/ 2/ 0%/ -8%
512/ 4/ -2%/ +4%
512/ 8/ +6%/ +9%
1024/ 1/ +3%/ +1%
1024/ 2/ +3%/ +9%
1024/ 4/ 0%/ +7%
1024/ 8/ 0%/ +7%
2048/ 1/ +8%/ +2%
2048/ 2/ +3%/ -1%
2048/ 4/ -1%/ +11%
2048/ 8/ +3%/ +9%
4096/ 1/ +8%/ +8%
4096/ 2/ 0%/ -7%
4096/ 4/ +4%/ +4%
4096/ 8/ +2%/ +5%
16384/ 1/ -3%/ +1%
16384/ 2/ -1%/ -12%
16384/ 4/ -1%/ +5%
16384/ 8/ 0%/ +1%
65535/ 1/ 0%/ -3%
65535/ 2/ +5%/ +16%
65535/ 4/ +1%/ +2%
65535/ 8/ +1%/ -1%
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[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: static void handle_rx(struct vhost_net *net)
{
struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
struct vhost_virtqueue *vq = &nvq->vq;
unsigned uninitialized_var(in), log;
struct vhost_log *vq_log;
struct msghdr msg = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_control = NULL, /* FIXME: get and handle RX aux data. */
.msg_controllen = 0,
.msg_flags = MSG_DONTWAIT,
};
struct virtio_net_hdr hdr = {
.flags = 0,
.gso_type = VIRTIO_NET_HDR_GSO_NONE
};
size_t total_len = 0;
int err, mergeable;
s16 headcount, nheads = 0;
size_t vhost_hlen, sock_hlen;
size_t vhost_len, sock_len;
struct socket *sock;
struct iov_iter fixup;
__virtio16 num_buffers;
mutex_lock_nested(&vq->mutex, 0);
sock = vq->private_data;
if (!sock)
goto out;
if (!vq_iotlb_prefetch(vq))
goto out;
vhost_disable_notify(&net->dev, vq);
vhost_net_disable_vq(net, vq);
vhost_hlen = nvq->vhost_hlen;
sock_hlen = nvq->sock_hlen;
vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
vq->log : NULL;
mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
while ((sock_len = vhost_net_rx_peek_head_len(net, sock->sk))) {
sock_len += sock_hlen;
vhost_len = sock_len + vhost_hlen;
headcount = get_rx_bufs(vq, vq->heads + nheads, vhost_len,
&in, vq_log, &log,
likely(mergeable) ? UIO_MAXIOV : 1);
/* On error, stop handling until the next kick. */
if (unlikely(headcount < 0))
goto out;
/* OK, now we need to know about added descriptors. */
if (!headcount) {
if (unlikely(vhost_enable_notify(&net->dev, vq))) {
/* They have slipped one in as we were
* doing that: check again. */
vhost_disable_notify(&net->dev, vq);
continue;
}
/* Nothing new? Wait for eventfd to tell us
* they refilled. */
goto out;
}
if (nvq->rx_ring)
msg.msg_control = vhost_net_buf_consume(&nvq->rxq);
/* On overrun, truncate and discard */
if (unlikely(headcount > UIO_MAXIOV)) {
iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
err = sock->ops->recvmsg(sock, &msg,
1, MSG_DONTWAIT | MSG_TRUNC);
pr_debug("Discarded rx packet: len %zd\n", sock_len);
continue;
}
/* We don't need to be notified again. */
iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
fixup = msg.msg_iter;
if (unlikely((vhost_hlen))) {
/* We will supply the header ourselves
* TODO: support TSO.
*/
iov_iter_advance(&msg.msg_iter, vhost_hlen);
}
err = sock->ops->recvmsg(sock, &msg,
sock_len, MSG_DONTWAIT | MSG_TRUNC);
/* Userspace might have consumed the packet meanwhile:
* it's not supposed to do this usually, but might be hard
* to prevent. Discard data we got (if any) and keep going. */
if (unlikely(err != sock_len)) {
pr_debug("Discarded rx packet: "
" len %d, expected %zd\n", err, sock_len);
vhost_discard_vq_desc(vq, headcount);
continue;
}
/* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
if (unlikely(vhost_hlen)) {
if (copy_to_iter(&hdr, sizeof(hdr),
&fixup) != sizeof(hdr)) {
vq_err(vq, "Unable to write vnet_hdr "
"at addr %p\n", vq->iov->iov_base);
goto out;
}
} else {
/* Header came from socket; we'll need to patch
* ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
*/
iov_iter_advance(&fixup, sizeof(hdr));
}
/* TODO: Should check and handle checksum. */
num_buffers = cpu_to_vhost16(vq, headcount);
if (likely(mergeable) &&
copy_to_iter(&num_buffers, sizeof num_buffers,
&fixup) != sizeof num_buffers) {
vq_err(vq, "Failed num_buffers write");
vhost_discard_vq_desc(vq, headcount);
goto out;
}
nheads += headcount;
if (nheads > VHOST_RX_BATCH) {
vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
nheads);
nheads = 0;
}
if (unlikely(vq_log))
vhost_log_write(vq, vq_log, log, vhost_len);
total_len += vhost_len;
if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
vhost_poll_queue(&vq->poll);
goto out;
}
}
vhost_net_enable_vq(net, vq);
out:
if (nheads)
vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
nheads);
mutex_unlock(&vq->mutex);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'vhost_net: flush batched heads before trying to busy polling
After commit e2b3b35eb989 ("vhost_net: batch used ring update in rx"),
we tend to batch updating used heads. But it doesn't flush batched
heads before trying to do busy polling, this will cause vhost to wait
for guest TX which waits for the used RX. Fixing by flush batched
heads before busy loop.
1 byte TCP_RR performance recovers from 13107.83 to 50402.65.
Fixes: e2b3b35eb989 ("vhost_net: batch used ring update in rx")
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[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: static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
strlcpy(rcipher.type, "cipher", sizeof(rcipher.type));
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[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 crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_akcipher rakcipher;
strlcpy(rakcipher.type, "akcipher", sizeof(rakcipher.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,
sizeof(struct crypto_report_akcipher), &rakcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[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 crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_kpp rkpp;
strlcpy(rkpp.type, "kpp", sizeof(rkpp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_KPP,
sizeof(struct crypto_report_kpp), &rkpp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[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 jas_image_readcmpt(jas_image_t *image, int cmptno, jas_image_coord_t x,
jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
jas_matrix_t *data)
{
jas_image_cmpt_t *cmpt;
jas_image_coord_t i;
jas_image_coord_t j;
int k;
jas_seqent_t v;
int c;
jas_seqent_t *dr;
jas_seqent_t *d;
int drs;
JAS_DBGLOG(100, ("jas_image_readcmpt(%p, %d, %ld, %ld, %ld, %ld, %p)\n",
image, cmptno, JAS_CAST(long, x), JAS_CAST(long, y),
JAS_CAST(long, width), JAS_CAST(long, height), data));
if (cmptno < 0 || cmptno >= image->numcmpts_) {
return -1;
}
cmpt = image->cmpts_[cmptno];
if (x >= cmpt->width_ || y >= cmpt->height_ ||
x + width > cmpt->width_ ||
y + height > cmpt->height_) {
return -1;
}
if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) {
return -1;
}
if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
if (jas_matrix_resize(data, height, width)) {
return -1;
}
}
dr = jas_matrix_getref(data, 0, 0);
drs = jas_matrix_rowstep(data);
for (i = 0; i < height; ++i, dr += drs) {
d = dr;
if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
* cmpt->cps_, SEEK_SET) < 0) {
return -1;
}
for (j = width; j > 0; --j, ++d) {
v = 0;
for (k = cmpt->cps_; k > 0; --k) {
if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
return -1;
}
v = (v << 8) | (c & 0xff);
}
*d = bitstoint(v, cmpt->prec_, cmpt->sgnd_);
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'Check data in jas_image
Regarding CVE-2018-19539.
Fix by Markus Koschany <[email protected]>.
From https://gist.github.com/apoleon/7c0f3a0c28437c18fee8a51b1aa16164.'</s> |
<s>[INST] Given the following code containing errors, provide 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 dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset);
if (n == 0)
goto err;
dest += n;
nb_bytes += n;
goto out;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'BUG: dns: Prevent stack-exhaustion via recursion loop in dns_read_name
When a compressed pointer is encountered, dns_read_name() will call
itself with the pointed-to offset in the packet.
With a specially crafted packet, it was possible to trigger an
infinite-loop recursion by making the pointer points to itself.
While it would be possible to handle that particular case differently
by making sure that the target is different from the current offset,
it would still be possible to craft a packet with a very long chain
of valid pointers, always pointing backwards. To prevent a stack
exhaustion in that case, this patch restricts the number of recursive
calls to 100, which should be more than enough.
To be backported to 1.8, probably also 1.7.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
{
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
int req_pack_id = -1;
sg_io_hdr_t *hp;
struct sg_header *old_hdr = NULL;
int retval = 0;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_read: count=%d\n", (int) count));
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
if (sfp->force_packid && (count >= SZ_SG_HEADER)) {
old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
if (!old_hdr)
return -ENOMEM;
if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
if (old_hdr->reply_len < 0) {
if (count >= SZ_SG_IO_HDR) {
sg_io_hdr_t *new_hdr;
new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);
if (!new_hdr) {
retval = -ENOMEM;
goto free_old_hdr;
}
retval =__copy_from_user
(new_hdr, buf, SZ_SG_IO_HDR);
req_pack_id = new_hdr->pack_id;
kfree(new_hdr);
if (retval) {
retval = -EFAULT;
goto free_old_hdr;
}
}
} else
req_pack_id = old_hdr->pack_id;
}
srp = sg_get_rq_mark(sfp, req_pack_id);
if (!srp) { /* now wait on packet to arrive */
if (atomic_read(&sdp->detaching)) {
retval = -ENODEV;
goto free_old_hdr;
}
if (filp->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto free_old_hdr;
}
retval = wait_event_interruptible(sfp->read_wait,
(atomic_read(&sdp->detaching) ||
(srp = sg_get_rq_mark(sfp, req_pack_id))));
if (atomic_read(&sdp->detaching)) {
retval = -ENODEV;
goto free_old_hdr;
}
if (retval) {
/* -ERESTARTSYS as signal hit process */
goto free_old_hdr;
}
}
if (srp->header.interface_id != '\0') {
retval = sg_new_read(sfp, buf, count, srp);
goto free_old_hdr;
}
hp = &srp->header;
if (old_hdr == NULL) {
old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
if (! old_hdr) {
retval = -ENOMEM;
goto free_old_hdr;
}
}
memset(old_hdr, 0, SZ_SG_HEADER);
old_hdr->reply_len = (int) hp->timeout;
old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */
old_hdr->pack_id = hp->pack_id;
old_hdr->twelve_byte =
((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
old_hdr->target_status = hp->masked_status;
old_hdr->host_status = hp->host_status;
old_hdr->driver_status = hp->driver_status;
if ((CHECK_CONDITION & hp->masked_status) ||
(DRIVER_SENSE & hp->driver_status))
memcpy(old_hdr->sense_buffer, srp->sense_b,
sizeof (old_hdr->sense_buffer));
switch (hp->host_status) {
/* This setup of 'result' is for backward compatibility and is best
ignored by the user who should use target, host + driver status */
case DID_OK:
case DID_PASSTHROUGH:
case DID_SOFT_ERROR:
old_hdr->result = 0;
break;
case DID_NO_CONNECT:
case DID_BUS_BUSY:
case DID_TIME_OUT:
old_hdr->result = EBUSY;
break;
case DID_BAD_TARGET:
case DID_ABORT:
case DID_PARITY:
case DID_RESET:
case DID_BAD_INTR:
old_hdr->result = EIO;
break;
case DID_ERROR:
old_hdr->result = (srp->sense_b[0] == 0 &&
hp->masked_status == GOOD) ? 0 : EIO;
break;
default:
old_hdr->result = EIO;
break;
}
/* Now copy the result back to the user buffer. */
if (count >= SZ_SG_HEADER) {
if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
buf += SZ_SG_HEADER;
if (count > old_hdr->reply_len)
count = old_hdr->reply_len;
if (count > SZ_SG_HEADER) {
if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
}
} else
count = (old_hdr->result == 0) ? 0 : -EIO;
sg_finish_rem_req(srp);
retval = count;
free_old_hdr:
kfree(old_hdr);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-732'], 'message': 'ANDROID: scsi: Add segment checking in sg_read
Bug: 65023233
Signed-off-by: Roberto Pereira <[email protected]>
Change-Id: I91b6b5dbcea7c39643beffdc12a23ee3d8f8775d'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
{
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
int req_pack_id = -1;
sg_io_hdr_t *hp;
struct sg_header *old_hdr = NULL;
int retval = 0;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_read: count=%d\n", (int) count));
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
if (sfp->force_packid && (count >= SZ_SG_HEADER)) {
old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
if (!old_hdr)
return -ENOMEM;
if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
if (old_hdr->reply_len < 0) {
if (count >= SZ_SG_IO_HDR) {
sg_io_hdr_t *new_hdr;
new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);
if (!new_hdr) {
retval = -ENOMEM;
goto free_old_hdr;
}
retval =__copy_from_user
(new_hdr, buf, SZ_SG_IO_HDR);
req_pack_id = new_hdr->pack_id;
kfree(new_hdr);
if (retval) {
retval = -EFAULT;
goto free_old_hdr;
}
}
} else
req_pack_id = old_hdr->pack_id;
}
srp = sg_get_rq_mark(sfp, req_pack_id);
if (!srp) { /* now wait on packet to arrive */
if (atomic_read(&sdp->detaching)) {
retval = -ENODEV;
goto free_old_hdr;
}
if (filp->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto free_old_hdr;
}
retval = wait_event_interruptible(sfp->read_wait,
(atomic_read(&sdp->detaching) ||
(srp = sg_get_rq_mark(sfp, req_pack_id))));
if (atomic_read(&sdp->detaching)) {
retval = -ENODEV;
goto free_old_hdr;
}
if (retval) {
/* -ERESTARTSYS as signal hit process */
goto free_old_hdr;
}
}
if (srp->header.interface_id != '\0') {
retval = sg_new_read(sfp, buf, count, srp);
goto free_old_hdr;
}
hp = &srp->header;
if (old_hdr == NULL) {
old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
if (! old_hdr) {
retval = -ENOMEM;
goto free_old_hdr;
}
}
memset(old_hdr, 0, SZ_SG_HEADER);
old_hdr->reply_len = (int) hp->timeout;
old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */
old_hdr->pack_id = hp->pack_id;
old_hdr->twelve_byte =
((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
old_hdr->target_status = hp->masked_status;
old_hdr->host_status = hp->host_status;
old_hdr->driver_status = hp->driver_status;
if ((CHECK_CONDITION & hp->masked_status) ||
(DRIVER_SENSE & hp->driver_status))
memcpy(old_hdr->sense_buffer, srp->sense_b,
sizeof (old_hdr->sense_buffer));
switch (hp->host_status) {
/* This setup of 'result' is for backward compatibility and is best
ignored by the user who should use target, host + driver status */
case DID_OK:
case DID_PASSTHROUGH:
case DID_SOFT_ERROR:
old_hdr->result = 0;
break;
case DID_NO_CONNECT:
case DID_BUS_BUSY:
case DID_TIME_OUT:
old_hdr->result = EBUSY;
break;
case DID_BAD_TARGET:
case DID_ABORT:
case DID_PARITY:
case DID_RESET:
case DID_BAD_INTR:
old_hdr->result = EIO;
break;
case DID_ERROR:
old_hdr->result = (srp->sense_b[0] == 0 &&
hp->masked_status == GOOD) ? 0 : EIO;
break;
default:
old_hdr->result = EIO;
break;
}
/* Now copy the result back to the user buffer. */
if (count >= SZ_SG_HEADER) {
if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
buf += SZ_SG_HEADER;
if (count > old_hdr->reply_len)
count = old_hdr->reply_len;
if (count > SZ_SG_HEADER) {
if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
}
} else
count = (old_hdr->result == 0) ? 0 : -EIO;
sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
retval = count;
free_old_hdr:
kfree(old_hdr);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-732'], 'message': 'scsi: sg: mitigate read/write abuse
As Al Viro noted in commit 128394eff343 ("sg_write()/bsg_write() is not fit
to be called under KERNEL_DS"), sg improperly accesses userspace memory
outside the provided buffer, permitting kernel memory corruption via
splice(). But it doesn't just do it on ->write(), also on ->read().
As a band-aid, make sure that the ->read() and ->write() handlers can not
be called in weird contexts (kernel context or credentials different from
file opener), like for ib_safe_file_access().
If someone needs to use these interfaces from different security contexts,
a new interface should be written that goes through the ->ioctl() handler.
I've mostly copypasted ib_safe_file_access() over as sg_safe_file_access()
because I couldn't find a good common header - please tell me if you know a
better way.
[mkp: s/_safe_/_check_/]
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: <[email protected]>
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Douglas Gilbert <[email protected]>
Signed-off-by: Martin K. Petersen <[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: wav_write_header (SF_PRIVATE *psf, int calc_length)
{ sf_count_t current ;
int error, has_data = SF_FALSE ;
current = psf_ftell (psf) ;
if (current > psf->dataoffset)
has_data = SF_TRUE ;
if (calc_length)
{ psf->filelength = psf_get_filelen (psf) ;
psf->datalength = psf->filelength - psf->dataoffset ;
if (psf->dataend)
psf->datalength -= psf->filelength - psf->dataend ;
else if (psf->bytewidth > 0 && psf->sf.seekable == SF_TRUE)
psf->datalength = psf->sf.frames * psf->bytewidth * psf->sf.channels ;
} ;
/* Reset the current header length to zero. */
psf->header.ptr [0] = 0 ;
psf->header.indx = 0 ;
psf_fseek (psf, 0, SEEK_SET) ;
/*
** RIFX signifies big-endian format for all header and data.
** To prevent lots of code copying here, we'll set the psf->rwf_endian flag
** once here, and never specify endian-ness for all other header operations.
*/
/* RIFF/RIFX marker, length, WAVE and 'fmt ' markers. */
if (psf->endian == SF_ENDIAN_LITTLE)
psf_binheader_writef (psf, "etm8", BHWm (RIFF_MARKER), BHW8 ((psf->filelength < 8) ? 8 : psf->filelength - 8)) ;
else
psf_binheader_writef (psf, "Etm8", BHWm (RIFX_MARKER), BHW8 ((psf->filelength < 8) ? 8 : psf->filelength - 8)) ;
/* WAVE and 'fmt ' markers. */
psf_binheader_writef (psf, "mm", BHWm (WAVE_MARKER), BHWm (fmt_MARKER)) ;
/* Write the 'fmt ' chunk. */
switch (SF_CONTAINER (psf->sf.format))
{ case SF_FORMAT_WAV :
if ((error = wav_write_fmt_chunk (psf)) != 0)
return error ;
break ;
case SF_FORMAT_WAVEX :
if ((error = wavex_write_fmt_chunk (psf)) != 0)
return error ;
break ;
default :
return SFE_UNIMPLEMENTED ;
} ;
/* The LIST/INFO chunk. */
if (psf->strings.flags & SF_STR_LOCATE_START)
wavlike_write_strings (psf, SF_STR_LOCATE_START) ;
if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_START)
wavlike_write_peak_chunk (psf) ;
if (psf->broadcast_16k != NULL)
wavlike_write_bext_chunk (psf) ;
if (psf->cart_16k != NULL)
wavlike_write_cart_chunk (psf) ;
if (psf->cues != NULL)
{ uint32_t k ;
psf_binheader_writef (psf, "em44", BHWm (cue_MARKER), BHW4 (4 + psf->cues->cue_count * 6 * 4), BHW4 (psf->cues->cue_count)) ;
for (k = 0 ; k < psf->cues->cue_count ; k++)
psf_binheader_writef (psf, "e44m444", BHW4 (psf->cues->cue_points [k].indx), BHW4 (psf->cues->cue_points [k].position),
BHWm (psf->cues->cue_points [k].fcc_chunk), BHW4 (psf->cues->cue_points [k].chunk_start),
BHW4 (psf->cues->cue_points [k].block_start), BHW4 (psf->cues->cue_points [k].sample_offset)) ;
} ;
if (psf->instrument != NULL)
{ int tmp ;
double dtune = (double) (0x40000000) / 25.0 ;
psf_binheader_writef (psf, "m4", BHWm (smpl_MARKER), BHW4 (9 * 4 + psf->instrument->loop_count * 6 * 4)) ;
psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (0)) ; /* Manufacturer zero is everyone */
tmp = (int) (1.0e9 / psf->sf.samplerate) ; /* Sample period in nano seconds */
psf_binheader_writef (psf, "44", BHW4 (tmp), BHW4 (psf->instrument->basenote)) ;
tmp = (uint32_t) (psf->instrument->detune * dtune + 0.5) ;
psf_binheader_writef (psf, "4", BHW4 (tmp)) ;
psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (0)) ; /* SMTPE format */
psf_binheader_writef (psf, "44", BHW4 (psf->instrument->loop_count), BHW4 (0)) ;
for (tmp = 0 ; tmp < psf->instrument->loop_count ; tmp++)
{ int type ;
type = psf->instrument->loops [tmp].mode ;
type = (type == SF_LOOP_FORWARD ? 0 : type == SF_LOOP_BACKWARD ? 2 : type == SF_LOOP_ALTERNATING ? 1 : 32) ;
psf_binheader_writef (psf, "44", BHW4 (tmp), BHW4 (type)) ;
psf_binheader_writef (psf, "44", BHW4 (psf->instrument->loops [tmp].start), BHW4 (psf->instrument->loops [tmp].end - 1)) ;
psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (psf->instrument->loops [tmp].count)) ;
} ;
} ;
/* Write custom headers. */
if (psf->wchunks.used > 0)
wavlike_write_custom_chunks (psf) ;
if (psf->header.indx + 16 < psf->dataoffset)
{ /* Add PAD data if necessary. */
size_t k = psf->dataoffset - (psf->header.indx + 16) ;
psf_binheader_writef (psf, "m4z", BHWm (PAD_MARKER), BHW4 (k), BHWz (k)) ;
} ;
psf_binheader_writef (psf, "tm8", BHWm (data_MARKER), BHW8 (psf->datalength)) ;
psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
if (psf->error)
return psf->error ;
if (has_data && psf->dataoffset != psf->header.indx)
{ psf_log_printf (psf, "Oooops : has_data && psf->dataoffset != psf->header.indx\n") ;
return psf->error = SFE_INTERNAL ;
} ;
psf->dataoffset = psf->header.indx ;
if (! has_data)
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
else if (current > 0)
psf_fseek (psf, current, SEEK_SET) ;
return psf->error ;
} /* wav_write_header */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'src/wav.c: Fix heap read overflow
This is CVE-2018-19758.
Closes: https://github.com/erikd/libsndfile/issues/435'</s> |
<s>[INST] Given the following code containing errors, provide 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 hwahc_security_create(struct hwahc *hwahc)
{
int result;
struct wusbhc *wusbhc = &hwahc->wusbhc;
struct usb_device *usb_dev = hwahc->wa.usb_dev;
struct device *dev = &usb_dev->dev;
struct usb_security_descriptor *secd;
struct usb_encryption_descriptor *etd;
void *itr, *top;
size_t itr_size, needed, bytes;
u8 index;
char buf[64];
/* Find the host's security descriptors in the config descr bundle */
index = (usb_dev->actconfig - usb_dev->config) /
sizeof(usb_dev->config[0]);
itr = usb_dev->rawdescriptors[index];
itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength);
top = itr + itr_size;
result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index],
le16_to_cpu(usb_dev->actconfig->desc.wTotalLength),
USB_DT_SECURITY, (void **) &secd);
if (result == -1) {
dev_warn(dev, "BUG? WUSB host has no security descriptors\n");
return 0;
}
needed = sizeof(*secd);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptor header (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
needed = le16_to_cpu(secd->wTotalLength);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptors (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
/* Walk over the sec descriptors and store CCM1's on wusbhc */
itr = (void *) secd + sizeof(*secd);
top = (void *) secd + le16_to_cpu(secd->wTotalLength);
index = 0;
bytes = 0;
while (itr < top) {
etd = itr;
if (top - itr < sizeof(*etd)) {
dev_err(dev, "BUG: bad host security descriptor; "
"not enough data (%zu vs %zu left)\n",
top - itr, sizeof(*etd));
break;
}
if (etd->bLength < sizeof(*etd)) {
dev_err(dev, "BUG: bad host encryption descriptor; "
"descriptor is too short "
"(%zu vs %zu needed)\n",
(size_t)etd->bLength, sizeof(*etd));
break;
}
itr += etd->bLength;
bytes += snprintf(buf + bytes, sizeof(buf) - bytes,
"%s (0x%02x) ",
wusb_et_name(etd->bEncryptionType),
etd->bEncryptionValue);
wusbhc->ccm1_etd = etd;
}
dev_info(dev, "supported encryption types: %s\n", buf);
if (wusbhc->ccm1_etd == NULL) {
dev_err(dev, "E: host doesn't support CCM-1 crypto\n");
return 0;
}
/* Pretty print what we support */
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[])
{
int i;
int port_tmp;
for(i=1; i<argc; i++){
if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){
if(i<argc-1){
db->config_file = argv[i+1];
if(config__read(db, config, false)){
log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file.");
return MOSQ_ERR_INVAL;
}
}else{
log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified.");
return MOSQ_ERR_INVAL;
}
i++;
}else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){
config->daemon = true;
}else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){
print_usage();
return MOSQ_ERR_INVAL;
}else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
if(i<argc-1){
port_tmp = atoi(argv[i+1]);
if(port_tmp<1 || port_tmp>65535){
log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp);
return MOSQ_ERR_INVAL;
}else{
if(config->default_listener.port){
log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used.");
}
config->default_listener.port = port_tmp;
}
}else{
log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified.");
return MOSQ_ERR_INVAL;
}
i++;
}else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
db->verbose = true;
}else{
fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
print_usage();
return MOSQ_ERR_INVAL;
}
}
if(config->listener_count == 0
#ifdef WITH_TLS
|| config->default_listener.cafile
|| config->default_listener.capath
|| config->default_listener.certfile
|| config->default_listener.keyfile
|| config->default_listener.ciphers
|| config->default_listener.psk_hint
|| config->default_listener.require_certificate
|| config->default_listener.crlfile
|| config->default_listener.use_identity_as_username
|| config->default_listener.use_subject_as_username
#endif
|| config->default_listener.use_username_as_clientid
|| config->default_listener.host
|| config->default_listener.port
|| config->default_listener.max_connections != -1
|| config->default_listener.mount_point
|| config->default_listener.protocol != mp_mqtt
|| config->default_listener.socket_domain
|| config->default_listener.security_options.password_file
|| config->default_listener.security_options.psk_file
|| config->default_listener.security_options.auth_plugin_config_count
|| config->default_listener.security_options.allow_anonymous != -1
){
config->listener_count++;
config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count);
if(!config->listeners){
log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory.");
return MOSQ_ERR_NOMEM;
}
memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener));
if(config->default_listener.port){
config->listeners[config->listener_count-1].port = config->default_listener.port;
}else{
config->listeners[config->listener_count-1].port = 1883;
}
if(config->default_listener.host){
config->listeners[config->listener_count-1].host = config->default_listener.host;
}else{
config->listeners[config->listener_count-1].host = NULL;
}
if(config->default_listener.mount_point){
config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point;
}else{
config->listeners[config->listener_count-1].mount_point = NULL;
}
config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections;
config->listeners[config->listener_count-1].protocol = config->default_listener.protocol;
config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain;
config->listeners[config->listener_count-1].client_count = 0;
config->listeners[config->listener_count-1].socks = NULL;
config->listeners[config->listener_count-1].sock_count = 0;
config->listeners[config->listener_count-1].client_count = 0;
config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid;
#ifdef WITH_TLS
config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version;
config->listeners[config->listener_count-1].cafile = config->default_listener.cafile;
config->listeners[config->listener_count-1].capath = config->default_listener.capath;
config->listeners[config->listener_count-1].certfile = config->default_listener.certfile;
config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile;
config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers;
config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint;
config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate;
config->listeners[config->listener_count-1].ssl_ctx = NULL;
config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile;
config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username;
config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username;
#endif
config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file;
config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file;
config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs;
config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count;
config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous;
}
/* Default to drop to mosquitto user if we are privileged and no user specified. */
if(!config->user){
config->user = "mosquitto";
}
if(db->verbose){
config->log_type = INT_MAX;
}
return config__check(config);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-732', 'CWE-254'], 'message': 'Fix acl_file being ignore for default listener if with per_listener_settings
Close #1073. Thanks to Jef Driesen.
Bug: https://github.com/eclipse/mosquitto/issues/1073'</s> |
<s>[INST] Given the following code containing errors, provide 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 *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)
{
char *buffer=NULL;
int n=0;
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL);
/*
rfbLog("rfbProcessFileTransferReadBuffer(%dlen)\n", length);
*/
if (length>0) {
buffer=malloc(length+1);
if (buffer!=NULL) {
if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessFileTransferReadBuffer: read");
rfbCloseClient(cl);
/* NOTE: don't forget to free(buffer) if you return early! */
if (buffer!=NULL) free(buffer);
return NULL;
}
/* Null Terminate */
buffer[length]=0;
}
}
return buffer;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCServer: fix heap out-of-bound write access
Closes #243'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CloseUndoneFileDownload(rfbClientPtr cl, rfbTightClientPtr rtcp)
{
if(cl == NULL)
return;
if(rtcp->rcft.rcfd.downloadInProgress == TRUE) {
rtcp->rcft.rcfd.downloadInProgress = FALSE;
if(rtcp->rcft.rcfd.downloadFD != -1) {
close(rtcp->rcft.rcfd.downloadFD);
rtcp->rcft.rcfd.downloadFD = -1;
}
memset(rtcp->rcft.rcfd.fName, 0 , PATH_MAX);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'tightvnc-filetransfer: wait for download thread end in CloseUndoneFileDownload()
...and use it when deregistering the file transfer extension.
Closes #242'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length))
return FALSE;
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: fix three possible heap buffer overflows
An attacker could feed `0xffffffff`, causing a `malloc(0)` for the
buffers which are subsequently written to.
Closes #247'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh)
{
rfbRREHeader hdr;
int i;
CARDBPP pix;
uint8_t *ptr;
int x, y, w, h;
if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader))
return FALSE;
hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects);
if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix)))
return FALSE;
client->GotFillRect(client, rx, ry, rw, rh, pix);
if (hdr.nSubrects * (4 + (BPP / 8)) > RFB_BUFFER_SIZE || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8))))
return FALSE;
ptr = (uint8_t *)client->buffer;
for (i = 0; i < hdr.nSubrects; i++) {
pix = *(CARDBPP *)ptr;
ptr += BPP/8;
x = *ptr++;
y = *ptr++;
w = *ptr++;
h = *ptr++;
client->GotFillRect(client, rx+x, ry+y, w, h, pix);
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: really fix #250'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
linesToRead = RFB_BUFFER_SIZE / bytesPerLine;
while (h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
CopyRectangle(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
} break;
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
if (client->GotCopyRect != NULL) {
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
} else
CopyRectangleFromRectangle(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
#ifdef LIBVNCSERVER_CONFIG_LIBVA
case rfbEncodingH264:
{
if (!HandleH264(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length))
return FALSE;
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'Avoid divide-by-zero in raw encoding (OSX RealVNC)
OS X RealVNC server crashes out Remmina because the server can provoke
bytesPerLine to be zero. Assume this is coding for zero lines.
The condition could be checked before the calculation of bytesPerLine.
I don’t understand the preconditions of this code to say one way or the
other.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665'], 'message': 'LibVNCClient: don't leak uninitialised memory to remote
The pad fields of the rfbClientCutTextMsg and rfbKeyEventMsg could contain arbitray memory belonging to the process,
don't leak this to the remote.
Closes #252'</s> |
<s>[INST] Given the following code containing errors, provide 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 *repeaterHost;
int repeaterPort, sock;
char id[250];
rfbClientPtr cl;
int i,j;
uint16_t* f;
/* Parse command-line arguments */
if (argc < 3) {
fprintf(stderr,
"Usage: %s <id> <repeater-host> [<repeater-port>]\n", argv[0]);
exit(1);
}
snprintf(id, sizeof(id) - 1, "ID:%s", argv[1]);
repeaterHost = argv[2];
repeaterPort = argc < 4 ? 5500 : atoi(argv[3]);
/* The initialization is identical to simple15.c */
rfbScreenInfoPtr server=rfbGetScreen(&argc,argv,400,300,5,3,2);
if(!server)
return 0;
server->frameBuffer=(char*)malloc(400*300*2);
f=(uint16_t*)server->frameBuffer;
for(j=0;j<300;j++)
for(i=0;i<400;i++)
f[j*400+i]=/* red */ ((j*32/300) << 10) |
/* green */ (((j+400-i)*32/700) << 5) |
/* blue */ ((i*32/400));
/* Now for the repeater-specific part: */
server->port = -1; /* do not listen on any port */
server->ipv6port = -1; /* do not listen on any port */
sock = rfbConnectToTcpAddr(repeaterHost, repeaterPort);
if (sock < 0) {
perror("connect to repeater");
return 1;
}
if (write(sock, id, sizeof(id)) != sizeof(id)) {
perror("writing id");
return 1;
}
cl = rfbNewClient(server, sock);
if (!cl) {
perror("new client");
return 1;
}
cl->reverseConnection = 0;
cl->clientGoneHook = clientGone;
/* Run the server */
rfbInitServer(server);
rfbRunEventLoop(server,-1,FALSE);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665'], 'message': 'When connecting to a repeater, only send initialised string
Closes #253'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: HandleUltraBPP (rfbClient* client, int rx, int ry, int rw, int rh)
{
rfbZlibHeader hdr;
int toRead=0;
int inflateResult=0;
lzo_uint uncompressedBytes = (( rw * rh ) * ( BPP / 8 ));
if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbZlibHeader))
return FALSE;
toRead = rfbClientSwap32IfLE(hdr.nBytes);
if (toRead==0) return TRUE;
if (uncompressedBytes==0)
{
rfbClientLog("ultra error: rectangle has 0 uncomressed bytes ((%dw * %dh) * (%d / 8))\n", rw, rh, BPP);
return FALSE;
}
/* First make sure we have a large enough raw buffer to hold the
* decompressed data. In practice, with a fixed BPP, fixed frame
* buffer size and the first update containing the entire frame
* buffer, this buffer allocation should only happen once, on the
* first update.
*/
if ( client->raw_buffer_size < (int)uncompressedBytes) {
if ( client->raw_buffer != NULL ) {
free( client->raw_buffer );
}
client->raw_buffer_size = uncompressedBytes;
/* buffer needs to be aligned on 4-byte boundaries */
if ((client->raw_buffer_size % 4)!=0)
client->raw_buffer_size += (4-(client->raw_buffer_size % 4));
client->raw_buffer = (char*) malloc( client->raw_buffer_size );
}
/* allocate enough space to store the incoming compressed packet */
if ( client->ultra_buffer_size < toRead ) {
if ( client->ultra_buffer != NULL ) {
free( client->ultra_buffer );
}
client->ultra_buffer_size = toRead;
/* buffer needs to be aligned on 4-byte boundaries */
if ((client->ultra_buffer_size % 4)!=0)
client->ultra_buffer_size += (4-(client->ultra_buffer_size % 4));
client->ultra_buffer = (char*) malloc( client->ultra_buffer_size );
}
/* Fill the buffer, obtaining data from the server. */
if (!ReadFromRFBServer(client, client->ultra_buffer, toRead))
return FALSE;
/* uncompress the data */
uncompressedBytes = client->raw_buffer_size;
inflateResult = lzo1x_decompress_safe(
(lzo_byte *)client->ultra_buffer, toRead,
(lzo_byte *)client->raw_buffer, (lzo_uintp) &uncompressedBytes,
NULL);
/* Note that uncompressedBytes will be 0 on output overrun */
if ((rw * rh * (BPP / 8)) != uncompressedBytes)
rfbClientLog("Ultra decompressed unexpected amount of data (%d != %d)\n", (rw * rh * (BPP / 8)), uncompressedBytes);
/* Put the uncompressed contents of the update on the screen. */
if ( inflateResult == LZO_E_OK )
{
client->GotBitmap(client, (unsigned char *)client->raw_buffer, rx, ry, rw, rh);
}
else
{
rfbClientLog("ultra decompress returned error: %d\n",
inflateResult);
return FALSE;
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'LibVNCClient: make sure Ultra decoding cannot dereference a null pointer
Closes #254'</s> |
<s>[INST] Given the following code containing errors, provide 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 WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
// most options that don't apply to DSD we can simply ignore for now, but NOT hybrid mode!
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
// with DSD, very few PCM options work (or make sense), so only allow those that do
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
// all of this stuff only applies to PCM
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
// if a channel-identities string was specified, process that here, otherwise all channels
// not present in the channel mask are considered "unassigned"
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
// skip past channels that are specified in the channel mask (no reason to store those)
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
// now scan the string for an actually defined channel (and don't store if there aren't any)
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
// This loop goes through all the channels and creates the Wavpack "streams" for them to go in.
// A stream can hold either one or two channels, so we have several rules to determine how many
// channels will go in each stream.
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
// allocate the stream and initialize the pointer to it
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
// if there are any bits [still] set in the channel_mask, get the next one or two IDs from there
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
// next check for any channels identified in the channel-identities string
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
// assume anything we did not get is "unassigned"
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
// if we have 2 channels, this is where we decide if we can combine them into one stream:
// 1. they are "unassigned" and we've been told to combine unassigned pairs, or
// 2. they appear together in the valid "pairings" list
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'issue #53: error out on zero sample rate'</s> |
<s>[INST] Given the following code containing errors, provide 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 remove_trailing_spaces(char *string, size_t len)
{
if(len<1) return; // not needed, b/c sizeof of make/model is 64
string[len-1]=0;
if(len<3) return; // also not needed
len = strnlen(string,len-1);
for(int i=len-1; i>=0; i--)
{
if(isspace(string[i]))
string[i]=0;
else
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw
Secunia 81800#2: find_green
Secunia 81800#3: rollei_load_raw
remove_trailing_spaces: isspace() does not works right with signed non-latin chars
Secunia 81800#5/6: nikon_coolscan_load_raw
Secunia 81800#4: rollei_load_raw'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS rollei_load_raw()
{
uchar pixel[10];
unsigned iten=0, isix, i, buffer=0, todo[16];
isix = raw_width * raw_height * 5 / 8;
while (fread (pixel, 1, 10, ifp) == 10) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (i=0; i < 10; i+=2) {
todo[i] = iten++;
todo[i+1] = pixel[i] << 8 | pixel[i+1];
buffer = pixel[i] >> 2 | buffer << 6;
}
for ( ; i < 16; i+=2) {
todo[i] = isix++;
todo[i+1] = buffer >> (14-i)*5;
}
for (i=0; i < 16; i+=2)
raw_image[todo[i]] = (todo[i+1] & 0x3ff);
}
maximum = 0x3ff;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw
Secunia 81800#2: find_green
Secunia 81800#3: rollei_load_raw
remove_trailing_spaces: isspace() does not works right with signed non-latin chars
Secunia 81800#5/6: nikon_coolscan_load_raw
Secunia 81800#4: rollei_load_raw'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS nikon_coolscan_load_raw()
{
int bufsize = width*3*tiff_bps/8;
if(tiff_bps <= 8)
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);
else
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);
fseek (ifp, data_offset, SEEK_SET);
unsigned char *buf = (unsigned char*)malloc(bufsize);
unsigned short *ubuf = (unsigned short *)buf;
for(int row = 0; row < raw_height; row++)
{
int red = fread (buf, 1, bufsize, ifp);
unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width;
if(tiff_bps <= 8)
for(int col=0; col<width;col++)
{
ip[col][0] = curve[buf[col*3]];
ip[col][1] = curve[buf[col*3+1]];
ip[col][2] = curve[buf[col*3+2]];
ip[col][3]=0;
}
else
for(int col=0; col<width;col++)
{
ip[col][0] = curve[ubuf[col*3]];
ip[col][1] = curve[ubuf[col*3+1]];
ip[col][2] = curve[ubuf[col*3+2]];
ip[col][3]=0;
}
}
free(buf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw
Secunia 81800#2: find_green
Secunia 81800#3: rollei_load_raw
remove_trailing_spaces: isspace() does not works right with signed non-latin chars
Secunia 81800#5/6: nikon_coolscan_load_raw
Secunia 81800#4: rollei_load_raw'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) ||
!strncasecmp(model, "KODAK P712", 10))
{
if (tag == 0xf90b)
{
imgdata.makernotes.kodak.clipBlack = get2();
}
else if (tag == 0xf90c)
{
imgdata.makernotes.kodak.clipWhite = get2();
}
}
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) ||
!strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0045)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2);
break;
case 0x20400612:
case 0x30000612:
imgdata.sizes.raw_crop.cleft = get2();
break;
case 0x20400613:
case 0x30000613:
imgdata.sizes.raw_crop.ctop = get2();
break;
case 0x20400614:
case 0x30000614:
imgdata.sizes.raw_crop.cwidth = get2();
break;
case 0x20400615:
case 0x30000615:
imgdata.sizes.raw_crop.cheight = get2();
break;
case 0x20401112:
imgdata.makernotes.olympus.OlympusCropID = get2();
break;
case 0x20401113:
FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2();
break;
case 0x20100201:
{
unsigned long long oly_lensid[3];
oly_lensid[0] = fgetc(ifp);
fgetc(ifp);
oly_lensid[1] = fgetc(ifp);
oly_lensid[2] = fgetc(ifp);
imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2];
}
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f;
}
else if (tag == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
fseek(ifp, _pos, SEEK_SET);
#endif
if (tag == 2 && strstr(make, "NIKON") && !iso_speed)
iso_speed = (get2(), get2());
if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = int(100.0 * libraw_powf64l(2.0f, float(cc) / 12.0 - 5.0));
}
if (tag == 4 && len > 26 && len < 35)
{
if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535))
iso_speed = 50 * libraw_powf64l(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = libraw_powf64l(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = libraw_powf64l(2.0, (short)i / -32.0);
wbi = (get2(), get2());
shot_order = (get2(), get2());
}
if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6))
{
fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR);
switch (get2())
{
case 72:
flip = 0;
break;
case 76:
flip = 6;
break;
case 82:
flip = 5;
break;
}
}
if (tag == 7 && type == 2 && len > 20)
fgets(model2, 64, ifp);
if (tag == 8 && type == 4)
shot_order = get4();
if (tag == 9 && !strncmp(make, "Canon", 5))
fread(artist, 64, 1, ifp);
if (tag == 0xc && len == 4)
FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
if (tag == 0xd && type == 7 && get2() == 0xaaaa)
{
#if 0 /* Canon rotation data is handled by EXIF.Orientation */
for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++)
c = c << 8 | fgetc(ifp);
while ((i += 4) < len - 5)
if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3)
flip = "065"[c] - '0';
#endif
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x10 && type == 4)
unique_id = get4();
#endif
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos2 = ftell(ifp);
if (!strncasecmp(make, "Olympus", 7))
{
short nWB, tWB;
if ((tag == 0x20300108) || (tag == 0x20310109))
imgdata.makernotes.olympus.ColorSpace = get2();
if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5)))
{
int i;
for (i = 0; i < 64; i++)
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] =
imgdata.color.WB_Coeffs[i][3] = 0x100;
for (i = 64; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
nWB = tag - 0x20400101;
tWB = Oly_wb_list2[nWB << 1];
ushort CT = Oly_wb_list2[(nWB << 1) | 1];
int wb[4];
wb[0] = get2();
wb[2] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = wb[0];
imgdata.color.WB_Coeffs[tWB][2] = wb[2];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT;
imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0];
imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2];
}
if (len == 4)
{
wb[1] = get2();
wb[3] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][1] = wb[1];
imgdata.color.WB_Coeffs[tWB][3] = wb[3];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1];
imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3];
}
}
}
if ((tag >= 0x20400112) && (tag <= 0x2040011e))
{
nWB = tag - 0x20400112;
int wbG = get2();
tWB = Oly_wb_list2[nWB << 1];
if (nWB)
imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG;
if (tWB != 0x100)
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG;
}
if (tag == 0x20400121)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
if (len == 4)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2();
}
}
if (tag == 0x2040011f)
{
int wbG = get2();
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG;
FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] =
wbG;
}
if ((tag == 0x30000110) && strcmp(software, "v757-71"))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2();
if (len == 2)
{
for (int i = 0; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
}
if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) &&
strcmp(software, "v757-71"))
{
int wb_ind;
if (tag <= 0x30000124)
wb_ind = tag - 0x30000120;
else
wb_ind = tag - 0x30000130 + 5;
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2();
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2();
}
if ((tag == 0x20400805) && (len == 2))
{
imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type);
imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type);
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0];
}
if (tag == 0x20200306)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
if (tag == 0x20200307)
{
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'possible buffer overrun in Fuji makernotes parser'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'Fixed Secunia Advisory SA86384
- possible infinite loop in unpacked_load_raw()
- possible infinite loop in parse_rollei()
- possible infinite loop in parse_sinar_ia()
Credits: Laurent Delosieres, Secunia Research at Flexera'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: print_help (void)
{
#ifndef TESTING
/* We split the help text this way to ease translation of individual
entries. */
static const char *help[] = {
"\n",
N_("\
Mandatory arguments to long options are mandatory for short options too.\n\n"),
N_("\
Startup:\n"),
N_("\
-V, --version display the version of Wget and exit\n"),
N_("\
-h, --help print this help\n"),
N_("\
-b, --background go to background after startup\n"),
N_("\
-e, --execute=COMMAND execute a `.wgetrc'-style command\n"),
"\n",
N_("\
Logging and input file:\n"),
N_("\
-o, --output-file=FILE log messages to FILE\n"),
N_("\
-a, --append-output=FILE append messages to FILE\n"),
#ifdef ENABLE_DEBUG
N_("\
-d, --debug print lots of debugging information\n"),
#endif
#ifdef USE_WATT32
N_("\
--wdebug print Watt-32 debug output\n"),
#endif
N_("\
-q, --quiet quiet (no output)\n"),
N_("\
-v, --verbose be verbose (this is the default)\n"),
N_("\
-nv, --no-verbose turn off verboseness, without being quiet\n"),
N_("\
--report-speed=TYPE output bandwidth as TYPE. TYPE can be bits\n"),
N_("\
-i, --input-file=FILE download URLs found in local or external FILE\n"),
#ifdef HAVE_METALINK
N_("\
--input-metalink=FILE download files covered in local Metalink FILE\n"),
#endif
N_("\
-F, --force-html treat input file as HTML\n"),
N_("\
-B, --base=URL resolves HTML input-file links (-i -F)\n\
relative to URL\n"),
N_("\
--config=FILE specify config file to use\n"),
N_("\
--no-config do not read any config file\n"),
N_("\
--rejected-log=FILE log reasons for URL rejection to FILE\n"),
"\n",
N_("\
Download:\n"),
N_("\
-t, --tries=NUMBER set number of retries to NUMBER (0 unlimits)\n"),
N_("\
--retry-connrefused retry even if connection is refused\n"),
N_("\
--retry-on-http-error=ERRORS comma-separated list of HTTP errors to retry\n"),
N_("\
-O, --output-document=FILE write documents to FILE\n"),
N_("\
-nc, --no-clobber skip downloads that would download to\n\
existing files (overwriting them)\n"),
N_("\
--no-netrc don't try to obtain credentials from .netrc\n"),
N_("\
-c, --continue resume getting a partially-downloaded file\n"),
N_("\
--start-pos=OFFSET start downloading from zero-based position OFFSET\n"),
N_("\
--progress=TYPE select progress gauge type\n"),
N_("\
--show-progress display the progress bar in any verbosity mode\n"),
N_("\
-N, --timestamping don't re-retrieve files unless newer than\n\
local\n"),
N_("\
--no-if-modified-since don't use conditional if-modified-since get\n\
requests in timestamping mode\n"),
N_("\
--no-use-server-timestamps don't set the local file's timestamp by\n\
the one on the server\n"),
N_("\
-S, --server-response print server response\n"),
N_("\
--spider don't download anything\n"),
N_("\
-T, --timeout=SECONDS set all timeout values to SECONDS\n"),
#ifdef HAVE_LIBCARES
N_("\
--dns-servers=ADDRESSES list of DNS servers to query (comma separated)\n"),
N_("\
--bind-dns-address=ADDRESS bind DNS resolver to ADDRESS (hostname or IP) on local host\n"),
#endif
N_("\
--dns-timeout=SECS set the DNS lookup timeout to SECS\n"),
N_("\
--connect-timeout=SECS set the connect timeout to SECS\n"),
N_("\
--read-timeout=SECS set the read timeout to SECS\n"),
N_("\
-w, --wait=SECONDS wait SECONDS between retrievals\n"),
N_("\
--waitretry=SECONDS wait 1..SECONDS between retries of a retrieval\n"),
N_("\
--random-wait wait from 0.5*WAIT...1.5*WAIT secs between retrievals\n"),
N_("\
--no-proxy explicitly turn off proxy\n"),
N_("\
-Q, --quota=NUMBER set retrieval quota to NUMBER\n"),
N_("\
--bind-address=ADDRESS bind to ADDRESS (hostname or IP) on local host\n"),
N_("\
--limit-rate=RATE limit download rate to RATE\n"),
N_("\
--no-dns-cache disable caching DNS lookups\n"),
N_("\
--restrict-file-names=OS restrict chars in file names to ones OS allows\n"),
N_("\
--ignore-case ignore case when matching files/directories\n"),
#ifdef ENABLE_IPV6
N_("\
-4, --inet4-only connect only to IPv4 addresses\n"),
N_("\
-6, --inet6-only connect only to IPv6 addresses\n"),
N_("\
--prefer-family=FAMILY connect first to addresses of specified family,\n\
one of IPv6, IPv4, or none\n"),
#endif
N_("\
--user=USER set both ftp and http user to USER\n"),
N_("\
--password=PASS set both ftp and http password to PASS\n"),
N_("\
--ask-password prompt for passwords\n"),
N_("\
--use-askpass=COMMAND specify credential handler for requesting \n\
username and password. If no COMMAND is \n\
specified the WGET_ASKPASS or the SSH_ASKPASS \n\
environment variable is used.\n"),
N_("\
--no-iri turn off IRI support\n"),
N_("\
--local-encoding=ENC use ENC as the local encoding for IRIs\n"),
N_("\
--remote-encoding=ENC use ENC as the default remote encoding\n"),
N_("\
--unlink remove file before clobber\n"),
#ifdef HAVE_METALINK
N_("\
--keep-badhash keep files with checksum mismatch (append .badhash)\n"),
N_("\
--metalink-index=NUMBER Metalink application/metalink4+xml metaurl ordinal NUMBER\n"),
N_("\
--metalink-over-http use Metalink metadata from HTTP response headers\n"),
N_("\
--preferred-location preferred location for Metalink resources\n"),
#endif
#ifdef ENABLE_XATTR
N_("\
--no-xattr turn off storage of metadata in extended file attributes\n"),
#endif
"\n",
N_("\
Directories:\n"),
N_("\
-nd, --no-directories don't create directories\n"),
N_("\
-x, --force-directories force creation of directories\n"),
N_("\
-nH, --no-host-directories don't create host directories\n"),
N_("\
--protocol-directories use protocol name in directories\n"),
N_("\
-P, --directory-prefix=PREFIX save files to PREFIX/..\n"),
N_("\
--cut-dirs=NUMBER ignore NUMBER remote directory components\n"),
"\n",
N_("\
HTTP options:\n"),
N_("\
--http-user=USER set http user to USER\n"),
N_("\
--http-password=PASS set http password to PASS\n"),
N_("\
--no-cache disallow server-cached data\n"),
N_ ("\
--default-page=NAME change the default page name (normally\n\
this is 'index.html'.)\n"),
N_("\
-E, --adjust-extension save HTML/CSS documents with proper extensions\n"),
N_("\
--ignore-length ignore 'Content-Length' header field\n"),
N_("\
--header=STRING insert STRING among the headers\n"),
#ifdef HAVE_LIBZ
N_("\
--compression=TYPE choose compression, one of auto, gzip and none. (default: none)\n"),
#endif
N_("\
--max-redirect maximum redirections allowed per page\n"),
N_("\
--proxy-user=USER set USER as proxy username\n"),
N_("\
--proxy-password=PASS set PASS as proxy password\n"),
N_("\
--referer=URL include 'Referer: URL' header in HTTP request\n"),
N_("\
--save-headers save the HTTP headers to file\n"),
N_("\
-U, --user-agent=AGENT identify as AGENT instead of Wget/VERSION\n"),
N_("\
--no-http-keep-alive disable HTTP keep-alive (persistent connections)\n"),
N_("\
--no-cookies don't use cookies\n"),
N_("\
--load-cookies=FILE load cookies from FILE before session\n"),
N_("\
--save-cookies=FILE save cookies to FILE after session\n"),
N_("\
--keep-session-cookies load and save session (non-permanent) cookies\n"),
N_("\
--post-data=STRING use the POST method; send STRING as the data\n"),
N_("\
--post-file=FILE use the POST method; send contents of FILE\n"),
N_("\
--method=HTTPMethod use method \"HTTPMethod\" in the request\n"),
N_("\
--body-data=STRING send STRING as data. --method MUST be set\n"),
N_("\
--body-file=FILE send contents of FILE. --method MUST be set\n"),
N_("\
--content-disposition honor the Content-Disposition header when\n\
choosing local file names (EXPERIMENTAL)\n"),
N_("\
--content-on-error output the received content on server errors\n"),
N_("\
--auth-no-challenge send Basic HTTP authentication information\n\
without first waiting for the server's\n\
challenge\n"),
"\n",
#ifdef HAVE_SSL
N_("\
HTTPS (SSL/TLS) options:\n"),
N_("\
--secure-protocol=PR choose secure protocol, one of auto, SSLv2,\n\
SSLv3, TLSv1, TLSv1_1, TLSv1_2 and PFS\n"),
N_("\
--https-only only follow secure HTTPS links\n"),
N_("\
--no-check-certificate don't validate the server's certificate\n"),
N_("\
--certificate=FILE client certificate file\n"),
N_("\
--certificate-type=TYPE client certificate type, PEM or DER\n"),
N_("\
--private-key=FILE private key file\n"),
N_("\
--private-key-type=TYPE private key type, PEM or DER\n"),
N_("\
--ca-certificate=FILE file with the bundle of CAs\n"),
N_("\
--ca-directory=DIR directory where hash list of CAs is stored\n"),
N_("\
--crl-file=FILE file with bundle of CRLs\n"),
N_("\
--pinnedpubkey=FILE/HASHES Public key (PEM/DER) file, or any number\n\
of base64 encoded sha256 hashes preceded by\n\
\'sha256//\' and separated by \';\', to verify\n\
peer against\n"),
#if defined(HAVE_LIBSSL) || defined(HAVE_LIBSSL32)
N_("\
--random-file=FILE file with random data for seeding the SSL PRNG\n"),
#endif
#if (defined(HAVE_LIBSSL) || defined(HAVE_LIBSSL32)) && defined(HAVE_RAND_EGD)
N_("\
--egd-file=FILE file naming the EGD socket with random data\n"),
#endif
"\n",
N_("\
--ciphers=STR Set the priority string (GnuTLS) or cipher list string (OpenSSL) directly.\n\
Use with care. This option overrides --secure-protocol.\n\
The format and syntax of this string depend on the specific SSL/TLS engine.\n"),
#endif /* HAVE_SSL */
#ifdef HAVE_HSTS
N_("\
HSTS options:\n"),
N_("\
--no-hsts disable HSTS\n"),
N_("\
--hsts-file path of HSTS database (will override default)\n"),
"\n",
#endif
N_("\
FTP options:\n"),
#ifdef __VMS
N_("\
--ftp-stmlf use Stream_LF format for all binary FTP files\n"),
#endif /* def __VMS */
N_("\
--ftp-user=USER set ftp user to USER\n"),
N_("\
--ftp-password=PASS set ftp password to PASS\n"),
N_("\
--no-remove-listing don't remove '.listing' files\n"),
N_("\
--no-glob turn off FTP file name globbing\n"),
N_("\
--no-passive-ftp disable the \"passive\" transfer mode\n"),
N_("\
--preserve-permissions preserve remote file permissions\n"),
N_("\
--retr-symlinks when recursing, get linked-to files (not dir)\n"),
"\n",
#ifdef HAVE_SSL
N_("\
FTPS options:\n"),
N_("\
--ftps-implicit use implicit FTPS (default port is 990)\n"),
N_("\
--ftps-resume-ssl resume the SSL/TLS session started in the control connection when\n"
" opening a data connection\n"),
N_("\
--ftps-clear-data-connection cipher the control channel only; all the data will be in plaintext\n"),
N_("\
--ftps-fallback-to-ftp fall back to FTP if FTPS is not supported in the target server\n"),
#endif
N_("\
WARC options:\n"),
N_("\
--warc-file=FILENAME save request/response data to a .warc.gz file\n"),
N_("\
--warc-header=STRING insert STRING into the warcinfo record\n"),
N_("\
--warc-max-size=NUMBER set maximum size of WARC files to NUMBER\n"),
N_("\
--warc-cdx write CDX index files\n"),
N_("\
--warc-dedup=FILENAME do not store records listed in this CDX file\n"),
#ifdef HAVE_LIBZ
N_("\
--no-warc-compression do not compress WARC files with GZIP\n"),
#endif
N_("\
--no-warc-digests do not calculate SHA1 digests\n"),
N_("\
--no-warc-keep-log do not store the log file in a WARC record\n"),
N_("\
--warc-tempdir=DIRECTORY location for temporary files created by the\n\
WARC writer\n"),
"\n",
N_("\
Recursive download:\n"),
N_("\
-r, --recursive specify recursive download\n"),
N_("\
-l, --level=NUMBER maximum recursion depth (inf or 0 for infinite)\n"),
N_("\
--delete-after delete files locally after downloading them\n"),
N_("\
-k, --convert-links make links in downloaded HTML or CSS point to\n\
local files\n"),
N_("\
--convert-file-only convert the file part of the URLs only (usually known as the basename)\n"),
N_("\
--backups=N before writing file X, rotate up to N backup files\n"),
#ifdef __VMS
N_("\
-K, --backup-converted before converting file X, back up as X_orig\n"),
#else /* def __VMS */
N_("\
-K, --backup-converted before converting file X, back up as X.orig\n"),
#endif /* def __VMS [else] */
N_("\
-m, --mirror shortcut for -N -r -l inf --no-remove-listing\n"),
N_("\
-p, --page-requisites get all images, etc. needed to display HTML page\n"),
N_("\
--strict-comments turn on strict (SGML) handling of HTML comments\n"),
"\n",
N_("\
Recursive accept/reject:\n"),
N_("\
-A, --accept=LIST comma-separated list of accepted extensions\n"),
N_("\
-R, --reject=LIST comma-separated list of rejected extensions\n"),
N_("\
--accept-regex=REGEX regex matching accepted URLs\n"),
N_("\
--reject-regex=REGEX regex matching rejected URLs\n"),
#if defined HAVE_LIBPCRE || defined HAVE_LIBPCRE2
N_("\
--regex-type=TYPE regex type (posix|pcre)\n"),
#else
N_("\
--regex-type=TYPE regex type (posix)\n"),
#endif
N_("\
-D, --domains=LIST comma-separated list of accepted domains\n"),
N_("\
--exclude-domains=LIST comma-separated list of rejected domains\n"),
N_("\
--follow-ftp follow FTP links from HTML documents\n"),
N_("\
--follow-tags=LIST comma-separated list of followed HTML tags\n"),
N_("\
--ignore-tags=LIST comma-separated list of ignored HTML tags\n"),
N_("\
-H, --span-hosts go to foreign hosts when recursive\n"),
N_("\
-L, --relative follow relative links only\n"),
N_("\
-I, --include-directories=LIST list of allowed directories\n"),
N_("\
--trust-server-names use the name specified by the redirection\n\
URL's last component\n"),
N_("\
-X, --exclude-directories=LIST list of excluded directories\n"),
N_("\
-np, --no-parent don't ascend to the parent directory\n"),
"\n",
N_("Email bug reports, questions, discussions to <[email protected]>\n"),
N_("and/or open issues at https://savannah.gnu.org/bugs/?func=additem&group=wget.\n")
};
size_t i;
if (printf (_("GNU Wget %s, a non-interactive network retriever.\n"),
version_string) < 0)
exit (WGET_EXIT_IO_FAIL);
if (print_usage (0) < 0)
exit (WGET_EXIT_IO_FAIL);
for (i = 0; i < countof (help); i++)
if (fputs (_(help[i]), stdout) < 0)
exit (WGET_EXIT_IO_FAIL);
#endif /* TESTING */
exit (WGET_EXIT_SUCCESS);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Don't use extended attributes (--xattr) by default
* src/init.c (defaults): Set enable_xattr to false by default
* src/main.c (print_help): Reverse option logic of --xattr
* doc/wget.texi: Add description for --xattr
Users may not be aware that the origin URL and Referer are saved
including credentials, and possibly access tokens within
the urls.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gethttp (const struct url *u, struct url *original_url, struct http_stat *hs,
int *dt, struct url *proxy, struct iri *iri, int count)
{
struct request *req = NULL;
char *type = NULL;
char *user, *passwd;
char *proxyauth;
int statcode;
int write_error;
wgint contlen, contrange;
const struct url *conn;
FILE *fp;
int err;
uerr_t retval;
#ifdef HAVE_HSTS
#ifdef TESTING
/* we don't link against main.o when we're testing */
hsts_store_t hsts_store = NULL;
#else
extern hsts_store_t hsts_store;
#endif
const char *hsts_params;
time_t max_age;
bool include_subdomains;
#endif
int sock = -1;
/* Set to 1 when the authorization has already been sent and should
not be tried again. */
bool auth_finished = false;
/* Set to 1 when just globally-set Basic authorization has been sent;
* should prevent further Basic negotiations, but not other
* mechanisms. */
bool basic_auth_finished = false;
/* Whether NTLM authentication is used for this request. */
bool ntlm_seen = false;
/* Whether our connection to the remote host is through SSL. */
bool using_ssl = false;
/* Whether a HEAD request will be issued (as opposed to GET or
POST). */
bool head_only = !!(*dt & HEAD_ONLY);
/* Whether conditional get request will be issued. */
bool cond_get = !!(*dt & IF_MODIFIED_SINCE);
#ifdef HAVE_METALINK
/* Are we looking for metalink info in HTTP headers? */
bool metalink = !!(*dt & METALINK_METADATA);
#endif
char *head = NULL;
struct response *resp = NULL;
char hdrval[512];
char *message = NULL;
/* Declare WARC variables. */
bool warc_enabled = (opt.warc_filename != NULL);
FILE *warc_tmp = NULL;
char warc_timestamp_str [21];
char warc_request_uuid [48];
ip_address *warc_ip = NULL;
off_t warc_payload_offset = -1;
/* Whether this connection will be kept alive after the HTTP request
is done. */
bool keep_alive;
/* Is the server using the chunked transfer encoding? */
bool chunked_transfer_encoding = false;
/* Whether keep-alive should be inhibited. */
bool inhibit_keep_alive =
!opt.http_keep_alive || opt.ignore_length;
/* Headers sent when using POST. */
wgint body_data_size = 0;
#ifdef HAVE_SSL
if (u->scheme == SCHEME_HTTPS)
{
/* Initialize the SSL context. After this has once been done,
it becomes a no-op. */
if (!ssl_init ())
{
scheme_disable (SCHEME_HTTPS);
logprintf (LOG_NOTQUIET,
_("Disabling SSL due to encountered errors.\n"));
retval = SSLINITFAILED;
goto cleanup;
}
}
#endif /* HAVE_SSL */
/* Initialize certain elements of struct http_stat. */
hs->len = 0;
hs->contlen = -1;
hs->res = -1;
hs->rderrmsg = NULL;
hs->newloc = NULL;
xfree (hs->remote_time);
hs->error = NULL;
hs->message = NULL;
hs->local_encoding = ENC_NONE;
hs->remote_encoding = ENC_NONE;
conn = u;
{
uerr_t ret;
req = initialize_request (u, hs, dt, proxy, inhibit_keep_alive,
&basic_auth_finished, &body_data_size,
&user, &passwd, &ret);
if (req == NULL)
{
retval = ret;
goto cleanup;
}
}
retry_with_auth:
/* We need to come back here when the initial attempt to retrieve
without authorization header fails. (Expected to happen at least
for the Digest authorization scheme.) */
if (opt.cookies)
request_set_header (req, "Cookie",
cookie_header (wget_cookie_jar,
u->host, u->port, u->path,
#ifdef HAVE_SSL
u->scheme == SCHEME_HTTPS
#else
0
#endif
),
rel_value);
/* Add the user headers. */
if (opt.user_headers)
{
int i;
for (i = 0; opt.user_headers[i]; i++)
request_set_user_header (req, opt.user_headers[i]);
}
proxyauth = NULL;
if (proxy)
{
conn = proxy;
initialize_proxy_configuration (u, req, proxy, &proxyauth);
}
keep_alive = true;
/* Establish the connection. */
if (inhibit_keep_alive)
keep_alive = false;
{
uerr_t conn_err = establish_connection (u, &conn, hs, proxy, &proxyauth, &req,
&using_ssl, inhibit_keep_alive, &sock);
if (conn_err != RETROK)
{
retval = conn_err;
goto cleanup;
}
}
/* Open the temporary file where we will write the request. */
if (warc_enabled)
{
warc_tmp = warc_tempfile ();
if (warc_tmp == NULL)
{
CLOSE_INVALIDATE (sock);
retval = WARC_TMP_FOPENERR;
goto cleanup;
}
if (! proxy)
{
warc_ip = (ip_address *) alloca (sizeof (ip_address));
socket_ip_address (sock, warc_ip, ENDPOINT_PEER);
}
}
/* Send the request to server. */
write_error = request_send (req, sock, warc_tmp);
if (write_error >= 0)
{
if (opt.body_data)
{
DEBUGP (("[BODY data: %s]\n", opt.body_data));
write_error = fd_write (sock, opt.body_data, body_data_size, -1);
if (write_error >= 0 && warc_tmp != NULL)
{
int warc_tmp_written;
/* Remember end of headers / start of payload. */
warc_payload_offset = ftello (warc_tmp);
/* Write a copy of the data to the WARC record. */
warc_tmp_written = fwrite (opt.body_data, 1, body_data_size, warc_tmp);
if (warc_tmp_written != body_data_size)
write_error = -2;
}
}
else if (opt.body_file && body_data_size != 0)
{
if (warc_tmp != NULL)
/* Remember end of headers / start of payload */
warc_payload_offset = ftello (warc_tmp);
write_error = body_file_send (sock, opt.body_file, body_data_size, warc_tmp);
}
}
if (write_error < 0)
{
CLOSE_INVALIDATE (sock);
if (warc_tmp != NULL)
fclose (warc_tmp);
if (write_error == -2)
retval = WARC_TMP_FWRITEERR;
else
retval = WRITEFAILED;
goto cleanup;
}
logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
proxy ? "Proxy" : "HTTP");
contlen = -1;
contrange = 0;
*dt &= ~RETROKF;
if (warc_enabled)
{
bool warc_result;
/* Generate a timestamp and uuid for this request. */
warc_timestamp (warc_timestamp_str, sizeof (warc_timestamp_str));
warc_uuid_str (warc_request_uuid);
/* Create a request record and store it in the WARC file. */
warc_result = warc_write_request_record (u->url, warc_timestamp_str,
warc_request_uuid, warc_ip,
warc_tmp, warc_payload_offset);
if (! warc_result)
{
CLOSE_INVALIDATE (sock);
retval = WARC_ERR;
goto cleanup;
}
/* warc_write_request_record has also closed warc_tmp. */
}
/* Repeat while we receive a 10x response code. */
{
bool _repeat;
do
{
head = read_http_response_head (sock);
if (!head)
{
if (errno == 0)
{
logputs (LOG_NOTQUIET, _("No data received.\n"));
CLOSE_INVALIDATE (sock);
retval = HEOF;
}
else
{
logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
retval = HERR;
}
goto cleanup;
}
DEBUGP (("\n---response begin---\n%s---response end---\n", head));
resp = resp_new (head);
/* Check for status line. */
xfree (message);
statcode = resp_status (resp, &message);
if (statcode < 0)
{
char *tms = datetime_str (time (NULL));
logprintf (LOG_VERBOSE, "%d\n", statcode);
logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
quotearg_style (escape_quoting_style,
_("Malformed status line")));
CLOSE_INVALIDATE (sock);
retval = HERR;
goto cleanup;
}
if (H_10X (statcode))
{
xfree (head);
resp_free (&resp);
_repeat = true;
DEBUGP (("Ignoring response\n"));
}
else
{
_repeat = false;
}
}
while (_repeat);
}
xfree (hs->message);
hs->message = xstrdup (message);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
message ? quotearg_style (escape_quoting_style, message) : "");
else
{
logprintf (LOG_VERBOSE, "\n");
print_server_response (resp, " ");
}
if (!opt.ignore_length
&& resp_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
{
wgint parsed;
errno = 0;
parsed = str_to_wgint (hdrval, NULL, 10);
if (parsed == WGINT_MAX && errno == ERANGE)
{
/* Out of range.
#### If Content-Length is out of range, it most likely
means that the file is larger than 2G and that we're
compiled without LFS. In that case we should probably
refuse to even attempt to download the file. */
contlen = -1;
}
else if (parsed < 0)
{
/* Negative Content-Length; nonsensical, so we can't
assume any information about the content to receive. */
contlen = -1;
}
else
contlen = parsed;
}
/* Check for keep-alive related responses. */
if (!inhibit_keep_alive)
{
if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
{
if (0 == c_strcasecmp (hdrval, "Close"))
keep_alive = false;
}
}
chunked_transfer_encoding = false;
if (resp_header_copy (resp, "Transfer-Encoding", hdrval, sizeof (hdrval))
&& 0 == c_strcasecmp (hdrval, "chunked"))
chunked_transfer_encoding = true;
/* Handle (possibly multiple instances of) the Set-Cookie header. */
if (opt.cookies)
{
int scpos;
const char *scbeg, *scend;
/* The jar should have been created by now. */
assert (wget_cookie_jar != NULL);
for (scpos = 0;
(scpos = resp_header_locate (resp, "Set-Cookie", scpos,
&scbeg, &scend)) != -1;
++scpos)
{
char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port,
u->path, set_cookie);
}
}
if (keep_alive)
/* The server has promised that it will not close the connection
when we're done. This means that we can register it. */
register_persistent (conn->host, conn->port, sock, using_ssl);
#ifdef HAVE_METALINK
/* We need to check for the Metalink data in the very first response
we get from the server (before redirections, authorization, etc.). */
if (metalink)
{
hs->metalink = metalink_from_http (resp, hs, u);
/* Bugfix: hs->local_file is NULL (opt.content_disposition). */
if (!hs->local_file && hs->metalink && hs->metalink->origin)
hs->local_file = xstrdup (hs->metalink->origin);
xfree (hs->message);
retval = RETR_WITH_METALINK;
CLOSE_FINISH (sock);
goto cleanup;
}
#endif
if (statcode == HTTP_STATUS_UNAUTHORIZED)
{
/* Authorization is required. */
uerr_t auth_err = RETROK;
bool retry;
/* Normally we are not interested in the response body.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err;
type = resp_header_strdup (resp, "Content-Type");
_err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
xfree (type);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
pconn.authorized = false;
{
auth_err = check_auth (u, user, passwd, resp, req,
&ntlm_seen, &retry,
&basic_auth_finished,
&auth_finished);
if (auth_err == RETROK && retry)
{
xfree (hs->message);
resp_free (&resp);
xfree (message);
xfree (head);
goto retry_with_auth;
}
}
if (auth_err == RETROK)
retval = AUTHFAILED;
else
retval = auth_err;
goto cleanup;
}
else /* statcode != HTTP_STATUS_UNAUTHORIZED */
{
/* Kludge: if NTLM is used, mark the TCP connection as authorized. */
if (ntlm_seen)
pconn.authorized = true;
}
{
uerr_t ret = check_file_output (u, hs, resp, hdrval, sizeof hdrval);
if (ret != RETROK)
{
retval = ret;
goto cleanup;
}
}
hs->statcode = statcode;
if (statcode == -1)
hs->error = xstrdup (_("Malformed status line"));
else if (!*message)
hs->error = xstrdup (_("(no description)"));
else
hs->error = xstrdup (message);
#ifdef HAVE_HSTS
if (opt.hsts && hsts_store)
{
hsts_params = resp_header_strdup (resp, "Strict-Transport-Security");
if (parse_strict_transport_security (hsts_params, &max_age, &include_subdomains))
{
/* process strict transport security */
if (hsts_store_entry (hsts_store, u->scheme, u->host, u->port, max_age, include_subdomains))
DEBUGP(("Added new HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
else
DEBUGP(("Updated HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
}
}
#endif
type = resp_header_strdup (resp, "Content-Type");
if (type)
{
char *tmp = strchr (type, ';');
if (tmp)
{
#ifdef ENABLE_IRI
/* sXXXav: only needed if IRI support is enabled */
char *tmp2 = tmp + 1;
#endif
while (tmp > type && c_isspace (tmp[-1]))
--tmp;
*tmp = '\0';
#ifdef ENABLE_IRI
/* Try to get remote encoding if needed */
if (opt.enable_iri && !opt.encoding_remote)
{
tmp = parse_charset (tmp2);
if (tmp)
set_content_encoding (iri, tmp);
xfree (tmp);
}
#endif
}
}
hs->newloc = resp_header_strdup (resp, "Location");
hs->remote_time = resp_header_strdup (resp, "Last-Modified");
if (!hs->remote_time) // now look for the Wayback Machine's timestamp
hs->remote_time = resp_header_strdup (resp, "X-Archive-Orig-last-modified");
if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
{
wgint first_byte_pos, last_byte_pos, entity_length;
if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
&entity_length))
{
contrange = first_byte_pos;
contlen = last_byte_pos - first_byte_pos + 1;
}
}
if (resp_header_copy (resp, "Content-Encoding", hdrval, sizeof (hdrval)))
{
hs->local_encoding = ENC_INVALID;
switch (hdrval[0])
{
case 'b': case 'B':
if (0 == c_strcasecmp(hdrval, "br"))
hs->local_encoding = ENC_BROTLI;
break;
case 'c': case 'C':
if (0 == c_strcasecmp(hdrval, "compress"))
hs->local_encoding = ENC_COMPRESS;
break;
case 'd': case 'D':
if (0 == c_strcasecmp(hdrval, "deflate"))
hs->local_encoding = ENC_DEFLATE;
break;
case 'g': case 'G':
if (0 == c_strcasecmp(hdrval, "gzip"))
hs->local_encoding = ENC_GZIP;
break;
case 'i': case 'I':
if (0 == c_strcasecmp(hdrval, "identity"))
hs->local_encoding = ENC_NONE;
break;
case 'x': case 'X':
if (0 == c_strcasecmp(hdrval, "x-compress"))
hs->local_encoding = ENC_COMPRESS;
else if (0 == c_strcasecmp(hdrval, "x-gzip"))
hs->local_encoding = ENC_GZIP;
break;
case '\0':
hs->local_encoding = ENC_NONE;
}
if (hs->local_encoding == ENC_INVALID)
{
DEBUGP (("Unrecognized Content-Encoding: %s\n", hdrval));
hs->local_encoding = ENC_NONE;
}
#ifdef HAVE_LIBZ
else if (hs->local_encoding == ENC_GZIP
&& opt.compression != compression_none)
{
const char *p;
/* Make sure the Content-Type is not gzip before decompressing */
if (type)
{
p = strchr (type, '/');
if (p == NULL)
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
else
{
p++;
if (c_tolower(p[0]) == 'x' && p[1] == '-')
p += 2;
if (0 != c_strcasecmp (p, "gzip"))
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
}
}
else
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
/* don't uncompress if a file ends with '.gz' or '.tgz' */
if (hs->remote_encoding == ENC_GZIP
&& (p = strrchr(u->file, '.'))
&& (c_strcasecmp(p, ".gz") == 0 || c_strcasecmp(p, ".tgz") == 0))
{
DEBUGP (("Enabling broken server workaround. Will not decompress this GZip file.\n"));
hs->remote_encoding = ENC_NONE;
}
}
#endif
}
/* 20x responses are counted among successful by default. */
if (H_20X (statcode))
*dt |= RETROKF;
if (statcode == HTTP_STATUS_NO_CONTENT)
{
/* 204 response has no body (RFC 2616, 4.3) */
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
CLOSE_FINISH (sock);
retval = RETRFINISHED;
goto cleanup;
}
/* Return if redirected. */
if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
{
/* RFC2068 says that in case of the 300 (multiple choices)
response, the server can output a preferred URL through
`Location' header; otherwise, the request should be treated
like GET. So, if the location is set, it will be a
redirection; otherwise, just proceed normally. */
if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
*dt |= RETROKF;
else
{
logprintf (LOG_VERBOSE,
_("Location: %s%s\n"),
hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
hs->newloc ? _(" [following]") : "");
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a redirect.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
/* From RFC2616: The status codes 303 and 307 have
been added for servers that wish to make unambiguously
clear which kind of reaction is expected of the client.
A 307 should be redirected using the same method,
in other words, a POST should be preserved and not
converted to a GET in that case.
With strict adherence to RFC2616, POST requests are not
converted to a GET request on 301 Permanent Redirect
or 302 Temporary Redirect.
A switch may be provided later based on the HTTPbis draft
that allows clients to convert POST requests to GET
requests on 301 and 302 response codes. */
switch (statcode)
{
case HTTP_STATUS_TEMPORARY_REDIRECT:
case HTTP_STATUS_PERMANENT_REDIRECT:
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
case HTTP_STATUS_MOVED_PERMANENTLY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
}
retval = NEWLOCATION;
goto cleanup;
}
}
if (cond_get)
{
if (statcode == HTTP_STATUS_NOT_MODIFIED)
{
logprintf (LOG_VERBOSE,
_ ("File %s not modified on server. Omitting download.\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_FINISH (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
set_content_type (dt, type);
if (opt.adjust_extension)
{
const char *encoding_ext = NULL;
switch (hs->local_encoding)
{
case ENC_INVALID:
case ENC_NONE:
break;
case ENC_BROTLI:
encoding_ext = ".br";
break;
case ENC_COMPRESS:
encoding_ext = ".Z";
break;
case ENC_DEFLATE:
encoding_ext = ".zlib";
break;
case ENC_GZIP:
encoding_ext = ".gz";
break;
default:
DEBUGP (("No extension found for encoding %d\n",
hs->local_encoding));
}
if (encoding_ext != NULL)
{
char *file_ext = strrchr (hs->local_file, '.');
/* strip Content-Encoding extension (it will be re-added later) */
if (file_ext != NULL && 0 == strcasecmp (file_ext, encoding_ext))
*file_ext = '\0';
}
if (*dt & TEXTHTML)
/* -E / --adjust-extension / adjust_extension = on was specified,
and this is a text/html file. If some case-insensitive
variation on ".htm[l]" isn't already the file's suffix,
tack on ".html". */
{
ensure_extension (hs, ".html", dt);
}
else if (*dt & TEXTCSS)
{
ensure_extension (hs, ".css", dt);
}
if (encoding_ext != NULL)
{
ensure_extension (hs, encoding_ext, dt);
}
}
if (cond_get)
{
/* Handle the case when server ignores If-Modified-Since header. */
if (statcode == HTTP_STATUS_OK && hs->remote_time)
{
time_t tmr = http_atotm (hs->remote_time);
/* Check if the local file is up-to-date based on Last-Modified header
and content length. */
if (tmr != (time_t) - 1 && tmr <= hs->orig_file_tstamp
&& (contlen == -1 || contlen == hs->orig_file_size))
{
logprintf (LOG_VERBOSE,
_("Server ignored If-Modified-Since header for file %s.\n"
"You might want to add --no-if-modified-since option."
"\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
}
if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
|| (!opt.timestamping && hs->restval > 0 && statcode == HTTP_STATUS_OK
&& contrange == 0 && contlen >= 0 && hs->restval >= contlen))
{
/* If `-c' is in use and the file has been fully downloaded (or
the remote file has shrunk), Wget effectively requests bytes
after the end of file and the server response with 416
(or 200 with a <= Content-Length. */
logputs (LOG_VERBOSE, _("\
\n The file is already fully retrieved; nothing to do.\n\n"));
/* In case the caller inspects. */
hs->len = contlen;
hs->res = 0;
/* Mark as successfully retrieved. */
*dt |= RETROKF;
/* Try to maintain the keep-alive connection. It is often cheaper to
* consume some bytes which have already been sent than to negotiate
* a new connection. However, if the body is too large, or we don't
* care about keep-alive, then simply terminate the connection */
if (keep_alive &&
skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
if ((contrange != 0 && contrange != hs->restval)
|| (H_PARTIAL (statcode) && !contrange && hs->restval))
{
/* The Range request was somehow misunderstood by the server.
Bail out. */
CLOSE_INVALIDATE (sock);
retval = RANGEERR;
goto cleanup;
}
if (contlen == -1)
hs->contlen = -1;
/* If the response is gzipped, the uncompressed size is unknown. */
else if (hs->remote_encoding == ENC_GZIP)
hs->contlen = -1;
else
hs->contlen = contlen + contrange;
if (opt.verbose)
{
if (*dt & RETROKF)
{
/* No need to print this output if the body won't be
downloaded at all, or if the original server response is
printed. */
logputs (LOG_VERBOSE, _("Length: "));
if (contlen != -1)
{
logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange));
if (contlen + contrange >= 1024)
logprintf (LOG_VERBOSE, " (%s)",
human_readable (contlen + contrange, 10, 1));
if (contrange)
{
if (contlen >= 1024)
logprintf (LOG_VERBOSE, _(", %s (%s) remaining"),
number_to_static_string (contlen),
human_readable (contlen, 10, 1));
else
logprintf (LOG_VERBOSE, _(", %s remaining"),
number_to_static_string (contlen));
}
}
else
logputs (LOG_VERBOSE,
opt.ignore_length ? _("ignored") : _("unspecified"));
if (type)
logprintf (LOG_VERBOSE, " [%s]\n", quotearg_style (escape_quoting_style, type));
else
logputs (LOG_VERBOSE, "\n");
}
}
/* Return if we have no intention of further downloading. */
if ((!(*dt & RETROKF) && !opt.content_on_error) || head_only || (opt.spider && !opt.recursive))
{
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a error responses.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (head_only)
/* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the
servers not to send body in response to a HEAD request, and
those that do will likely be caught by test_socket_open.
If not, they can be worked around using
`--no-http-keep-alive'. */
CLOSE_FINISH (sock);
else if (opt.spider && !opt.recursive)
/* we just want to see if the page exists - no downloading required */
CLOSE_INVALIDATE (sock);
else if (keep_alive
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
/* Successfully skipped the body; also keep using the socket. */
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
if (statcode == HTTP_STATUS_GATEWAY_TIMEOUT)
retval = GATEWAYTIMEOUT;
else
retval = RETRFINISHED;
goto cleanup;
}
err = open_output_stream (hs, count, &fp);
if (err != RETROK)
{
CLOSE_INVALIDATE (sock);
retval = err;
goto cleanup;
}
#ifdef ENABLE_XATTR
if (opt.enable_xattr)
{
if (original_url != u)
set_file_metadata (u->url, original_url->url, fp);
else
set_file_metadata (u->url, NULL, fp);
}
#endif
err = read_response_body (hs, sock, fp, contlen, contrange,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (hs->res >= 0)
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
if (!output_stream)
fclose (fp);
retval = err;
cleanup:
xfree (head);
xfree (type);
xfree (message);
resp_free (&resp);
request_free (&req);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Don't save user/pw with --xattr
Also the Referer info is reduced to scheme+host+port.
* src/ftp.c (getftp): Change params of set_file_metadata()
* src/http.c (gethttp): Change params of set_file_metadata()
* src/xattr.c (set_file_metadata): Remove user/password from origin URL,
reduce Referer value to scheme/host/port.
* src/xattr.h: Change prototype of set_file_metadata()'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.