instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
const struct lxc_rootfs *rootfs,
const char *lxc_name)
{
char *aux;
char path[MAXPATHLEN];
int r, ret = 0, offset;
const char *lxcpath;
lxcpath = lxc_global_config_value("lxc.lxcpath");
if (!lxcpath) {
ERROR("Out of memory");
return -1;
}
/* if rootfs->path is a blockdev path, allow container fstab to
* use $lxcpath/CN/rootfs as the target prefix */
r = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name);
if (r < 0 || r >= MAXPATHLEN)
goto skipvarlib;
aux = strstr(mntent->mnt_dir, path);
if (aux) {
offset = strlen(path);
goto skipabs;
}
skipvarlib:
aux = strstr(mntent->mnt_dir, rootfs->path);
if (!aux) {
WARN("ignoring mount point '%s'", mntent->mnt_dir);
return ret;
}
offset = strlen(rootfs->path);
skipabs:
r = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount,
aux + offset);
if (r < 0 || r >= MAXPATHLEN) {
WARN("pathnme too long for '%s'", mntent->mnt_dir);
return -1;
}
return mount_entry_on_generic(mntent, path);
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59 | static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
const struct lxc_rootfs *rootfs,
const char *lxc_name)
{
char *aux;
char path[MAXPATHLEN];
int r, ret = 0, offset;
const char *lxcpath;
lxcpath = lxc_global_config_value("lxc.lxcpath");
if (!lxcpath) {
ERROR("Out of memory");
return -1;
}
/* if rootfs->path is a blockdev path, allow container fstab to
* use $lxcpath/CN/rootfs as the target prefix */
r = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name);
if (r < 0 || r >= MAXPATHLEN)
goto skipvarlib;
aux = strstr(mntent->mnt_dir, path);
if (aux) {
offset = strlen(path);
goto skipabs;
}
skipvarlib:
aux = strstr(mntent->mnt_dir, rootfs->path);
if (!aux) {
WARN("ignoring mount point '%s'", mntent->mnt_dir);
return ret;
}
offset = strlen(rootfs->path);
skipabs:
r = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount,
aux + offset);
if (r < 0 || r >= MAXPATHLEN) {
WARN("pathnme too long for '%s'", mntent->mnt_dir);
return -1;
}
return mount_entry_on_generic(mntent, path, rootfs->mount);
}
| 166,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
xmlXPathStepOpPtr op,
xmlNodeSetPtr set,
int contextSize,
int minPos,
int maxPos,
int hasNsNodes)
{
if (op->ch1 != -1) {
xmlXPathCompExprPtr comp = ctxt->comp;
if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
/*
* TODO: raise an internal error.
*/
}
contextSize = xmlXPathCompOpEvalPredicate(ctxt,
&comp->steps[op->ch1], set, contextSize, hasNsNodes);
CHECK_ERROR0;
if (contextSize <= 0)
return(0);
}
/*
* Check if the node set contains a sufficient number of nodes for
* the requested range.
*/
if (contextSize < minPos) {
xmlXPathNodeSetClear(set, hasNsNodes);
return(0);
}
if (op->ch2 == -1) {
/*
* TODO: Can this ever happen?
*/
return (contextSize);
} else {
xmlDocPtr oldContextDoc;
int i, pos = 0, newContextSize = 0, contextPos = 0, res;
xmlXPathStepOpPtr exprOp;
xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
xmlNodePtr oldContextNode, contextNode = NULL;
xmlXPathContextPtr xpctxt = ctxt->context;
#ifdef LIBXML_XPTR_ENABLED
/*
* URGENT TODO: Check the following:
* We don't expect location sets if evaluating prediates, right?
* Only filters should expect location sets, right?
*/
#endif /* LIBXML_XPTR_ENABLED */
/*
* Save old context.
*/
oldContextNode = xpctxt->node;
oldContextDoc = xpctxt->doc;
/*
* Get the expression of this predicate.
*/
exprOp = &ctxt->comp->steps[op->ch2];
for (i = 0; i < set->nodeNr; i++) {
if (set->nodeTab[i] == NULL)
continue;
contextNode = set->nodeTab[i];
xpctxt->node = contextNode;
xpctxt->contextSize = contextSize;
xpctxt->proximityPosition = ++contextPos;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
if ((contextNode->type != XML_NAMESPACE_DECL) &&
(contextNode->doc != NULL))
xpctxt->doc = contextNode->doc;
/*
* Evaluate the predicate expression with 1 context node
* at a time; this node is packaged into a node set; this
* node set is handed over to the evaluation mechanism.
*/
if (contextObj == NULL)
contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
else
xmlXPathNodeSetAddUnique(contextObj->nodesetval,
contextNode);
valuePush(ctxt, contextObj);
res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
xmlXPathObjectPtr tmp;
/* pop the result if any */
tmp = valuePop(ctxt);
if (tmp != contextObj)
/*
* Free up the result
* then pop off contextObj, which will be freed later
*/
xmlXPathReleaseObject(xpctxt, tmp);
valuePop(ctxt);
goto evaluation_error;
}
if (res)
pos++;
if (res && (pos >= minPos) && (pos <= maxPos)) {
/*
* Fits in the requested range.
*/
newContextSize++;
if (minPos == maxPos) {
/*
* Only 1 node was requested.
*/
if (contextNode->type == XML_NAMESPACE_DECL) {
/*
* As always: take care of those nasty
* namespace nodes.
*/
set->nodeTab[i] = NULL;
}
xmlXPathNodeSetClear(set, hasNsNodes);
set->nodeNr = 1;
set->nodeTab[0] = contextNode;
goto evaluation_exit;
}
if (pos == maxPos) {
/*
* We are done.
*/
xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
goto evaluation_exit;
}
} else {
/*
* Remove the entry from the initial node set.
*/
set->nodeTab[i] = NULL;
if (contextNode->type == XML_NAMESPACE_DECL)
xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
}
if (exprRes != NULL) {
xmlXPathReleaseObject(ctxt->context, exprRes);
exprRes = NULL;
}
if (ctxt->value == contextObj) {
/*
* Don't free the temporary XPath object holding the
* context node, in order to avoid massive recreation
* inside this loop.
*/
valuePop(ctxt);
xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
} else {
/*
* The object was lost in the evaluation machinery.
* Can this happen? Maybe in case of internal-errors.
*/
contextObj = NULL;
}
}
goto evaluation_exit;
evaluation_error:
xmlXPathNodeSetClear(set, hasNsNodes);
newContextSize = 0;
evaluation_exit:
if (contextObj != NULL) {
if (ctxt->value == contextObj)
valuePop(ctxt);
xmlXPathReleaseObject(xpctxt, contextObj);
}
if (exprRes != NULL)
xmlXPathReleaseObject(ctxt->context, exprRes);
/*
* Reset/invalidate the context.
*/
xpctxt->node = oldContextNode;
xpctxt->doc = oldContextDoc;
xpctxt->contextSize = -1;
xpctxt->proximityPosition = -1;
return(newContextSize);
}
return(contextSize);
}
Commit Message: Fix libxml XPath bug.
BUG=89402
Review URL: http://codereview.chromium.org/7508039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95382 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
xmlXPathStepOpPtr op,
xmlNodeSetPtr set,
int contextSize,
int minPos,
int maxPos,
int hasNsNodes)
{
if (op->ch1 != -1) {
xmlXPathCompExprPtr comp = ctxt->comp;
if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
/*
* TODO: raise an internal error.
*/
}
contextSize = xmlXPathCompOpEvalPredicate(ctxt,
&comp->steps[op->ch1], set, contextSize, hasNsNodes);
CHECK_ERROR0;
if (contextSize <= 0)
return(0);
}
/*
* Check if the node set contains a sufficient number of nodes for
* the requested range.
*/
if (contextSize < minPos) {
xmlXPathNodeSetClear(set, hasNsNodes);
return(0);
}
if (op->ch2 == -1) {
/*
* TODO: Can this ever happen?
*/
return (contextSize);
} else {
xmlDocPtr oldContextDoc;
int i, pos = 0, newContextSize = 0, contextPos = 0, res;
xmlXPathStepOpPtr exprOp;
xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
xmlNodePtr oldContextNode, contextNode = NULL;
xmlXPathContextPtr xpctxt = ctxt->context;
#ifdef LIBXML_XPTR_ENABLED
/*
* URGENT TODO: Check the following:
* We don't expect location sets if evaluating prediates, right?
* Only filters should expect location sets, right?
*/
#endif /* LIBXML_XPTR_ENABLED */
/*
* Save old context.
*/
oldContextNode = xpctxt->node;
oldContextDoc = xpctxt->doc;
/*
* Get the expression of this predicate.
*/
exprOp = &ctxt->comp->steps[op->ch2];
for (i = 0; i < set->nodeNr; i++) {
if (set->nodeTab[i] == NULL)
continue;
contextNode = set->nodeTab[i];
xpctxt->node = contextNode;
xpctxt->contextSize = contextSize;
xpctxt->proximityPosition = ++contextPos;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
if ((contextNode->type != XML_NAMESPACE_DECL) &&
(contextNode->doc != NULL))
xpctxt->doc = contextNode->doc;
/*
* Evaluate the predicate expression with 1 context node
* at a time; this node is packaged into a node set; this
* node set is handed over to the evaluation mechanism.
*/
if (contextObj == NULL)
contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
else
xmlXPathNodeSetAddUnique(contextObj->nodesetval,
contextNode);
valuePush(ctxt, contextObj);
res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
xmlXPathObjectPtr tmp;
/* pop the result if any */
tmp = valuePop(ctxt);
while (tmp != contextObj) {
/*
* Free up the result
* then pop off contextObj, which will be freed later
*/
xmlXPathReleaseObject(xpctxt, tmp);
tmp = valuePop(ctxt);
}
goto evaluation_error;
}
if (res)
pos++;
if (res && (pos >= minPos) && (pos <= maxPos)) {
/*
* Fits in the requested range.
*/
newContextSize++;
if (minPos == maxPos) {
/*
* Only 1 node was requested.
*/
if (contextNode->type == XML_NAMESPACE_DECL) {
/*
* As always: take care of those nasty
* namespace nodes.
*/
set->nodeTab[i] = NULL;
}
xmlXPathNodeSetClear(set, hasNsNodes);
set->nodeNr = 1;
set->nodeTab[0] = contextNode;
goto evaluation_exit;
}
if (pos == maxPos) {
/*
* We are done.
*/
xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
goto evaluation_exit;
}
} else {
/*
* Remove the entry from the initial node set.
*/
set->nodeTab[i] = NULL;
if (contextNode->type == XML_NAMESPACE_DECL)
xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
}
if (exprRes != NULL) {
xmlXPathReleaseObject(ctxt->context, exprRes);
exprRes = NULL;
}
if (ctxt->value == contextObj) {
/*
* Don't free the temporary XPath object holding the
* context node, in order to avoid massive recreation
* inside this loop.
*/
valuePop(ctxt);
xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
} else {
/*
* The object was lost in the evaluation machinery.
* Can this happen? Maybe in case of internal-errors.
*/
contextObj = NULL;
}
}
goto evaluation_exit;
evaluation_error:
xmlXPathNodeSetClear(set, hasNsNodes);
newContextSize = 0;
evaluation_exit:
if (contextObj != NULL) {
if (ctxt->value == contextObj)
valuePop(ctxt);
xmlXPathReleaseObject(xpctxt, contextObj);
}
if (exprRes != NULL)
xmlXPathReleaseObject(ctxt->context, exprRes);
/*
* Reset/invalidate the context.
*/
xpctxt->node = oldContextNode;
xpctxt->doc = oldContextDoc;
xpctxt->contextSize = -1;
xpctxt->proximityPosition = -1;
return(newContextSize);
}
return(contextSize);
}
| 170,365 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string MediaStreamManager::MakeMediaAccessRequest(
int render_process_id,
int render_frame_id,
int page_request_id,
const StreamControls& controls,
const url::Origin& security_origin,
MediaAccessRequestCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_DEVICE_ACCESS, controls,
MediaDeviceSaltAndOrigin{std::string() /* salt */,
std::string() /* group_id_salt */,
security_origin});
const std::string& label = AddRequest(request);
request->media_access_request_cb = std::move(callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
return label;
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | std::string MediaStreamManager::MakeMediaAccessRequest(
int render_process_id,
int render_frame_id,
int requester_id,
int page_request_id,
const StreamControls& controls,
const url::Origin& security_origin,
MediaAccessRequestCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
false /* user gesture */, MEDIA_DEVICE_ACCESS, controls,
MediaDeviceSaltAndOrigin{std::string() /* salt */,
std::string() /* group_id_salt */,
security_origin});
const std::string& label = AddRequest(request);
request->media_access_request_cb = std::move(callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
return label;
}
| 173,104 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void parser(void)
{
char *arg;
#ifndef MINIMAL
char *sitearg;
#endif
#ifdef WITH_RFC2640
char *narg = NULL;
#endif
size_t n;
#ifdef IMPLICIT_TLS
(void) tls_init_new_session();
data_protection_level = CPL_PRIVATE;
#endif
for (;;) {
xferfd = -1;
if (state_needs_update != 0) {
state_needs_update = 0;
setprocessname("pure-ftpd (IDLE)");
#ifdef FTPWHO
if (shm_data_cur != NULL) {
ftpwho_lock();
shm_data_cur->state = FTPWHO_STATE_IDLE;
*shm_data_cur->filename = 0;
ftpwho_unlock();
}
#endif
}
doreply();
alarm(idletime * 2);
switch (sfgets()) {
case -1:
#ifdef BORING_MODE
die(421, LOG_INFO, MSG_TIMEOUT);
#else
die(421, LOG_INFO, MSG_TIMEOUT_PARSER);
#endif
case -2:
return;
}
#ifdef DEBUG
if (debug != 0) {
addreply(0, "%s", cmd);
}
#endif
n = (size_t) 0U;
while ((isalpha((unsigned char) cmd[n]) || cmd[n] == '@') &&
n < cmdsize) {
cmd[n] = (char) tolower((unsigned char) cmd[n]);
n++;
}
if (n >= cmdsize) { /* overparanoid, it should never happen */
die(421, LOG_WARNING, MSG_LINE_TOO_LONG);
}
if (n == (size_t) 0U) {
nop:
addreply_noformat(500, "?");
continue;
}
#ifdef SKIP_COMMAND_TRAILING_SPACES
while (isspace((unsigned char) cmd[n]) && n < cmdsize) {
cmd[n++] = 0;
}
arg = cmd + n;
while (cmd[n] != 0 && n < cmdsize) {
n++;
}
n--;
while (isspace((unsigned char) cmd[n])) {
cmd[n--] = 0;
}
#else
if (cmd[n] == 0) {
arg = cmd + n;
} else if (isspace((unsigned char) cmd[n])) {
cmd[n] = 0;
arg = cmd + n + 1;
} else {
goto nop;
}
#endif
if (logging != 0) {
#ifdef DEBUG
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, arg);
#else
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, strcmp(cmd, "pass") ? arg : "<*>");
#endif
}
#ifdef WITH_RFC2640
narg = charset_client2fs(arg);
arg = narg;
#endif
/*
* antiidle() is called with dummy commands, usually used by clients
* who are wanting extra idle time. We give them some, but not too much.
* When we jump to wayout, the idle timer is not zeroed. It means that
* we didn't issue an 'active' command like RETR.
*/
#ifndef MINIMAL
if (!strcmp(cmd, "noop")) {
antiidle();
donoop();
goto wayout;
}
#endif
if (!strcmp(cmd, "user")) {
#ifdef WITH_TLS
if (enforce_tls_auth > 1 && tls_cnx == NULL) {
die(421, LOG_WARNING, MSG_TLS_NEEDED);
}
#endif
douser(arg);
} else if (!strcmp(cmd, "acct")) {
addreply(202, MSG_WHOAREYOU);
} else if (!strcmp(cmd, "pass")) {
if (guest == 0) {
randomdelay();
}
dopass(arg);
} else if (!strcmp(cmd, "quit")) {
addreply(221, MSG_GOODBYE,
(unsigned long long) ((uploaded + 1023ULL) / 1024ULL),
(unsigned long long) ((downloaded + 1023ULL) / 1024ULL));
return;
} else if (!strcmp(cmd, "syst")) {
antiidle();
addreply_noformat(215, "UNIX Type: L8");
goto wayout;
#ifdef WITH_TLS
} else if (enforce_tls_auth > 0 &&
!strcmp(cmd, "auth") && !strcasecmp(arg, "tls")) {
addreply_noformat(234, "AUTH TLS OK.");
doreply();
if (tls_cnx == NULL) {
(void) tls_init_new_session();
}
goto wayout;
} else if (!strcmp(cmd, "pbsz")) {
addreply_noformat(tls_cnx == NULL ? 503 : 200, "PBSZ=0");
} else if (!strcmp(cmd, "prot")) {
if (tls_cnx == NULL) {
addreply_noformat(503, MSG_PROT_BEFORE_PBSZ);
goto wayout;
}
switch (*arg) {
case 0:
addreply_noformat(503, MSG_MISSING_ARG);
data_protection_level = CPL_NONE;
break;
case 'C':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "clear");
data_protection_level = CPL_CLEAR;
break;
}
case 'S':
case 'E':
if (arg[1] == 0) {
addreply(200, MSG_PROT_UNKNOWN_LEVEL, arg, "private");
data_protection_level = CPL_PRIVATE;
break;
}
case 'P':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "private");
data_protection_level = CPL_PRIVATE;
break;
}
default:
addreply_noformat(534, "Fallback to [C]");
data_protection_level = CPL_CLEAR;
break;
}
#endif
} else if (!strcmp(cmd, "auth") || !strcmp(cmd, "adat")) {
addreply_noformat(500, MSG_AUTH_UNIMPLEMENTED);
} else if (!strcmp(cmd, "type")) {
antiidle();
dotype(arg);
goto wayout;
} else if (!strcmp(cmd, "mode")) {
antiidle();
domode(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "feat")) {
dofeat();
goto wayout;
} else if (!strcmp(cmd, "opts")) {
doopts(arg);
goto wayout;
#endif
} else if (!strcmp(cmd, "stru")) {
dostru(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "help")) {
goto help_site;
#endif
#ifdef DEBUG
} else if (!strcmp(cmd, "xdbg")) {
debug++;
addreply(200, MSG_XDBG_OK, debug);
goto wayout;
#endif
} else if (loggedin == 0) {
/* from this point, all commands need authentication */
addreply_noformat(530, MSG_NOT_LOGGED_IN);
goto wayout;
} else {
if (!strcmp(cmd, "cwd") || !strcmp(cmd, "xcwd")) {
antiidle();
docwd(arg);
goto wayout;
} else if (!strcmp(cmd, "port")) {
doport(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "eprt")) {
doeprt(arg);
} else if (!strcmp(cmd, "esta") &&
disallow_passive == 0 &&
STORAGE_FAMILY(force_passive_ip) == 0) {
doesta();
} else if (!strcmp(cmd, "estp")) {
doestp();
#endif
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "pasv") || !strcmp(cmd, "p@sw"))) {
dopasv(0);
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "epsv") &&
(broken_client_compat == 0 ||
STORAGE_FAMILY(ctrlconn) == AF_INET6))) {
if (!strcasecmp(arg, "all")) {
epsv_all = 1;
addreply_noformat(220, MSG_ACTIVE_DISABLED);
} else if (!strcmp(arg, "2") && !v6ready) {
addreply_noformat(522, MSG_ONLY_IPV4);
} else {
dopasv(1);
}
#ifndef MINIMAL
} else if (disallow_passive == 0 && !strcmp(cmd, "spsv")) {
dopasv(2);
} else if (!strcmp(cmd, "allo")) {
if (*arg == 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
const off_t size = (off_t) strtoull(arg, NULL, 10);
if (size < (off_t) 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
doallo(size);
}
}
#endif
} else if (!strcmp(cmd, "pwd") || !strcmp(cmd, "xpwd")) {
#ifdef WITH_RFC2640
char *nwd;
#endif
antiidle();
#ifdef WITH_RFC2640
nwd = charset_fs2client(wd);
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, nwd);
free(nwd);
#else
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, wd);
#endif
goto wayout;
} else if (!strcmp(cmd, "cdup") || !strcmp(cmd, "xcup")) {
docwd("..");
} else if (!strcmp(cmd, "retr")) {
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
}
else
#endif
{
doretr(arg);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rest")) {
antiidle();
if (*arg != 0) {
dorest(arg);
} else {
addreply_noformat(501, MSG_NO_RESTART_POINT);
restartat = (off_t) 0;
}
goto wayout;
} else if (!strcmp(cmd, "dele")) {
if (*arg != 0) {
dodele(arg);
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "stor")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 0, autorename);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "appe")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 1, 0);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "stou")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostou();
}
#endif
#ifndef DISABLE_MKD_RMD
} else if (!strcmp(cmd, "mkd") || !strcmp(cmd, "xmkd")) {
arg = revealextraspc(arg);
if (*arg != 0) {
domkd(arg);
} else {
addreply_noformat(501, MSG_NO_DIRECTORY_NAME);
}
} else if (!strcmp(cmd, "rmd") || !strcmp(cmd, "xrmd")) {
if (*arg != 0) {
dormd(arg);
} else {
addreply_noformat(550, MSG_NO_DIRECTORY_NAME);
}
#endif
#ifndef MINIMAL
} else if (!strcmp(cmd, "stat")) {
if (*arg != 0) {
modern_listings = 0;
donlist(arg, 1, 1, 1, 1);
} else {
addreply_noformat(211, "http://www.pureftpd.org/");
}
#endif
} else if (!strcmp(cmd, "list")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 0, 1);
}
} else if (!strcmp(cmd, "nlst")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 0, 0, broken_client_compat);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "mlst")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
domlst(*arg != 0 ? arg : ".");
}
} else if (!strcmp(cmd, "mlsd")) {
modern_listings = 1;
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 1, 0);
}
#endif
} else if (!strcmp(cmd, "abor")) {
addreply_noformat(226, MSG_ABOR_SUCCESS);
#ifndef MINIMAL
} else if (!strcmp(cmd, "site")) {
if ((sitearg = arg) != NULL) {
while (*sitearg != 0 && !isspace((unsigned char) *sitearg)) {
sitearg++;
}
if (*sitearg != 0) {
*sitearg++ = 0;
}
}
if (!strcasecmp(arg, "idle")) {
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, "SITE IDLE: " MSG_MISSING_ARG);
} else {
unsigned long int i = 0;
i = strtoul(sitearg, &sitearg, 10);
if (sitearg && *sitearg)
addreply(501, MSG_GARBAGE_FOUND " : %s", sitearg);
else if (i > MAX_SITE_IDLE)
addreply_noformat(501, MSG_VALUE_TOO_LARGE);
else {
idletime = i;
addreply(200, MSG_IDLE_TIME, idletime);
idletime_noop = (double) idletime * 2.0;
}
}
} else if (!strcasecmp(arg, "time")) {
dositetime();
} else if (!strcasecmp(arg, "help")) {
help_site:
addreply_noformat(214, MSG_SITE_HELP CRLF
# ifdef WITH_DIRALIASES
" ALIAS" CRLF
# endif
" CHMOD" CRLF " IDLE" CRLF " UTIME");
addreply_noformat(214, "Pure-FTPd - http://pureftpd.org/");
} else if (!strcasecmp(arg, "chmod")) {
char *sitearg2;
mode_t mode;
parsechmod:
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_MISSING_ARG);
goto chmod_wayout;
}
sitearg2 = sitearg;
while (*sitearg2 != 0 && !isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
while (*sitearg2 != 0 && isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
if (*sitearg2 == 0) {
addreply_noformat(550, MSG_NO_FILE_NAME);
goto chmod_wayout;
}
mode = (mode_t) strtoul(sitearg, NULL, 8);
if (mode > (mode_t) 07777) {
addreply_noformat(501, MSG_BAD_CHMOD);
goto chmod_wayout;
}
dochmod(sitearg2, mode);
chmod_wayout:
(void) 0;
} else if (!strcasecmp(arg, "utime")) {
char *sitearg2;
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_NO_FILE_NAME);
goto utime_wayout;
}
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
if (strcasecmp(sitearg2, " UTC") != 0) {
addreply_noformat(500, "UTC Only");
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
utime_no_arg:
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2++ = 0;
if (*sitearg2 == 0) {
goto utime_no_arg;
}
doutime(sitearg, sitearg2);
utime_wayout:
(void) 0;
# ifdef WITH_DIRALIASES
} else if (!strcasecmp(arg, "alias")) {
if (sitearg == NULL || *sitearg == 0) {
print_aliases();
} else {
const char *alias;
if ((alias = lookup_alias(sitearg)) != NULL) {
addreply(214, MSG_ALIASES_ALIAS, sitearg, alias);
} else {
addreply(502, MSG_ALIASES_UNKNOWN, sitearg);
}
}
# endif
} else if (*arg != 0) {
addreply(500, "SITE %s " MSG_UNKNOWN_EXTENSION, arg);
} else {
addreply_noformat(500, "SITE: " MSG_MISSING_ARG);
}
#endif
} else if (!strcmp(cmd, "mdtm")) {
domdtm(arg);
} else if (!strcmp(cmd, "size")) {
dosize(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "chmod")) {
sitearg = arg;
goto parsechmod;
#endif
} else if (!strcmp(cmd, "rnfr")) {
if (*arg != 0) {
dornfr(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rnto")) {
arg = revealextraspc(arg);
if (*arg != 0) {
dornto(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else {
addreply_noformat(500, MSG_UNKNOWN_COMMAND);
}
}
noopidle = (time_t) -1;
wayout:
#ifdef WITH_RFC2640
free(narg);
narg = NULL;
#endif
#ifdef THROTTLING
if (throttling_delay != 0UL) {
usleep2(throttling_delay);
}
#else
(void) 0;
#endif
}
}
Commit Message: Flush the command buffer after switching to TLS.
Fixes a flaw similar to CVE-2011-0411.
CWE ID: CWE-399 | void parser(void)
{
char *arg;
#ifndef MINIMAL
char *sitearg;
#endif
#ifdef WITH_RFC2640
char *narg = NULL;
#endif
size_t n;
#ifdef IMPLICIT_TLS
(void) tls_init_new_session();
data_protection_level = CPL_PRIVATE;
#endif
for (;;) {
xferfd = -1;
if (state_needs_update != 0) {
state_needs_update = 0;
setprocessname("pure-ftpd (IDLE)");
#ifdef FTPWHO
if (shm_data_cur != NULL) {
ftpwho_lock();
shm_data_cur->state = FTPWHO_STATE_IDLE;
*shm_data_cur->filename = 0;
ftpwho_unlock();
}
#endif
}
doreply();
alarm(idletime * 2);
switch (sfgets()) {
case -1:
#ifdef BORING_MODE
die(421, LOG_INFO, MSG_TIMEOUT);
#else
die(421, LOG_INFO, MSG_TIMEOUT_PARSER);
#endif
case -2:
return;
}
#ifdef DEBUG
if (debug != 0) {
addreply(0, "%s", cmd);
}
#endif
n = (size_t) 0U;
while ((isalpha((unsigned char) cmd[n]) || cmd[n] == '@') &&
n < cmdsize) {
cmd[n] = (char) tolower((unsigned char) cmd[n]);
n++;
}
if (n >= cmdsize) { /* overparanoid, it should never happen */
die(421, LOG_WARNING, MSG_LINE_TOO_LONG);
}
if (n == (size_t) 0U) {
nop:
addreply_noformat(500, "?");
continue;
}
#ifdef SKIP_COMMAND_TRAILING_SPACES
while (isspace((unsigned char) cmd[n]) && n < cmdsize) {
cmd[n++] = 0;
}
arg = cmd + n;
while (cmd[n] != 0 && n < cmdsize) {
n++;
}
n--;
while (isspace((unsigned char) cmd[n])) {
cmd[n--] = 0;
}
#else
if (cmd[n] == 0) {
arg = cmd + n;
} else if (isspace((unsigned char) cmd[n])) {
cmd[n] = 0;
arg = cmd + n + 1;
} else {
goto nop;
}
#endif
if (logging != 0) {
#ifdef DEBUG
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, arg);
#else
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, strcmp(cmd, "pass") ? arg : "<*>");
#endif
}
#ifdef WITH_RFC2640
narg = charset_client2fs(arg);
arg = narg;
#endif
/*
* antiidle() is called with dummy commands, usually used by clients
* who are wanting extra idle time. We give them some, but not too much.
* When we jump to wayout, the idle timer is not zeroed. It means that
* we didn't issue an 'active' command like RETR.
*/
#ifndef MINIMAL
if (!strcmp(cmd, "noop")) {
antiidle();
donoop();
goto wayout;
}
#endif
if (!strcmp(cmd, "user")) {
#ifdef WITH_TLS
if (enforce_tls_auth > 1 && tls_cnx == NULL) {
die(421, LOG_WARNING, MSG_TLS_NEEDED);
}
#endif
douser(arg);
} else if (!strcmp(cmd, "acct")) {
addreply(202, MSG_WHOAREYOU);
} else if (!strcmp(cmd, "pass")) {
if (guest == 0) {
randomdelay();
}
dopass(arg);
} else if (!strcmp(cmd, "quit")) {
addreply(221, MSG_GOODBYE,
(unsigned long long) ((uploaded + 1023ULL) / 1024ULL),
(unsigned long long) ((downloaded + 1023ULL) / 1024ULL));
return;
} else if (!strcmp(cmd, "syst")) {
antiidle();
addreply_noformat(215, "UNIX Type: L8");
goto wayout;
#ifdef WITH_TLS
} else if (enforce_tls_auth > 0 &&
!strcmp(cmd, "auth") && !strcasecmp(arg, "tls")) {
addreply_noformat(234, "AUTH TLS OK.");
doreply();
if (tls_cnx == NULL) {
flush_cmd();
(void) tls_init_new_session();
}
goto wayout;
} else if (!strcmp(cmd, "pbsz")) {
addreply_noformat(tls_cnx == NULL ? 503 : 200, "PBSZ=0");
} else if (!strcmp(cmd, "prot")) {
if (tls_cnx == NULL) {
addreply_noformat(503, MSG_PROT_BEFORE_PBSZ);
goto wayout;
}
switch (*arg) {
case 0:
addreply_noformat(503, MSG_MISSING_ARG);
data_protection_level = CPL_NONE;
break;
case 'C':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "clear");
data_protection_level = CPL_CLEAR;
break;
}
case 'S':
case 'E':
if (arg[1] == 0) {
addreply(200, MSG_PROT_UNKNOWN_LEVEL, arg, "private");
data_protection_level = CPL_PRIVATE;
break;
}
case 'P':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "private");
data_protection_level = CPL_PRIVATE;
break;
}
default:
addreply_noformat(534, "Fallback to [C]");
data_protection_level = CPL_CLEAR;
break;
}
#endif
} else if (!strcmp(cmd, "auth") || !strcmp(cmd, "adat")) {
addreply_noformat(500, MSG_AUTH_UNIMPLEMENTED);
} else if (!strcmp(cmd, "type")) {
antiidle();
dotype(arg);
goto wayout;
} else if (!strcmp(cmd, "mode")) {
antiidle();
domode(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "feat")) {
dofeat();
goto wayout;
} else if (!strcmp(cmd, "opts")) {
doopts(arg);
goto wayout;
#endif
} else if (!strcmp(cmd, "stru")) {
dostru(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "help")) {
goto help_site;
#endif
#ifdef DEBUG
} else if (!strcmp(cmd, "xdbg")) {
debug++;
addreply(200, MSG_XDBG_OK, debug);
goto wayout;
#endif
} else if (loggedin == 0) {
/* from this point, all commands need authentication */
addreply_noformat(530, MSG_NOT_LOGGED_IN);
goto wayout;
} else {
if (!strcmp(cmd, "cwd") || !strcmp(cmd, "xcwd")) {
antiidle();
docwd(arg);
goto wayout;
} else if (!strcmp(cmd, "port")) {
doport(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "eprt")) {
doeprt(arg);
} else if (!strcmp(cmd, "esta") &&
disallow_passive == 0 &&
STORAGE_FAMILY(force_passive_ip) == 0) {
doesta();
} else if (!strcmp(cmd, "estp")) {
doestp();
#endif
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "pasv") || !strcmp(cmd, "p@sw"))) {
dopasv(0);
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "epsv") &&
(broken_client_compat == 0 ||
STORAGE_FAMILY(ctrlconn) == AF_INET6))) {
if (!strcasecmp(arg, "all")) {
epsv_all = 1;
addreply_noformat(220, MSG_ACTIVE_DISABLED);
} else if (!strcmp(arg, "2") && !v6ready) {
addreply_noformat(522, MSG_ONLY_IPV4);
} else {
dopasv(1);
}
#ifndef MINIMAL
} else if (disallow_passive == 0 && !strcmp(cmd, "spsv")) {
dopasv(2);
} else if (!strcmp(cmd, "allo")) {
if (*arg == 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
const off_t size = (off_t) strtoull(arg, NULL, 10);
if (size < (off_t) 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
doallo(size);
}
}
#endif
} else if (!strcmp(cmd, "pwd") || !strcmp(cmd, "xpwd")) {
#ifdef WITH_RFC2640
char *nwd;
#endif
antiidle();
#ifdef WITH_RFC2640
nwd = charset_fs2client(wd);
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, nwd);
free(nwd);
#else
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, wd);
#endif
goto wayout;
} else if (!strcmp(cmd, "cdup") || !strcmp(cmd, "xcup")) {
docwd("..");
} else if (!strcmp(cmd, "retr")) {
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
}
else
#endif
{
doretr(arg);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rest")) {
antiidle();
if (*arg != 0) {
dorest(arg);
} else {
addreply_noformat(501, MSG_NO_RESTART_POINT);
restartat = (off_t) 0;
}
goto wayout;
} else if (!strcmp(cmd, "dele")) {
if (*arg != 0) {
dodele(arg);
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "stor")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 0, autorename);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "appe")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 1, 0);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "stou")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostou();
}
#endif
#ifndef DISABLE_MKD_RMD
} else if (!strcmp(cmd, "mkd") || !strcmp(cmd, "xmkd")) {
arg = revealextraspc(arg);
if (*arg != 0) {
domkd(arg);
} else {
addreply_noformat(501, MSG_NO_DIRECTORY_NAME);
}
} else if (!strcmp(cmd, "rmd") || !strcmp(cmd, "xrmd")) {
if (*arg != 0) {
dormd(arg);
} else {
addreply_noformat(550, MSG_NO_DIRECTORY_NAME);
}
#endif
#ifndef MINIMAL
} else if (!strcmp(cmd, "stat")) {
if (*arg != 0) {
modern_listings = 0;
donlist(arg, 1, 1, 1, 1);
} else {
addreply_noformat(211, "http://www.pureftpd.org/");
}
#endif
} else if (!strcmp(cmd, "list")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 0, 1);
}
} else if (!strcmp(cmd, "nlst")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 0, 0, broken_client_compat);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "mlst")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
domlst(*arg != 0 ? arg : ".");
}
} else if (!strcmp(cmd, "mlsd")) {
modern_listings = 1;
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 1, 0);
}
#endif
} else if (!strcmp(cmd, "abor")) {
addreply_noformat(226, MSG_ABOR_SUCCESS);
#ifndef MINIMAL
} else if (!strcmp(cmd, "site")) {
if ((sitearg = arg) != NULL) {
while (*sitearg != 0 && !isspace((unsigned char) *sitearg)) {
sitearg++;
}
if (*sitearg != 0) {
*sitearg++ = 0;
}
}
if (!strcasecmp(arg, "idle")) {
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, "SITE IDLE: " MSG_MISSING_ARG);
} else {
unsigned long int i = 0;
i = strtoul(sitearg, &sitearg, 10);
if (sitearg && *sitearg)
addreply(501, MSG_GARBAGE_FOUND " : %s", sitearg);
else if (i > MAX_SITE_IDLE)
addreply_noformat(501, MSG_VALUE_TOO_LARGE);
else {
idletime = i;
addreply(200, MSG_IDLE_TIME, idletime);
idletime_noop = (double) idletime * 2.0;
}
}
} else if (!strcasecmp(arg, "time")) {
dositetime();
} else if (!strcasecmp(arg, "help")) {
help_site:
addreply_noformat(214, MSG_SITE_HELP CRLF
# ifdef WITH_DIRALIASES
" ALIAS" CRLF
# endif
" CHMOD" CRLF " IDLE" CRLF " UTIME");
addreply_noformat(214, "Pure-FTPd - http://pureftpd.org/");
} else if (!strcasecmp(arg, "chmod")) {
char *sitearg2;
mode_t mode;
parsechmod:
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_MISSING_ARG);
goto chmod_wayout;
}
sitearg2 = sitearg;
while (*sitearg2 != 0 && !isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
while (*sitearg2 != 0 && isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
if (*sitearg2 == 0) {
addreply_noformat(550, MSG_NO_FILE_NAME);
goto chmod_wayout;
}
mode = (mode_t) strtoul(sitearg, NULL, 8);
if (mode > (mode_t) 07777) {
addreply_noformat(501, MSG_BAD_CHMOD);
goto chmod_wayout;
}
dochmod(sitearg2, mode);
chmod_wayout:
(void) 0;
} else if (!strcasecmp(arg, "utime")) {
char *sitearg2;
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_NO_FILE_NAME);
goto utime_wayout;
}
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
if (strcasecmp(sitearg2, " UTC") != 0) {
addreply_noformat(500, "UTC Only");
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
utime_no_arg:
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2++ = 0;
if (*sitearg2 == 0) {
goto utime_no_arg;
}
doutime(sitearg, sitearg2);
utime_wayout:
(void) 0;
# ifdef WITH_DIRALIASES
} else if (!strcasecmp(arg, "alias")) {
if (sitearg == NULL || *sitearg == 0) {
print_aliases();
} else {
const char *alias;
if ((alias = lookup_alias(sitearg)) != NULL) {
addreply(214, MSG_ALIASES_ALIAS, sitearg, alias);
} else {
addreply(502, MSG_ALIASES_UNKNOWN, sitearg);
}
}
# endif
} else if (*arg != 0) {
addreply(500, "SITE %s " MSG_UNKNOWN_EXTENSION, arg);
} else {
addreply_noformat(500, "SITE: " MSG_MISSING_ARG);
}
#endif
} else if (!strcmp(cmd, "mdtm")) {
domdtm(arg);
} else if (!strcmp(cmd, "size")) {
dosize(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "chmod")) {
sitearg = arg;
goto parsechmod;
#endif
} else if (!strcmp(cmd, "rnfr")) {
if (*arg != 0) {
dornfr(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rnto")) {
arg = revealextraspc(arg);
if (*arg != 0) {
dornto(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else {
addreply_noformat(500, MSG_UNKNOWN_COMMAND);
}
}
noopidle = (time_t) -1;
wayout:
#ifdef WITH_RFC2640
free(narg);
narg = NULL;
#endif
#ifdef THROTTLING
if (throttling_delay != 0UL) {
usleep2(throttling_delay);
}
#else
(void) 0;
#endif
}
}
| 165,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reflectStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::reflectstringattributeAttr, cppValue);
}
Commit Message: binding: Removes unused code in templates/attributes.cpp.
Faking {{cpp_class}} and {{c8_class}} doesn't make sense.
Probably it made sense before the introduction of virtual
ScriptWrappable::wrap().
Checking the existence of window->document() doesn't seem
making sense to me, and CQ tests seem passing without the
check.
BUG=
Review-Url: https://codereview.chromium.org/2268433002
Cr-Commit-Position: refs/heads/master@{#413375}
CWE ID: CWE-189 | static void reflectStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::reflectstringattributeAttr, cppValue);
}
| 171,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: chpass_principal_2_svc(chpass_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
FALSE, 0, NULL, arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal((void *)handle, arg->princ,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if (ret.code != KADM5_AUTH_CHANGEPW) {
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | chpass_principal_2_svc(chpass_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
FALSE, 0, NULL, arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal((void *)handle, arg->princ,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if (ret.code != KADM5_AUTH_CHANGEPW) {
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,505 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_TCHECK2(tptr[0], 5);
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
ND_TCHECK2(tptr[0], 3);
tlen = len;
while (tlen >= 3) {
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length - 3);
switch (type) {
case BGP_AIGP_TLV:
ND_TCHECK2(tptr[3], 8);
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr+3)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr+3,"\n\t ", length-3);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
Commit Message: CVE-2017-12991/BGP: Add missing bounds check.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (len - (tptr - pptr) > 0) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_TCHECK2(tptr[0], 5);
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
ND_TCHECK2(tptr[0], 3);
tlen = len;
while (tlen >= 3) {
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length - 3);
switch (type) {
case BGP_AIGP_TLV:
ND_TCHECK2(tptr[3], 8);
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr+3)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr+3,"\n\t ", length-3);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
| 167,923 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return key;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
rb_ivar_set(self, id_key_set, Qtrue);
return key;
}
| 168,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_client_master_key(SSL *s)
{
int is_export, i, n, keya;
unsigned int num_encrypted_key_bytes, key_length;
unsigned long len;
unsigned char *p;
const SSL_CIPHER *cp;
const EVP_CIPHER *c;
const EVP_MD *md;
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char decrypt_good;
size_t j;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num);
if (i < (10 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
s->init_num = 10;
if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR);
return (-1);
}
cp = ssl2_get_cipher_by_char(p);
if (cp == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = cp;
p += 3;
n2s(p, i);
s->s2->tmp.clear = i;
n2s(p, i);
s->s2->tmp.enc = i;
n2s(p, i);
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG);
return -1;
}
s->session->key_arg_length = i;
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B;
}
/* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
p = (unsigned char *)s->init_buf->data;
if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
keya = s->session->key_arg_length;
len =
10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc +
(unsigned long)keya;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
if (s->msg_callback) {
/* CLIENT-MASTER-KEY */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 10;
memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]),
(unsigned int)keya);
if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY);
return (-1);
}
is_export = SSL_C_IS_EXPORT(s->session->cipher);
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
/*
* The format of the CLIENT-MASTER-KEY message is
* 1 byte message type
* 3 bytes cipher
* 2-byte clear key length (stored in s->s2->tmp.clear)
* 2-byte encrypted key length (stored in s->s2->tmp.enc)
* 2-byte key args length (IV etc)
* clear key
* encrypted key
* key args
*
* If the cipher is an export cipher, then the encrypted key bytes
* are a fixed portion of the total key (5 or 8 bytes). The size of
* this portion is in |num_encrypted_key_bytes|. If the cipher is not an
* export cipher, then the entire key material is encrypted (i.e., clear
* key length must be zero).
*/
key_length = (unsigned int)EVP_CIPHER_key_length(c);
if (key_length > SSL_MAX_MASTER_KEY_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) {
is_export = 1;
num_encrypted_key_bytes = 8;
} else if (is_export) {
num_encrypted_key_bytes = 5;
} else {
num_encrypted_key_bytes = key_length;
}
if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH);
return -1;
}
/*
* The encrypted blob must decrypt to the encrypted portion of the key.
* Decryption can't be expanding, so if we don't have enough encrypted
* bytes to fit the key in the buffer, stop now.
*/
if (s->s2->tmp.enc < num_encrypted_key_bytes) {
ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT);
return -1;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
(int)num_encrypted_key_bytes) <= 0)
return 0;
i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc,
&(p[s->s2->tmp.clear]),
&(p[s->s2->tmp.clear]),
(s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING :
RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* If a bad decrypt, continue with protocol but with a random master
* secret (Bleichenbacher attack)
*/
decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes);
for (j = 0; j < num_encrypted_key_bytes; j++) {
p[s->s2->tmp.clear + j] =
constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j],
rand_premaster_secret[j]);
}
s->session->master_key_length = (int)key_length;
memcpy(s->session->master_key, p, key_length);
OPENSSL_cleanse(p, key_length);
return 1;
}
Commit Message:
CWE ID: CWE-310 | static int get_client_master_key(SSL *s)
{
int is_export, i, n, keya;
unsigned int num_encrypted_key_bytes, key_length;
unsigned long len;
unsigned char *p;
const SSL_CIPHER *cp;
const EVP_CIPHER *c;
const EVP_MD *md;
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char decrypt_good;
size_t j;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num);
if (i < (10 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
s->init_num = 10;
if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR);
return (-1);
}
cp = ssl2_get_cipher_by_char(p);
if (cp == NULL || sk_SSL_CIPHER_find(s->session->ciphers, cp) < 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = cp;
p += 3;
n2s(p, i);
s->s2->tmp.clear = i;
n2s(p, i);
s->s2->tmp.enc = i;
n2s(p, i);
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG);
return -1;
}
s->session->key_arg_length = i;
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B;
}
/* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
p = (unsigned char *)s->init_buf->data;
if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
keya = s->session->key_arg_length;
len =
10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc +
(unsigned long)keya;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
if (s->msg_callback) {
/* CLIENT-MASTER-KEY */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 10;
memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]),
(unsigned int)keya);
if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY);
return (-1);
}
is_export = SSL_C_IS_EXPORT(s->session->cipher);
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
/*
* The format of the CLIENT-MASTER-KEY message is
* 1 byte message type
* 3 bytes cipher
* 2-byte clear key length (stored in s->s2->tmp.clear)
* 2-byte encrypted key length (stored in s->s2->tmp.enc)
* 2-byte key args length (IV etc)
* clear key
* encrypted key
* key args
*
* If the cipher is an export cipher, then the encrypted key bytes
* are a fixed portion of the total key (5 or 8 bytes). The size of
* this portion is in |num_encrypted_key_bytes|. If the cipher is not an
* export cipher, then the entire key material is encrypted (i.e., clear
* key length must be zero).
*/
key_length = (unsigned int)EVP_CIPHER_key_length(c);
if (key_length > SSL_MAX_MASTER_KEY_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) {
is_export = 1;
num_encrypted_key_bytes = 8;
} else if (is_export) {
num_encrypted_key_bytes = 5;
} else {
num_encrypted_key_bytes = key_length;
}
if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH);
return -1;
}
/*
* The encrypted blob must decrypt to the encrypted portion of the key.
* Decryption can't be expanding, so if we don't have enough encrypted
* bytes to fit the key in the buffer, stop now.
*/
if (s->s2->tmp.enc < num_encrypted_key_bytes) {
ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT);
return -1;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
(int)num_encrypted_key_bytes) <= 0)
return 0;
i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc,
&(p[s->s2->tmp.clear]),
&(p[s->s2->tmp.clear]),
(s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING :
RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* If a bad decrypt, continue with protocol but with a random master
* secret (Bleichenbacher attack)
*/
decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes);
for (j = 0; j < num_encrypted_key_bytes; j++) {
p[s->s2->tmp.clear + j] =
constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j],
rand_premaster_secret[j]);
}
s->session->master_key_length = (int)key_length;
memcpy(s->session->master_key, p, key_length);
OPENSSL_cleanse(p, key_length);
return 1;
}
| 165,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
{
int rc = -ENOMEM, xid;
struct cifsSesInfo *ses;
xid = GetXid();
ses = cifs_find_smb_ses(server, volume_info->username);
if (ses) {
cFYI(1, "Existing smb sess found (status=%d)", ses->status);
/* existing SMB ses has a server reference already */
cifs_put_tcp_session(server);
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our ses reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
if (ses->need_reconnect) {
cFYI(1, "Session needs reconnect");
rc = cifs_setup_session(xid, ses,
volume_info->local_nls);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
}
mutex_unlock(&ses->session_mutex);
FreeXid(xid);
return ses;
}
cFYI(1, "Existing smb sess not found");
ses = sesInfoAlloc();
if (ses == NULL)
goto get_ses_fail;
/* new SMB session uses our server ref */
ses->server = server;
if (server->addr.sockAddr6.sin6_family == AF_INET6)
sprintf(ses->serverName, "%pI6",
&server->addr.sockAddr6.sin6_addr);
else
sprintf(ses->serverName, "%pI4",
&server->addr.sockAddr.sin_addr.s_addr);
if (volume_info->username)
strncpy(ses->userName, volume_info->username,
MAX_USERNAME_SIZE);
/* volume_info->password freed at unmount */
if (volume_info->password) {
ses->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!ses->password)
goto get_ses_fail;
}
if (volume_info->domainname) {
int len = strlen(volume_info->domainname);
ses->domainName = kmalloc(len + 1, GFP_KERNEL);
if (ses->domainName)
strcpy(ses->domainName, volume_info->domainname);
}
ses->linux_uid = volume_info->linux_uid;
ses->overrideSecFlg = volume_info->secFlg;
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (!rc)
rc = cifs_setup_session(xid, ses, volume_info->local_nls);
mutex_unlock(&ses->session_mutex);
if (rc)
goto get_ses_fail;
/* success, put it on the list */
write_lock(&cifs_tcp_ses_lock);
list_add(&ses->smb_ses_list, &server->smb_ses_list);
write_unlock(&cifs_tcp_ses_lock);
FreeXid(xid);
return ses;
get_ses_fail:
sesInfoFree(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
Commit Message: cifs: clean up cifs_find_smb_ses (try #2)
This patch replaces the earlier patch by the same name. The only
difference is that MAX_PASSWORD_SIZE has been increased to attempt to
match the limits that windows enforces.
Do a better job of matching sessions by authtype. Matching by username
for a Kerberos session is incorrect, and anonymous sessions need special
handling.
Also, in the case where we do match by username, we also need to match
by password. That ensures that someone else doesn't "borrow" an existing
session without needing to know the password.
Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE
to 512 to match the size that the userspace mount helper allows.
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[email protected]>
CWE ID: CWE-264 | cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
{
int rc = -ENOMEM, xid;
struct cifsSesInfo *ses;
xid = GetXid();
ses = cifs_find_smb_ses(server, volume_info);
if (ses) {
cFYI(1, "Existing smb sess found (status=%d)", ses->status);
/* existing SMB ses has a server reference already */
cifs_put_tcp_session(server);
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our ses reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
if (ses->need_reconnect) {
cFYI(1, "Session needs reconnect");
rc = cifs_setup_session(xid, ses,
volume_info->local_nls);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
}
mutex_unlock(&ses->session_mutex);
FreeXid(xid);
return ses;
}
cFYI(1, "Existing smb sess not found");
ses = sesInfoAlloc();
if (ses == NULL)
goto get_ses_fail;
/* new SMB session uses our server ref */
ses->server = server;
if (server->addr.sockAddr6.sin6_family == AF_INET6)
sprintf(ses->serverName, "%pI6",
&server->addr.sockAddr6.sin6_addr);
else
sprintf(ses->serverName, "%pI4",
&server->addr.sockAddr.sin_addr.s_addr);
if (volume_info->username)
strncpy(ses->userName, volume_info->username,
MAX_USERNAME_SIZE);
/* volume_info->password freed at unmount */
if (volume_info->password) {
ses->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!ses->password)
goto get_ses_fail;
}
if (volume_info->domainname) {
int len = strlen(volume_info->domainname);
ses->domainName = kmalloc(len + 1, GFP_KERNEL);
if (ses->domainName)
strcpy(ses->domainName, volume_info->domainname);
}
ses->linux_uid = volume_info->linux_uid;
ses->overrideSecFlg = volume_info->secFlg;
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (!rc)
rc = cifs_setup_session(xid, ses, volume_info->local_nls);
mutex_unlock(&ses->session_mutex);
if (rc)
goto get_ses_fail;
/* success, put it on the list */
write_lock(&cifs_tcp_ses_lock);
list_add(&ses->smb_ses_list, &server->smb_ses_list);
write_unlock(&cifs_tcp_ses_lock);
FreeXid(xid);
return ses;
get_ses_fail:
sesInfoFree(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
| 166,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
IncludePrivacySensitiveFields include_privacy_sensitive_fields) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
if (include_privacy_sensitive_fields == INCLUDE_PRIVACY_SENSITIVE_FIELDS) {
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
// Privacy-sensitive fields: these should be stripped off by
// ScrubTabValueForExtension if the extension should not see them.
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
| 171,455 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NetworkHandler::ContinueInterceptedRequest(
const std::string& interception_id,
Maybe<std::string> error_reason,
Maybe<std::string> base64_raw_response,
Maybe<std::string> url,
Maybe<std::string> method,
Maybe<std::string> post_data,
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
return;
}
raw_response = decoded;
}
base::Optional<net::Error> error;
bool mark_as_canceled = false;
if (error_reason.isJust()) {
bool ok;
error = NetErrorFromString(error_reason.fromJust(), &ok);
if (!ok) {
callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
return;
}
mark_as_canceled = true;
}
interceptor->ContinueInterceptedRequest(
interception_id,
std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
std::move(auth_challenge_response), mark_as_canceled),
std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::ContinueInterceptedRequest(
const std::string& interception_id,
Maybe<std::string> error_reason,
Maybe<std::string> base64_raw_response,
Maybe<std::string> url,
Maybe<std::string> method,
Maybe<std::string> post_data,
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
return;
}
raw_response = decoded;
}
base::Optional<net::Error> error;
bool mark_as_canceled = false;
if (error_reason.isJust()) {
bool ok;
error = NetErrorFromString(error_reason.fromJust(), &ok);
if (!ok) {
callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
return;
}
mark_as_canceled = true;
}
interceptor->ContinueInterceptedRequest(
interception_id,
std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
std::move(auth_challenge_response), mark_as_canceled),
std::move(callback));
}
| 172,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int netbk_set_skb_gso(struct xenvif *vif,
struct sk_buff *skb,
struct xen_netif_extra_info *gso)
{
if (!gso->u.gso.size) {
netdev_dbg(vif->dev, "GSO size must not be zero.\n");
return -EINVAL;
}
/* Currently only TCPv4 S.O. is supported. */
if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
netdev_dbg(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
return -EINVAL;
}
skb_shinfo(skb)->gso_size = gso->u.gso.size;
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
return 0;
}
Commit Message: xen/netback: shutdown the ring if it contains garbage.
A buggy or malicious frontend should not be able to confuse netback.
If we spot anything which is not as it should be then shutdown the
device and don't try to continue with the ring in a potentially
hostile state. Well behaved and non-hostile frontends will not be
penalised.
As well as making the existing checks for such errors fatal also add a
new check that ensures that there isn't an insane number of requests
on the ring (i.e. more than would fit in the ring). If the ring
contains garbage then previously is was possible to loop over this
insane number, getting an error each time and therefore not generating
any more pending requests and therefore not exiting the loop in
xen_netbk_tx_build_gops for an externded period.
Also turn various netdev_dbg calls which no precipitate a fatal error
into netdev_err, they are rate limited because the device is shutdown
afterwards.
This fixes at least one known DoS/softlockup of the backend domain.
Signed-off-by: Ian Campbell <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int netbk_set_skb_gso(struct xenvif *vif,
struct sk_buff *skb,
struct xen_netif_extra_info *gso)
{
if (!gso->u.gso.size) {
netdev_err(vif->dev, "GSO size must not be zero.\n");
netbk_fatal_tx_err(vif);
return -EINVAL;
}
/* Currently only TCPv4 S.O. is supported. */
if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
netdev_err(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
netbk_fatal_tx_err(vif);
return -EINVAL;
}
skb_shinfo(skb)->gso_size = gso->u.gso.size;
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
return 0;
}
| 166,173 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
struct userfaultfd_ctx *release_new_ctx;
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
release_new_ctx = NULL;
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (READ_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
/*
* &ewq->wq may be queued in fork_event, but
* __remove_wait_queue ignores the head
* parameter. It would be a problem if it
* didn't.
*/
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
release_new_ctx = new;
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, EPOLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
if (release_new_ctx) {
struct vm_area_struct *vma;
struct mm_struct *mm = release_new_ctx->mm;
/* the various vma->vm_userfaultfd_ctx still points to it */
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
}
up_write(&mm->mmap_sem);
userfaultfd_ctx_put(release_new_ctx);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
WRITE_ONCE(ctx->mmap_changing, false);
userfaultfd_ctx_put(ctx);
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
struct userfaultfd_ctx *release_new_ctx;
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
release_new_ctx = NULL;
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (READ_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
/*
* &ewq->wq may be queued in fork_event, but
* __remove_wait_queue ignores the head
* parameter. It would be a problem if it
* didn't.
*/
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
release_new_ctx = new;
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, EPOLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
if (release_new_ctx) {
struct vm_area_struct *vma;
struct mm_struct *mm = release_new_ctx->mm;
/* the various vma->vm_userfaultfd_ctx still points to it */
down_write(&mm->mmap_sem);
/* no task can run (and in turn coredump) yet */
VM_WARN_ON(!mmget_still_valid(mm));
for (vma = mm->mmap; vma; vma = vma->vm_next)
if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
}
up_write(&mm->mmap_sem);
userfaultfd_ctx_put(release_new_ctx);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
WRITE_ONCE(ctx->mmap_changing, false);
userfaultfd_ctx_put(ctx);
}
| 169,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_watching_parent (void)
{
pid_t child;
sigset_t ourset;
struct sigaction oldact[3];
int status = 0;
int retval;
retval = pam_open_session (pamh, 0);
if (is_pam_failure(retval))
{
cleanup_pam (retval);
errx (EXIT_FAILURE, _("cannot open session: %s"),
pam_strerror (pamh, retval));
}
else
_pam_session_opened = 1;
memset(oldact, 0, sizeof(oldact));
child = fork ();
if (child == (pid_t) -1)
{
cleanup_pam (PAM_ABORT);
err (EXIT_FAILURE, _("cannot create child process"));
}
/* the child proceeds to run the shell */
if (child == 0)
return;
/* In the parent watch the child. */
/* su without pam support does not have a helper that keeps
sitting on any directory so let's go to /. */
if (chdir ("/") != 0)
warn (_("cannot change directory to %s"), "/");
sigfillset (&ourset);
if (sigprocmask (SIG_BLOCK, &ourset, NULL))
{
warn (_("cannot block signals"));
caught_signal = true;
}
if (!caught_signal)
{
struct sigaction action;
action.sa_handler = su_catch_sig;
sigemptyset (&action.sa_mask);
action.sa_flags = 0;
sigemptyset (&ourset);
if (!same_session)
{
if (sigaddset(&ourset, SIGINT) || sigaddset(&ourset, SIGQUIT))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal && (sigaddset(&ourset, SIGTERM)
|| sigaddset(&ourset, SIGALRM)
|| sigaction(SIGTERM, &action, &oldact[0])
|| sigprocmask(SIG_UNBLOCK, &ourset, NULL))) {
warn (_("cannot set signal handler"));
caught_signal = true;
}
if (!caught_signal && !same_session && (sigaction(SIGINT, &action, &oldact[1])
|| sigaction(SIGQUIT, &action, &oldact[2])))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal)
{
pid_t pid;
for (;;)
{
pid = waitpid (child, &status, WUNTRACED);
if (pid != (pid_t)-1 && WIFSTOPPED (status))
{
kill (getpid (), SIGSTOP);
/* once we get here, we must have resumed */
kill (pid, SIGCONT);
}
else
break;
}
if (pid != (pid_t)-1)
{
if (WIFSIGNALED (status))
{
fprintf (stderr, "%s%s\n", strsignal (WTERMSIG (status)),
WCOREDUMP (status) ? _(" (core dumped)") : "");
status = WTERMSIG (status) + 128;
}
else
status = WEXITSTATUS (status);
}
else if (caught_signal)
status = caught_signal + 128;
else
status = 1;
}
else
status = 1;
if (caught_signal)
{
fprintf (stderr, _("\nSession terminated, killing shell..."));
kill (child, SIGTERM);
}
cleanup_pam (PAM_SUCCESS);
if (caught_signal)
{
sleep (2);
kill (child, SIGKILL);
fprintf (stderr, _(" ...killed.\n"));
/* Let's terminate itself with the received signal.
*
* It seems that shells use WIFSIGNALED() rather than our exit status
* value to detect situations when is necessary to cleanup (reset)
* terminal settings (kzak -- Jun 2013).
*/
switch (caught_signal) {
case SIGTERM:
sigaction(SIGTERM, &oldact[0], NULL);
break;
case SIGINT:
sigaction(SIGINT, &oldact[1], NULL);
break;
case SIGQUIT:
sigaction(SIGQUIT, &oldact[2], NULL);
break;
default:
/* just in case that signal stuff initialization failed and
* caught_signal = true */
caught_signal = SIGKILL;
break;
}
kill(getpid(), caught_signal);
}
exit (status);
}
Commit Message: su: properly clear child PID
Reported-by: Tobias Stöckmann <[email protected]>
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-362 | create_watching_parent (void)
{
pid_t child;
sigset_t ourset;
struct sigaction oldact[3];
int status = 0;
int retval;
retval = pam_open_session (pamh, 0);
if (is_pam_failure(retval))
{
cleanup_pam (retval);
errx (EXIT_FAILURE, _("cannot open session: %s"),
pam_strerror (pamh, retval));
}
else
_pam_session_opened = 1;
memset(oldact, 0, sizeof(oldact));
child = fork ();
if (child == (pid_t) -1)
{
cleanup_pam (PAM_ABORT);
err (EXIT_FAILURE, _("cannot create child process"));
}
/* the child proceeds to run the shell */
if (child == 0)
return;
/* In the parent watch the child. */
/* su without pam support does not have a helper that keeps
sitting on any directory so let's go to /. */
if (chdir ("/") != 0)
warn (_("cannot change directory to %s"), "/");
sigfillset (&ourset);
if (sigprocmask (SIG_BLOCK, &ourset, NULL))
{
warn (_("cannot block signals"));
caught_signal = true;
}
if (!caught_signal)
{
struct sigaction action;
action.sa_handler = su_catch_sig;
sigemptyset (&action.sa_mask);
action.sa_flags = 0;
sigemptyset (&ourset);
if (!same_session)
{
if (sigaddset(&ourset, SIGINT) || sigaddset(&ourset, SIGQUIT))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal && (sigaddset(&ourset, SIGTERM)
|| sigaddset(&ourset, SIGALRM)
|| sigaction(SIGTERM, &action, &oldact[0])
|| sigprocmask(SIG_UNBLOCK, &ourset, NULL))) {
warn (_("cannot set signal handler"));
caught_signal = true;
}
if (!caught_signal && !same_session && (sigaction(SIGINT, &action, &oldact[1])
|| sigaction(SIGQUIT, &action, &oldact[2])))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal)
{
pid_t pid;
for (;;)
{
pid = waitpid (child, &status, WUNTRACED);
if (pid != (pid_t)-1 && WIFSTOPPED (status))
{
kill (getpid (), SIGSTOP);
/* once we get here, we must have resumed */
kill (pid, SIGCONT);
}
else
break;
}
if (pid != (pid_t)-1)
{
if (WIFSIGNALED (status))
{
fprintf (stderr, "%s%s\n", strsignal (WTERMSIG (status)),
WCOREDUMP (status) ? _(" (core dumped)") : "");
status = WTERMSIG (status) + 128;
}
else
status = WEXITSTATUS (status);
/* child is gone, don't use the PID anymore */
child = (pid_t) -1;
}
else if (caught_signal)
status = caught_signal + 128;
else
status = 1;
}
else
status = 1;
if (caught_signal && child != (pid_t)-1)
{
fprintf (stderr, _("\nSession terminated, killing shell..."));
kill (child, SIGTERM);
}
cleanup_pam (PAM_SUCCESS);
if (caught_signal)
{
if (child != (pid_t)-1)
{
sleep (2);
kill (child, SIGKILL);
fprintf (stderr, _(" ...killed.\n"));
}
/* Let's terminate itself with the received signal.
*
* It seems that shells use WIFSIGNALED() rather than our exit status
* value to detect situations when is necessary to cleanup (reset)
* terminal settings (kzak -- Jun 2013).
*/
switch (caught_signal) {
case SIGTERM:
sigaction(SIGTERM, &oldact[0], NULL);
break;
case SIGINT:
sigaction(SIGINT, &oldact[1], NULL);
break;
case SIGQUIT:
sigaction(SIGQUIT, &oldact[2], NULL);
break;
default:
/* just in case that signal stuff initialization failed and
* caught_signal = true */
caught_signal = SIGKILL;
break;
}
kill(getpid(), caught_signal);
}
exit (status);
}
| 169,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::Info::~Info()
{
Clear();
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Track::Info::~Info()
| 174,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
Commit Message: [Extensions] Don't allow built-in extensions code to be overridden
BUG=546677
Review URL: https://codereview.chromium.org/1417513003
Cr-Commit-Position: refs/heads/master@{#356654}
CWE ID: CWE-264 | v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Object> exports = v8::Object::New(GetIsolate());
v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
GetIsolate(),
&SetExportsProperty);
v8::Local<v8::String> v8_key;
if (!v8_helpers::ToV8String(GetIsolate(), "$set", &v8_key)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> function;
if (!tmpl->GetFunction(v8_context).ToLocal(&function)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
exports->ForceSet(v8_key, function, v8::ReadOnly);
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
| 172,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool StopInputMethodProcess() {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive";
return false;
}
ibus_bus_exit_async(ibus_,
FALSE /* do not restart */,
-1 /* timeout */,
NULL /* cancellable */,
NULL /* callback */,
NULL /* user_data */);
if (ibus_config_) {
g_object_unref(ibus_config_);
ibus_config_ = NULL;
}
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool StopInputMethodProcess() {
// IBusController override.
virtual bool StopInputMethodProcess() {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive";
return false;
}
ibus_bus_exit_async(ibus_,
FALSE /* do not restart */,
-1 /* timeout */,
NULL /* cancellable */,
NULL /* callback */,
NULL /* user_data */);
if (ibus_config_) {
g_object_unref(ibus_config_);
ibus_config_ = NULL;
}
return true;
}
| 170,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (eptr - cptr >= dff_chunk_header.ckDataSize) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
Commit Message: issue #28, do not overwrite heap on corrupt DSDIFF file
CWE ID: CWE-125 | int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (eptr - cptr >= dff_chunk_header.ckDataSize) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
| 169,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
const size_t data_size,ExceptionInfo *exception)
{
#define MaxCode(number_bits) ((one << (number_bits))-1)
#define MaxHashTable 5003
#define MaxGIFBits 12UL
#define MaxGIFTable (1UL << MaxGIFBits)
#define GIFOutputCode(code) \
{ \
/* \
Emit a code. \
*/ \
if (bits > 0) \
datum|=(size_t) (code) << bits; \
else \
datum=(size_t) (code); \
bits+=number_bits; \
while (bits >= 8) \
{ \
/* \
Add a character to current packet. \
*/ \
packet[length++]=(unsigned char) (datum & 0xff); \
if (length >= 254) \
{ \
(void) WriteBlobByte(image,(unsigned char) length); \
(void) WriteBlob(image,length,packet); \
length=0; \
} \
datum>>=8; \
bits-=8; \
} \
if (free_code > max_code) \
{ \
number_bits++; \
if (number_bits == MaxGIFBits) \
max_code=MaxGIFTable; \
else \
max_code=MaxCode(number_bits); \
} \
}
Quantum
index;
short
*hash_code,
*hash_prefix,
waiting_code;
size_t
bits,
clear_code,
datum,
end_of_information_code,
free_code,
length,
max_code,
next_pixel,
number_bits,
one,
pass;
ssize_t
displacement,
offset,
k,
y;
unsigned char
*packet,
*hash_suffix;
/*
Allocate encoder tables.
*/
assert(image != (Image *) NULL);
one=1;
packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
sizeof(*hash_suffix));
if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
(hash_prefix == (short *) NULL) ||
(hash_suffix == (unsigned char *) NULL))
{
if (packet != (unsigned char *) NULL)
packet=(unsigned char *) RelinquishMagickMemory(packet);
if (hash_code != (short *) NULL)
hash_code=(short *) RelinquishMagickMemory(hash_code);
if (hash_prefix != (short *) NULL)
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
if (hash_suffix != (unsigned char *) NULL)
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
return(MagickFalse);
}
/*
Initialize GIF encoder.
*/
(void) memset(packet,0,256*sizeof(*packet));
(void) memset(hash_code,0,MaxHashTable*sizeof(*hash_code));
(void) memset(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix));
(void) memset(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix));
number_bits=data_size;
max_code=MaxCode(number_bits);
clear_code=((short) one << (data_size-1));
end_of_information_code=clear_code+1;
free_code=clear_code+2;
length=0;
datum=0;
bits=0;
GIFOutputCode(clear_code);
/*
Encode pixels.
*/
offset=0;
pass=0;
waiting_code=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,offset,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (y == 0)
{
waiting_code=(short) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++)
{
/*
Probe hash table.
*/
index=(Quantum) ((size_t) GetPixelIndex(image,p) & 0xff);
p+=GetPixelChannels(image);
k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code);
if (k >= MaxHashTable)
k-=MaxHashTable;
next_pixel=MagickFalse;
displacement=1;
if (hash_code[k] > 0)
{
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
continue;
}
if (k != 0)
displacement=MaxHashTable-k;
for ( ; ; )
{
k-=displacement;
if (k < 0)
k+=MaxHashTable;
if (hash_code[k] == 0)
break;
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
next_pixel=MagickTrue;
break;
}
}
if (next_pixel != MagickFalse)
continue;
}
GIFOutputCode(waiting_code);
if (free_code < MaxGIFTable)
{
hash_code[k]=(short) free_code++;
hash_prefix[k]=waiting_code;
hash_suffix[k]=(unsigned char) index;
}
else
{
/*
Fill the hash table with empty entries.
*/
for (k=0; k < MaxHashTable; k++)
hash_code[k]=0;
/*
Reset compressor and issue a clear code.
*/
free_code=clear_code+2;
GIFOutputCode(clear_code);
number_bits=data_size;
max_code=MaxCode(number_bits);
}
waiting_code=(short) index;
}
if (image_info->interlace == NoInterlace)
offset++;
else
switch (pass)
{
case 0:
default:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=4;
}
break;
}
case 1:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=2;
}
break;
}
case 2:
{
offset+=4;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=1;
}
break;
}
case 3:
{
offset+=2;
break;
}
}
}
/*
Flush out the buffered code.
*/
GIFOutputCode(waiting_code);
GIFOutputCode(end_of_information_code);
if (bits > 0)
{
/*
Add a character to current packet.
*/
packet[length++]=(unsigned char) (datum & 0xff);
if (length >= 254)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
length=0;
}
}
/*
Flush accumulated data.
*/
if (length > 0)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
}
/*
Free encoder memory.
*/
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
hash_code=(short *) RelinquishMagickMemory(hash_code);
packet=(unsigned char *) RelinquishMagickMemory(packet);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595
CWE ID: CWE-119 | static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
const size_t data_size,ExceptionInfo *exception)
{
#define MaxCode(number_bits) ((one << (number_bits))-1)
#define MaxHashTable 5003
#define MaxGIFBits 12UL
#define MaxGIFTable (1UL << MaxGIFBits)
#define GIFOutputCode(code) \
{ \
/* \
Emit a code. \
*/ \
if (bits > 0) \
datum|=(size_t) (code) << bits; \
else \
datum=(size_t) (code); \
bits+=number_bits; \
while (bits >= 8) \
{ \
/* \
Add a character to current packet. \
*/ \
packet[length++]=(unsigned char) (datum & 0xff); \
if (length >= 254) \
{ \
(void) WriteBlobByte(image,(unsigned char) length); \
(void) WriteBlob(image,length,packet); \
length=0; \
} \
datum>>=8; \
bits-=8; \
} \
if (free_code > max_code) \
{ \
number_bits++; \
if (number_bits == MaxGIFBits) \
max_code=MaxGIFTable; \
else \
max_code=MaxCode(number_bits); \
} \
}
Quantum
index;
short
*hash_code,
*hash_prefix,
waiting_code;
size_t
bits,
clear_code,
datum,
end_of_information_code,
free_code,
length,
max_code,
next_pixel,
number_bits,
one,
pass;
ssize_t
displacement,
offset,
k,
y;
unsigned char
*packet,
*hash_suffix;
/*
Allocate encoder tables.
*/
assert(image != (Image *) NULL);
one=1;
packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
sizeof(*hash_suffix));
if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
(hash_prefix == (short *) NULL) ||
(hash_suffix == (unsigned char *) NULL))
{
if (packet != (unsigned char *) NULL)
packet=(unsigned char *) RelinquishMagickMemory(packet);
if (hash_code != (short *) NULL)
hash_code=(short *) RelinquishMagickMemory(hash_code);
if (hash_prefix != (short *) NULL)
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
if (hash_suffix != (unsigned char *) NULL)
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
return(MagickFalse);
}
/*
Initialize GIF encoder.
*/
(void) memset(packet,0,256*sizeof(*packet));
(void) memset(hash_code,0,MaxHashTable*sizeof(*hash_code));
(void) memset(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix));
(void) memset(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix));
number_bits=data_size;
max_code=MaxCode(number_bits);
clear_code=((short) one << (data_size-1));
end_of_information_code=clear_code+1;
free_code=clear_code+2;
length=0;
datum=0;
bits=0;
GIFOutputCode(clear_code);
/*
Encode pixels.
*/
offset=0;
pass=0;
waiting_code=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,offset,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (y == 0)
{
waiting_code=(short) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++)
{
/*
Probe hash table.
*/
next_pixel=MagickFalse;
displacement=1;
index=(Quantum) ((size_t) GetPixelIndex(image,p) & 0xff);
p+=GetPixelChannels(image);
k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code);
if (k >= MaxHashTable)
k-=MaxHashTable;
if (k < 0)
continue;
if (hash_code[k] > 0)
{
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
continue;
}
if (k != 0)
displacement=MaxHashTable-k;
for ( ; ; )
{
k-=displacement;
if (k < 0)
k+=MaxHashTable;
if (hash_code[k] == 0)
break;
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
next_pixel=MagickTrue;
break;
}
}
if (next_pixel != MagickFalse)
continue;
}
GIFOutputCode(waiting_code);
if (free_code < MaxGIFTable)
{
hash_code[k]=(short) free_code++;
hash_prefix[k]=waiting_code;
hash_suffix[k]=(unsigned char) index;
}
else
{
/*
Fill the hash table with empty entries.
*/
for (k=0; k < MaxHashTable; k++)
hash_code[k]=0;
/*
Reset compressor and issue a clear code.
*/
free_code=clear_code+2;
GIFOutputCode(clear_code);
number_bits=data_size;
max_code=MaxCode(number_bits);
}
waiting_code=(short) index;
}
if (image_info->interlace == NoInterlace)
offset++;
else
switch (pass)
{
case 0:
default:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=4;
}
break;
}
case 1:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=2;
}
break;
}
case 2:
{
offset+=4;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=1;
}
break;
}
case 3:
{
offset+=2;
break;
}
}
}
/*
Flush out the buffered code.
*/
GIFOutputCode(waiting_code);
GIFOutputCode(end_of_information_code);
if (bits > 0)
{
/*
Add a character to current packet.
*/
packet[length++]=(unsigned char) (datum & 0xff);
if (length >= 254)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
length=0;
}
}
/*
Flush accumulated data.
*/
if (length > 0)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
}
/*
Free encoder memory.
*/
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
hash_code=(short *) RelinquishMagickMemory(hash_code);
packet=(unsigned char *) RelinquishMagickMemory(packet);
return(MagickTrue);
}
| 170,200 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display)
{
if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(this);
if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
{
if (this->colour_type == PNG_COLOR_TYPE_GRAY)
{
if (this->bit_depth < 8)
this->bit_depth = 8;
if (this->have_tRNS)
{
this->have_tRNS = 0;
/* Check the input, original, channel value here against the
* original tRNS gray chunk valie.
*/
if (this->red == display->transparent.red)
this->alphaf = 0;
else
this->alphaf = 1;
}
else
this->alphaf = 1;
this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
}
else if (this->colour_type == PNG_COLOR_TYPE_RGB)
{
if (this->have_tRNS)
{
this->have_tRNS = 0;
/* Again, check the exact input values, not the current transformed
* value!
*/
if (this->red == display->transparent.red &&
this->green == display->transparent.green &&
this->blue == display->transparent.blue)
this->alphaf = 0;
else
this->alphaf = 1;
this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
}
/* The error in the alpha is zero and the sBIT value comes from the
* original sBIT data (actually it will always be the original bit depth).
*/
this->alphae = 0;
this->alpha_sBIT = display->alpha_sBIT;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display)
image_pixel_add_alpha(image_pixel *this, const standard_display *display,
int for_background)
{
if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(this);
if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
{
if (this->colour_type == PNG_COLOR_TYPE_GRAY)
{
# if PNG_LIBPNG_VER < 10700
if (!for_background && this->bit_depth < 8)
this->bit_depth = this->sample_depth = 8;
# endif
if (this->have_tRNS)
{
/* After 1.7 the expansion of bit depth only happens if there is a
* tRNS chunk to expand at this point.
*/
# if PNG_LIBPNG_VER >= 10700
if (!for_background && this->bit_depth < 8)
this->bit_depth = this->sample_depth = 8;
# endif
this->have_tRNS = 0;
/* Check the input, original, channel value here against the
* original tRNS gray chunk valie.
*/
if (this->red == display->transparent.red)
this->alphaf = 0;
else
this->alphaf = 1;
}
else
this->alphaf = 1;
this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
}
else if (this->colour_type == PNG_COLOR_TYPE_RGB)
{
if (this->have_tRNS)
{
this->have_tRNS = 0;
/* Again, check the exact input values, not the current transformed
* value!
*/
if (this->red == display->transparent.red &&
this->green == display->transparent.green &&
this->blue == display->transparent.blue)
this->alphaf = 0;
else
this->alphaf = 1;
}
else
this->alphaf = 1;
this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
/* The error in the alpha is zero and the sBIT value comes from the
* original sBIT data (actually it will always be the original bit depth).
*/
this->alphae = 0;
this->alpha_sBIT = display->alpha_sBIT;
}
}
| 173,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
unsigned int flags)
{
struct fuse_file *ff = file->private_data;
struct fuse_conn *fc = ff->fc;
struct fuse_ioctl_in inarg = {
.fh = ff->fh,
.cmd = cmd,
.arg = arg,
.flags = flags
};
struct fuse_ioctl_out outarg;
struct fuse_req *req = NULL;
struct page **pages = NULL;
struct page *iov_page = NULL;
struct iovec *in_iov = NULL, *out_iov = NULL;
unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
size_t in_size, out_size, transferred;
int err;
/* assume all the iovs returned by client always fits in a page */
BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
err = -ENOMEM;
pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
iov_page = alloc_page(GFP_KERNEL);
if (!pages || !iov_page)
goto out;
/*
* If restricted, initialize IO parameters as encoded in @cmd.
* RETRY from server is not allowed.
*/
if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
struct iovec *iov = page_address(iov_page);
iov->iov_base = (void __user *)arg;
iov->iov_len = _IOC_SIZE(cmd);
if (_IOC_DIR(cmd) & _IOC_WRITE) {
in_iov = iov;
in_iovs = 1;
}
if (_IOC_DIR(cmd) & _IOC_READ) {
out_iov = iov;
out_iovs = 1;
}
}
retry:
inarg.in_size = in_size = iov_length(in_iov, in_iovs);
inarg.out_size = out_size = iov_length(out_iov, out_iovs);
/*
* Out data can be used either for actual out data or iovs,
* make sure there always is at least one page.
*/
out_size = max_t(size_t, out_size, PAGE_SIZE);
max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
/* make sure there are enough buffer pages and init request with them */
err = -ENOMEM;
if (max_pages > FUSE_MAX_PAGES_PER_REQ)
goto out;
while (num_pages < max_pages) {
pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[num_pages])
goto out;
num_pages++;
}
req = fuse_get_req(fc);
if (IS_ERR(req)) {
err = PTR_ERR(req);
req = NULL;
goto out;
}
memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
req->num_pages = num_pages;
/* okay, let's send it to the client */
req->in.h.opcode = FUSE_IOCTL;
req->in.h.nodeid = ff->nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
if (in_size) {
req->in.numargs++;
req->in.args[1].size = in_size;
req->in.argpages = 1;
err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
false);
if (err)
goto out;
}
req->out.numargs = 2;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
req->out.args[1].size = out_size;
req->out.argpages = 1;
req->out.argvar = 1;
fuse_request_send(fc, req);
err = req->out.h.error;
transferred = req->out.args[1].size;
fuse_put_request(fc, req);
req = NULL;
if (err)
goto out;
/* did it ask for retry? */
if (outarg.flags & FUSE_IOCTL_RETRY) {
char *vaddr;
/* no retry if in restricted mode */
err = -EIO;
if (!(flags & FUSE_IOCTL_UNRESTRICTED))
goto out;
in_iovs = outarg.in_iovs;
out_iovs = outarg.out_iovs;
/*
* Make sure things are in boundary, separate checks
* are to protect against overflow.
*/
err = -ENOMEM;
if (in_iovs > FUSE_IOCTL_MAX_IOV ||
out_iovs > FUSE_IOCTL_MAX_IOV ||
in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
goto out;
vaddr = kmap_atomic(pages[0], KM_USER0);
err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr,
transferred, in_iovs + out_iovs,
(flags & FUSE_IOCTL_COMPAT) != 0);
kunmap_atomic(vaddr, KM_USER0);
if (err)
goto out;
in_iov = page_address(iov_page);
out_iov = in_iov + in_iovs;
goto retry;
}
err = -EIO;
if (transferred > inarg.out_size)
goto out;
err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
out:
if (req)
fuse_put_request(fc, req);
if (iov_page)
__free_page(iov_page);
while (num_pages)
__free_page(pages[--num_pages]);
kfree(pages);
return err ? err : outarg.result;
}
Commit Message: fuse: verify ioctl retries
Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY
doesn't overflow iov_length().
Signed-off-by: Miklos Szeredi <[email protected]>
CC: Tejun Heo <[email protected]>
CC: <[email protected]> [2.6.31+]
CWE ID: CWE-119 | long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
unsigned int flags)
{
struct fuse_file *ff = file->private_data;
struct fuse_conn *fc = ff->fc;
struct fuse_ioctl_in inarg = {
.fh = ff->fh,
.cmd = cmd,
.arg = arg,
.flags = flags
};
struct fuse_ioctl_out outarg;
struct fuse_req *req = NULL;
struct page **pages = NULL;
struct page *iov_page = NULL;
struct iovec *in_iov = NULL, *out_iov = NULL;
unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
size_t in_size, out_size, transferred;
int err;
/* assume all the iovs returned by client always fits in a page */
BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
err = -ENOMEM;
pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
iov_page = alloc_page(GFP_KERNEL);
if (!pages || !iov_page)
goto out;
/*
* If restricted, initialize IO parameters as encoded in @cmd.
* RETRY from server is not allowed.
*/
if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
struct iovec *iov = page_address(iov_page);
iov->iov_base = (void __user *)arg;
iov->iov_len = _IOC_SIZE(cmd);
if (_IOC_DIR(cmd) & _IOC_WRITE) {
in_iov = iov;
in_iovs = 1;
}
if (_IOC_DIR(cmd) & _IOC_READ) {
out_iov = iov;
out_iovs = 1;
}
}
retry:
inarg.in_size = in_size = iov_length(in_iov, in_iovs);
inarg.out_size = out_size = iov_length(out_iov, out_iovs);
/*
* Out data can be used either for actual out data or iovs,
* make sure there always is at least one page.
*/
out_size = max_t(size_t, out_size, PAGE_SIZE);
max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
/* make sure there are enough buffer pages and init request with them */
err = -ENOMEM;
if (max_pages > FUSE_MAX_PAGES_PER_REQ)
goto out;
while (num_pages < max_pages) {
pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[num_pages])
goto out;
num_pages++;
}
req = fuse_get_req(fc);
if (IS_ERR(req)) {
err = PTR_ERR(req);
req = NULL;
goto out;
}
memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
req->num_pages = num_pages;
/* okay, let's send it to the client */
req->in.h.opcode = FUSE_IOCTL;
req->in.h.nodeid = ff->nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
if (in_size) {
req->in.numargs++;
req->in.args[1].size = in_size;
req->in.argpages = 1;
err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
false);
if (err)
goto out;
}
req->out.numargs = 2;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
req->out.args[1].size = out_size;
req->out.argpages = 1;
req->out.argvar = 1;
fuse_request_send(fc, req);
err = req->out.h.error;
transferred = req->out.args[1].size;
fuse_put_request(fc, req);
req = NULL;
if (err)
goto out;
/* did it ask for retry? */
if (outarg.flags & FUSE_IOCTL_RETRY) {
char *vaddr;
/* no retry if in restricted mode */
err = -EIO;
if (!(flags & FUSE_IOCTL_UNRESTRICTED))
goto out;
in_iovs = outarg.in_iovs;
out_iovs = outarg.out_iovs;
/*
* Make sure things are in boundary, separate checks
* are to protect against overflow.
*/
err = -ENOMEM;
if (in_iovs > FUSE_IOCTL_MAX_IOV ||
out_iovs > FUSE_IOCTL_MAX_IOV ||
in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
goto out;
vaddr = kmap_atomic(pages[0], KM_USER0);
err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr,
transferred, in_iovs + out_iovs,
(flags & FUSE_IOCTL_COMPAT) != 0);
kunmap_atomic(vaddr, KM_USER0);
if (err)
goto out;
in_iov = page_address(iov_page);
out_iov = in_iov + in_iovs;
err = fuse_verify_ioctl_iov(in_iov, in_iovs);
if (err)
goto out;
err = fuse_verify_ioctl_iov(out_iov, out_iovs);
if (err)
goto out;
goto retry;
}
err = -EIO;
if (transferred > inarg.out_size)
goto out;
err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
out:
if (req)
fuse_put_request(fc, req);
if (iov_page)
__free_page(iov_page);
while (num_pages)
__free_page(pages[--num_pages]);
kfree(pages);
return err ? err : outarg.result;
}
| 165,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
Commit Message: af_netlink: force credentials passing [CVE-2012-3520]
Pablo Neira Ayuso discovered that avahi and
potentially NetworkManager accept spoofed Netlink messages because of a
kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data
to the receiver if the sender did not provide such data, instead of not
including any such data at all or including the correct data from the
peer (as it is the case with AF_UNIX).
This bug was introduced in commit 16e572626961
(af_unix: dont send SCM_CREDENTIALS by default)
This patch forces passing credentials for netlink, as
before the regression.
Another fix would be to not add SCM_CREDENTIALS in
netlink messages if not provided by the sender, but it
might break some programs.
With help from Florian Weimer & Petr Matousek
This issue is designated as CVE-2012-3520
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Florian Weimer <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-287 | static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
| 165,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength);
PrintOutParsingResult(res, 1, caller);
return res;
}
| 170,144 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int p4_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
int overflow;
if (!test_bit(idx, cpuc->active_mask)) {
/* catch in-flight IRQs */
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
hwc = &event->hw;
WARN_ON_ONCE(hwc->idx != idx);
/* it might be unflagged overflow */
overflow = p4_pmu_clear_cccr_ovf(hwc);
val = x86_perf_event_update(event);
if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1))))
continue;
handled += overflow;
/* event overflow for sure */
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, 1, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
/*
* When dealing with the unmasking of the LVTPC on P4 perf hw, it has
* been observed that the OVF bit flag has to be cleared first _before_
* the LVTPC can be unmasked.
*
* The reason is the NMI line will continue to be asserted while the OVF
* bit is set. This causes a second NMI to generate if the LVTPC is
* unmasked before the OVF bit is cleared, leading to unknown NMI
* messages.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
return handled;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static int p4_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
int overflow;
if (!test_bit(idx, cpuc->active_mask)) {
/* catch in-flight IRQs */
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
hwc = &event->hw;
WARN_ON_ONCE(hwc->idx != idx);
/* it might be unflagged overflow */
overflow = p4_pmu_clear_cccr_ovf(hwc);
val = x86_perf_event_update(event);
if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1))))
continue;
handled += overflow;
/* event overflow for sure */
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
/*
* When dealing with the unmasking of the LVTPC on P4 perf hw, it has
* been observed that the OVF bit flag has to be cleared first _before_
* the LVTPC can be unmasked.
*
* The reason is the NMI line will continue to be asserted while the OVF
* bit is set. This causes a second NMI to generate if the LVTPC is
* unmasked before the OVF bit is cleared, leading to unknown NMI
* messages.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
return handled;
}
| 165,822 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
Commit Message: Fix a wrong check in rfc_parse_data
Bug: 78288018
Bug: 111436796
Test: manual
Change-Id: I16e6026acbaac230fe1453bbac040d1b75bcea2a
(cherry picked from commit d1ced302cd1066087588c891027b1756be31db46)
CWE ID: CWE-125 | uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len > RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
| 174,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
CWE ID: CWE-20 | static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) ||
(jp2_image->comps[i].data == NULL))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 170,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int _make_decode_table(codebook *s,char *lengthlist,long quantvals,
oggpack_buffer *opb,int maptype){
int i;
ogg_uint32_t *work;
if (!lengthlist) return 1;
if(s->dec_nodeb==4){
/* Over-allocate by using s->entries instead of used_entries.
* This means that we can use s->entries to enforce size in
* _make_words without messing up length list looping.
* This probably wastes a bit of space, but it shouldn't
* impact behavior or size too much.
*/
s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work));
if (!s->dec_table) return 1;
/* +1 (rather than -2) is to accommodate 0 and 1 sized books,
which are specialcased to nodeb==4 */
if(_make_words(lengthlist,s->entries,
s->dec_table,quantvals,s,opb,maptype))return 1;
return 0;
}
if (s->used_entries > INT_MAX/2 ||
s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1;
/* Overallocate as above */
work=calloc((s->entries*2+1),sizeof(*work));
if (!work) return 1;
if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out;
if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out;
if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out;
s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)*
s->dec_nodeb);
if (!s->dec_table) goto error_out;
if(s->dec_leafw==1){
switch(s->dec_nodeb){
case 1:
for(i=0;i<s->used_entries*2-2;i++)
((unsigned char *)s->dec_table)[i]=(unsigned char)
(((work[i] & 0x80000000UL) >> 24) | work[i]);
break;
case 2:
for(i=0;i<s->used_entries*2-2;i++)
((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t)
(((work[i] & 0x80000000UL) >> 16) | work[i]);
break;
}
}else{
/* more complex; we have to do a two-pass repack that updates the
node indexing. */
long top=s->used_entries*3-2;
if(s->dec_nodeb==1){
unsigned char *out=(unsigned char *)s->dec_table;
for(i=s->used_entries*2-4;i>=0;i-=2){
if(work[i]&0x80000000UL){
if(work[i+1]&0x80000000UL){
top-=4;
out[top]=(work[i]>>8 & 0x7f)|0x80;
out[top+1]=(work[i+1]>>8 & 0x7f)|0x80;
out[top+2]=work[i] & 0xff;
out[top+3]=work[i+1] & 0xff;
}else{
top-=3;
out[top]=(work[i]>>8 & 0x7f)|0x80;
out[top+1]=work[work[i+1]*2];
out[top+2]=work[i] & 0xff;
}
}else{
if(work[i+1]&0x80000000UL){
top-=3;
out[top]=work[work[i]*2];
out[top+1]=(work[i+1]>>8 & 0x7f)|0x80;
out[top+2]=work[i+1] & 0xff;
}else{
top-=2;
out[top]=work[work[i]*2];
out[top+1]=work[work[i+1]*2];
}
}
work[i]=top;
}
}else{
ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table;
for(i=s->used_entries*2-4;i>=0;i-=2){
if(work[i]&0x80000000UL){
if(work[i+1]&0x80000000UL){
top-=4;
out[top]=(work[i]>>16 & 0x7fff)|0x8000;
out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000;
out[top+2]=work[i] & 0xffff;
out[top+3]=work[i+1] & 0xffff;
}else{
top-=3;
out[top]=(work[i]>>16 & 0x7fff)|0x8000;
out[top+1]=work[work[i+1]*2];
out[top+2]=work[i] & 0xffff;
}
}else{
if(work[i+1]&0x80000000UL){
top-=3;
out[top]=work[work[i]*2];
out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000;
out[top+2]=work[i+1] & 0xffff;
}else{
top-=2;
out[top]=work[work[i]*2];
out[top+1]=work[work[i+1]*2];
}
}
work[i]=top;
}
}
}
free(work);
return 0;
error_out:
free(work);
return 1;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200 | static int _make_decode_table(codebook *s,char *lengthlist,long quantvals,
oggpack_buffer *opb,int maptype){
int i;
ogg_uint32_t *work;
if (!lengthlist) return 1;
if(s->dec_nodeb==4){
/* Over-allocate by using s->entries instead of used_entries.
* This means that we can use s->entries to enforce size in
* _make_words without messing up length list looping.
* This probably wastes a bit of space, but it shouldn't
* impact behavior or size too much.
*/
s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work));
if (!s->dec_table) return 1;
/* +1 (rather than -2) is to accommodate 0 and 1 sized books,
which are specialcased to nodeb==4 */
if(_make_words(lengthlist,s->entries,
s->dec_table,quantvals,s,opb,maptype))return 1;
return 0;
}
if (s->used_entries > INT_MAX/2 ||
s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1;
/* Overallocate as above */
work=calloc((s->entries*2+1),sizeof(*work));
if (!work) return 1;
if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out;
if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out;
if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out;
s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)*
s->dec_nodeb);
if (!s->dec_table) goto error_out;
if(s->dec_leafw==1){
switch(s->dec_nodeb){
case 1:
for(i=0;i<s->used_entries*2-2;i++)
((unsigned char *)s->dec_table)[i]=(unsigned char)
(((work[i] & 0x80000000UL) >> 24) | work[i]);
break;
case 2:
for(i=0;i<s->used_entries*2-2;i++)
((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t)
(((work[i] & 0x80000000UL) >> 16) | work[i]);
break;
}
}else{
/* more complex; we have to do a two-pass repack that updates the
node indexing. */
long top=s->used_entries*3-2;
if(s->dec_nodeb==1){
unsigned char *out=(unsigned char *)s->dec_table;
for(i=s->used_entries*2-4;i>=0;i-=2){
if(work[i]&0x80000000UL){
if(work[i+1]&0x80000000UL){
top-=4;
out[top]=(work[i]>>8 & 0x7f)|0x80;
out[top+1]=(work[i+1]>>8 & 0x7f)|0x80;
out[top+2]=work[i] & 0xff;
out[top+3]=work[i+1] & 0xff;
}else{
top-=3;
out[top]=(work[i]>>8 & 0x7f)|0x80;
out[top+1]=work[work[i+1]*2];
out[top+2]=work[i] & 0xff;
}
}else{
if(work[i+1]&0x80000000UL){
top-=3;
out[top]=work[work[i]*2];
out[top+1]=(work[i+1]>>8 & 0x7f)|0x80;
out[top+2]=work[i+1] & 0xff;
}else{
top-=2;
out[top]=work[work[i]*2];
out[top+1]=work[work[i+1]*2];
}
}
work[i]=top;
}
}else{
ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table;
for(i=s->used_entries*2-4;i>=0;i-=2){
if(work[i]&0x80000000UL){
if(work[i+1]&0x80000000UL){
top-=4;
out[top]=(work[i]>>16 & 0x7fff)|0x8000;
out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000;
out[top+2]=work[i] & 0xffff;
out[top+3]=work[i+1] & 0xffff;
}else{
top-=3;
out[top]=(work[i]>>16 & 0x7fff)|0x8000;
out[top+1]=work[work[i+1]*2];
out[top+2]=work[i] & 0xffff;
}
}else{
if(work[i+1]&0x80000000UL){
top-=3;
out[top]=work[work[i]*2];
out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000;
out[top+2]=work[i+1] & 0xffff;
}else{
top-=2;
out[top]=work[work[i]*2];
out[top+1]=work[work[i+1]*2];
}
}
work[i]=top;
}
}
}
free(work);
return 0;
error_out:
free(work);
return 1;
}
| 173,981 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) {
xmlChar *buffer, *cur;
int len;
int level;
if (name == NULL)
name = xmlXPathParseName(ctxt);
if (name == NULL)
XP_ERROR(XPATH_EXPR_ERROR);
if (CUR != '(')
XP_ERROR(XPATH_EXPR_ERROR);
NEXT;
level = 1;
len = xmlStrlen(ctxt->cur);
len++;
buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar));
if (buffer == NULL) {
xmlXPtrErrMemory("allocating buffer");
return;
}
cur = buffer;
while (CUR != 0) {
if (CUR == ')') {
level--;
if (level == 0) {
NEXT;
break;
}
*cur++ = CUR;
} else if (CUR == '(') {
level++;
*cur++ = CUR;
} else if (CUR == '^') {
NEXT;
if ((CUR == ')') || (CUR == '(') || (CUR == '^')) {
*cur++ = CUR;
} else {
*cur++ = '^';
*cur++ = CUR;
}
} else {
*cur++ = CUR;
}
NEXT;
}
*cur = 0;
if ((level != 0) && (CUR == 0)) {
xmlFree(buffer);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
if (xmlStrEqual(name, (xmlChar *) "xpointer")) {
const xmlChar *left = CUR_PTR;
CUR_PTR = buffer;
/*
* To evaluate an xpointer scheme element (4.3) we need:
* context initialized to the root
* context position initalized to 1
* context size initialized to 1
*/
ctxt->context->node = (xmlNodePtr)ctxt->context->doc;
ctxt->context->proximityPosition = 1;
ctxt->context->contextSize = 1;
xmlXPathEvalExpr(ctxt);
CUR_PTR=left;
} else if (xmlStrEqual(name, (xmlChar *) "element")) {
const xmlChar *left = CUR_PTR;
xmlChar *name2;
CUR_PTR = buffer;
if (buffer[0] == '/') {
xmlXPathRoot(ctxt);
xmlXPtrEvalChildSeq(ctxt, NULL);
} else {
name2 = xmlXPathParseName(ctxt);
if (name2 == NULL) {
CUR_PTR = left;
xmlFree(buffer);
XP_ERROR(XPATH_EXPR_ERROR);
}
xmlXPtrEvalChildSeq(ctxt, name2);
}
CUR_PTR = left;
#ifdef XPTR_XMLNS_SCHEME
} else if (xmlStrEqual(name, (xmlChar *) "xmlns")) {
const xmlChar *left = CUR_PTR;
xmlChar *prefix;
xmlChar *URI;
xmlURIPtr value;
CUR_PTR = buffer;
prefix = xmlXPathParseNCName(ctxt);
if (prefix == NULL) {
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
SKIP_BLANKS;
if (CUR != '=') {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
NEXT;
SKIP_BLANKS;
/* @@ check escaping in the XPointer WD */
value = xmlParseURI((const char *)ctxt->cur);
if (value == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
URI = xmlSaveUri(value);
xmlFreeURI(value);
if (URI == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPATH_MEMORY_ERROR);
}
xmlXPathRegisterNs(ctxt->context, prefix, URI);
CUR_PTR = left;
xmlFree(URI);
xmlFree(prefix);
#endif /* XPTR_XMLNS_SCHEME */
} else {
xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME,
"unsupported scheme '%s'\n", name);
}
xmlFree(buffer);
xmlFree(name);
}
Commit Message: Fix XPointer bug.
BUG=125462
[email protected]
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10344022
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@135174 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) {
xmlChar *buffer, *cur;
int len;
int level;
if (name == NULL)
name = xmlXPathParseName(ctxt);
if (name == NULL)
XP_ERROR(XPATH_EXPR_ERROR);
if (CUR != '(')
XP_ERROR(XPATH_EXPR_ERROR);
NEXT;
level = 1;
len = xmlStrlen(ctxt->cur);
len++;
buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar));
if (buffer == NULL) {
xmlXPtrErrMemory("allocating buffer");
return;
}
cur = buffer;
while (CUR != 0) {
if (CUR == ')') {
level--;
if (level == 0) {
NEXT;
break;
}
} else if (CUR == '(') {
level++;
} else if (CUR == '^') {
if ((NXT(1) == ')') || (NXT(1) == '(') || (NXT(1) == '^')) {
NEXT;
}
}
*cur++ = CUR;
NEXT;
}
*cur = 0;
if ((level != 0) && (CUR == 0)) {
xmlFree(buffer);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
if (xmlStrEqual(name, (xmlChar *) "xpointer")) {
const xmlChar *left = CUR_PTR;
CUR_PTR = buffer;
/*
* To evaluate an xpointer scheme element (4.3) we need:
* context initialized to the root
* context position initalized to 1
* context size initialized to 1
*/
ctxt->context->node = (xmlNodePtr)ctxt->context->doc;
ctxt->context->proximityPosition = 1;
ctxt->context->contextSize = 1;
xmlXPathEvalExpr(ctxt);
CUR_PTR=left;
} else if (xmlStrEqual(name, (xmlChar *) "element")) {
const xmlChar *left = CUR_PTR;
xmlChar *name2;
CUR_PTR = buffer;
if (buffer[0] == '/') {
xmlXPathRoot(ctxt);
xmlXPtrEvalChildSeq(ctxt, NULL);
} else {
name2 = xmlXPathParseName(ctxt);
if (name2 == NULL) {
CUR_PTR = left;
xmlFree(buffer);
XP_ERROR(XPATH_EXPR_ERROR);
}
xmlXPtrEvalChildSeq(ctxt, name2);
}
CUR_PTR = left;
#ifdef XPTR_XMLNS_SCHEME
} else if (xmlStrEqual(name, (xmlChar *) "xmlns")) {
const xmlChar *left = CUR_PTR;
xmlChar *prefix;
xmlChar *URI;
xmlURIPtr value;
CUR_PTR = buffer;
prefix = xmlXPathParseNCName(ctxt);
if (prefix == NULL) {
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
SKIP_BLANKS;
if (CUR != '=') {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
NEXT;
SKIP_BLANKS;
/* @@ check escaping in the XPointer WD */
value = xmlParseURI((const char *)ctxt->cur);
if (value == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
URI = xmlSaveUri(value);
xmlFreeURI(value);
if (URI == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPATH_MEMORY_ERROR);
}
xmlXPathRegisterNs(ctxt->context, prefix, URI);
CUR_PTR = left;
xmlFree(URI);
xmlFree(prefix);
#endif /* XPTR_XMLNS_SCHEME */
} else {
xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME,
"unsupported scheme '%s'\n", name);
}
xmlFree(buffer);
xmlFree(name);
}
| 171,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
Commit Message:
CWE ID: CWE-125 | static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS)
return EINVAL;
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
| 164,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END) {
if (c == LF) {
ctx->state = BODY_CHUNK;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for empty
* chunk size lines.
*/
return APR_EGENERAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
ctx->chunkbits = sizeof(long) * 8;
ctx->chunk_used = 0;
}
/* handle a chunk part, or a chunk extension */
/*
* In theory, we are supposed to expect CRLF only, but our
* test suite sends LF only. Tolerate a missing CR.
*/
if (c == ';' || c == CR) {
ctx->state = BODY_CHUNK_EXT;
}
else if (c == LF) {
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state != BODY_CHUNK_EXT) {
int xvalue = 0;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EGENERAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
ctx->chunkbits -= 4;
if (ctx->chunkbits <= 0 || ctx->remaining < 0) {
/* overflow */
return APR_ENOSPC;
}
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
}
Commit Message: Limit accepted chunk-size to 2^63-1 and be strict about chunk-ext
authorized characters.
Submitted by: Yann Ylavic
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684513 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20 | static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END
|| ctx->state == BODY_CHUNK_END_LF) {
if (c == LF) {
ctx->state = BODY_CHUNK;
}
else if (c == CR && ctx->state == BODY_CHUNK_END) {
ctx->state = BODY_CHUNK_END_LF;
}
else {
/*
* LF expected.
*/
return APR_EINVAL;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for
* empty chunk size lines.
*/
return APR_EINVAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
ctx->chunkbits = sizeof(apr_off_t) * 8;
ctx->chunk_used = 0;
}
if (c == LF) {
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state == BODY_CHUNK_LF) {
/*
* LF expected.
*/
return APR_EINVAL;
}
else if (c == CR) {
ctx->state = BODY_CHUNK_LF;
}
else if (c == ';') {
ctx->state = BODY_CHUNK_EXT;
}
else if (ctx->state == BODY_CHUNK_EXT) {
/*
* Control chars (but tabs) are invalid.
*/
if (c != '\t' && apr_iscntrl(c)) {
return APR_EINVAL;
}
}
else if (ctx->state == BODY_CHUNK_PART) {
int xvalue;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
ctx->chunkbits -= 4;
if (ctx->chunkbits < 0) {
/* overflow */
return APR_ENOSPC;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EINVAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
if (ctx->remaining < 0) {
/* overflow */
return APR_ENOSPC;
}
}
else {
/* Should not happen */
return APR_EGENERAL;
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
}
| 166,634 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGL2RenderingContextBase::texImage3D(
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels) {
TexImageHelperDOMArrayBufferView(kTexImage3D, target, level, internalformat,
width, height, depth, border, format, type,
0, 0, 0, pixels.View(), kNullAllowed, 0);
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125 | void WebGL2RenderingContextBase::texImage3D(
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels) {
if ((unpack_flip_y_ || unpack_premultiply_alpha_) && pixels) {
SynthesizeGLError(
GL_INVALID_OPERATION, "texImage3D",
"FLIP_Y or PREMULTIPLY_ALPHA isn't allowed for uploading 3D textures");
return;
}
TexImageHelperDOMArrayBufferView(kTexImage3D, target, level, internalformat,
width, height, depth, border, format, type,
0, 0, 0, pixels.View(), kNullAllowed, 0);
}
| 172,675 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_session(void)
{
int type;
int interactive = 0;
int have_tty = 0;
struct winsize ws;
char *cp;
const char *display;
/* Enable compression if requested. */
if (options.compression) {
options.compression_level);
if (options.compression_level < 1 ||
options.compression_level > 9)
fatal("Compression level must be from 1 (fast) to "
"9 (slow, best).");
/* Send the request. */
packet_start(SSH_CMSG_REQUEST_COMPRESSION);
packet_put_int(options.compression_level);
packet_send();
packet_write_wait();
type = packet_read();
if (type == SSH_SMSG_SUCCESS)
packet_start_compression(options.compression_level);
else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host refused compression.");
else
packet_disconnect("Protocol error waiting for "
"compression response.");
}
/* Allocate a pseudo tty if appropriate. */
if (tty_flag) {
debug("Requesting pty.");
/* Start the packet. */
packet_start(SSH_CMSG_REQUEST_PTY);
/* Store TERM in the packet. There is no limit on the
length of the string. */
cp = getenv("TERM");
if (!cp)
cp = "";
packet_put_cstring(cp);
/* Store window size in the packet. */
if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
memset(&ws, 0, sizeof(ws));
packet_put_int((u_int)ws.ws_row);
packet_put_int((u_int)ws.ws_col);
packet_put_int((u_int)ws.ws_xpixel);
packet_put_int((u_int)ws.ws_ypixel);
/* Store tty modes in the packet. */
tty_make_modes(fileno(stdin), NULL);
/* Send the packet, and wait for it to leave. */
packet_send();
packet_write_wait();
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
have_tty = 1;
} else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host failed or refused to "
"allocate a pseudo tty.");
else
packet_disconnect("Protocol error waiting for pty "
"request response.");
}
/* Request X11 forwarding if enabled and DISPLAY is set. */
display = getenv("DISPLAY");
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
if (options.forward_x11 && display != NULL) {
char *proto, *data;
/* Get reasonable local authentication information. */
client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted,
options.forward_x11_timeout,
&proto, &data);
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
x11_request_forwarding_with_spoofing(0, display, proto,
data, 0);
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
} else if (type == SSH_SMSG_FAILURE) {
logit("Warning: Remote host denied X11 forwarding.");
} else {
packet_disconnect("Protocol error waiting for X11 "
"forwarding");
}
}
/* Tell the packet module whether this is an interactive session. */
packet_set_interactive(interactive,
options.ip_qos_interactive, options.ip_qos_bulk);
/* Request authentication agent forwarding if appropriate. */
check_agent_present();
if (options.forward_agent) {
debug("Requesting authentication agent forwarding.");
auth_request_forwarding();
/* Read response from the server. */
type = packet_read();
packet_check_eom();
if (type != SSH_SMSG_SUCCESS)
logit("Warning: Remote host denied authentication agent forwarding.");
}
/* Initiate port forwardings. */
ssh_init_stdio_forwarding();
ssh_init_forwarding();
/* Execute a local command */
if (options.local_command != NULL &&
options.permit_local_command)
ssh_local_cmd(options.local_command);
/*
* If requested and we are not interested in replies to remote
* forwarding requests, then let ssh continue in the background.
*/
if (fork_after_authentication_flag) {
if (options.exit_on_forward_failure &&
options.num_remote_forwards > 0) {
debug("deferring postauth fork until remote forward "
"confirmation received");
} else
fork_postauth();
}
/*
* If a command was specified on the command line, execute the
* command now. Otherwise request the server to start a shell.
*/
if (buffer_len(&command) > 0) {
int len = buffer_len(&command);
if (len > 900)
len = 900;
debug("Sending command: %.*s", len,
(u_char *)buffer_ptr(&command));
packet_start(SSH_CMSG_EXEC_CMD);
packet_put_string(buffer_ptr(&command), buffer_len(&command));
packet_send();
packet_write_wait();
} else {
debug("Requesting shell.");
packet_start(SSH_CMSG_EXEC_SHELL);
packet_send();
packet_write_wait();
}
/* Enter the interactive session. */
return client_loop(have_tty, tty_flag ?
options.escape_char : SSH_ESCAPECHAR_NONE, 0);
}
Commit Message:
CWE ID: CWE-254 | ssh_session(void)
{
int type;
int interactive = 0;
int have_tty = 0;
struct winsize ws;
char *cp;
const char *display;
char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
options.compression_level);
if (options.compression_level < 1 ||
options.compression_level > 9)
fatal("Compression level must be from 1 (fast) to "
"9 (slow, best).");
/* Send the request. */
packet_start(SSH_CMSG_REQUEST_COMPRESSION);
packet_put_int(options.compression_level);
packet_send();
packet_write_wait();
type = packet_read();
if (type == SSH_SMSG_SUCCESS)
packet_start_compression(options.compression_level);
else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host refused compression.");
else
packet_disconnect("Protocol error waiting for "
"compression response.");
}
/* Allocate a pseudo tty if appropriate. */
if (tty_flag) {
debug("Requesting pty.");
/* Start the packet. */
packet_start(SSH_CMSG_REQUEST_PTY);
/* Store TERM in the packet. There is no limit on the
length of the string. */
cp = getenv("TERM");
if (!cp)
cp = "";
packet_put_cstring(cp);
/* Store window size in the packet. */
if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
memset(&ws, 0, sizeof(ws));
packet_put_int((u_int)ws.ws_row);
packet_put_int((u_int)ws.ws_col);
packet_put_int((u_int)ws.ws_xpixel);
packet_put_int((u_int)ws.ws_ypixel);
/* Store tty modes in the packet. */
tty_make_modes(fileno(stdin), NULL);
/* Send the packet, and wait for it to leave. */
packet_send();
packet_write_wait();
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
have_tty = 1;
} else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host failed or refused to "
"allocate a pseudo tty.");
else
packet_disconnect("Protocol error waiting for pty "
"request response.");
}
/* Request X11 forwarding if enabled and DISPLAY is set. */
display = getenv("DISPLAY");
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
if (options.forward_x11 && client_x11_get_proto(display,
options.xauth_location, options.forward_x11_trusted,
options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
x11_request_forwarding_with_spoofing(0, display, proto,
data, 0);
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
} else if (type == SSH_SMSG_FAILURE) {
logit("Warning: Remote host denied X11 forwarding.");
} else {
packet_disconnect("Protocol error waiting for X11 "
"forwarding");
}
}
/* Tell the packet module whether this is an interactive session. */
packet_set_interactive(interactive,
options.ip_qos_interactive, options.ip_qos_bulk);
/* Request authentication agent forwarding if appropriate. */
check_agent_present();
if (options.forward_agent) {
debug("Requesting authentication agent forwarding.");
auth_request_forwarding();
/* Read response from the server. */
type = packet_read();
packet_check_eom();
if (type != SSH_SMSG_SUCCESS)
logit("Warning: Remote host denied authentication agent forwarding.");
}
/* Initiate port forwardings. */
ssh_init_stdio_forwarding();
ssh_init_forwarding();
/* Execute a local command */
if (options.local_command != NULL &&
options.permit_local_command)
ssh_local_cmd(options.local_command);
/*
* If requested and we are not interested in replies to remote
* forwarding requests, then let ssh continue in the background.
*/
if (fork_after_authentication_flag) {
if (options.exit_on_forward_failure &&
options.num_remote_forwards > 0) {
debug("deferring postauth fork until remote forward "
"confirmation received");
} else
fork_postauth();
}
/*
* If a command was specified on the command line, execute the
* command now. Otherwise request the server to start a shell.
*/
if (buffer_len(&command) > 0) {
int len = buffer_len(&command);
if (len > 900)
len = 900;
debug("Sending command: %.*s", len,
(u_char *)buffer_ptr(&command));
packet_start(SSH_CMSG_EXEC_CMD);
packet_put_string(buffer_ptr(&command), buffer_len(&command));
packet_send();
packet_write_wait();
} else {
debug("Requesting shell.");
packet_start(SSH_CMSG_EXEC_SHELL);
packet_send();
packet_write_wait();
}
/* Enter the interactive session. */
return client_loop(have_tty, tty_flag ?
options.escape_char : SSH_ESCAPECHAR_NONE, 0);
}
| 165,353 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MagickPathExtent];
CINInfo
cin;
const unsigned char
*pixels;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register Quantum
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
memset(&cin,0,sizeof(cin));
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property,exception);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=ReadBlobSignedLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property,exception);
(void) memset(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property,exception);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property,exception);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
if (cin.file.user_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const unsigned char *) NULL,
cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile,exception);
profile=DestroyStringInfo(profile);
}
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
if (offset < (MagickOffsetType) cin.file.image_offset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace,exception);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1472
CWE ID: CWE-400 | static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MagickPathExtent];
CINInfo
cin;
const unsigned char
*pixels;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register Quantum
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
memset(&cin,0,sizeof(cin));
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property,exception);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=ReadBlobSignedLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property,exception);
(void) memset(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property,exception);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property,exception);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
if (cin.file.user_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const unsigned char *) NULL,
cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile,exception);
profile=DestroyStringInfo(profile);
}
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
if (((MagickSizeType) image->columns*image->rows) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
if (offset < (MagickOffsetType) cin.file.image_offset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace,exception);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 169,694 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PlatformSensorAmbientLightMac::PlatformSensorAmbientLightMac(
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider)
: PlatformSensor(SensorType::AMBIENT_LIGHT, std::move(mapping), provider),
light_sensor_port_(nullptr),
current_lux_(0.0) {}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | PlatformSensorAmbientLightMac::PlatformSensorAmbientLightMac(
SensorReadingSharedBuffer* reading_buffer,
PlatformSensorProvider* provider)
: PlatformSensor(SensorType::AMBIENT_LIGHT, reading_buffer, provider),
light_sensor_port_(nullptr),
current_lux_(0.0) {}
| 172,825 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
skb_dst_drop(skb);
}
Commit Message: ipv4: keep skb->dst around in presence of IP options
Andrey Konovalov got crashes in __ip_options_echo() when a NULL skb->dst
is accessed.
ipv4_pktinfo_prepare() should not drop the dst if (evil) IP options
are present.
We could refine the test to the presence of ts_needtime or srr,
but IP options are not often used, so let's be conservative.
Thanks to syzkaller team for finding this bug.
Fixes: d826eb14ecef ("ipv4: PKTINFO doesnt need dst reference")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
/* We need to keep the dst for __ip_options_echo()
* We could restrict the test to opt.ts_needtime || opt.srr,
* but the following is good enough as IP options are not often used.
*/
if (unlikely(IPCB(skb)->opt.optlen))
skb_dst_force(skb);
else
skb_dst_drop(skb);
}
| 168,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC)
{
char buffer[4096];
char buffer2[4096];
char *buf = buffer, *buf2 = buffer2, *d, *d_url;
int l;
if (name_len > sizeof(buffer)-2) {
buf = estrndup(name, name_len);
} else {
memcpy(buf, name, name_len);
buf[name_len] = 0;
}
name_len = php_url_decode(buf, name_len);
normalize_varname(buf);
name_len = strlen(buf);
if (SUHOSIN_G(cookie_plainlist)) {
if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) {
encrypt_return_plain:
if (buf != buffer) {
efree(buf);
}
return estrndup(value, value_len);
}
} else if (SUHOSIN_G(cookie_cryptlist)) {
if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) {
goto encrypt_return_plain;
}
}
if (strlen(value) <= sizeof(buffer2)-2) {
memcpy(buf2, value, value_len);
buf2[value_len] = 0;
} else {
buf2 = estrndup(value, value_len);
}
value_len = php_url_decode(buf2, value_len);
d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC);
d_url = php_url_encode(d, strlen(d), &l);
efree(d);
if (buf != buffer) {
efree(buf);
}
if (buf2 != buffer2) {
efree(buf2);
}
return d_url;
}
Commit Message: Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory)
CWE ID: CWE-119 | char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC)
{
char *buf, *buf2, *d, *d_url;
int l;
buf = estrndup(name, name_len);
name_len = php_url_decode(buf, name_len);
normalize_varname(buf);
name_len = strlen(buf);
if (SUHOSIN_G(cookie_plainlist)) {
if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) {
encrypt_return_plain:
efree(buf);
return estrndup(value, value_len);
}
} else if (SUHOSIN_G(cookie_cryptlist)) {
if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) {
goto encrypt_return_plain;
}
}
buf2 = estrndup(value, value_len);
value_len = php_url_decode(buf2, value_len);
d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC);
d_url = php_url_encode(d, strlen(d), &l);
efree(d);
efree(buf);
efree(buf2);
return d_url;
}
| 165,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
: download_file_manager_(new DownloadFileManager(NULL)),
save_file_manager_(new SaveFileManager()),
request_id_(-1),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)),
is_shutdown_(false),
max_outstanding_requests_cost_per_process_(
kMaxOutstandingRequestsCostPerProcess),
filter_(NULL),
delegate_(NULL),
allow_cross_origin_auth_prompt_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!g_resource_dispatcher_host);
g_resource_dispatcher_host = this;
GetContentClient()->browser()->ResourceDispatcherHostCreated();
ANNOTATE_BENIGN_RACE(
&last_user_gesture_time_,
"We don't care about the precise value, see http://crbug.com/92889");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&appcache::AppCacheInterceptor::EnsureRegistered));
update_load_states_timer_.reset(
new base::RepeatingTimer<ResourceDispatcherHostImpl>());
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
: download_file_manager_(new DownloadFileManager(NULL)),
save_file_manager_(new SaveFileManager()),
request_id_(-1),
is_shutdown_(false),
max_outstanding_requests_cost_per_process_(
kMaxOutstandingRequestsCostPerProcess),
filter_(NULL),
delegate_(NULL),
allow_cross_origin_auth_prompt_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!g_resource_dispatcher_host);
g_resource_dispatcher_host = this;
GetContentClient()->browser()->ResourceDispatcherHostCreated();
ANNOTATE_BENIGN_RACE(
&last_user_gesture_time_,
"We don't care about the precise value, see http://crbug.com/92889");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&appcache::AppCacheInterceptor::EnsureRegistered));
update_load_states_timer_.reset(
new base::RepeatingTimer<ResourceDispatcherHostImpl>());
}
| 170,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
Commit Message: Avoid OOB read (found by ASAN reported by F. Alonso)
CWE ID: CWE-125 | do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
| 169,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert.
CWE ID: CWE-20 | cleanup_pathname(struct archive_write_disk *a)
cleanup_pathname_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags)
{
char *dest, *src;
char separator = '\0';
dest = src = path;
if (*src == '\0') {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == path) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
| 167,136 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static InputMethodStatusConnection* GetConnection(
void* language_library,
LanguageCurrentInputMethodMonitorFunction current_input_method_changed,
LanguageRegisterImePropertiesFunction register_ime_properties,
LanguageUpdateImePropertyFunction update_ime_property,
LanguageConnectionChangeMonitorFunction connection_change_handler) {
DCHECK(language_library);
DCHECK(current_input_method_changed),
DCHECK(register_ime_properties);
DCHECK(update_ime_property);
InputMethodStatusConnection* object = GetInstance();
if (!object->language_library_) {
object->language_library_ = language_library;
object->current_input_method_changed_ = current_input_method_changed;
object->register_ime_properties_= register_ime_properties;
object->update_ime_property_ = update_ime_property;
object->connection_change_handler_ = connection_change_handler;
object->MaybeRestoreConnections();
} else if (object->language_library_ != language_library) {
LOG(ERROR) << "Unknown language_library is passed";
}
return object;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | static InputMethodStatusConnection* GetConnection(
// TODO(satorux,yusukes): Remove use of singleton here.
static IBusControllerImpl* GetInstance() {
return Singleton<IBusControllerImpl,
LeakySingletonTraits<IBusControllerImpl> >::get();
}
| 170,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id};
APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h);
sock_cmd_t* cmd_send = &cmd;
int size_send = sizeof(cmd);
if(data && size)
{
size_send = sizeof(cmd) + size;
cmd_send = (sock_cmd_t*)alloca(size_send);
if(cmd_send)
{
*cmd_send = cmd;
memcpy(cmd_send + 1, data, size);
}
else
{
APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send);
return FALSE;
}
}
return send(ts[h].cmd_fdw, cmd_send, size_send, 0) == size_send;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id};
APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h);
sock_cmd_t* cmd_send = &cmd;
int size_send = sizeof(cmd);
if(data && size)
{
size_send = sizeof(cmd) + size;
cmd_send = (sock_cmd_t*)alloca(size_send);
if(cmd_send)
{
*cmd_send = cmd;
memcpy(cmd_send + 1, data, size);
}
else
{
APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send);
return FALSE;
}
}
return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, cmd_send, size_send, 0)) == size_send;
}
| 173,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: eval_condition(uschar *s, BOOL *resetok, BOOL *yield)
{
BOOL testfor = TRUE;
BOOL tempcond, combined_cond;
BOOL *subcondptr;
BOOL sub2_honour_dollar = TRUE;
int i, rc, cond_type, roffset;
int_eximarith_t num[2];
struct stat statbuf;
uschar name[256];
uschar *sub[10];
const pcre *re;
const uschar *rerror;
for (;;)
{
while (isspace(*s)) s++;
if (*s == '!') { testfor = !testfor; s++; } else break;
}
/* Numeric comparisons are symbolic */
if (*s == '=' || *s == '>' || *s == '<')
{
int p = 0;
name[p++] = *s++;
if (*s == '=')
{
name[p++] = '=';
s++;
}
name[p] = 0;
}
/* All other conditions are named */
else s = read_name(name, 256, s, US"_");
/* If we haven't read a name, it means some non-alpha character is first. */
if (name[0] == 0)
{
expand_string_message = string_sprintf("condition name expected, "
"but found \"%.16s\"", s);
return NULL;
}
/* Find which condition we are dealing with, and switch on it */
cond_type = chop_match(name, cond_table, sizeof(cond_table)/sizeof(uschar *));
switch(cond_type)
{
/* def: tests for a non-empty variable, or for the existence of a header. If
yield == NULL we are in a skipping state, and don't care about the answer. */
case ECOND_DEF:
if (*s != ':')
{
expand_string_message = US"\":\" expected after \"def\"";
return NULL;
}
s = read_name(name, 256, s+1, US"_");
/* Test for a header's existence. If the name contains a closing brace
character, this may be a user error where the terminating colon has been
omitted. Set a flag to adjust a subsequent error message in this case. */
if (Ustrncmp(name, "h_", 2) == 0 ||
Ustrncmp(name, "rh_", 3) == 0 ||
Ustrncmp(name, "bh_", 3) == 0 ||
Ustrncmp(name, "header_", 7) == 0 ||
Ustrncmp(name, "rheader_", 8) == 0 ||
Ustrncmp(name, "bheader_", 8) == 0)
{
s = read_header_name(name, 256, s);
/* {-for-text-editors */
if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
if (yield != NULL) *yield =
(find_header(name, TRUE, NULL, FALSE, NULL) != NULL) == testfor;
}
/* Test for a variable's having a non-empty value. A non-existent variable
causes an expansion failure. */
else
{
uschar *value = find_variable(name, TRUE, yield == NULL, NULL);
if (value == NULL)
{
expand_string_message = (name[0] == 0)?
string_sprintf("variable name omitted after \"def:\"") :
string_sprintf("unknown variable \"%s\" after \"def:\"", name);
check_variable_error_message(name);
return NULL;
}
if (yield != NULL) *yield = (value[0] != 0) == testfor;
}
return s;
/* first_delivery tests for first delivery attempt */
case ECOND_FIRST_DELIVERY:
if (yield != NULL) *yield = deliver_firsttime == testfor;
return s;
/* queue_running tests for any process started by a queue runner */
case ECOND_QUEUE_RUNNING:
if (yield != NULL) *yield = (queue_run_pid != (pid_t)0) == testfor;
return s;
/* exists: tests for file existence
isip: tests for any IP address
isip4: tests for an IPv4 address
isip6: tests for an IPv6 address
pam: does PAM authentication
radius: does RADIUS authentication
ldapauth: does LDAP authentication
pwcheck: does Cyrus SASL pwcheck authentication
*/
case ECOND_EXISTS:
case ECOND_ISIP:
case ECOND_ISIP4:
case ECOND_ISIP6:
case ECOND_PAM:
case ECOND_RADIUS:
case ECOND_LDAPAUTH:
case ECOND_PWCHECK:
while (isspace(*s)) s++;
if (*s != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[0] = expand_string_internal(s+1, TRUE, &s, yield == NULL, TRUE, resetok);
if (sub[0] == NULL) return NULL;
/* {-for-text-editors */
if (*s++ != '}') goto COND_FAILED_CURLY_END;
if (yield == NULL) return s; /* No need to run the test if skipping */
switch(cond_type)
{
case ECOND_EXISTS:
if ((expand_forbid & RDO_EXISTS) != 0)
{
expand_string_message = US"File existence tests are not permitted";
return NULL;
}
*yield = (Ustat(sub[0], &statbuf) == 0) == testfor;
break;
case ECOND_ISIP:
case ECOND_ISIP4:
case ECOND_ISIP6:
rc = string_is_ip_address(sub[0], NULL);
*yield = ((cond_type == ECOND_ISIP)? (rc != 0) :
(cond_type == ECOND_ISIP4)? (rc == 4) : (rc == 6)) == testfor;
break;
/* Various authentication tests - all optionally compiled */
case ECOND_PAM:
#ifdef SUPPORT_PAM
rc = auth_call_pam(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* SUPPORT_PAM */
case ECOND_RADIUS:
#ifdef RADIUS_CONFIG_FILE
rc = auth_call_radius(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* RADIUS_CONFIG_FILE */
case ECOND_LDAPAUTH:
#ifdef LOOKUP_LDAP
{
/* Just to keep the interface the same */
BOOL do_cache;
int old_pool = store_pool;
store_pool = POOL_SEARCH;
rc = eldapauth_find((void *)(-1), NULL, sub[0], Ustrlen(sub[0]), NULL,
&expand_string_message, &do_cache);
store_pool = old_pool;
}
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* LOOKUP_LDAP */
case ECOND_PWCHECK:
#ifdef CYRUS_PWCHECK_SOCKET
rc = auth_call_pwcheck(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* CYRUS_PWCHECK_SOCKET */
#if defined(SUPPORT_PAM) || defined(RADIUS_CONFIG_FILE) || \
defined(LOOKUP_LDAP) || defined(CYRUS_PWCHECK_SOCKET)
END_AUTH:
if (rc == ERROR || rc == DEFER) return NULL;
*yield = (rc == OK) == testfor;
#endif
}
return s;
/* call ACL (in a conditional context). Accept true, deny false.
Defer is a forced-fail. Anything set by message= goes to $value.
Up to ten parameters are used; we use the braces round the name+args
like the saslauthd condition does, to permit a variable number of args.
See also the expansion-item version EITEM_ACL and the traditional
acl modifier ACLC_ACL.
Since the ACL may allocate new global variables, tell our caller to not
reclaim memory.
*/
case ECOND_ACL:
/* ${if acl {{name}{arg1}{arg2}...} {yes}{no}} */
{
uschar *user_msg;
BOOL cond = FALSE;
int size = 0;
int ptr = 0;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /*}*/
switch(read_subs(sub, sizeof(sub)/sizeof(*sub), 1,
&s, yield == NULL, TRUE, US"acl", resetok))
{
case 1: expand_string_message = US"too few arguments or bracketing "
"error for acl";
case 2:
case 3: return NULL;
}
*resetok = FALSE;
if (yield != NULL) switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg))
{
case OK:
cond = TRUE;
case FAIL:
lookup_value = NULL;
if (user_msg)
{
lookup_value = string_cat(NULL, &size, &ptr, user_msg, Ustrlen(user_msg));
lookup_value[ptr] = '\0';
}
*yield = cond == testfor;
break;
case DEFER:
expand_string_forcedfail = TRUE;
default:
expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]);
return NULL;
}
return s;
}
/* saslauthd: does Cyrus saslauthd authentication. Four parameters are used:
${if saslauthd {{username}{password}{service}{realm}} {yes}{no}}
However, the last two are optional. That is why the whole set is enclosed
in their own set of braces. */
case ECOND_SASLAUTHD:
#ifndef CYRUS_SASLAUTHD_SOCKET
goto COND_FAILED_NOT_COMPILED;
#else
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
switch(read_subs(sub, 4, 2, &s, yield == NULL, TRUE, US"saslauthd", resetok))
{
case 1: expand_string_message = US"too few arguments or bracketing "
"error for saslauthd";
case 2:
case 3: return NULL;
}
if (sub[2] == NULL) sub[3] = NULL; /* realm if no service */
if (yield != NULL)
{
int rc;
rc = auth_call_saslauthd(sub[0], sub[1], sub[2], sub[3],
&expand_string_message);
if (rc == ERROR || rc == DEFER) return NULL;
*yield = (rc == OK) == testfor;
}
return s;
#endif /* CYRUS_SASLAUTHD_SOCKET */
/* symbolic operators for numeric and string comparison, and a number of
other operators, all requiring two arguments.
crypteq: encrypts plaintext and compares against an encrypted text,
using crypt(), crypt16(), MD5 or SHA-1
inlist/inlisti: checks if first argument is in the list of the second
match: does a regular expression match and sets up the numerical
variables if it succeeds
match_address: matches in an address list
match_domain: matches in a domain list
match_ip: matches a host list that is restricted to IP addresses
match_local_part: matches in a local part list
*/
case ECOND_MATCH_ADDRESS:
case ECOND_MATCH_DOMAIN:
case ECOND_MATCH_IP:
case ECOND_MATCH_LOCAL_PART:
#ifndef EXPAND_LISTMATCH_RHS
sub2_honour_dollar = FALSE;
#endif
/* FALLTHROUGH */
case ECOND_CRYPTEQ:
case ECOND_INLIST:
case ECOND_INLISTI:
case ECOND_MATCH:
case ECOND_NUM_L: /* Numerical comparisons */
case ECOND_NUM_LE:
case ECOND_NUM_E:
case ECOND_NUM_EE:
case ECOND_NUM_G:
case ECOND_NUM_GE:
case ECOND_STR_LT: /* String comparisons */
case ECOND_STR_LTI:
case ECOND_STR_LE:
case ECOND_STR_LEI:
case ECOND_STR_EQ:
case ECOND_STR_EQI:
case ECOND_STR_GT:
case ECOND_STR_GTI:
case ECOND_STR_GE:
case ECOND_STR_GEI:
for (i = 0; i < 2; i++)
{
/* Sometimes, we don't expand substrings; too many insecure configurations
created using match_address{}{} and friends, where the second param
includes information from untrustworthy sources. */
BOOL honour_dollar = TRUE;
if ((i > 0) && !sub2_honour_dollar)
honour_dollar = FALSE;
while (isspace(*s)) s++;
if (*s != '{')
{
if (i == 0) goto COND_FAILED_CURLY_START;
expand_string_message = string_sprintf("missing 2nd string in {} "
"after \"%s\"", name);
return NULL;
}
sub[i] = expand_string_internal(s+1, TRUE, &s, yield == NULL,
honour_dollar, resetok);
if (sub[i] == NULL) return NULL;
if (*s++ != '}') goto COND_FAILED_CURLY_END;
/* Convert to numerical if required; we know that the names of all the
conditions that compare numbers do not start with a letter. This just saves
checking for them individually. */
if (!isalpha(name[0]) && yield != NULL)
{
if (sub[i][0] == 0)
{
num[i] = 0;
DEBUG(D_expand)
debug_printf("empty string cast to zero for numerical comparison\n");
}
else
{
num[i] = expand_string_integer(sub[i], FALSE);
if (expand_string_message != NULL) return NULL;
}
}
}
/* Result not required */
if (yield == NULL) return s;
/* Do an appropriate comparison */
switch(cond_type)
{
case ECOND_NUM_E:
case ECOND_NUM_EE:
tempcond = (num[0] == num[1]);
break;
case ECOND_NUM_G:
tempcond = (num[0] > num[1]);
break;
case ECOND_NUM_GE:
tempcond = (num[0] >= num[1]);
break;
case ECOND_NUM_L:
tempcond = (num[0] < num[1]);
break;
case ECOND_NUM_LE:
tempcond = (num[0] <= num[1]);
break;
case ECOND_STR_LT:
tempcond = (Ustrcmp(sub[0], sub[1]) < 0);
break;
case ECOND_STR_LTI:
tempcond = (strcmpic(sub[0], sub[1]) < 0);
break;
case ECOND_STR_LE:
tempcond = (Ustrcmp(sub[0], sub[1]) <= 0);
break;
case ECOND_STR_LEI:
tempcond = (strcmpic(sub[0], sub[1]) <= 0);
break;
case ECOND_STR_EQ:
tempcond = (Ustrcmp(sub[0], sub[1]) == 0);
break;
case ECOND_STR_EQI:
tempcond = (strcmpic(sub[0], sub[1]) == 0);
break;
case ECOND_STR_GT:
tempcond = (Ustrcmp(sub[0], sub[1]) > 0);
break;
case ECOND_STR_GTI:
tempcond = (strcmpic(sub[0], sub[1]) > 0);
break;
case ECOND_STR_GE:
tempcond = (Ustrcmp(sub[0], sub[1]) >= 0);
break;
case ECOND_STR_GEI:
tempcond = (strcmpic(sub[0], sub[1]) >= 0);
break;
case ECOND_MATCH: /* Regular expression match */
re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
NULL);
if (re == NULL)
{
expand_string_message = string_sprintf("regular expression error in "
"\"%s\": %s at offset %d", sub[1], rerror, roffset);
return NULL;
}
tempcond = regex_match_and_setup(re, sub[0], 0, -1);
break;
case ECOND_MATCH_ADDRESS: /* Match in an address list */
rc = match_address_list(sub[0], TRUE, FALSE, &(sub[1]), NULL, -1, 0, NULL);
goto MATCHED_SOMETHING;
case ECOND_MATCH_DOMAIN: /* Match in a domain list */
rc = match_isinlist(sub[0], &(sub[1]), 0, &domainlist_anchor, NULL,
MCL_DOMAIN + MCL_NOEXPAND, TRUE, NULL);
goto MATCHED_SOMETHING;
case ECOND_MATCH_IP: /* Match IP address in a host list */
if (sub[0][0] != 0 && string_is_ip_address(sub[0], NULL) == 0)
{
expand_string_message = string_sprintf("\"%s\" is not an IP address",
sub[0]);
return NULL;
}
else
{
unsigned int *nullcache = NULL;
check_host_block cb;
cb.host_name = US"";
cb.host_address = sub[0];
/* If the host address starts off ::ffff: it is an IPv6 address in
IPv4-compatible mode. Find the IPv4 part for checking against IPv4
addresses. */
cb.host_ipv4 = (Ustrncmp(cb.host_address, "::ffff:", 7) == 0)?
cb.host_address + 7 : cb.host_address;
rc = match_check_list(
&sub[1], /* the list */
0, /* separator character */
&hostlist_anchor, /* anchor pointer */
&nullcache, /* cache pointer */
check_host, /* function for testing */
&cb, /* argument for function */
MCL_HOST, /* type of check */
sub[0], /* text for debugging */
NULL); /* where to pass back data */
}
goto MATCHED_SOMETHING;
case ECOND_MATCH_LOCAL_PART:
rc = match_isinlist(sub[0], &(sub[1]), 0, &localpartlist_anchor, NULL,
MCL_LOCALPART + MCL_NOEXPAND, TRUE, NULL);
/* Fall through */
/* VVVVVVVVVVVV */
MATCHED_SOMETHING:
switch(rc)
{
case OK:
tempcond = TRUE;
break;
case FAIL:
tempcond = FALSE;
break;
case DEFER:
expand_string_message = string_sprintf("unable to complete match "
"against \"%s\": %s", sub[1], search_error_message);
return NULL;
}
break;
/* Various "encrypted" comparisons. If the second string starts with
"{" then an encryption type is given. Default to crypt() or crypt16()
(build-time choice). */
/* }-for-text-editors */
case ECOND_CRYPTEQ:
#ifndef SUPPORT_CRYPTEQ
goto COND_FAILED_NOT_COMPILED;
#else
if (strncmpic(sub[1], US"{md5}", 5) == 0)
{
int sublen = Ustrlen(sub[1]+5);
md5 base;
uschar digest[16];
md5_start(&base);
md5_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
/* If the length that we are comparing against is 24, the MD5 digest
is expressed as a base64 string. This is the way LDAP does it. However,
some other software uses a straightforward hex representation. We assume
this if the length is 32. Other lengths fail. */
if (sublen == 24)
{
uschar *coded = auth_b64encode((uschar *)digest, 16);
DEBUG(D_auth) debug_printf("crypteq: using MD5+B64 hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+5);
tempcond = (Ustrcmp(coded, sub[1]+5) == 0);
}
else if (sublen == 32)
{
int i;
uschar coded[36];
for (i = 0; i < 16; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
coded[32] = 0;
DEBUG(D_auth) debug_printf("crypteq: using MD5+hex hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+5);
tempcond = (strcmpic(coded, sub[1]+5) == 0);
}
else
{
DEBUG(D_auth) debug_printf("crypteq: length for MD5 not 24 or 32: "
"fail\n crypted=%s\n", sub[1]+5);
tempcond = FALSE;
}
}
else if (strncmpic(sub[1], US"{sha1}", 6) == 0)
{
int sublen = Ustrlen(sub[1]+6);
sha1 base;
uschar digest[20];
sha1_start(&base);
sha1_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
/* If the length that we are comparing against is 28, assume the SHA1
digest is expressed as a base64 string. If the length is 40, assume a
straightforward hex representation. Other lengths fail. */
if (sublen == 28)
{
uschar *coded = auth_b64encode((uschar *)digest, 20);
DEBUG(D_auth) debug_printf("crypteq: using SHA1+B64 hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+6);
tempcond = (Ustrcmp(coded, sub[1]+6) == 0);
}
else if (sublen == 40)
{
int i;
uschar coded[44];
for (i = 0; i < 20; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
coded[40] = 0;
DEBUG(D_auth) debug_printf("crypteq: using SHA1+hex hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+6);
tempcond = (strcmpic(coded, sub[1]+6) == 0);
}
else
{
DEBUG(D_auth) debug_printf("crypteq: length for SHA-1 not 28 or 40: "
"fail\n crypted=%s\n", sub[1]+6);
tempcond = FALSE;
}
}
else /* {crypt} or {crypt16} and non-{ at start */
/* }-for-text-editors */
{
int which = 0;
uschar *coded;
if (strncmpic(sub[1], US"{crypt}", 7) == 0)
{
sub[1] += 7;
which = 1;
}
else if (strncmpic(sub[1], US"{crypt16}", 9) == 0)
{
sub[1] += 9;
which = 2;
}
else if (sub[1][0] == '{') /* }-for-text-editors */
{
expand_string_message = string_sprintf("unknown encryption mechanism "
"in \"%s\"", sub[1]);
return NULL;
}
switch(which)
{
case 0: coded = US DEFAULT_CRYPT(CS sub[0], CS sub[1]); break;
case 1: coded = US crypt(CS sub[0], CS sub[1]); break;
default: coded = US crypt16(CS sub[0], CS sub[1]); break;
}
#define STR(s) # s
#define XSTR(s) STR(s)
DEBUG(D_auth) debug_printf("crypteq: using %s()\n"
" subject=%s\n crypted=%s\n",
(which == 0)? XSTR(DEFAULT_CRYPT) : (which == 1)? "crypt" : "crypt16",
coded, sub[1]);
#undef STR
#undef XSTR
/* If the encrypted string contains fewer than two characters (for the
salt), force failure. Otherwise we get false positives: with an empty
string the yield of crypt() is an empty string! */
tempcond = (Ustrlen(sub[1]) < 2)? FALSE :
(Ustrcmp(coded, sub[1]) == 0);
}
break;
#endif /* SUPPORT_CRYPTEQ */
case ECOND_INLIST:
case ECOND_INLISTI:
{
int sep = 0;
uschar *save_iterate_item = iterate_item;
int (*compare)(const uschar *, const uschar *);
tempcond = FALSE;
if (cond_type == ECOND_INLISTI)
compare = strcmpic;
else
compare = (int (*)(const uschar *, const uschar *)) strcmp;
while ((iterate_item = string_nextinlist(&sub[1], &sep, NULL, 0)) != NULL)
if (compare(sub[0], iterate_item) == 0)
{
tempcond = TRUE;
break;
}
iterate_item = save_iterate_item;
}
} /* Switch for comparison conditions */
*yield = tempcond == testfor;
return s; /* End of comparison conditions */
/* and/or: computes logical and/or of several conditions */
case ECOND_AND:
case ECOND_OR:
subcondptr = (yield == NULL)? NULL : &tempcond;
combined_cond = (cond_type == ECOND_AND);
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
for (;;)
{
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s == '}') break;
if (*s != '{') /* }-for-text-editors */
{
expand_string_message = string_sprintf("each subcondition "
"inside an \"%s{...}\" condition must be in its own {}", name);
return NULL;
}
if (!(s = eval_condition(s+1, resetok, subcondptr)))
{
expand_string_message = string_sprintf("%s inside \"%s{...}\" condition",
expand_string_message, name);
return NULL;
}
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s++ != '}')
{
/* {-for-text-editors */
expand_string_message = string_sprintf("missing } at end of condition "
"inside \"%s\" group", name);
return NULL;
}
if (yield != NULL)
{
if (cond_type == ECOND_AND)
{
combined_cond &= tempcond;
if (!combined_cond) subcondptr = NULL; /* once false, don't */
} /* evaluate any more */
else
{
combined_cond |= tempcond;
if (combined_cond) subcondptr = NULL; /* once true, don't */
} /* evaluate any more */
}
}
if (yield != NULL) *yield = (combined_cond == testfor);
return ++s;
/* forall/forany: iterates a condition with different values */
case ECOND_FORALL:
case ECOND_FORANY:
{
int sep = 0;
uschar *save_iterate_item = iterate_item;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[0] = expand_string_internal(s, TRUE, &s, (yield == NULL), TRUE, resetok);
if (sub[0] == NULL) return NULL;
/* {-for-text-editors */
if (*s++ != '}') goto COND_FAILED_CURLY_END;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[1] = s;
/* Call eval_condition once, with result discarded (as if scanning a
"false" part). This allows us to find the end of the condition, because if
the list it empty, we won't actually evaluate the condition for real. */
if (!(s = eval_condition(sub[1], resetok, NULL)))
{
expand_string_message = string_sprintf("%s inside \"%s\" condition",
expand_string_message, name);
return NULL;
}
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s++ != '}')
{
/* {-for-text-editors */
expand_string_message = string_sprintf("missing } at end of condition "
"inside \"%s\"", name);
return NULL;
}
if (yield != NULL) *yield = !testfor;
while ((iterate_item = string_nextinlist(&sub[0], &sep, NULL, 0)) != NULL)
{
DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item);
if (!eval_condition(sub[1], resetok, &tempcond))
{
expand_string_message = string_sprintf("%s inside \"%s\" condition",
expand_string_message, name);
iterate_item = save_iterate_item;
return NULL;
}
DEBUG(D_expand) debug_printf("%s: condition evaluated to %s\n", name,
tempcond? "true":"false");
if (yield != NULL) *yield = (tempcond == testfor);
if (tempcond == (cond_type == ECOND_FORANY)) break;
}
iterate_item = save_iterate_item;
return s;
}
/* The bool{} expansion condition maps a string to boolean.
The values supported should match those supported by the ACL condition
(acl.c, ACLC_CONDITION) so that we keep to a minimum the different ideas
of true/false. Note that Router "condition" rules have a different
interpretation, where general data can be used and only a few values
map to FALSE.
Note that readconf.c boolean matching, for boolean configuration options,
only matches true/yes/false/no.
The bool_lax{} condition matches the Router logic, which is much more
liberal. */
case ECOND_BOOL:
case ECOND_BOOL_LAX:
{
uschar *sub_arg[1];
uschar *t, *t2;
uschar *ourname;
size_t len;
BOOL boolvalue = FALSE;
while (isspace(*s)) s++;
if (*s != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
ourname = cond_type == ECOND_BOOL_LAX ? US"bool_lax" : US"bool";
switch(read_subs(sub_arg, 1, 1, &s, yield == NULL, FALSE, ourname, resetok))
{
case 1: expand_string_message = string_sprintf(
"too few arguments or bracketing error for %s",
ourname);
/*FALLTHROUGH*/
case 2:
case 3: return NULL;
}
t = sub_arg[0];
while (isspace(*t)) t++;
len = Ustrlen(t);
if (len)
{
/* trailing whitespace: seems like a good idea to ignore it too */
t2 = t + len - 1;
while (isspace(*t2)) t2--;
if (t2 != (t + len))
{
*++t2 = '\0';
len = t2 - t;
}
}
DEBUG(D_expand)
debug_printf("considering %s: %s\n", ourname, len ? t : US"<empty>");
/* logic for the lax case from expand_check_condition(), which also does
expands, and the logic is both short and stable enough that there should
be no maintenance burden from replicating it. */
if (len == 0)
boolvalue = FALSE;
else if (*t == '-'
? Ustrspn(t+1, "0123456789") == len-1
: Ustrspn(t, "0123456789") == len)
{
boolvalue = (Uatoi(t) == 0) ? FALSE : TRUE;
/* expand_check_condition only does a literal string "0" check */
if ((cond_type == ECOND_BOOL_LAX) && (len > 1))
boolvalue = TRUE;
}
else if (strcmpic(t, US"true") == 0 || strcmpic(t, US"yes") == 0)
boolvalue = TRUE;
else if (strcmpic(t, US"false") == 0 || strcmpic(t, US"no") == 0)
boolvalue = FALSE;
else if (cond_type == ECOND_BOOL_LAX)
boolvalue = TRUE;
else
{
expand_string_message = string_sprintf("unrecognised boolean "
"value \"%s\"", t);
return NULL;
}
if (yield != NULL) *yield = (boolvalue == testfor);
return s;
}
/* Unknown condition */
default:
expand_string_message = string_sprintf("unknown condition \"%s\"", name);
return NULL;
} /* End switch on condition type */
/* Missing braces at start and end of data */
COND_FAILED_CURLY_START:
expand_string_message = string_sprintf("missing { after \"%s\"", name);
return NULL;
COND_FAILED_CURLY_END:
expand_string_message = string_sprintf("missing } at end of \"%s\" condition",
name);
return NULL;
/* A condition requires code that is not compiled */
#if !defined(SUPPORT_PAM) || !defined(RADIUS_CONFIG_FILE) || \
!defined(LOOKUP_LDAP) || !defined(CYRUS_PWCHECK_SOCKET) || \
!defined(SUPPORT_CRYPTEQ) || !defined(CYRUS_SASLAUTHD_SOCKET)
COND_FAILED_NOT_COMPILED:
expand_string_message = string_sprintf("support for \"%s\" not compiled",
name);
return NULL;
#endif
}
Commit Message:
CWE ID: CWE-189 | eval_condition(uschar *s, BOOL *resetok, BOOL *yield)
{
BOOL testfor = TRUE;
BOOL tempcond, combined_cond;
BOOL *subcondptr;
BOOL sub2_honour_dollar = TRUE;
int i, rc, cond_type, roffset;
int_eximarith_t num[2];
struct stat statbuf;
uschar name[256];
uschar *sub[10];
const pcre *re;
const uschar *rerror;
for (;;)
{
while (isspace(*s)) s++;
if (*s == '!') { testfor = !testfor; s++; } else break;
}
/* Numeric comparisons are symbolic */
if (*s == '=' || *s == '>' || *s == '<')
{
int p = 0;
name[p++] = *s++;
if (*s == '=')
{
name[p++] = '=';
s++;
}
name[p] = 0;
}
/* All other conditions are named */
else s = read_name(name, 256, s, US"_");
/* If we haven't read a name, it means some non-alpha character is first. */
if (name[0] == 0)
{
expand_string_message = string_sprintf("condition name expected, "
"but found \"%.16s\"", s);
return NULL;
}
/* Find which condition we are dealing with, and switch on it */
cond_type = chop_match(name, cond_table, sizeof(cond_table)/sizeof(uschar *));
switch(cond_type)
{
/* def: tests for a non-empty variable, or for the existence of a header. If
yield == NULL we are in a skipping state, and don't care about the answer. */
case ECOND_DEF:
if (*s != ':')
{
expand_string_message = US"\":\" expected after \"def\"";
return NULL;
}
s = read_name(name, 256, s+1, US"_");
/* Test for a header's existence. If the name contains a closing brace
character, this may be a user error where the terminating colon has been
omitted. Set a flag to adjust a subsequent error message in this case. */
if (Ustrncmp(name, "h_", 2) == 0 ||
Ustrncmp(name, "rh_", 3) == 0 ||
Ustrncmp(name, "bh_", 3) == 0 ||
Ustrncmp(name, "header_", 7) == 0 ||
Ustrncmp(name, "rheader_", 8) == 0 ||
Ustrncmp(name, "bheader_", 8) == 0)
{
s = read_header_name(name, 256, s);
/* {-for-text-editors */
if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
if (yield != NULL) *yield =
(find_header(name, TRUE, NULL, FALSE, NULL) != NULL) == testfor;
}
/* Test for a variable's having a non-empty value. A non-existent variable
causes an expansion failure. */
else
{
uschar *value = find_variable(name, TRUE, yield == NULL, NULL);
if (value == NULL)
{
expand_string_message = (name[0] == 0)?
string_sprintf("variable name omitted after \"def:\"") :
string_sprintf("unknown variable \"%s\" after \"def:\"", name);
check_variable_error_message(name);
return NULL;
}
if (yield != NULL) *yield = (value[0] != 0) == testfor;
}
return s;
/* first_delivery tests for first delivery attempt */
case ECOND_FIRST_DELIVERY:
if (yield != NULL) *yield = deliver_firsttime == testfor;
return s;
/* queue_running tests for any process started by a queue runner */
case ECOND_QUEUE_RUNNING:
if (yield != NULL) *yield = (queue_run_pid != (pid_t)0) == testfor;
return s;
/* exists: tests for file existence
isip: tests for any IP address
isip4: tests for an IPv4 address
isip6: tests for an IPv6 address
pam: does PAM authentication
radius: does RADIUS authentication
ldapauth: does LDAP authentication
pwcheck: does Cyrus SASL pwcheck authentication
*/
case ECOND_EXISTS:
case ECOND_ISIP:
case ECOND_ISIP4:
case ECOND_ISIP6:
case ECOND_PAM:
case ECOND_RADIUS:
case ECOND_LDAPAUTH:
case ECOND_PWCHECK:
while (isspace(*s)) s++;
if (*s != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[0] = expand_string_internal(s+1, TRUE, &s, yield == NULL, TRUE, resetok);
if (sub[0] == NULL) return NULL;
/* {-for-text-editors */
if (*s++ != '}') goto COND_FAILED_CURLY_END;
if (yield == NULL) return s; /* No need to run the test if skipping */
switch(cond_type)
{
case ECOND_EXISTS:
if ((expand_forbid & RDO_EXISTS) != 0)
{
expand_string_message = US"File existence tests are not permitted";
return NULL;
}
*yield = (Ustat(sub[0], &statbuf) == 0) == testfor;
break;
case ECOND_ISIP:
case ECOND_ISIP4:
case ECOND_ISIP6:
rc = string_is_ip_address(sub[0], NULL);
*yield = ((cond_type == ECOND_ISIP)? (rc != 0) :
(cond_type == ECOND_ISIP4)? (rc == 4) : (rc == 6)) == testfor;
break;
/* Various authentication tests - all optionally compiled */
case ECOND_PAM:
#ifdef SUPPORT_PAM
rc = auth_call_pam(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* SUPPORT_PAM */
case ECOND_RADIUS:
#ifdef RADIUS_CONFIG_FILE
rc = auth_call_radius(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* RADIUS_CONFIG_FILE */
case ECOND_LDAPAUTH:
#ifdef LOOKUP_LDAP
{
/* Just to keep the interface the same */
BOOL do_cache;
int old_pool = store_pool;
store_pool = POOL_SEARCH;
rc = eldapauth_find((void *)(-1), NULL, sub[0], Ustrlen(sub[0]), NULL,
&expand_string_message, &do_cache);
store_pool = old_pool;
}
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* LOOKUP_LDAP */
case ECOND_PWCHECK:
#ifdef CYRUS_PWCHECK_SOCKET
rc = auth_call_pwcheck(sub[0], &expand_string_message);
goto END_AUTH;
#else
goto COND_FAILED_NOT_COMPILED;
#endif /* CYRUS_PWCHECK_SOCKET */
#if defined(SUPPORT_PAM) || defined(RADIUS_CONFIG_FILE) || \
defined(LOOKUP_LDAP) || defined(CYRUS_PWCHECK_SOCKET)
END_AUTH:
if (rc == ERROR || rc == DEFER) return NULL;
*yield = (rc == OK) == testfor;
#endif
}
return s;
/* call ACL (in a conditional context). Accept true, deny false.
Defer is a forced-fail. Anything set by message= goes to $value.
Up to ten parameters are used; we use the braces round the name+args
like the saslauthd condition does, to permit a variable number of args.
See also the expansion-item version EITEM_ACL and the traditional
acl modifier ACLC_ACL.
Since the ACL may allocate new global variables, tell our caller to not
reclaim memory.
*/
case ECOND_ACL:
/* ${if acl {{name}{arg1}{arg2}...} {yes}{no}} */
{
uschar *user_msg;
BOOL cond = FALSE;
int size = 0;
int ptr = 0;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /*}*/
switch(read_subs(sub, sizeof(sub)/sizeof(*sub), 1,
&s, yield == NULL, TRUE, US"acl", resetok))
{
case 1: expand_string_message = US"too few arguments or bracketing "
"error for acl";
case 2:
case 3: return NULL;
}
*resetok = FALSE;
if (yield != NULL) switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg))
{
case OK:
cond = TRUE;
case FAIL:
lookup_value = NULL;
if (user_msg)
{
lookup_value = string_cat(NULL, &size, &ptr, user_msg, Ustrlen(user_msg));
lookup_value[ptr] = '\0';
}
*yield = cond == testfor;
break;
case DEFER:
expand_string_forcedfail = TRUE;
default:
expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]);
return NULL;
}
return s;
}
/* saslauthd: does Cyrus saslauthd authentication. Four parameters are used:
${if saslauthd {{username}{password}{service}{realm}} {yes}{no}}
However, the last two are optional. That is why the whole set is enclosed
in their own set of braces. */
case ECOND_SASLAUTHD:
#ifndef CYRUS_SASLAUTHD_SOCKET
goto COND_FAILED_NOT_COMPILED;
#else
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
switch(read_subs(sub, 4, 2, &s, yield == NULL, TRUE, US"saslauthd", resetok))
{
case 1: expand_string_message = US"too few arguments or bracketing "
"error for saslauthd";
case 2:
case 3: return NULL;
}
if (sub[2] == NULL) sub[3] = NULL; /* realm if no service */
if (yield != NULL)
{
int rc;
rc = auth_call_saslauthd(sub[0], sub[1], sub[2], sub[3],
&expand_string_message);
if (rc == ERROR || rc == DEFER) return NULL;
*yield = (rc == OK) == testfor;
}
return s;
#endif /* CYRUS_SASLAUTHD_SOCKET */
/* symbolic operators for numeric and string comparison, and a number of
other operators, all requiring two arguments.
crypteq: encrypts plaintext and compares against an encrypted text,
using crypt(), crypt16(), MD5 or SHA-1
inlist/inlisti: checks if first argument is in the list of the second
match: does a regular expression match and sets up the numerical
variables if it succeeds
match_address: matches in an address list
match_domain: matches in a domain list
match_ip: matches a host list that is restricted to IP addresses
match_local_part: matches in a local part list
*/
case ECOND_MATCH_ADDRESS:
case ECOND_MATCH_DOMAIN:
case ECOND_MATCH_IP:
case ECOND_MATCH_LOCAL_PART:
#ifndef EXPAND_LISTMATCH_RHS
sub2_honour_dollar = FALSE;
#endif
/* FALLTHROUGH */
case ECOND_CRYPTEQ:
case ECOND_INLIST:
case ECOND_INLISTI:
case ECOND_MATCH:
case ECOND_NUM_L: /* Numerical comparisons */
case ECOND_NUM_LE:
case ECOND_NUM_E:
case ECOND_NUM_EE:
case ECOND_NUM_G:
case ECOND_NUM_GE:
case ECOND_STR_LT: /* String comparisons */
case ECOND_STR_LTI:
case ECOND_STR_LE:
case ECOND_STR_LEI:
case ECOND_STR_EQ:
case ECOND_STR_EQI:
case ECOND_STR_GT:
case ECOND_STR_GTI:
case ECOND_STR_GE:
case ECOND_STR_GEI:
for (i = 0; i < 2; i++)
{
/* Sometimes, we don't expand substrings; too many insecure configurations
created using match_address{}{} and friends, where the second param
includes information from untrustworthy sources. */
BOOL honour_dollar = TRUE;
if ((i > 0) && !sub2_honour_dollar)
honour_dollar = FALSE;
while (isspace(*s)) s++;
if (*s != '{')
{
if (i == 0) goto COND_FAILED_CURLY_START;
expand_string_message = string_sprintf("missing 2nd string in {} "
"after \"%s\"", name);
return NULL;
}
sub[i] = expand_string_internal(s+1, TRUE, &s, yield == NULL,
honour_dollar, resetok);
if (sub[i] == NULL) return NULL;
if (*s++ != '}') goto COND_FAILED_CURLY_END;
/* Convert to numerical if required; we know that the names of all the
conditions that compare numbers do not start with a letter. This just saves
checking for them individually. */
if (!isalpha(name[0]) && yield != NULL)
{
if (sub[i][0] == 0)
{
num[i] = 0;
DEBUG(D_expand)
debug_printf("empty string cast to zero for numerical comparison\n");
}
else
{
num[i] = expanded_string_integer(sub[i], FALSE);
if (expand_string_message != NULL) return NULL;
}
}
}
/* Result not required */
if (yield == NULL) return s;
/* Do an appropriate comparison */
switch(cond_type)
{
case ECOND_NUM_E:
case ECOND_NUM_EE:
tempcond = (num[0] == num[1]);
break;
case ECOND_NUM_G:
tempcond = (num[0] > num[1]);
break;
case ECOND_NUM_GE:
tempcond = (num[0] >= num[1]);
break;
case ECOND_NUM_L:
tempcond = (num[0] < num[1]);
break;
case ECOND_NUM_LE:
tempcond = (num[0] <= num[1]);
break;
case ECOND_STR_LT:
tempcond = (Ustrcmp(sub[0], sub[1]) < 0);
break;
case ECOND_STR_LTI:
tempcond = (strcmpic(sub[0], sub[1]) < 0);
break;
case ECOND_STR_LE:
tempcond = (Ustrcmp(sub[0], sub[1]) <= 0);
break;
case ECOND_STR_LEI:
tempcond = (strcmpic(sub[0], sub[1]) <= 0);
break;
case ECOND_STR_EQ:
tempcond = (Ustrcmp(sub[0], sub[1]) == 0);
break;
case ECOND_STR_EQI:
tempcond = (strcmpic(sub[0], sub[1]) == 0);
break;
case ECOND_STR_GT:
tempcond = (Ustrcmp(sub[0], sub[1]) > 0);
break;
case ECOND_STR_GTI:
tempcond = (strcmpic(sub[0], sub[1]) > 0);
break;
case ECOND_STR_GE:
tempcond = (Ustrcmp(sub[0], sub[1]) >= 0);
break;
case ECOND_STR_GEI:
tempcond = (strcmpic(sub[0], sub[1]) >= 0);
break;
case ECOND_MATCH: /* Regular expression match */
re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
NULL);
if (re == NULL)
{
expand_string_message = string_sprintf("regular expression error in "
"\"%s\": %s at offset %d", sub[1], rerror, roffset);
return NULL;
}
tempcond = regex_match_and_setup(re, sub[0], 0, -1);
break;
case ECOND_MATCH_ADDRESS: /* Match in an address list */
rc = match_address_list(sub[0], TRUE, FALSE, &(sub[1]), NULL, -1, 0, NULL);
goto MATCHED_SOMETHING;
case ECOND_MATCH_DOMAIN: /* Match in a domain list */
rc = match_isinlist(sub[0], &(sub[1]), 0, &domainlist_anchor, NULL,
MCL_DOMAIN + MCL_NOEXPAND, TRUE, NULL);
goto MATCHED_SOMETHING;
case ECOND_MATCH_IP: /* Match IP address in a host list */
if (sub[0][0] != 0 && string_is_ip_address(sub[0], NULL) == 0)
{
expand_string_message = string_sprintf("\"%s\" is not an IP address",
sub[0]);
return NULL;
}
else
{
unsigned int *nullcache = NULL;
check_host_block cb;
cb.host_name = US"";
cb.host_address = sub[0];
/* If the host address starts off ::ffff: it is an IPv6 address in
IPv4-compatible mode. Find the IPv4 part for checking against IPv4
addresses. */
cb.host_ipv4 = (Ustrncmp(cb.host_address, "::ffff:", 7) == 0)?
cb.host_address + 7 : cb.host_address;
rc = match_check_list(
&sub[1], /* the list */
0, /* separator character */
&hostlist_anchor, /* anchor pointer */
&nullcache, /* cache pointer */
check_host, /* function for testing */
&cb, /* argument for function */
MCL_HOST, /* type of check */
sub[0], /* text for debugging */
NULL); /* where to pass back data */
}
goto MATCHED_SOMETHING;
case ECOND_MATCH_LOCAL_PART:
rc = match_isinlist(sub[0], &(sub[1]), 0, &localpartlist_anchor, NULL,
MCL_LOCALPART + MCL_NOEXPAND, TRUE, NULL);
/* Fall through */
/* VVVVVVVVVVVV */
MATCHED_SOMETHING:
switch(rc)
{
case OK:
tempcond = TRUE;
break;
case FAIL:
tempcond = FALSE;
break;
case DEFER:
expand_string_message = string_sprintf("unable to complete match "
"against \"%s\": %s", sub[1], search_error_message);
return NULL;
}
break;
/* Various "encrypted" comparisons. If the second string starts with
"{" then an encryption type is given. Default to crypt() or crypt16()
(build-time choice). */
/* }-for-text-editors */
case ECOND_CRYPTEQ:
#ifndef SUPPORT_CRYPTEQ
goto COND_FAILED_NOT_COMPILED;
#else
if (strncmpic(sub[1], US"{md5}", 5) == 0)
{
int sublen = Ustrlen(sub[1]+5);
md5 base;
uschar digest[16];
md5_start(&base);
md5_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
/* If the length that we are comparing against is 24, the MD5 digest
is expressed as a base64 string. This is the way LDAP does it. However,
some other software uses a straightforward hex representation. We assume
this if the length is 32. Other lengths fail. */
if (sublen == 24)
{
uschar *coded = auth_b64encode((uschar *)digest, 16);
DEBUG(D_auth) debug_printf("crypteq: using MD5+B64 hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+5);
tempcond = (Ustrcmp(coded, sub[1]+5) == 0);
}
else if (sublen == 32)
{
int i;
uschar coded[36];
for (i = 0; i < 16; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
coded[32] = 0;
DEBUG(D_auth) debug_printf("crypteq: using MD5+hex hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+5);
tempcond = (strcmpic(coded, sub[1]+5) == 0);
}
else
{
DEBUG(D_auth) debug_printf("crypteq: length for MD5 not 24 or 32: "
"fail\n crypted=%s\n", sub[1]+5);
tempcond = FALSE;
}
}
else if (strncmpic(sub[1], US"{sha1}", 6) == 0)
{
int sublen = Ustrlen(sub[1]+6);
sha1 base;
uschar digest[20];
sha1_start(&base);
sha1_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
/* If the length that we are comparing against is 28, assume the SHA1
digest is expressed as a base64 string. If the length is 40, assume a
straightforward hex representation. Other lengths fail. */
if (sublen == 28)
{
uschar *coded = auth_b64encode((uschar *)digest, 20);
DEBUG(D_auth) debug_printf("crypteq: using SHA1+B64 hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+6);
tempcond = (Ustrcmp(coded, sub[1]+6) == 0);
}
else if (sublen == 40)
{
int i;
uschar coded[44];
for (i = 0; i < 20; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
coded[40] = 0;
DEBUG(D_auth) debug_printf("crypteq: using SHA1+hex hashing\n"
" subject=%s\n crypted=%s\n", coded, sub[1]+6);
tempcond = (strcmpic(coded, sub[1]+6) == 0);
}
else
{
DEBUG(D_auth) debug_printf("crypteq: length for SHA-1 not 28 or 40: "
"fail\n crypted=%s\n", sub[1]+6);
tempcond = FALSE;
}
}
else /* {crypt} or {crypt16} and non-{ at start */
/* }-for-text-editors */
{
int which = 0;
uschar *coded;
if (strncmpic(sub[1], US"{crypt}", 7) == 0)
{
sub[1] += 7;
which = 1;
}
else if (strncmpic(sub[1], US"{crypt16}", 9) == 0)
{
sub[1] += 9;
which = 2;
}
else if (sub[1][0] == '{') /* }-for-text-editors */
{
expand_string_message = string_sprintf("unknown encryption mechanism "
"in \"%s\"", sub[1]);
return NULL;
}
switch(which)
{
case 0: coded = US DEFAULT_CRYPT(CS sub[0], CS sub[1]); break;
case 1: coded = US crypt(CS sub[0], CS sub[1]); break;
default: coded = US crypt16(CS sub[0], CS sub[1]); break;
}
#define STR(s) # s
#define XSTR(s) STR(s)
DEBUG(D_auth) debug_printf("crypteq: using %s()\n"
" subject=%s\n crypted=%s\n",
(which == 0)? XSTR(DEFAULT_CRYPT) : (which == 1)? "crypt" : "crypt16",
coded, sub[1]);
#undef STR
#undef XSTR
/* If the encrypted string contains fewer than two characters (for the
salt), force failure. Otherwise we get false positives: with an empty
string the yield of crypt() is an empty string! */
tempcond = (Ustrlen(sub[1]) < 2)? FALSE :
(Ustrcmp(coded, sub[1]) == 0);
}
break;
#endif /* SUPPORT_CRYPTEQ */
case ECOND_INLIST:
case ECOND_INLISTI:
{
int sep = 0;
uschar *save_iterate_item = iterate_item;
int (*compare)(const uschar *, const uschar *);
tempcond = FALSE;
if (cond_type == ECOND_INLISTI)
compare = strcmpic;
else
compare = (int (*)(const uschar *, const uschar *)) strcmp;
while ((iterate_item = string_nextinlist(&sub[1], &sep, NULL, 0)) != NULL)
if (compare(sub[0], iterate_item) == 0)
{
tempcond = TRUE;
break;
}
iterate_item = save_iterate_item;
}
} /* Switch for comparison conditions */
*yield = tempcond == testfor;
return s; /* End of comparison conditions */
/* and/or: computes logical and/or of several conditions */
case ECOND_AND:
case ECOND_OR:
subcondptr = (yield == NULL)? NULL : &tempcond;
combined_cond = (cond_type == ECOND_AND);
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
for (;;)
{
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s == '}') break;
if (*s != '{') /* }-for-text-editors */
{
expand_string_message = string_sprintf("each subcondition "
"inside an \"%s{...}\" condition must be in its own {}", name);
return NULL;
}
if (!(s = eval_condition(s+1, resetok, subcondptr)))
{
expand_string_message = string_sprintf("%s inside \"%s{...}\" condition",
expand_string_message, name);
return NULL;
}
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s++ != '}')
{
/* {-for-text-editors */
expand_string_message = string_sprintf("missing } at end of condition "
"inside \"%s\" group", name);
return NULL;
}
if (yield != NULL)
{
if (cond_type == ECOND_AND)
{
combined_cond &= tempcond;
if (!combined_cond) subcondptr = NULL; /* once false, don't */
} /* evaluate any more */
else
{
combined_cond |= tempcond;
if (combined_cond) subcondptr = NULL; /* once true, don't */
} /* evaluate any more */
}
}
if (yield != NULL) *yield = (combined_cond == testfor);
return ++s;
/* forall/forany: iterates a condition with different values */
case ECOND_FORALL:
case ECOND_FORANY:
{
int sep = 0;
uschar *save_iterate_item = iterate_item;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[0] = expand_string_internal(s, TRUE, &s, (yield == NULL), TRUE, resetok);
if (sub[0] == NULL) return NULL;
/* {-for-text-editors */
if (*s++ != '}') goto COND_FAILED_CURLY_END;
while (isspace(*s)) s++;
if (*s++ != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
sub[1] = s;
/* Call eval_condition once, with result discarded (as if scanning a
"false" part). This allows us to find the end of the condition, because if
the list it empty, we won't actually evaluate the condition for real. */
if (!(s = eval_condition(sub[1], resetok, NULL)))
{
expand_string_message = string_sprintf("%s inside \"%s\" condition",
expand_string_message, name);
return NULL;
}
while (isspace(*s)) s++;
/* {-for-text-editors */
if (*s++ != '}')
{
/* {-for-text-editors */
expand_string_message = string_sprintf("missing } at end of condition "
"inside \"%s\"", name);
return NULL;
}
if (yield != NULL) *yield = !testfor;
while ((iterate_item = string_nextinlist(&sub[0], &sep, NULL, 0)) != NULL)
{
DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item);
if (!eval_condition(sub[1], resetok, &tempcond))
{
expand_string_message = string_sprintf("%s inside \"%s\" condition",
expand_string_message, name);
iterate_item = save_iterate_item;
return NULL;
}
DEBUG(D_expand) debug_printf("%s: condition evaluated to %s\n", name,
tempcond? "true":"false");
if (yield != NULL) *yield = (tempcond == testfor);
if (tempcond == (cond_type == ECOND_FORANY)) break;
}
iterate_item = save_iterate_item;
return s;
}
/* The bool{} expansion condition maps a string to boolean.
The values supported should match those supported by the ACL condition
(acl.c, ACLC_CONDITION) so that we keep to a minimum the different ideas
of true/false. Note that Router "condition" rules have a different
interpretation, where general data can be used and only a few values
map to FALSE.
Note that readconf.c boolean matching, for boolean configuration options,
only matches true/yes/false/no.
The bool_lax{} condition matches the Router logic, which is much more
liberal. */
case ECOND_BOOL:
case ECOND_BOOL_LAX:
{
uschar *sub_arg[1];
uschar *t, *t2;
uschar *ourname;
size_t len;
BOOL boolvalue = FALSE;
while (isspace(*s)) s++;
if (*s != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
ourname = cond_type == ECOND_BOOL_LAX ? US"bool_lax" : US"bool";
switch(read_subs(sub_arg, 1, 1, &s, yield == NULL, FALSE, ourname, resetok))
{
case 1: expand_string_message = string_sprintf(
"too few arguments or bracketing error for %s",
ourname);
/*FALLTHROUGH*/
case 2:
case 3: return NULL;
}
t = sub_arg[0];
while (isspace(*t)) t++;
len = Ustrlen(t);
if (len)
{
/* trailing whitespace: seems like a good idea to ignore it too */
t2 = t + len - 1;
while (isspace(*t2)) t2--;
if (t2 != (t + len))
{
*++t2 = '\0';
len = t2 - t;
}
}
DEBUG(D_expand)
debug_printf("considering %s: %s\n", ourname, len ? t : US"<empty>");
/* logic for the lax case from expand_check_condition(), which also does
expands, and the logic is both short and stable enough that there should
be no maintenance burden from replicating it. */
if (len == 0)
boolvalue = FALSE;
else if (*t == '-'
? Ustrspn(t+1, "0123456789") == len-1
: Ustrspn(t, "0123456789") == len)
{
boolvalue = (Uatoi(t) == 0) ? FALSE : TRUE;
/* expand_check_condition only does a literal string "0" check */
if ((cond_type == ECOND_BOOL_LAX) && (len > 1))
boolvalue = TRUE;
}
else if (strcmpic(t, US"true") == 0 || strcmpic(t, US"yes") == 0)
boolvalue = TRUE;
else if (strcmpic(t, US"false") == 0 || strcmpic(t, US"no") == 0)
boolvalue = FALSE;
else if (cond_type == ECOND_BOOL_LAX)
boolvalue = TRUE;
else
{
expand_string_message = string_sprintf("unrecognised boolean "
"value \"%s\"", t);
return NULL;
}
if (yield != NULL) *yield = (boolvalue == testfor);
return s;
}
/* Unknown condition */
default:
expand_string_message = string_sprintf("unknown condition \"%s\"", name);
return NULL;
} /* End switch on condition type */
/* Missing braces at start and end of data */
COND_FAILED_CURLY_START:
expand_string_message = string_sprintf("missing { after \"%s\"", name);
return NULL;
COND_FAILED_CURLY_END:
expand_string_message = string_sprintf("missing } at end of \"%s\" condition",
name);
return NULL;
/* A condition requires code that is not compiled */
#if !defined(SUPPORT_PAM) || !defined(RADIUS_CONFIG_FILE) || \
!defined(LOOKUP_LDAP) || !defined(CYRUS_PWCHECK_SOCKET) || \
!defined(SUPPORT_CRYPTEQ) || !defined(CYRUS_SASLAUTHD_SOCKET)
COND_FAILED_NOT_COMPILED:
expand_string_message = string_sprintf("support for \"%s\" not compiled",
name);
return NULL;
#endif
}
| 165,190 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList,
const char* Name,
cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS])
{
cmsUInt32Number i;
if (NamedColorList == NULL) return FALSE;
if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) {
if (!GrowNamedColorList(NamedColorList)) return FALSE;
}
for (i=0; i < NamedColorList ->ColorantCount; i++)
NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i];
for (i=0; i < 3; i++)
NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i];
if (Name != NULL) {
strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name,
sizeof(NamedColorList ->List[NamedColorList ->nColors].Name));
NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0;
}
else
NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0;
NamedColorList ->nColors++;
return TRUE;
}
Commit Message: Non happy-path fixes
CWE ID: | cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList,
const char* Name,
cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS])
{
cmsUInt32Number i;
if (NamedColorList == NULL) return FALSE;
if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) {
if (!GrowNamedColorList(NamedColorList)) return FALSE;
}
for (i=0; i < NamedColorList ->ColorantCount; i++)
NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i];
for (i=0; i < 3; i++)
NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i];
if (Name != NULL) {
strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name, cmsMAX_PATH-1);
NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0;
}
else
NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0;
NamedColorList ->nColors++;
return TRUE;
}
| 166,543 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) ALIGN16(u2_width);
}
}
else
{
if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
return SET_IVD_FATAL_ERROR(e_error);
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Check for Valid Frame Rate in Header
Bug: 34093952
Change-Id: I9f009edda84555e8d14b138684a38114fb888bf8
(cherry picked from commit 3f068a4e66cc972cf798c79a196099bd7d3bfceb)
CWE ID: CWE-200 | IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) ALIGN16(u2_width);
}
}
else
{
if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
return SET_IVD_FATAL_ERROR(e_error);
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE)
{
return IMPEG2D_FRM_HDR_DECODE_ERR;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 174,036 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
int cmd, void __user *p)
{
struct sem_array *sma;
struct sem* curr;
int err, nsems;
ushort fast_sem_io[SEMMSL_FAST];
ushort* sem_io = fast_sem_io;
struct list_head tasks;
INIT_LIST_HEAD(&tasks);
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return PTR_ERR(sma);
}
nsems = sma->sem_nsems;
err = -EACCES;
if (ipcperms(ns, &sma->sem_perm,
cmd == SETALL ? S_IWUGO : S_IRUGO)) {
rcu_read_unlock();
goto out_wakeup;
}
err = security_sem_semctl(sma, cmd);
if (err) {
rcu_read_unlock();
goto out_wakeup;
}
err = -EACCES;
switch (cmd) {
case GETALL:
{
ushort __user *array = p;
int i;
if(nsems > SEMMSL_FAST) {
sem_getref(sma);
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma);
err = -EIDRM;
goto out_free;
}
}
spin_lock(&sma->sem_perm.lock);
for (i = 0; i < sma->sem_nsems; i++)
sem_io[i] = sma->sem_base[i].semval;
sem_unlock(sma);
err = 0;
if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
err = -EFAULT;
goto out_free;
}
case SETALL:
{
int i;
struct sem_undo *un;
ipc_rcu_getref(sma);
rcu_read_unlock();
if(nsems > SEMMSL_FAST) {
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
}
if (copy_from_user (sem_io, p, nsems*sizeof(ushort))) {
sem_putref(sma);
err = -EFAULT;
goto out_free;
}
for (i = 0; i < nsems; i++) {
if (sem_io[i] > SEMVMX) {
sem_putref(sma);
err = -ERANGE;
goto out_free;
}
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma);
err = -EIDRM;
goto out_free;
}
for (i = 0; i < nsems; i++)
sma->sem_base[i].semval = sem_io[i];
assert_spin_locked(&sma->sem_perm.lock);
list_for_each_entry(un, &sma->list_id, list_id) {
for (i = 0; i < nsems; i++)
un->semadj[i] = 0;
}
sma->sem_ctime = get_seconds();
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 0, &tasks);
err = 0;
goto out_unlock;
}
/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
}
err = -EINVAL;
if (semnum < 0 || semnum >= nsems) {
rcu_read_unlock();
goto out_wakeup;
}
spin_lock(&sma->sem_perm.lock);
curr = &sma->sem_base[semnum];
switch (cmd) {
case GETVAL:
err = curr->semval;
goto out_unlock;
case GETPID:
err = curr->sempid;
goto out_unlock;
case GETNCNT:
err = count_semncnt(sma,semnum);
goto out_unlock;
case GETZCNT:
err = count_semzcnt(sma,semnum);
goto out_unlock;
}
out_unlock:
sem_unlock(sma);
out_wakeup:
wake_up_sem_queue_do(&tasks);
out_free:
if(sem_io != fast_sem_io)
ipc_free(sem_io, sizeof(ushort)*nsems);
return err;
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
int cmd, void __user *p)
{
struct sem_array *sma;
struct sem* curr;
int err, nsems;
ushort fast_sem_io[SEMMSL_FAST];
ushort* sem_io = fast_sem_io;
struct list_head tasks;
INIT_LIST_HEAD(&tasks);
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return PTR_ERR(sma);
}
nsems = sma->sem_nsems;
err = -EACCES;
if (ipcperms(ns, &sma->sem_perm,
cmd == SETALL ? S_IWUGO : S_IRUGO)) {
rcu_read_unlock();
goto out_wakeup;
}
err = security_sem_semctl(sma, cmd);
if (err) {
rcu_read_unlock();
goto out_wakeup;
}
err = -EACCES;
switch (cmd) {
case GETALL:
{
ushort __user *array = p;
int i;
if(nsems > SEMMSL_FAST) {
sem_getref(sma);
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma, -1);
err = -EIDRM;
goto out_free;
}
} else
sem_lock(sma, NULL, -1);
for (i = 0; i < sma->sem_nsems; i++)
sem_io[i] = sma->sem_base[i].semval;
sem_unlock(sma, -1);
err = 0;
if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
err = -EFAULT;
goto out_free;
}
case SETALL:
{
int i;
struct sem_undo *un;
if (!ipc_rcu_getref(sma)) {
rcu_read_unlock();
return -EIDRM;
}
rcu_read_unlock();
if(nsems > SEMMSL_FAST) {
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
}
if (copy_from_user (sem_io, p, nsems*sizeof(ushort))) {
sem_putref(sma);
err = -EFAULT;
goto out_free;
}
for (i = 0; i < nsems; i++) {
if (sem_io[i] > SEMVMX) {
sem_putref(sma);
err = -ERANGE;
goto out_free;
}
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma, -1);
err = -EIDRM;
goto out_free;
}
for (i = 0; i < nsems; i++)
sma->sem_base[i].semval = sem_io[i];
assert_spin_locked(&sma->sem_perm.lock);
list_for_each_entry(un, &sma->list_id, list_id) {
for (i = 0; i < nsems; i++)
un->semadj[i] = 0;
}
sma->sem_ctime = get_seconds();
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 0, &tasks);
err = 0;
goto out_unlock;
}
/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
}
err = -EINVAL;
if (semnum < 0 || semnum >= nsems) {
rcu_read_unlock();
goto out_wakeup;
}
sem_lock(sma, NULL, -1);
curr = &sma->sem_base[semnum];
switch (cmd) {
case GETVAL:
err = curr->semval;
goto out_unlock;
case GETPID:
err = curr->sempid;
goto out_unlock;
case GETNCNT:
err = count_semncnt(sma,semnum);
goto out_unlock;
case GETZCNT:
err = count_semzcnt(sma,semnum);
goto out_unlock;
}
out_unlock:
sem_unlock(sma, -1);
out_wakeup:
wake_up_sem_queue_do(&tasks);
out_free:
if(sem_io != fast_sem_io)
ipc_free(sem_io, sizeof(ushort)*nsems);
return err;
}
| 165,980 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MountError PerformFakeMount(const std::string& source_path,
const base::FilePath& mounted_path) {
if (mounted_path.empty())
return MOUNT_ERROR_INVALID_ARGUMENT;
if (!base::CreateDirectory(mounted_path)) {
DLOG(ERROR) << "Failed to create directory at " << mounted_path.value();
return MOUNT_ERROR_DIRECTORY_CREATION_FAILED;
}
const base::FilePath dummy_file_path =
mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt");
const std::string dummy_file_content = "This is a dummy file.";
const int write_result = base::WriteFile(
dummy_file_path, dummy_file_content.data(), dummy_file_content.size());
if (write_result != static_cast<int>(dummy_file_content.size())) {
DLOG(ERROR) << "Failed to put a dummy file at "
<< dummy_file_path.value();
return MOUNT_ERROR_MOUNT_PROGRAM_FAILED;
}
return MOUNT_ERROR_NONE;
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <[email protected]>
Commit-Queue: Sam McNally <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID: | MountError PerformFakeMount(const std::string& source_path,
const base::FilePath& mounted_path,
MountType type) {
if (mounted_path.empty())
return MOUNT_ERROR_INVALID_ARGUMENT;
if (!base::CreateDirectory(mounted_path)) {
DLOG(ERROR) << "Failed to create directory at " << mounted_path.value();
return MOUNT_ERROR_DIRECTORY_CREATION_FAILED;
}
// Fake network mounts are responsible for populating their mount paths so
// don't need a dummy file.
if (type == MOUNT_TYPE_NETWORK_STORAGE)
return MOUNT_ERROR_NONE;
const base::FilePath dummy_file_path =
mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt");
const std::string dummy_file_content = "This is a dummy file.";
const int write_result = base::WriteFile(
dummy_file_path, dummy_file_content.data(), dummy_file_content.size());
if (write_result != static_cast<int>(dummy_file_content.size())) {
DLOG(ERROR) << "Failed to put a dummy file at "
<< dummy_file_path.value();
return MOUNT_ERROR_MOUNT_PROGRAM_FAILED;
}
return MOUNT_ERROR_NONE;
}
| 171,731 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t o2nm_node_ipv4_address_store(struct config_item *item,
const char *page,
size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
int ret, i;
struct rb_node **p, *parent;
unsigned int octets[4];
__be32 ipv4_addr = 0;
ret = sscanf(page, "%3u.%3u.%3u.%3u", &octets[3], &octets[2],
&octets[1], &octets[0]);
if (ret != 4)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(octets); i++) {
if (octets[i] > 255)
return -ERANGE;
be32_add_cpu(&ipv4_addr, octets[i] << (i * 8));
}
ret = 0;
write_lock(&cluster->cl_nodes_lock);
if (o2nm_node_ip_tree_lookup(cluster, ipv4_addr, &p, &parent))
ret = -EEXIST;
else if (test_and_set_bit(O2NM_NODE_ATTR_ADDRESS,
&node->nd_set_attributes))
ret = -EBUSY;
else {
rb_link_node(&node->nd_ip_node, parent, p);
rb_insert_color(&node->nd_ip_node, &cluster->cl_node_ip_tree);
}
write_unlock(&cluster->cl_nodes_lock);
if (ret)
return ret;
memcpy(&node->nd_ipv4_address, &ipv4_addr, sizeof(ipv4_addr));
return count;
}
Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[[email protected]: v2]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | static ssize_t o2nm_node_ipv4_address_store(struct config_item *item,
const char *page,
size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster;
int ret, i;
struct rb_node **p, *parent;
unsigned int octets[4];
__be32 ipv4_addr = 0;
ret = sscanf(page, "%3u.%3u.%3u.%3u", &octets[3], &octets[2],
&octets[1], &octets[0]);
if (ret != 4)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(octets); i++) {
if (octets[i] > 255)
return -ERANGE;
be32_add_cpu(&ipv4_addr, octets[i] << (i * 8));
}
o2nm_lock_subsystem();
cluster = to_o2nm_cluster_from_node(node);
if (!cluster) {
o2nm_unlock_subsystem();
return -EINVAL;
}
ret = 0;
write_lock(&cluster->cl_nodes_lock);
if (o2nm_node_ip_tree_lookup(cluster, ipv4_addr, &p, &parent))
ret = -EEXIST;
else if (test_and_set_bit(O2NM_NODE_ATTR_ADDRESS,
&node->nd_set_attributes))
ret = -EBUSY;
else {
rb_link_node(&node->nd_ip_node, parent, p);
rb_insert_color(&node->nd_ip_node, &cluster->cl_node_ip_tree);
}
write_unlock(&cluster->cl_nodes_lock);
o2nm_unlock_subsystem();
if (ret)
return ret;
memcpy(&node->nd_ipv4_address, &ipv4_addr, sizeof(ipv4_addr));
return count;
}
| 169,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
| 168,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125 | int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
| 169,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dprintf_formatf(
void *data, /* untouched by format(), just sent to the stream() function in
the second argument */
/* function pointer called for each output character */
int (*stream)(int, FILE *),
const char *format, /* %-formatted string */
va_list ap_save) /* list of parameters */
{
/* Base-36 digits for numbers. */
const char *digits = lower_digits;
/* Pointer into the format string. */
char *f;
/* Number of characters written. */
int done = 0;
long param; /* current parameter to read */
long param_num=0; /* parameter counter */
va_stack_t vto[MAX_PARAMETERS];
char *endpos[MAX_PARAMETERS];
char **end;
char work[BUFFSIZE];
va_stack_t *p;
/* 'workend' points to the final buffer byte position, but with an extra
byte as margin to avoid the (false?) warning Coverity gives us
otherwise */
char *workend = &work[sizeof(work) - 2];
/* Do the actual %-code parsing */
if(dprintf_Pass1(format, vto, endpos, ap_save))
return -1;
end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
created for us */
f = (char *)format;
while(*f != '\0') {
/* Format spec modifiers. */
int is_alt;
/* Width of a field. */
long width;
/* Precision of a field. */
long prec;
/* Decimal integer is negative. */
int is_neg;
/* Base of a number to be written. */
long base;
/* Integral values to be written. */
mp_uintmax_t num;
/* Used to convert negative in positive. */
mp_intmax_t signed_num;
char *w;
if(*f != '%') {
/* This isn't a format spec, so write everything out until the next one
OR end of string is reached. */
do {
OUTCHAR(*f);
} while(*++f && ('%' != *f));
continue;
}
++f;
/* Check for "%%". Note that although the ANSI standard lists
'%' as a conversion specifier, it says "The complete format
specification shall be `%%'," so we can avoid all the width
and precision processing. */
if(*f == '%') {
++f;
OUTCHAR('%');
continue;
}
/* If this is a positional parameter, the position must follow immediately
after the %, thus create a %<num>$ sequence */
param=dprintf_DollarString(f, &f);
if(!param)
param = param_num;
else
--param;
param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
third %s will pick the 3rd argument */
p = &vto[param];
/* pick up the specified width */
if(p->flags & FLAGS_WIDTHPARAM) {
width = (long)vto[p->width].data.num.as_signed;
param_num++; /* since the width is extracted from a parameter, we
must skip that to get to the next one properly */
if(width < 0) {
/* "A negative field width is taken as a '-' flag followed by a
positive field width." */
width = -width;
p->flags |= FLAGS_LEFT;
p->flags &= ~FLAGS_PAD_NIL;
}
}
else
width = p->width;
/* pick up the specified precision */
if(p->flags & FLAGS_PRECPARAM) {
prec = (long)vto[p->precision].data.num.as_signed;
param_num++; /* since the precision is extracted from a parameter, we
must skip that to get to the next one properly */
if(prec < 0)
/* "A negative precision is taken as if the precision were
omitted." */
prec = -1;
}
else if(p->flags & FLAGS_PREC)
prec = p->precision;
else
prec = -1;
is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
switch(p->type) {
case FORMAT_INT:
num = p->data.num.as_unsigned;
if(p->flags & FLAGS_CHAR) {
/* Character. */
if(!(p->flags & FLAGS_LEFT))
while(--width > 0)
OUTCHAR(' ');
OUTCHAR((char) num);
if(p->flags & FLAGS_LEFT)
while(--width > 0)
OUTCHAR(' ');
break;
}
if(p->flags & FLAGS_OCTAL) {
/* Octal unsigned integer. */
base = 8;
goto unsigned_number;
}
else if(p->flags & FLAGS_HEX) {
/* Hexadecimal unsigned integer. */
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
base = 16;
goto unsigned_number;
}
else if(p->flags & FLAGS_UNSIGNED) {
/* Decimal unsigned integer. */
base = 10;
goto unsigned_number;
}
/* Decimal integer. */
base = 10;
is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
if(is_neg) {
/* signed_num might fail to hold absolute negative minimum by 1 */
signed_num = p->data.num.as_signed + (mp_intmax_t)1;
signed_num = -signed_num;
num = (mp_uintmax_t)signed_num;
num += (mp_uintmax_t)1;
}
goto number;
unsigned_number:
/* Unsigned number of base BASE. */
is_neg = 0;
number:
/* Number of base BASE. */
/* Supply a default precision if none was given. */
if(prec == -1)
prec = 1;
/* Put the number in WORK. */
w = workend;
while(num > 0) {
*w-- = digits[num % base];
num /= base;
}
width -= (long)(workend - w);
prec -= (long)(workend - w);
if(is_alt && base == 8 && prec <= 0) {
*w-- = '0';
--width;
}
if(prec > 0) {
width -= prec;
while(prec-- > 0)
*w-- = '0';
}
if(is_alt && base == 16)
width -= 2;
if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
--width;
if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR(' ');
if(is_neg)
OUTCHAR('-');
else if(p->flags & FLAGS_SHOWSIGN)
OUTCHAR('+');
else if(p->flags & FLAGS_SPACE)
OUTCHAR(' ');
if(is_alt && base == 16) {
OUTCHAR('0');
if(p->flags & FLAGS_UPPER)
OUTCHAR('X');
else
OUTCHAR('x');
}
if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR('0');
/* Write the number. */
while(++w <= workend) {
OUTCHAR(*w);
}
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
break;
case FORMAT_STRING:
/* String. */
{
static const char null[] = "(nil)";
const char *str;
size_t len;
str = (char *) p->data.str;
if(str == NULL) {
/* Write null[] if there's space. */
if(prec == -1 || prec >= (long) sizeof(null) - 1) {
str = null;
len = sizeof(null) - 1;
/* Disable quotes around (nil) */
p->flags &= (~FLAGS_ALT);
}
else {
str = "";
len = 0;
}
}
else if(prec != -1)
len = (size_t)prec;
else
len = strlen(str);
width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
if(!(p->flags&FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
while((len-- > 0) && *str)
OUTCHAR(*str++);
if(p->flags&FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
}
break;
case FORMAT_PTR:
/* Generic pointer. */
{
void *ptr;
ptr = (void *) p->data.ptr;
if(ptr != NULL) {
/* If the pointer is not NULL, write it as a %#x spec. */
base = 16;
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
is_alt = 1;
num = (size_t) ptr;
is_neg = 0;
goto number;
}
else {
/* Write "(nil)" for a nil pointer. */
static const char strnil[] = "(nil)";
const char *point;
width -= (long)(sizeof(strnil) - 1);
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
for(point = strnil; *point != '\0'; ++point)
OUTCHAR(*point);
if(! (p->flags & FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
}
}
break;
case FORMAT_DOUBLE:
{
char formatbuf[32]="%";
char *fptr = &formatbuf[1];
size_t left = sizeof(formatbuf)-strlen(formatbuf);
int len;
width = -1;
if(p->flags & FLAGS_WIDTH)
width = p->width;
else if(p->flags & FLAGS_WIDTHPARAM)
width = (long)vto[p->width].data.num.as_signed;
prec = -1;
if(p->flags & FLAGS_PREC)
prec = p->precision;
else if(p->flags & FLAGS_PRECPARAM)
prec = (long)vto[p->precision].data.num.as_signed;
if(p->flags & FLAGS_LEFT)
*fptr++ = '-';
if(p->flags & FLAGS_SHOWSIGN)
*fptr++ = '+';
if(p->flags & FLAGS_SPACE)
*fptr++ = ' ';
if(p->flags & FLAGS_ALT)
*fptr++ = '#';
*fptr = 0;
if(width >= 0) {
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, "%ld", width);
fptr += len;
left -= len;
}
if(prec >= 0) {
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, ".%ld", prec);
fptr += len;
}
if(p->flags & FLAGS_LONG)
*fptr++ = 'l';
if(p->flags & FLAGS_FLOATE)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
else if(p->flags & FLAGS_FLOATG)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
else
*fptr++ = 'f';
*fptr = 0; /* and a final zero termination */
/* NOTE NOTE NOTE!! Not all sprintf implementations return number of
output characters */
(sprintf)(work, formatbuf, p->data.dnum);
for(fptr=work; *fptr; fptr++)
OUTCHAR(*fptr);
}
break;
case FORMAT_INTPTR:
/* Answer the count of characters written. */
#ifdef HAVE_LONG_LONG_TYPE
if(p->flags & FLAGS_LONGLONG)
*(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
else
#endif
if(p->flags & FLAGS_LONG)
*(long *) p->data.ptr = (long)done;
else if(!(p->flags & FLAGS_SHORT))
*(int *) p->data.ptr = (int)done;
else
*(short *) p->data.ptr = (short)done;
break;
default:
break;
}
f = *end++; /* goto end of %-code */
}
return done;
}
Commit Message: printf: fix floating point buffer overflow issues
... and add a bunch of floating point printf tests
CWE ID: CWE-119 | static int dprintf_formatf(
void *data, /* untouched by format(), just sent to the stream() function in
the second argument */
/* function pointer called for each output character */
int (*stream)(int, FILE *),
const char *format, /* %-formatted string */
va_list ap_save) /* list of parameters */
{
/* Base-36 digits for numbers. */
const char *digits = lower_digits;
/* Pointer into the format string. */
char *f;
/* Number of characters written. */
int done = 0;
long param; /* current parameter to read */
long param_num=0; /* parameter counter */
va_stack_t vto[MAX_PARAMETERS];
char *endpos[MAX_PARAMETERS];
char **end;
char work[BUFFSIZE];
va_stack_t *p;
/* 'workend' points to the final buffer byte position, but with an extra
byte as margin to avoid the (false?) warning Coverity gives us
otherwise */
char *workend = &work[sizeof(work) - 2];
/* Do the actual %-code parsing */
if(dprintf_Pass1(format, vto, endpos, ap_save))
return -1;
end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
created for us */
f = (char *)format;
while(*f != '\0') {
/* Format spec modifiers. */
int is_alt;
/* Width of a field. */
long width;
/* Precision of a field. */
long prec;
/* Decimal integer is negative. */
int is_neg;
/* Base of a number to be written. */
long base;
/* Integral values to be written. */
mp_uintmax_t num;
/* Used to convert negative in positive. */
mp_intmax_t signed_num;
char *w;
if(*f != '%') {
/* This isn't a format spec, so write everything out until the next one
OR end of string is reached. */
do {
OUTCHAR(*f);
} while(*++f && ('%' != *f));
continue;
}
++f;
/* Check for "%%". Note that although the ANSI standard lists
'%' as a conversion specifier, it says "The complete format
specification shall be `%%'," so we can avoid all the width
and precision processing. */
if(*f == '%') {
++f;
OUTCHAR('%');
continue;
}
/* If this is a positional parameter, the position must follow immediately
after the %, thus create a %<num>$ sequence */
param=dprintf_DollarString(f, &f);
if(!param)
param = param_num;
else
--param;
param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
third %s will pick the 3rd argument */
p = &vto[param];
/* pick up the specified width */
if(p->flags & FLAGS_WIDTHPARAM) {
width = (long)vto[p->width].data.num.as_signed;
param_num++; /* since the width is extracted from a parameter, we
must skip that to get to the next one properly */
if(width < 0) {
/* "A negative field width is taken as a '-' flag followed by a
positive field width." */
width = -width;
p->flags |= FLAGS_LEFT;
p->flags &= ~FLAGS_PAD_NIL;
}
}
else
width = p->width;
/* pick up the specified precision */
if(p->flags & FLAGS_PRECPARAM) {
prec = (long)vto[p->precision].data.num.as_signed;
param_num++; /* since the precision is extracted from a parameter, we
must skip that to get to the next one properly */
if(prec < 0)
/* "A negative precision is taken as if the precision were
omitted." */
prec = -1;
}
else if(p->flags & FLAGS_PREC)
prec = p->precision;
else
prec = -1;
is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
switch(p->type) {
case FORMAT_INT:
num = p->data.num.as_unsigned;
if(p->flags & FLAGS_CHAR) {
/* Character. */
if(!(p->flags & FLAGS_LEFT))
while(--width > 0)
OUTCHAR(' ');
OUTCHAR((char) num);
if(p->flags & FLAGS_LEFT)
while(--width > 0)
OUTCHAR(' ');
break;
}
if(p->flags & FLAGS_OCTAL) {
/* Octal unsigned integer. */
base = 8;
goto unsigned_number;
}
else if(p->flags & FLAGS_HEX) {
/* Hexadecimal unsigned integer. */
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
base = 16;
goto unsigned_number;
}
else if(p->flags & FLAGS_UNSIGNED) {
/* Decimal unsigned integer. */
base = 10;
goto unsigned_number;
}
/* Decimal integer. */
base = 10;
is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
if(is_neg) {
/* signed_num might fail to hold absolute negative minimum by 1 */
signed_num = p->data.num.as_signed + (mp_intmax_t)1;
signed_num = -signed_num;
num = (mp_uintmax_t)signed_num;
num += (mp_uintmax_t)1;
}
goto number;
unsigned_number:
/* Unsigned number of base BASE. */
is_neg = 0;
number:
/* Number of base BASE. */
/* Supply a default precision if none was given. */
if(prec == -1)
prec = 1;
/* Put the number in WORK. */
w = workend;
while(num > 0) {
*w-- = digits[num % base];
num /= base;
}
width -= (long)(workend - w);
prec -= (long)(workend - w);
if(is_alt && base == 8 && prec <= 0) {
*w-- = '0';
--width;
}
if(prec > 0) {
width -= prec;
while(prec-- > 0)
*w-- = '0';
}
if(is_alt && base == 16)
width -= 2;
if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
--width;
if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR(' ');
if(is_neg)
OUTCHAR('-');
else if(p->flags & FLAGS_SHOWSIGN)
OUTCHAR('+');
else if(p->flags & FLAGS_SPACE)
OUTCHAR(' ');
if(is_alt && base == 16) {
OUTCHAR('0');
if(p->flags & FLAGS_UPPER)
OUTCHAR('X');
else
OUTCHAR('x');
}
if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR('0');
/* Write the number. */
while(++w <= workend) {
OUTCHAR(*w);
}
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
break;
case FORMAT_STRING:
/* String. */
{
static const char null[] = "(nil)";
const char *str;
size_t len;
str = (char *) p->data.str;
if(str == NULL) {
/* Write null[] if there's space. */
if(prec == -1 || prec >= (long) sizeof(null) - 1) {
str = null;
len = sizeof(null) - 1;
/* Disable quotes around (nil) */
p->flags &= (~FLAGS_ALT);
}
else {
str = "";
len = 0;
}
}
else if(prec != -1)
len = (size_t)prec;
else
len = strlen(str);
width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
if(!(p->flags&FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
while((len-- > 0) && *str)
OUTCHAR(*str++);
if(p->flags&FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
}
break;
case FORMAT_PTR:
/* Generic pointer. */
{
void *ptr;
ptr = (void *) p->data.ptr;
if(ptr != NULL) {
/* If the pointer is not NULL, write it as a %#x spec. */
base = 16;
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
is_alt = 1;
num = (size_t) ptr;
is_neg = 0;
goto number;
}
else {
/* Write "(nil)" for a nil pointer. */
static const char strnil[] = "(nil)";
const char *point;
width -= (long)(sizeof(strnil) - 1);
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
for(point = strnil; *point != '\0'; ++point)
OUTCHAR(*point);
if(! (p->flags & FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
}
}
break;
case FORMAT_DOUBLE:
{
char formatbuf[32]="%";
char *fptr = &formatbuf[1];
size_t left = sizeof(formatbuf)-strlen(formatbuf);
int len;
width = -1;
if(p->flags & FLAGS_WIDTH)
width = p->width;
else if(p->flags & FLAGS_WIDTHPARAM)
width = (long)vto[p->width].data.num.as_signed;
prec = -1;
if(p->flags & FLAGS_PREC)
prec = p->precision;
else if(p->flags & FLAGS_PRECPARAM)
prec = (long)vto[p->precision].data.num.as_signed;
if(p->flags & FLAGS_LEFT)
*fptr++ = '-';
if(p->flags & FLAGS_SHOWSIGN)
*fptr++ = '+';
if(p->flags & FLAGS_SPACE)
*fptr++ = ' ';
if(p->flags & FLAGS_ALT)
*fptr++ = '#';
*fptr = 0;
if(width >= 0) {
if(width >= (long)sizeof(work))
width = sizeof(work)-1;
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, "%ld", width);
fptr += len;
left -= len;
}
if(prec >= 0) {
/* for each digit in the integer part, we can have one less
precision */
size_t maxprec = sizeof(work) - 2;
double val = p->data.dnum;
while(val >= 10.0) {
val /= 10;
maxprec--;
}
if(prec > (long)maxprec)
prec = maxprec-1;
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, ".%ld", prec);
fptr += len;
}
if(p->flags & FLAGS_LONG)
*fptr++ = 'l';
if(p->flags & FLAGS_FLOATE)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
else if(p->flags & FLAGS_FLOATG)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
else
*fptr++ = 'f';
*fptr = 0; /* and a final zero termination */
/* NOTE NOTE NOTE!! Not all sprintf implementations return number of
output characters */
(sprintf)(work, formatbuf, p->data.dnum);
#ifdef CURLDEBUG
assert(strlen(work) <= sizeof(work));
#endif
for(fptr=work; *fptr; fptr++)
OUTCHAR(*fptr);
}
break;
case FORMAT_INTPTR:
/* Answer the count of characters written. */
#ifdef HAVE_LONG_LONG_TYPE
if(p->flags & FLAGS_LONGLONG)
*(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
else
#endif
if(p->flags & FLAGS_LONG)
*(long *) p->data.ptr = (long)done;
else if(!(p->flags & FLAGS_SHORT))
*(int *) p->data.ptr = (int)done;
else
*(short *) p->data.ptr = (short)done;
break;
default:
break;
}
f = *end++; /* goto end of %-code */
}
return done;
}
| 169,436 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MultibufferDataSource::DidPassCORSAccessCheck() const {
if (url_data()->cors_mode() == UrlData::CORS_UNSPECIFIED)
return false;
if (init_cb_)
return false;
if (failed_)
return false;
return true;
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool MultibufferDataSource::DidPassCORSAccessCheck() const {
| 172,624 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt,
int newtype,
struct ipv6_opt_hdr __user *newopt, int newoptlen)
{
int tot_len = 0;
char *p;
struct ipv6_txoptions *opt2;
int err;
if (opt) {
if (newtype != IPV6_HOPOPTS && opt->hopopt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt));
if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt));
if (newtype != IPV6_RTHDR && opt->srcrt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt));
if (newtype != IPV6_DSTOPTS && opt->dst1opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt));
}
if (newopt && newoptlen)
tot_len += CMSG_ALIGN(newoptlen);
if (!tot_len)
return NULL;
tot_len += sizeof(*opt2);
opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC);
if (!opt2)
return ERR_PTR(-ENOBUFS);
memset(opt2, 0, tot_len);
opt2->tot_len = tot_len;
p = (char *)(opt2 + 1);
err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen,
newtype != IPV6_HOPOPTS,
&opt2->hopopt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDRDSTOPTS,
&opt2->dst0opt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDR,
(struct ipv6_opt_hdr **)&opt2->srcrt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen,
newtype != IPV6_DSTOPTS,
&opt2->dst1opt, &p);
if (err)
goto out;
opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) +
(opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) +
(opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0);
opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0);
return opt2;
out:
sock_kfree_s(sk, opt2, opt2->tot_len);
return ERR_PTR(err);
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt,
int newtype,
struct ipv6_opt_hdr __user *newopt, int newoptlen)
{
int tot_len = 0;
char *p;
struct ipv6_txoptions *opt2;
int err;
if (opt) {
if (newtype != IPV6_HOPOPTS && opt->hopopt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt));
if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt));
if (newtype != IPV6_RTHDR && opt->srcrt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt));
if (newtype != IPV6_DSTOPTS && opt->dst1opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt));
}
if (newopt && newoptlen)
tot_len += CMSG_ALIGN(newoptlen);
if (!tot_len)
return NULL;
tot_len += sizeof(*opt2);
opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC);
if (!opt2)
return ERR_PTR(-ENOBUFS);
memset(opt2, 0, tot_len);
atomic_set(&opt2->refcnt, 1);
opt2->tot_len = tot_len;
p = (char *)(opt2 + 1);
err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen,
newtype != IPV6_HOPOPTS,
&opt2->hopopt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDRDSTOPTS,
&opt2->dst0opt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDR,
(struct ipv6_opt_hdr **)&opt2->srcrt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen,
newtype != IPV6_DSTOPTS,
&opt2->dst1opt, &p);
if (err)
goto out;
opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) +
(opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) +
(opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0);
opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0);
return opt2;
out:
sock_kfree_s(sk, opt2, opt2->tot_len);
return ERR_PTR(err);
}
| 167,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width,
const unsigned int new_height)
{
const unsigned int src_width = src->sx;
const unsigned int src_height = src->sy;
gdImagePtr tmp_im = NULL;
gdImagePtr dst = NULL;
/* First, handle the trivial case. */
if (src_width == new_width && src_height == new_height) {
return gdImageClone(src);
}/* if */
/* Convert to truecolor if it isn't; this code requires it. */
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}/* if */
/* Scale horizontally unless sizes are the same. */
if (src_width == new_width) {
tmp_im = src;
} else {
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL);
}/* if .. else*/
/* If vertical sizes match, we're done. */
if (src_height == new_height) {
assert(tmp_im != src);
return tmp_im;
}/* if */
/* Otherwise, we need to scale vertically. */
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst != NULL) {
gdImageSetInterpolationMethod(dst, src->interpolation_id);
_gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL);
}/* if */
if (src != tmp_im) {
gdFree(tmp_im);
}/* if */
return dst;
}/* gdImageScaleTwoPass*/
Commit Message: gdImageScaleTwoPass memory leak fix
Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and
confirmed by @vapier. This bug actually bit me in production and I'm
very thankful that it was reported with an easy fix.
Fixes #173.
CWE ID: CWE-399 | gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width,
const unsigned int new_height)
{
const unsigned int src_width = src->sx;
const unsigned int src_height = src->sy;
gdImagePtr tmp_im = NULL;
gdImagePtr dst = NULL;
/* First, handle the trivial case. */
if (src_width == new_width && src_height == new_height) {
return gdImageClone(src);
}/* if */
/* Convert to truecolor if it isn't; this code requires it. */
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}/* if */
/* Scale horizontally unless sizes are the same. */
if (src_width == new_width) {
tmp_im = src;
} else {
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL);
}/* if .. else*/
/* If vertical sizes match, we're done. */
if (src_height == new_height) {
assert(tmp_im != src);
return tmp_im;
}/* if */
/* Otherwise, we need to scale vertically. */
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst != NULL) {
gdImageSetInterpolationMethod(dst, src->interpolation_id);
_gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL);
}/* if */
if (src != tmp_im) {
gdImageDestroy(tmp_im);
}/* if */
return dst;
}/* gdImageScaleTwoPass*/
| 167,473 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Blob::Blob()
: m_size(0)
{
ScriptWrappable::init(this);
OwnPtr<BlobData> blobData = BlobData::create();
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release());
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | Blob::Blob()
: m_size(0)
{
ScriptWrappable::init(this);
OwnPtr<BlobData> blobData = BlobData::create();
m_internalURL = BlobURL::createInternalURL();
BlobRegistry::registerBlobURL(m_internalURL, blobData.release());
}
| 170,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_video::allocate_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes);
if (!m_out_mem_ptr) {
int nBufHdrSize = 0;
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
if (m_out_mem_ptr && m_pOutput_pmem) {
bufHdr = m_out_mem_ptr;
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i];
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem");
eRet = OMX_ErrorInsufficientResources;
}
}
DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual);
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i);
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096;
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer");
close (m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
else {
m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
native_handle_t *handle = native_handle_create(1, 0);
handle->data[0] = m_pOutput_pmem[i].fd;
char *data = (char*) m_pOutput_pmem[i].buffer;
OMX_U32 type = 1;
memcpy(data, &type, sizeof(OMX_U32));
memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*));
}
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer;
(*bufferHdr)->pAppPrivate = appData;
BITMASK_SET(&m_out_bm_count,i);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call"
"for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual);
}
}
return eRet;
}
Commit Message: DO NOT MERGE Fix wrong nAllocLen
Set nAllocLen to the size of the opaque handle itself.
Bug: 28816964
Bug: 28816827
Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099
CWE ID: CWE-119 | OMX_ERRORTYPE omx_video::allocate_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes);
if (!m_out_mem_ptr) {
int nBufHdrSize = 0;
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
if (m_out_mem_ptr && m_pOutput_pmem) {
bufHdr = m_out_mem_ptr;
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i];
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem");
eRet = OMX_ErrorInsufficientResources;
}
}
DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual);
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i);
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096;
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer");
close (m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
else {
m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
native_handle_t *handle = native_handle_create(1, 0);
handle->data[0] = m_pOutput_pmem[i].fd;
char *data = (char*) m_pOutput_pmem[i].buffer;
OMX_U32 type = 1;
memcpy(data, &type, sizeof(OMX_U32));
memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*));
}
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer;
(*bufferHdr)->pAppPrivate = appData;
BITMASK_SET(&m_out_bm_count,i);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call"
"for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual);
}
}
return eRet;
}
| 173,520 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) {
HANDLE pump_messages_event_for_renderer = NULL;
DuplicateHandle(GetCurrentProcess(), pump_messages_event,
channel_->renderer_handle(),
&pump_messages_event_for_renderer,
0, FALSE, DUPLICATE_SAME_ACCESS);
DCHECK(pump_messages_event_for_renderer != NULL);
Send(new PluginHostMsg_SetWindowlessPumpEvent(
route_id_, pump_messages_event_for_renderer));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) {
HANDLE pump_messages_event_for_renderer = NULL;
sandbox::BrokerDuplicateHandle(pump_messages_event, channel_->peer_pid(),
&pump_messages_event_for_renderer,
SYNCHRONIZE | EVENT_MODIFY_STATE, 0);
DCHECK(pump_messages_event_for_renderer != NULL);
Send(new PluginHostMsg_SetWindowlessPumpEvent(
route_id_, pump_messages_event_for_renderer));
}
| 170,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void read_conf(FILE *conffile)
{
char *buffer, *line, *val;
buffer = loadfile(conffile);
for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) {
if (!strncmp(line, "export ", 7))
continue;
val = strchr(line, '=');
if (!val) {
printf("invalid configuration line\n");
break;
}
*val++ = '\0';
if (!strcmp(line, "JSON_INDENT"))
conf.indent = atoi(val);
if (!strcmp(line, "JSON_COMPACT"))
conf.compact = atoi(val);
if (!strcmp(line, "JSON_ENSURE_ASCII"))
conf.ensure_ascii = atoi(val);
if (!strcmp(line, "JSON_PRESERVE_ORDER"))
conf.preserve_order = atoi(val);
if (!strcmp(line, "JSON_SORT_KEYS"))
conf.sort_keys = atoi(val);
if (!strcmp(line, "STRIP"))
conf.strip = atoi(val);
}
free(buffer);
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static void read_conf(FILE *conffile)
{
char *buffer, *line, *val;
buffer = loadfile(conffile);
for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) {
if (!strncmp(line, "export ", 7))
continue;
val = strchr(line, '=');
if (!val) {
printf("invalid configuration line\n");
break;
}
*val++ = '\0';
if (!strcmp(line, "JSON_INDENT"))
conf.indent = atoi(val);
if (!strcmp(line, "JSON_COMPACT"))
conf.compact = atoi(val);
if (!strcmp(line, "JSON_ENSURE_ASCII"))
conf.ensure_ascii = atoi(val);
if (!strcmp(line, "JSON_PRESERVE_ORDER"))
conf.preserve_order = atoi(val);
if (!strcmp(line, "JSON_SORT_KEYS"))
conf.sort_keys = atoi(val);
if (!strcmp(line, "STRIP"))
conf.strip = atoi(val);
if (!strcmp(line, "HASHSEED")) {
conf.have_hashseed = 1;
conf.hashseed = atoi(val);
} else {
conf.have_hashseed = 0;
}
}
free(buffer);
}
| 166,536 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format-1) >= EXIF_NUM_FORMATS)
break;
components=(ssize_t) ReadProfileLong(endian,q+4);
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((size_t) (offset+number_bytes) > length)
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
return(MagickTrue);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (q > (exif+length-12))
break; /* corrupt EXIF */
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format-1) >= EXIF_NUM_FORMATS)
break;
components=(ssize_t) ReadProfileLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((size_t) (offset+number_bytes) > length)
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
return(MagickTrue);
}
| 169,949 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AccessType GetExtensionAccess(const Extension* extension,
const GURL& url,
int tab_id) {
bool allowed_script = IsAllowedScript(extension, url, tab_id);
bool allowed_capture =
extension->permissions_data()->CanCaptureVisiblePage(tab_id, nullptr);
if (allowed_script && allowed_capture)
return ALLOWED_SCRIPT_AND_CAPTURE;
if (allowed_script)
return ALLOWED_SCRIPT_ONLY;
if (allowed_capture)
return ALLOWED_CAPTURE_ONLY;
return DISALLOWED;
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | AccessType GetExtensionAccess(const Extension* extension,
const GURL& url,
int tab_id) {
bool allowed_script = IsAllowedScript(extension, url, tab_id);
bool allowed_capture = extension->permissions_data()->CanCaptureVisiblePage(
url, extension, tab_id, nullptr);
if (allowed_script && allowed_capture)
return ALLOWED_SCRIPT_AND_CAPTURE;
if (allowed_script)
return ALLOWED_SCRIPT_ONLY;
if (allowed_capture)
return ALLOWED_CAPTURE_ONLY;
return DISALLOWED;
}
| 173,232 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_to_user_inatomic(iov->iov_base, from, copy))
return -EFAULT;
} else {
if (copy_to_user(iov->iov_base, from, copy))
return -EFAULT;
}
from += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
| 169,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
exit_code_ = exit_code;
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
| 171,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
if (!js_regexec(re->prog, text, &m, opts)) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400 | void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int result;
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
result = js_regexec(re->prog, text, &m, opts);
if (result < 0)
js_error(J, "regexec failed");
if (result == 0) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
| 169,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXTableCell::isRowHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringCase(scope, "row") ||
equalIgnoringCase(scope, "rowgroup");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXTableCell::isRowHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringASCIICase(scope, "row") ||
equalIgnoringASCIICase(scope, "rowgroup");
}
| 171,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct eigrp_common_header *eigrp_com_header;
const struct eigrp_tlv_header *eigrp_tlv_header;
const u_char *tptr,*tlv_tptr;
u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length;
uint8_t prefix[4];
union {
const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm;
const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version;
const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int;
const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext;
const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup;
const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int;
const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext;
} tlv_ptr;
tptr=pptr;
eigrp_com_header = (const struct eigrp_common_header *)pptr;
ND_TCHECK(*eigrp_com_header);
/*
* Sanity checking of the header.
*/
if (eigrp_com_header->version != EIGRP_VERSION) {
ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "EIGRP %s, length: %u",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=len-sizeof(struct eigrp_common_header);
/* FIXME print other header info */
ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u",
eigrp_com_header->version,
tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode),
eigrp_com_header->opcode,
EXTRACT_16BITS(&eigrp_com_header->checksum),
tok2str(eigrp_common_header_flag_values,
"none",
EXTRACT_32BITS(&eigrp_com_header->flags)),
EXTRACT_32BITS(&eigrp_com_header->seq),
EXTRACT_32BITS(&eigrp_com_header->ack),
EXTRACT_32BITS(&eigrp_com_header->asn),
tlen));
tptr+=sizeof(const struct eigrp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header));
eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr;
eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length);
eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type);
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) ||
eigrp_tlv_len > tlen) {
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen);
return;
}
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u",
tok2str(eigrp_tlv_values,
"Unknown",
eigrp_tlv_type),
eigrp_tlv_type,
eigrp_tlv_len));
tlv_tptr=tptr+sizeof(struct eigrp_tlv_header);
tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, eigrp_tlv_len);
switch(eigrp_tlv_type) {
case EIGRP_TLV_GENERAL_PARM:
tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u",
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime),
tlv_ptr.eigrp_tlv_general_parm->k1,
tlv_ptr.eigrp_tlv_general_parm->k2,
tlv_ptr.eigrp_tlv_general_parm->k3,
tlv_ptr.eigrp_tlv_general_parm->k4,
tlv_ptr.eigrp_tlv_general_parm->k5));
break;
case EIGRP_TLV_SW_VERSION:
tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u",
tlv_ptr.eigrp_tlv_sw_version->ios_major,
tlv_ptr.eigrp_tlv_sw_version->ios_minor,
tlv_ptr.eigrp_tlv_sw_version->eigrp_major,
tlv_ptr.eigrp_tlv_sw_version->eigrp_minor));
break;
case EIGRP_TLV_IP_INT:
tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_int->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu),
tlv_ptr.eigrp_tlv_ip_int->hopcount,
tlv_ptr.eigrp_tlv_ip_int->reliability,
tlv_ptr.eigrp_tlv_ip_int->load));
break;
case EIGRP_TLV_IP_EXT:
tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop)));
ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id),
tlv_ptr.eigrp_tlv_ip_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu),
tlv_ptr.eigrp_tlv_ip_ext->hopcount,
tlv_ptr.eigrp_tlv_ip_ext->reliability,
tlv_ptr.eigrp_tlv_ip_ext->load));
break;
case EIGRP_TLV_AT_CABLE_SETUP:
tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id)));
break;
case EIGRP_TLV_AT_INT:
tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2])));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu),
tlv_ptr.eigrp_tlv_at_int->hopcount,
tlv_ptr.eigrp_tlv_at_int->reliability,
tlv_ptr.eigrp_tlv_at_int->load));
break;
case EIGRP_TLV_AT_EXT:
tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2])));
ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id),
tlv_ptr.eigrp_tlv_at_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag),
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu),
tlv_ptr.eigrp_tlv_at_ext->hopcount,
tlv_ptr.eigrp_tlv_at_ext->reliability,
tlv_ptr.eigrp_tlv_at_ext->load));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case EIGRP_TLV_AUTH:
case EIGRP_TLV_SEQ:
case EIGRP_TLV_MCAST_SEQ:
case EIGRP_TLV_IPX_INT:
case EIGRP_TLV_IPX_EXT:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",
eigrp_tlv_len-sizeof(struct eigrp_tlv_header));
tptr+=eigrp_tlv_len;
tlen-=eigrp_tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
Commit Message: CVE-2017-12901/EIGRP: Do more length checks.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct eigrp_common_header *eigrp_com_header;
const struct eigrp_tlv_header *eigrp_tlv_header;
const u_char *tptr,*tlv_tptr;
u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length;
uint8_t prefix[4];
union {
const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm;
const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version;
const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int;
const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext;
const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup;
const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int;
const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext;
} tlv_ptr;
tptr=pptr;
eigrp_com_header = (const struct eigrp_common_header *)pptr;
ND_TCHECK(*eigrp_com_header);
/*
* Sanity checking of the header.
*/
if (eigrp_com_header->version != EIGRP_VERSION) {
ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "EIGRP %s, length: %u",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
if (len < sizeof(struct eigrp_common_header)) {
ND_PRINT((ndo, "EIGRP %s, length: %u (too short, < %u)",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len, (u_int) sizeof(struct eigrp_common_header)));
return;
}
tlen=len-sizeof(struct eigrp_common_header);
/* FIXME print other header info */
ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u",
eigrp_com_header->version,
tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode),
eigrp_com_header->opcode,
EXTRACT_16BITS(&eigrp_com_header->checksum),
tok2str(eigrp_common_header_flag_values,
"none",
EXTRACT_32BITS(&eigrp_com_header->flags)),
EXTRACT_32BITS(&eigrp_com_header->seq),
EXTRACT_32BITS(&eigrp_com_header->ack),
EXTRACT_32BITS(&eigrp_com_header->asn),
tlen));
tptr+=sizeof(const struct eigrp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header));
eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr;
eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length);
eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type);
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) ||
eigrp_tlv_len > tlen) {
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen);
return;
}
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u",
tok2str(eigrp_tlv_values,
"Unknown",
eigrp_tlv_type),
eigrp_tlv_type,
eigrp_tlv_len));
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) sizeof(struct eigrp_tlv_header)));
break;
}
tlv_tptr=tptr+sizeof(struct eigrp_tlv_header);
tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, eigrp_tlv_len);
switch(eigrp_tlv_type) {
case EIGRP_TLV_GENERAL_PARM:
tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_general_parm)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_general_parm))));
break;
}
ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u",
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime),
tlv_ptr.eigrp_tlv_general_parm->k1,
tlv_ptr.eigrp_tlv_general_parm->k2,
tlv_ptr.eigrp_tlv_general_parm->k3,
tlv_ptr.eigrp_tlv_general_parm->k4,
tlv_ptr.eigrp_tlv_general_parm->k5));
break;
case EIGRP_TLV_SW_VERSION:
tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_sw_version)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_sw_version))));
break;
}
ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u",
tlv_ptr.eigrp_tlv_sw_version->ios_major,
tlv_ptr.eigrp_tlv_sw_version->ios_minor,
tlv_ptr.eigrp_tlv_sw_version->eigrp_major,
tlv_ptr.eigrp_tlv_sw_version->eigrp_minor));
break;
case EIGRP_TLV_IP_INT:
tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_int)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_int))));
break;
}
bit_length = tlv_ptr.eigrp_tlv_ip_int->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu),
tlv_ptr.eigrp_tlv_ip_int->hopcount,
tlv_ptr.eigrp_tlv_ip_int->reliability,
tlv_ptr.eigrp_tlv_ip_int->load));
break;
case EIGRP_TLV_IP_EXT:
tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_ext)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_ext))));
break;
}
bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop)));
ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id),
tlv_ptr.eigrp_tlv_ip_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu),
tlv_ptr.eigrp_tlv_ip_ext->hopcount,
tlv_ptr.eigrp_tlv_ip_ext->reliability,
tlv_ptr.eigrp_tlv_ip_ext->load));
break;
case EIGRP_TLV_AT_CABLE_SETUP:
tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup))));
break;
}
ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id)));
break;
case EIGRP_TLV_AT_INT:
tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_int)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_int))));
break;
}
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2])));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu),
tlv_ptr.eigrp_tlv_at_int->hopcount,
tlv_ptr.eigrp_tlv_at_int->reliability,
tlv_ptr.eigrp_tlv_at_int->load));
break;
case EIGRP_TLV_AT_EXT:
tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_ext)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_ext))));
break;
}
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2])));
ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id),
tlv_ptr.eigrp_tlv_at_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag),
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu),
tlv_ptr.eigrp_tlv_at_ext->hopcount,
tlv_ptr.eigrp_tlv_at_ext->reliability,
tlv_ptr.eigrp_tlv_at_ext->load));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case EIGRP_TLV_AUTH:
case EIGRP_TLV_SEQ:
case EIGRP_TLV_MCAST_SEQ:
case EIGRP_TLV_IPX_INT:
case EIGRP_TLV_IPX_EXT:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",
eigrp_tlv_len-sizeof(struct eigrp_tlv_header));
tptr+=eigrp_tlv_len;
tlen-=eigrp_tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
| 167,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsDataSource::StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) {
std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
bundled_path_prefix += "/";
if (base::StartsWith(path, bundled_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
StartBundledDataRequest(path.substr(bundled_path_prefix.length()),
callback);
return;
}
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory());
return;
}
std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath);
remote_path_prefix += "/";
if (base::StartsWith(path, remote_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length()));
CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback);
} else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(new base::RefCountedStaticMemory(kHttpNotFound,
strlen(kHttpNotFound)));
}
return;
}
std::string custom_frontend_url =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kCustomDevtoolsFrontend);
if (custom_frontend_url.empty()) {
callback.Run(NULL);
return;
}
std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath);
custom_path_prefix += "/";
if (base::StartsWith(path, custom_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url = GURL(custom_frontend_url +
path.substr(custom_path_prefix.length()));
StartCustomDataRequest(url, callback);
return;
}
callback.Run(NULL);
}
Commit Message: Hide DevTools frontend from webRequest API
Prevent extensions from observing requests for remote DevTools frontends
and add regression tests.
And update ExtensionTestApi to support initializing the embedded test
server and port from SetUpCommandLine (before SetUpOnMainThread).
BUG=797497,797500
TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735
Reviewed-on: https://chromium-review.googlesource.com/844316
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528187}
CWE ID: CWE-200 | void DevToolsDataSource::StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) {
std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
bundled_path_prefix += "/";
if (base::StartsWith(path, bundled_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
StartBundledDataRequest(path.substr(bundled_path_prefix.length()),
callback);
return;
}
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory());
return;
}
std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath);
remote_path_prefix += "/";
if (base::StartsWith(path, remote_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length()));
CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback);
} else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(new base::RefCountedStaticMemory(kHttpNotFound,
strlen(kHttpNotFound)));
}
return;
}
std::string custom_frontend_url =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kCustomDevtoolsFrontend);
if (custom_frontend_url.empty()) {
callback.Run(NULL);
return;
}
std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath);
custom_path_prefix += "/";
if (base::StartsWith(path, custom_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url = GURL(custom_frontend_url +
path.substr(custom_path_prefix.length()));
DCHECK(url.is_valid());
StartCustomDataRequest(url, callback);
return;
}
callback.Run(NULL);
}
| 172,671 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int libevt_record_values_read_event(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
uint8_t strict_mode,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_event";
size_t record_data_offset = 0;
size_t strings_data_offset = 0;
ssize_t value_data_size = 0;
uint32_t data_offset = 0;
uint32_t data_size = 0;
uint32_t members_data_size = 0;
uint32_t size = 0;
uint32_t size_copy = 0;
uint32_t strings_offset = 0;
uint32_t strings_size = 0;
uint32_t user_sid_offset = 0;
uint32_t user_sid_size = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
uint16_t value_16bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->record_number,
record_values->number );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->creation_time,
record_values->creation_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->written_time,
record_values->written_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->event_identifier,
record_values->event_identifier );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_type,
record_values->event_type );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_category,
record_values->event_category );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->strings_offset,
strings_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_size,
user_sid_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_offset,
user_sid_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_size,
data_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_offset,
data_offset );
byte_stream_copy_to_uint32_little_endian(
&( record_data[ record_data_size - 4 ] ),
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t\t: %" PRIu32 "\n",
function,
size );
libcnotify_printf(
"%s: signature\t\t\t\t: %c%c%c%c\n",
function,
( (evt_record_event_header_t *) record_data )->signature[ 0 ],
( (evt_record_event_header_t *) record_data )->signature[ 1 ],
( (evt_record_event_header_t *) record_data )->signature[ 2 ],
( (evt_record_event_header_t *) record_data )->signature[ 3 ] );
libcnotify_printf(
"%s: record number\t\t\t\t: %" PRIu32 "\n",
function,
record_values->number );
if( libevt_debug_print_posix_time_value(
function,
"creation time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->creation_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
if( libevt_debug_print_posix_time_value(
function,
"written time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->written_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
libcnotify_printf(
"%s: event identifier\t\t\t: 0x%08" PRIx32 "\n",
function,
record_values->event_identifier );
libcnotify_printf(
"%s: event identifier: code\t\t\t: %" PRIu32 "\n",
function,
record_values->event_identifier & 0x0000ffffUL );
libcnotify_printf(
"%s: event identifier: facility\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x0fff0000UL ) >> 16 );
libcnotify_printf(
"%s: event identifier: reserved\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x10000000UL ) >> 28 );
libcnotify_printf(
"%s: event identifier: customer flags\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x20000000UL ) >> 29 );
libcnotify_printf(
"%s: event identifier: severity\t\t: %" PRIu32 " (",
function,
( record_values->event_identifier & 0xc0000000UL ) >> 30 );
libevt_debug_print_event_identifier_severity(
record_values->event_identifier );
libcnotify_printf(
")\n" );
libcnotify_printf(
"%s: event type\t\t\t\t: %" PRIu16 " (",
function,
record_values->event_type );
libevt_debug_print_event_type(
record_values->event_type );
libcnotify_printf(
")\n" );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->number_of_strings,
value_16bit );
libcnotify_printf(
"%s: number of strings\t\t\t: %" PRIu16 "\n",
function,
value_16bit );
libcnotify_printf(
"%s: event category\t\t\t\t: %" PRIu16 "\n",
function,
record_values->event_category );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_flags,
value_16bit );
libcnotify_printf(
"%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n",
function,
value_16bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->closing_record_number,
value_32bit );
libcnotify_printf(
"%s: closing record values number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: strings offset\t\t\t\t: %" PRIu32 "\n",
function,
strings_offset );
libcnotify_printf(
"%s: user security identifier (SID) size\t: %" PRIu32 "\n",
function,
user_sid_size );
libcnotify_printf(
"%s: user security identifier (SID) offset\t: %" PRIu32 "\n",
function,
user_sid_offset );
libcnotify_printf(
"%s: data size\t\t\t\t: %" PRIu32 "\n",
function,
data_size );
libcnotify_printf(
"%s: data offset\t\t\t\t: %" PRIu32 "\n",
function,
data_offset );
}
#endif
record_data_offset = sizeof( evt_record_event_header_t );
if( ( user_sid_offset == 0 )
&& ( user_sid_size != 0 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset or size value out of bounds.",
function );
goto on_error;
}
if( user_sid_offset != 0 )
{
if( ( (size_t) user_sid_offset < record_data_offset )
|| ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset value out of bounds.",
function );
goto on_error;
}
if( user_sid_size != 0 )
{
if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID size value out of bounds.",
function );
goto on_error;
}
}
}
/* If the strings offset is points at the offset at record data size - 4
* the strings are empty. For this to be sane the data offset should
* be the same as the strings offset or the data size 0.
*/
if( ( (size_t) strings_offset < user_sid_offset )
|| ( (size_t) strings_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( ( (size_t) data_offset < strings_offset )
|| ( (size_t) data_offset >= ( record_data_size - 4 ) ) )
{
if( data_size != 0 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data offset value out of bounds.",
function );
goto on_error;
}
data_offset = (uint32_t) record_data_size - 4;
}
if( ( (size_t) strings_offset >= ( record_data_size - 4 ) )
&& ( strings_offset != data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( strings_offset != 0 )
{
if( strings_offset < record_data_offset )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
}
if( user_sid_offset != 0 )
{
members_data_size = user_sid_offset - (uint32_t) record_data_offset;
}
else if( strings_offset != 0 )
{
members_data_size = strings_offset - (uint32_t) record_data_offset;
}
if( strings_offset != 0 )
{
strings_size = data_offset - strings_offset;
}
if( data_size != 0 )
{
if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
}
if( members_data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->source_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create source name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->source_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of source name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: source name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->source_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print source name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( libfvalue_value_type_initialize(
&( record_values->computer_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create computer name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->computer_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of computer name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: computer name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->computer_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print computer name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( members_data_size > 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members trailing data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
record_data_offset += members_data_size;
}
}
if( user_sid_size != 0 )
{
if( libfvalue_value_type_initialize(
&( record_values->user_security_identifier ),
LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create user security identifier (SID) value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->user_security_identifier,
&( record_data[ user_sid_offset ] ),
(size_t) user_sid_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of user security identifier (SID) value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: user security identifier (SID)\t\t: ",
function );
if( libfvalue_value_print(
record_values->user_security_identifier,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print user security identifier (SID) value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += user_sid_size;
}
if( strings_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: strings data:\n",
function );
libcnotify_print_data(
&( record_data[ strings_offset ] ),
strings_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( size_copy == 0 )
{
/* If the strings data is truncated
*/
strings_data_offset = strings_offset + strings_size - 2;
while( strings_data_offset > strings_offset )
{
if( ( record_data[ strings_data_offset ] != 0 )
|| ( record_data[ strings_data_offset + 1 ] != 0 ) )
{
strings_size += 2;
break;
}
strings_data_offset -= 2;
strings_size -= 2;
}
}
if( libfvalue_value_type_initialize(
&( record_values->strings ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create strings value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_strings_array(
record_values->strings,
&( record_data[ strings_offset ] ),
strings_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of strings value.",
function );
goto on_error;
}
record_data_offset += strings_size;
}
if( data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: data:\n",
function );
libcnotify_print_data(
&( record_data[ data_offset ] ),
(size_t) data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->data ),
LIBFVALUE_VALUE_TYPE_BINARY_DATA,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create data value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->data,
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of data value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
record_data_offset += data_size;
#endif
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
if( record_data_offset < ( record_data_size - 4 ) )
{
libcnotify_printf(
"%s: padding:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) record_data_size - record_data_offset - 4,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
libcnotify_printf(
"%s: size copy\t\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( ( strict_mode == 0 )
&& ( size_copy == 0 ) )
{
size_copy = size;
}
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
goto on_error;
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record_values data size and size.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values->data != NULL )
{
libfvalue_value_free(
&( record_values->data ),
NULL );
}
if( record_values->strings != NULL )
{
libfvalue_value_free(
&( record_values->strings ),
NULL );
}
if( record_values->user_security_identifier != NULL )
{
libfvalue_value_free(
&( record_values->user_security_identifier ),
NULL );
}
if( record_values->computer_name != NULL )
{
libfvalue_value_free(
&( record_values->computer_name ),
NULL );
}
if( record_values->source_name != NULL )
{
libfvalue_value_free(
&( record_values->source_name ),
NULL );
}
return( -1 );
}
Commit Message: Applied updates and addition boundary checks for corrupted data
CWE ID: CWE-125 | int libevt_record_values_read_event(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
uint8_t strict_mode,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_event";
size_t record_data_offset = 0;
size_t strings_data_offset = 0;
ssize_t value_data_size = 0;
uint32_t data_offset = 0;
uint32_t data_size = 0;
uint32_t members_data_size = 0;
uint32_t size = 0;
uint32_t size_copy = 0;
uint32_t strings_offset = 0;
uint32_t strings_size = 0;
uint32_t user_sid_offset = 0;
uint32_t user_sid_size = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
uint16_t value_16bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->record_number,
record_values->number );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->creation_time,
record_values->creation_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->written_time,
record_values->written_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->event_identifier,
record_values->event_identifier );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_type,
record_values->event_type );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_category,
record_values->event_category );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->strings_offset,
strings_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_size,
user_sid_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_offset,
user_sid_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_size,
data_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_offset,
data_offset );
byte_stream_copy_to_uint32_little_endian(
&( record_data[ record_data_size - 4 ] ),
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t\t: %" PRIu32 "\n",
function,
size );
libcnotify_printf(
"%s: signature\t\t\t\t: %c%c%c%c\n",
function,
( (evt_record_event_header_t *) record_data )->signature[ 0 ],
( (evt_record_event_header_t *) record_data )->signature[ 1 ],
( (evt_record_event_header_t *) record_data )->signature[ 2 ],
( (evt_record_event_header_t *) record_data )->signature[ 3 ] );
libcnotify_printf(
"%s: record number\t\t\t\t: %" PRIu32 "\n",
function,
record_values->number );
if( libevt_debug_print_posix_time_value(
function,
"creation time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->creation_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
if( libevt_debug_print_posix_time_value(
function,
"written time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->written_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
libcnotify_printf(
"%s: event identifier\t\t\t: 0x%08" PRIx32 "\n",
function,
record_values->event_identifier );
libcnotify_printf(
"%s: event identifier: code\t\t\t: %" PRIu32 "\n",
function,
record_values->event_identifier & 0x0000ffffUL );
libcnotify_printf(
"%s: event identifier: facility\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x0fff0000UL ) >> 16 );
libcnotify_printf(
"%s: event identifier: reserved\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x10000000UL ) >> 28 );
libcnotify_printf(
"%s: event identifier: customer flags\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x20000000UL ) >> 29 );
libcnotify_printf(
"%s: event identifier: severity\t\t: %" PRIu32 " (",
function,
( record_values->event_identifier & 0xc0000000UL ) >> 30 );
libevt_debug_print_event_identifier_severity(
record_values->event_identifier );
libcnotify_printf(
")\n" );
libcnotify_printf(
"%s: event type\t\t\t\t: %" PRIu16 " (",
function,
record_values->event_type );
libevt_debug_print_event_type(
record_values->event_type );
libcnotify_printf(
")\n" );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->number_of_strings,
value_16bit );
libcnotify_printf(
"%s: number of strings\t\t\t: %" PRIu16 "\n",
function,
value_16bit );
libcnotify_printf(
"%s: event category\t\t\t\t: %" PRIu16 "\n",
function,
record_values->event_category );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_flags,
value_16bit );
libcnotify_printf(
"%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n",
function,
value_16bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->closing_record_number,
value_32bit );
libcnotify_printf(
"%s: closing record values number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: strings offset\t\t\t\t: %" PRIu32 "\n",
function,
strings_offset );
libcnotify_printf(
"%s: user security identifier (SID) size\t: %" PRIu32 "\n",
function,
user_sid_size );
libcnotify_printf(
"%s: user security identifier (SID) offset\t: %" PRIu32 "\n",
function,
user_sid_offset );
libcnotify_printf(
"%s: data size\t\t\t\t: %" PRIu32 "\n",
function,
data_size );
libcnotify_printf(
"%s: data offset\t\t\t\t: %" PRIu32 "\n",
function,
data_offset );
}
#endif
record_data_offset = sizeof( evt_record_event_header_t );
if( ( user_sid_offset == 0 )
&& ( user_sid_size != 0 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset or size value out of bounds.",
function );
goto on_error;
}
if( user_sid_offset != 0 )
{
if( ( (size_t) user_sid_offset < record_data_offset )
|| ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset value out of bounds.",
function );
goto on_error;
}
if( user_sid_size != 0 )
{
if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID size value out of bounds.",
function );
goto on_error;
}
}
}
/* If the strings offset is points at the offset at record data size - 4
* the strings are empty. For this to be sane the data offset should
* be the same as the strings offset or the data size 0.
*/
if( ( (size_t) strings_offset < user_sid_offset )
|| ( (size_t) strings_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( ( (size_t) data_offset < strings_offset )
|| ( (size_t) data_offset >= ( record_data_size - 4 ) ) )
{
if( data_size != 0 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data offset value out of bounds.",
function );
goto on_error;
}
data_offset = (uint32_t) record_data_size - 4;
}
if( ( (size_t) strings_offset >= ( record_data_size - 4 ) )
&& ( strings_offset != data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( strings_offset != 0 )
{
if( strings_offset < record_data_offset )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
}
if( user_sid_offset != 0 )
{
members_data_size = user_sid_offset - (uint32_t) record_data_offset;
}
else if( strings_offset != 0 )
{
members_data_size = strings_offset - (uint32_t) record_data_offset;
}
if( strings_offset != 0 )
{
strings_size = data_offset - strings_offset;
}
if( data_size != 0 )
{
if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
}
if( members_data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->source_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create source name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->source_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of source name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: source name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->source_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print source name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( libfvalue_value_type_initialize(
&( record_values->computer_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create computer name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->computer_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of computer name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: computer name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->computer_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print computer name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( members_data_size > 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members trailing data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
record_data_offset += members_data_size;
}
}
if( user_sid_size != 0 )
{
if( user_sid_size > ( ( record_data_size - 4 ) - user_sid_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID data size value out of bounds.",
function );
goto on_error;
}
if( libfvalue_value_type_initialize(
&( record_values->user_security_identifier ),
LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create user security identifier (SID) value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->user_security_identifier,
&( record_data[ user_sid_offset ] ),
(size_t) user_sid_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of user security identifier (SID) value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: user security identifier (SID)\t\t: ",
function );
if( libfvalue_value_print(
record_values->user_security_identifier,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print user security identifier (SID) value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += user_sid_size;
}
if( strings_size != 0 )
{
if( strings_size > ( ( record_data_size - 4 ) - strings_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings size value out of bounds.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: strings data:\n",
function );
libcnotify_print_data(
&( record_data[ strings_offset ] ),
strings_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( size_copy == 0 )
{
/* If the strings data is truncated
*/
strings_data_offset = strings_offset + strings_size - 2;
while( strings_data_offset > strings_offset )
{
if( ( record_data[ strings_data_offset ] != 0 )
|| ( record_data[ strings_data_offset + 1 ] != 0 ) )
{
strings_size += 2;
break;
}
strings_data_offset -= 2;
strings_size -= 2;
}
}
if( libfvalue_value_type_initialize(
&( record_values->strings ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create strings value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_strings_array(
record_values->strings,
&( record_data[ strings_offset ] ),
strings_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of strings value.",
function );
goto on_error;
}
record_data_offset += strings_size;
}
if( data_size != 0 )
{
if( data_size > ( ( record_data_size - 4 ) - data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->data ),
LIBFVALUE_VALUE_TYPE_BINARY_DATA,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create data value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->data,
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of data value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
record_data_offset += data_size;
#endif
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
if( record_data_offset < ( record_data_size - 4 ) )
{
libcnotify_printf(
"%s: padding:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) record_data_size - record_data_offset - 4,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
libcnotify_printf(
"%s: size copy\t\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( ( strict_mode == 0 )
&& ( size_copy == 0 ) )
{
size_copy = size;
}
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
goto on_error;
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record_values data size and size.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values->data != NULL )
{
libfvalue_value_free(
&( record_values->data ),
NULL );
}
if( record_values->strings != NULL )
{
libfvalue_value_free(
&( record_values->strings ),
NULL );
}
if( record_values->user_security_identifier != NULL )
{
libfvalue_value_free(
&( record_values->user_security_identifier ),
NULL );
}
if( record_values->computer_name != NULL )
{
libfvalue_value_free(
&( record_values->computer_name ),
NULL );
}
if( record_values->source_name != NULL )
{
libfvalue_value_free(
&( record_values->source_name ),
NULL );
}
return( -1 );
}
| 169,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
switch (data_type) {
case syncable::SESSIONS:
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableSyncTabs)) {
return;
}
RegisterDataTypeController(
new browser_sync::SessionDataTypeController(factory_.get(),
profile_,
this));
return;
default:
break;
}
NOTREACHED();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
NOTREACHED();
}
| 170,788 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BlobDataHandle::~BlobDataHandle()
{
ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | BlobDataHandle::~BlobDataHandle()
{
BlobRegistry::unregisterBlobURL(m_internalURL);
}
| 170,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.addBluetoothDevice", device->AsDictionary());
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
SendDeviceNotification(device, NULL);
}
| 170,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
Commit Message:
CWE ID: CWE-119 | Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
| 164,913 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: HRESULT CGaiaCredentialBase::ValidateOrCreateUser(
const base::DictionaryValue* result,
BSTR* domain,
BSTR* username,
BSTR* sid,
BSTR* error_text) {
LOGFN(INFO);
DCHECK(domain);
DCHECK(username);
DCHECK(sid);
DCHECK(error_text);
DCHECK(sid);
*error_text = nullptr;
base::string16 local_password = GetDictString(result, kKeyPassword);
wchar_t found_username[kWindowsUsernameBufferLength];
wchar_t found_domain[kWindowsDomainBufferLength];
wchar_t found_sid[kWindowsSidBufferLength];
base::string16 gaia_id;
MakeUsernameForAccount(
result, &gaia_id, found_username, base::size(found_username),
found_domain, base::size(found_domain), found_sid, base::size(found_sid));
if (found_sid[0]) {
HRESULT hr = ValidateExistingUser(found_username, found_domain, found_sid,
error_text);
if (FAILED(hr)) {
LOGFN(ERROR) << "ValidateExistingUser hr=" << putHR(hr);
return hr;
}
*username = ::SysAllocString(found_username);
*domain = ::SysAllocString(found_domain);
*sid = ::SysAllocString(found_sid);
return S_OK;
}
DWORD cpus = 0;
provider()->GetUsageScenario(&cpus);
if (cpus == CPUS_UNLOCK_WORKSTATION) {
*error_text = AllocErrorString(IDS_INVALID_UNLOCK_WORKSTATION_USER_BASE);
return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED);
} else if (!CGaiaCredentialProvider::CanNewUsersBeCreated(
static_cast<CREDENTIAL_PROVIDER_USAGE_SCENARIO>(cpus))) {
*error_text = AllocErrorString(IDS_ADD_USER_DISALLOWED_BASE);
return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED);
}
base::string16 local_fullname = GetDictString(result, kKeyFullname);
base::string16 comment(GetStringResource(IDS_USER_ACCOUNT_COMMENT_BASE));
HRESULT hr = CreateNewUser(
OSUserManager::Get(), found_username, local_password.c_str(),
local_fullname.c_str(), comment.c_str(),
/*add_to_users_group=*/true, kMaxUsernameAttempts, username, sid);
if (hr == HRESULT_FROM_WIN32(NERR_UserExists)) {
LOGFN(ERROR) << "Could not find a new username based on desired username '"
<< found_domain << "\\" << found_username
<< "'. Maximum attempts reached.";
*error_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE);
return hr;
}
*domain = ::SysAllocString(found_domain);
return hr;
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284 | HRESULT CGaiaCredentialBase::ValidateOrCreateUser(
const base::DictionaryValue* result,
BSTR* domain,
BSTR* username,
BSTR* sid,
BSTR* error_text) {
LOGFN(INFO);
DCHECK(domain);
DCHECK(username);
DCHECK(sid);
DCHECK(error_text);
DCHECK(sid);
*error_text = nullptr;
base::string16 local_password = GetDictString(result, kKeyPassword);
wchar_t found_username[kWindowsUsernameBufferLength];
wchar_t found_domain[kWindowsDomainBufferLength];
wchar_t found_sid[kWindowsSidBufferLength];
bool is_consumer_account = false;
base::string16 gaia_id;
MakeUsernameForAccount(result, &gaia_id, found_username,
base::size(found_username), found_domain,
base::size(found_domain), found_sid,
base::size(found_sid), &is_consumer_account);
// Disallow consumer accounts when mdm enrollment is enabled and the global
// flag to allow consumer accounts is not set.
if (MdmEnrollmentEnabled() && is_consumer_account) {
DWORD allow_consumer_accounts = 0;
if (FAILED(GetGlobalFlag(kRegMdmAllowConsumerAccounts,
&allow_consumer_accounts)) ||
allow_consumer_accounts == 0) {
LOGFN(ERROR) << "Consumer accounts are not allowed mdm_aca="
<< allow_consumer_accounts;
*error_text = AllocErrorString(IDS_INVALID_EMAIL_DOMAIN_BASE);
return E_FAIL;
}
}
if (found_sid[0]) {
HRESULT hr = ValidateExistingUser(found_username, found_domain, found_sid,
error_text);
if (FAILED(hr)) {
LOGFN(ERROR) << "ValidateExistingUser hr=" << putHR(hr);
return hr;
}
*username = ::SysAllocString(found_username);
*domain = ::SysAllocString(found_domain);
*sid = ::SysAllocString(found_sid);
return S_OK;
}
DWORD cpus = 0;
provider()->GetUsageScenario(&cpus);
if (cpus == CPUS_UNLOCK_WORKSTATION) {
*error_text = AllocErrorString(IDS_INVALID_UNLOCK_WORKSTATION_USER_BASE);
return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED);
} else if (!CGaiaCredentialProvider::CanNewUsersBeCreated(
static_cast<CREDENTIAL_PROVIDER_USAGE_SCENARIO>(cpus))) {
*error_text = AllocErrorString(IDS_ADD_USER_DISALLOWED_BASE);
return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED);
}
base::string16 local_fullname = GetDictString(result, kKeyFullname);
base::string16 comment(GetStringResource(IDS_USER_ACCOUNT_COMMENT_BASE));
HRESULT hr = CreateNewUser(
OSUserManager::Get(), found_username, local_password.c_str(),
local_fullname.c_str(), comment.c_str(),
/*add_to_users_group=*/true, kMaxUsernameAttempts, username, sid);
if (hr == HRESULT_FROM_WIN32(NERR_UserExists)) {
LOGFN(ERROR) << "Could not find a new username based on desired username '"
<< found_domain << "\\" << found_username
<< "'. Maximum attempts reached.";
*error_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE);
return hr;
}
*domain = ::SysAllocString(found_domain);
return hr;
}
| 172,101 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: IDN display: Block U+0307 after i or U+0131
U+0307 (dot above) after i, j, l, or U+0131 (dotless i) would be
very hard to see if possible at all. This is not blocked
by the 'repeated diacritic' check because i is not decomposed
into dotless-i + U+0307. So, it has to be blocked separately.
Also, change the indentation in the output of
idn_test_case_generator.py .
This change blocks 80+ domains out of a million IDNs in .com TLD.
BUG=750239
TEST=components_unittests --gtest_filter=*IDN*
Change-Id: I4950aeb7aa080f92e38a2b5dea46ef4e5c25b65b
Reviewed-on: https://chromium-review.googlesource.com/607907
Reviewed-by: Peter Kasting <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Matt Giuca <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#502987}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disallow U+0307 (dot above) after 'i', 'j', 'l' or dotless i (U+0131).
// Dotless j (U+0237) is not in the allowed set to begin with.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
{
struct session_state *state = ssh->state;
u_int padlen, need;
u_char *cp;
u_int maclen, aadlen = 0, authlen = 0, block_size;
struct sshenc *enc = NULL;
struct sshmac *mac = NULL;
struct sshcomp *comp = NULL;
int r;
*typep = SSH_MSG_NONE;
if (state->packet_discard)
return 0;
if (state->newkeys[MODE_IN] != NULL) {
enc = &state->newkeys[MODE_IN]->enc;
mac = &state->newkeys[MODE_IN]->mac;
comp = &state->newkeys[MODE_IN]->comp;
/* disable mac for authenticated encryption */
if ((authlen = cipher_authlen(enc->cipher)) != 0)
mac = NULL;
}
maclen = mac && mac->enabled ? mac->mac_len : 0;
block_size = enc ? enc->block_size : 8;
aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
if (aadlen && state->packlen == 0) {
if (cipher_get_length(state->receive_context,
&state->packlen, state->p_read.seqnr,
sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
return 0;
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
sshbuf_dump(state->input, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
sshbuf_reset(state->incoming_packet);
} else if (state->packlen == 0) {
/*
* check if input size is less than the cipher block size,
* decrypt first block and extract length of incoming packet
*/
if (sshbuf_len(state->input) < block_size)
return 0;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_reserve(state->incoming_packet, block_size,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context,
state->p_send.seqnr, cp, sshbuf_ptr(state->input),
block_size, 0, 0)) != 0)
goto out;
state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
fprintf(stderr, "input: \n");
sshbuf_dump(state->input, stderr);
fprintf(stderr, "incoming_packet: \n");
sshbuf_dump(state->incoming_packet, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE);
}
if ((r = sshbuf_consume(state->input, block_size)) != 0)
goto out;
}
DBG(debug("input: packet len %u", state->packlen+4));
if (aadlen) {
/* only the payload is encrypted */
need = state->packlen;
} else {
/*
* the payload size and the payload are encrypted, but we
* have a partial packet of block_size bytes
*/
need = 4 + state->packlen - block_size;
}
DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
" aadlen %d", block_size, need, maclen, authlen, aadlen));
if (need % block_size != 0) {
logit("padding error: need %d block %d mod %d",
need, block_size, need % block_size);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE - block_size);
}
/*
* check if the entire packet has been received and
* decrypt into incoming_packet:
* 'aadlen' bytes are unencrypted, but authenticated.
* 'need' bytes are encrypted, followed by either
* 'authlen' bytes of authentication tag or
* 'maclen' bytes of message authentication code.
*/
if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
return 0; /* packet is incomplete */
#ifdef PACKET_DEBUG
fprintf(stderr, "read_poll enc/full: ");
sshbuf_dump(state->input, stderr);
#endif
/* EtM: check mac over encrypted input */
if (mac && mac->enabled && mac->etm) {
if ((r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->input), aadlen + need,
sshbuf_ptr(state->input) + aadlen + need + authlen,
maclen)) != 0) {
if (r == SSH_ERR_MAC_INVALID)
logit("Corrupted MAC on input.");
goto out;
}
}
if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
goto out;
if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
goto out;
if (mac && mac->enabled) {
/* Not EtM: check MAC over cleartext */
if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->incoming_packet),
sshbuf_len(state->incoming_packet),
sshbuf_ptr(state->input), maclen)) != 0) {
if (r != SSH_ERR_MAC_INVALID)
goto out;
logit("Corrupted MAC on input.");
if (need > PACKET_MAX_SIZE)
return SSH_ERR_INTERNAL_ERROR;
return ssh_packet_start_discard(ssh, enc, mac,
sshbuf_len(state->incoming_packet),
PACKET_MAX_SIZE - need);
}
/* Remove MAC from input buffer */
DBG(debug("MAC #%d ok", state->p_read.seqnr));
if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
goto out;
}
if (seqnr_p != NULL)
*seqnr_p = state->p_read.seqnr;
if (++state->p_read.seqnr == 0)
logit("incoming seqnr wraps around");
if (++state->p_read.packets == 0)
if (!(ssh->compat & SSH_BUG_NOREKEY))
return SSH_ERR_NEED_REKEY;
state->p_read.blocks += (state->packlen + 4) / block_size;
state->p_read.bytes += state->packlen + 4;
/* get padlen */
padlen = sshbuf_ptr(state->incoming_packet)[4];
DBG(debug("input: padlen %d", padlen));
if (padlen < 4) {
if ((r = sshpkt_disconnect(ssh,
"Corrupted padlen %d on input.", padlen)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
/* skip packet size + padlen, discard padding */
if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
goto out;
DBG(debug("input: len before de-compress %zd",
sshbuf_len(state->incoming_packet)));
if (comp && comp->enabled) {
sshbuf_reset(state->compression_buffer);
if ((r = uncompress_buffer(ssh, state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_putb(state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
DBG(debug("input: len after de-compress %zd",
sshbuf_len(state->incoming_packet)));
}
/*
* get packet type, implies consume.
* return length of payload (without type field)
*/
if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
goto out;
if (ssh_packet_log_type(*typep))
debug3("receive packet: type %u", *typep);
if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
if ((r = sshpkt_disconnect(ssh,
"Invalid ssh2 packet type: %d", *typep)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_PROTOCOL_ERROR;
}
if (*typep == SSH2_MSG_NEWKEYS)
r = ssh_set_newkeys(ssh, MODE_IN);
else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
r = ssh_packet_enable_delayed_compress(ssh);
else
r = 0;
else
r = 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read/plain[%d]:\r\n", *typep);
sshbuf_dump(state->incoming_packet, stderr);
#endif
/* reset for next packet */
state->packlen = 0;
/* do we need to rekey? */
if (ssh_packet_need_rekeying(ssh, 0)) {
debug3("%s: rekex triggered", __func__);
if ((r = kex_start_rekex(ssh)) != 0)
return r;
}
out:
return r;
}
Commit Message:
CWE ID: CWE-476 | ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
{
struct session_state *state = ssh->state;
u_int padlen, need;
u_char *cp;
u_int maclen, aadlen = 0, authlen = 0, block_size;
struct sshenc *enc = NULL;
struct sshmac *mac = NULL;
struct sshcomp *comp = NULL;
int r;
*typep = SSH_MSG_NONE;
if (state->packet_discard)
return 0;
if (state->newkeys[MODE_IN] != NULL) {
enc = &state->newkeys[MODE_IN]->enc;
mac = &state->newkeys[MODE_IN]->mac;
comp = &state->newkeys[MODE_IN]->comp;
/* disable mac for authenticated encryption */
if ((authlen = cipher_authlen(enc->cipher)) != 0)
mac = NULL;
}
maclen = mac && mac->enabled ? mac->mac_len : 0;
block_size = enc ? enc->block_size : 8;
aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
if (aadlen && state->packlen == 0) {
if (cipher_get_length(state->receive_context,
&state->packlen, state->p_read.seqnr,
sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
return 0;
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
sshbuf_dump(state->input, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
sshbuf_reset(state->incoming_packet);
} else if (state->packlen == 0) {
/*
* check if input size is less than the cipher block size,
* decrypt first block and extract length of incoming packet
*/
if (sshbuf_len(state->input) < block_size)
return 0;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_reserve(state->incoming_packet, block_size,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context,
state->p_send.seqnr, cp, sshbuf_ptr(state->input),
block_size, 0, 0)) != 0)
goto out;
state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
fprintf(stderr, "input: \n");
sshbuf_dump(state->input, stderr);
fprintf(stderr, "incoming_packet: \n");
sshbuf_dump(state->incoming_packet, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE);
}
if ((r = sshbuf_consume(state->input, block_size)) != 0)
goto out;
}
DBG(debug("input: packet len %u", state->packlen+4));
if (aadlen) {
/* only the payload is encrypted */
need = state->packlen;
} else {
/*
* the payload size and the payload are encrypted, but we
* have a partial packet of block_size bytes
*/
need = 4 + state->packlen - block_size;
}
DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
" aadlen %d", block_size, need, maclen, authlen, aadlen));
if (need % block_size != 0) {
logit("padding error: need %d block %d mod %d",
need, block_size, need % block_size);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE - block_size);
}
/*
* check if the entire packet has been received and
* decrypt into incoming_packet:
* 'aadlen' bytes are unencrypted, but authenticated.
* 'need' bytes are encrypted, followed by either
* 'authlen' bytes of authentication tag or
* 'maclen' bytes of message authentication code.
*/
if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
return 0; /* packet is incomplete */
#ifdef PACKET_DEBUG
fprintf(stderr, "read_poll enc/full: ");
sshbuf_dump(state->input, stderr);
#endif
/* EtM: check mac over encrypted input */
if (mac && mac->enabled && mac->etm) {
if ((r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->input), aadlen + need,
sshbuf_ptr(state->input) + aadlen + need + authlen,
maclen)) != 0) {
if (r == SSH_ERR_MAC_INVALID)
logit("Corrupted MAC on input.");
goto out;
}
}
if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
goto out;
if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
goto out;
if (mac && mac->enabled) {
/* Not EtM: check MAC over cleartext */
if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->incoming_packet),
sshbuf_len(state->incoming_packet),
sshbuf_ptr(state->input), maclen)) != 0) {
if (r != SSH_ERR_MAC_INVALID)
goto out;
logit("Corrupted MAC on input.");
if (need > PACKET_MAX_SIZE)
return SSH_ERR_INTERNAL_ERROR;
return ssh_packet_start_discard(ssh, enc, mac,
sshbuf_len(state->incoming_packet),
PACKET_MAX_SIZE - need);
}
/* Remove MAC from input buffer */
DBG(debug("MAC #%d ok", state->p_read.seqnr));
if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
goto out;
}
if (seqnr_p != NULL)
*seqnr_p = state->p_read.seqnr;
if (++state->p_read.seqnr == 0)
logit("incoming seqnr wraps around");
if (++state->p_read.packets == 0)
if (!(ssh->compat & SSH_BUG_NOREKEY))
return SSH_ERR_NEED_REKEY;
state->p_read.blocks += (state->packlen + 4) / block_size;
state->p_read.bytes += state->packlen + 4;
/* get padlen */
padlen = sshbuf_ptr(state->incoming_packet)[4];
DBG(debug("input: padlen %d", padlen));
if (padlen < 4) {
if ((r = sshpkt_disconnect(ssh,
"Corrupted padlen %d on input.", padlen)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
/* skip packet size + padlen, discard padding */
if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
goto out;
DBG(debug("input: len before de-compress %zd",
sshbuf_len(state->incoming_packet)));
if (comp && comp->enabled) {
sshbuf_reset(state->compression_buffer);
if ((r = uncompress_buffer(ssh, state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_putb(state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
DBG(debug("input: len after de-compress %zd",
sshbuf_len(state->incoming_packet)));
}
/*
* get packet type, implies consume.
* return length of payload (without type field)
*/
if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
goto out;
if (ssh_packet_log_type(*typep))
debug3("receive packet: type %u", *typep);
if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
if ((r = sshpkt_disconnect(ssh,
"Invalid ssh2 packet type: %d", *typep)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_PROTOCOL_ERROR;
}
if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
r = ssh_packet_enable_delayed_compress(ssh);
else
r = 0;
else
r = 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read/plain[%d]:\r\n", *typep);
sshbuf_dump(state->incoming_packet, stderr);
#endif
/* reset for next packet */
state->packlen = 0;
/* do we need to rekey? */
if (ssh_packet_need_rekeying(ssh, 0)) {
debug3("%s: rekex triggered", __func__);
if ((r = kex_start_rekex(ssh)) != 0)
return r;
}
out:
return r;
}
| 165,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithUnsignedLongArray(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
Vector<unsigned long> unsignedLongArray(jsUnsignedLongArrayToVector(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithUnsignedLongArray(unsignedLongArray);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithUnsignedLongArray(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
Vector<unsigned long> unsignedLongArray(jsUnsignedLongArrayToVector(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithUnsignedLongArray(unsignedLongArray);
return JSValue::encode(jsUndefined());
}
| 170,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
CWE ID: CWE-200 | status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
// update backup buffer
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
| 174,146 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sparse_dump_region (struct tar_sparse_file *file, size_t i)
{
union block *blk;
off_t bytes_left = file->stat_info->sparse_map[i].numbytes;
if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset))
return false;
while (bytes_left > 0)
{
size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left;
size_t bytes_read;
blk = find_next_block ();
bytes_read = safe_read (file->fd, blk->buffer, bufsize);
if (bytes_read == SAFE_READ_ERROR)
{
read_diag_details (file->stat_info->orig_file_name,
(file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left),
bufsize);
return false;
}
memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read);
bytes_left -= bytes_read;
{
size_t count;
size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size;
union block *blk = find_next_block ();
if (!blk)
{
ERROR ((0, 0, _("Unexpected EOF in archive")));
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
{
write_error_details (file->stat_info->orig_file_name,
count, wrbytes);
return false;
}
}
return true;
}
/* Interface functions */
enum dump_status
sparse_dump_file (int fd, struct tar_stat_info *st)
{
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
rc = sparse_scan_file (&file);
if (rc && file.optab->dump_region)
{
tar_sparse_dump_header (&file);
if (fd >= 0)
{
size_t i;
mv_begin_write (file.stat_info->file_name,
file.stat_info->stat.st_size,
file.stat_info->archive_file_size - file.dumped_size);
for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++)
rc = tar_sparse_dump_region (&file, i);
}
}
pad_archive (file.stat_info->archive_file_size - file.dumped_size);
return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short;
}
Commit Message:
CWE ID: CWE-835 | sparse_dump_region (struct tar_sparse_file *file, size_t i)
{
union block *blk;
off_t bytes_left = file->stat_info->sparse_map[i].numbytes;
if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset))
return false;
while (bytes_left > 0)
{
size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left;
size_t bytes_read;
blk = find_next_block ();
bytes_read = safe_read (file->fd, blk->buffer, bufsize);
if (bytes_read == SAFE_READ_ERROR)
{
read_diag_details (file->stat_info->orig_file_name,
(file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left),
bufsize);
return false;
}
else if (bytes_read == 0)
{
char buf[UINTMAX_STRSIZE_BOUND];
struct stat st;
size_t n;
if (fstat (file->fd, &st) == 0)
n = file->stat_info->stat.st_size - st.st_size;
else
n = file->stat_info->stat.st_size
- (file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left);
WARNOPT (WARN_FILE_SHRANK,
(0, 0,
ngettext ("%s: File shrank by %s byte; padding with zeros",
"%s: File shrank by %s bytes; padding with zeros",
n),
quotearg_colon (file->stat_info->orig_file_name),
STRINGIFY_BIGINT (n, buf)));
if (! ignore_failed_read_option)
set_exit_status (TAREXIT_DIFFERS);
return false;
}
memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read);
bytes_left -= bytes_read;
{
size_t count;
size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size;
union block *blk = find_next_block ();
if (!blk)
{
ERROR ((0, 0, _("Unexpected EOF in archive")));
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
{
write_error_details (file->stat_info->orig_file_name,
count, wrbytes);
return false;
}
}
return true;
}
/* Interface functions */
enum dump_status
sparse_dump_file (int fd, struct tar_stat_info *st)
{
return false;
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE;
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
rc = sparse_scan_file (&file);
if (rc && file.optab->dump_region)
{
tar_sparse_dump_header (&file);
if (fd >= 0)
{
size_t i;
mv_begin_write (file.stat_info->file_name,
file.stat_info->stat.st_size,
file.stat_info->archive_file_size - file.dumped_size);
for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++)
rc = tar_sparse_dump_region (&file, i);
}
}
pad_archive (file.stat_info->archive_file_size - file.dumped_size);
return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short;
}
| 164,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: __u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
__u32 seq;
__u32 hash[4];
struct keydata *keyptr = get_keyptr();
/*
* Pick a unique starting offset for each TCP connection endpoints
* (saddr, daddr, sport, dport).
* Note that the words are placed into the starting vector, which is
* then mixed with a partial MD4 over random data.
*/
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = keyptr->secret[11];
seq = half_md4_transform(hash, keyptr->secret) & HASH_MASK;
seq += keyptr->count;
/*
* As close as possible to RFC 793, which
* suggests using a 250 kHz clock.
* Further reading shows this assumes 2 Mb/s networks.
* For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
* For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but
* we also need to limit the resolution so that the u32 seq
* overlaps less than one time per MSL (2 minutes).
* Choosing a clock of 64 ns period is OK. (period of 274 s)
*/
seq += ktime_to_ns(ktime_get_real()) >> 6;
return seq;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | __u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
| 165,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)
{
mrb_value orig;
mrb_value buf;
struct mrb_io *fptr_copy;
struct mrb_io *fptr_orig;
mrb_bool failed = TRUE;
mrb_get_args(mrb, "o", &orig);
fptr_copy = (struct mrb_io *)DATA_PTR(copy);
if (fptr_copy != NULL) {
fptr_finalize(mrb, fptr_copy, FALSE);
mrb_free(mrb, fptr_copy);
}
fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);
fptr_orig = io_get_open_fptr(mrb, orig);
DATA_TYPE(copy) = &mrb_io_type;
DATA_PTR(copy) = fptr_copy;
buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf"));
mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf);
fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);
if (failed) {
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd);
if (fptr_orig->fd2 != -1) {
fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);
if (failed) {
close(fptr_copy->fd);
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd2);
}
fptr_copy->pid = fptr_orig->pid;
fptr_copy->readable = fptr_orig->readable;
fptr_copy->writable = fptr_orig->writable;
fptr_copy->sync = fptr_orig->sync;
fptr_copy->is_socket = fptr_orig->is_socket;
return copy;
}
Commit Message: Fix `use after free in File#initilialize_copy`; fix #4001
The bug and the fix were reported by https://hackerone.com/pnoltof
CWE ID: CWE-416 | mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)
{
mrb_value orig;
mrb_value buf;
struct mrb_io *fptr_copy;
struct mrb_io *fptr_orig;
mrb_bool failed = TRUE;
mrb_get_args(mrb, "o", &orig);
fptr_orig = io_get_open_fptr(mrb, orig);
fptr_copy = (struct mrb_io *)DATA_PTR(copy);
if (fptr_copy != NULL) {
fptr_finalize(mrb, fptr_copy, FALSE);
mrb_free(mrb, fptr_copy);
}
fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);
DATA_TYPE(copy) = &mrb_io_type;
DATA_PTR(copy) = fptr_copy;
buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf"));
mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf);
fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);
if (failed) {
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd);
if (fptr_orig->fd2 != -1) {
fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);
if (failed) {
close(fptr_copy->fd);
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd2);
}
fptr_copy->pid = fptr_orig->pid;
fptr_copy->readable = fptr_orig->readable;
fptr_copy->writable = fptr_orig->writable;
fptr_copy->sync = fptr_orig->sync;
fptr_copy->is_socket = fptr_orig->is_socket;
return copy;
}
| 169,255 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const PropertyTreeState& PropertyTreeState::Root() {
DEFINE_STATIC_LOCAL(
std::unique_ptr<PropertyTreeState>, root,
(std::make_unique<PropertyTreeState>(TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root(),
EffectPaintPropertyNode::Root())));
return *root;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | const PropertyTreeState& PropertyTreeState::Root() {
DEFINE_STATIC_LOCAL(
PropertyTreeState, root,
(&TransformPaintPropertyNode::Root(), &ClipPaintPropertyNode::Root(),
&EffectPaintPropertyNode::Root()));
return root;
}
| 171,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WallpaperManagerBase::GetCustomWallpaperInternal(
const AccountId& account_id,
const WallpaperInfo& info,
const base::FilePath& wallpaper_path,
bool update_wallpaper,
const scoped_refptr<base::SingleThreadTaskRunner>& reply_task_runner,
MovableOnDestroyCallbackHolder on_finish,
base::WeakPtr<WallpaperManagerBase> weak_ptr) {
base::FilePath valid_path = wallpaper_path;
if (!base::PathExists(wallpaper_path)) {
valid_path = GetCustomWallpaperDir(kOriginalWallpaperSubDir);
valid_path = valid_path.Append(info.location);
}
if (!base::PathExists(valid_path)) {
LOG(ERROR) << "Failed to load custom wallpaper from its original fallback "
"file path: " << valid_path.value();
const std::string& old_path = account_id.GetUserEmail(); // Migrated
valid_path = GetCustomWallpaperPath(kOriginalWallpaperSubDir,
WallpaperFilesId::FromString(old_path),
info.location);
}
if (!base::PathExists(valid_path)) {
LOG(ERROR) << "Failed to load previously selected custom wallpaper. "
<< "Fallback to default wallpaper. Expected wallpaper path: "
<< wallpaper_path.value();
reply_task_runner->PostTask(
FROM_HERE,
base::Bind(&WallpaperManagerBase::DoSetDefaultWallpaper, weak_ptr,
account_id, base::Passed(std::move(on_finish))));
} else {
reply_task_runner->PostTask(
FROM_HERE, base::Bind(&WallpaperManagerBase::StartLoad, weak_ptr,
account_id, info, update_wallpaper, valid_path,
base::Passed(std::move(on_finish))));
}
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void WallpaperManagerBase::GetCustomWallpaperInternal(
const AccountId& account_id,
const WallpaperInfo& info,
const base::FilePath& wallpaper_path,
bool update_wallpaper,
const scoped_refptr<base::SingleThreadTaskRunner>& reply_task_runner,
MovableOnDestroyCallbackHolder on_finish,
base::WeakPtr<WallpaperManagerBase> weak_ptr) {
base::FilePath valid_path = wallpaper_path;
if (!base::PathExists(wallpaper_path)) {
valid_path = GetCustomWallpaperDir(kOriginalWallpaperSubDir);
valid_path = valid_path.Append(info.location);
}
if (!base::PathExists(valid_path)) {
const std::string& old_path = account_id.GetUserEmail(); // Migrated
valid_path = GetCustomWallpaperPath(kOriginalWallpaperSubDir,
WallpaperFilesId::FromString(old_path),
info.location);
}
if (!base::PathExists(valid_path)) {
reply_task_runner->PostTask(
FROM_HERE,
base::Bind(&WallpaperManagerBase::OnCustomWallpaperFileNotFound,
weak_ptr, account_id, wallpaper_path, update_wallpaper,
base::Passed(std::move(on_finish))));
} else {
reply_task_runner->PostTask(
FROM_HERE, base::Bind(&WallpaperManagerBase::StartLoad, weak_ptr,
account_id, info, update_wallpaper, valid_path,
base::Passed(std::move(on_finish))));
}
}
| 171,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | 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;
}
Commit 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]>
CWE ID: | static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
strncpy(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;
}
| 168,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-13026/IS-IS: Clean up processing of subTLVs.
Add bounds checks, do a common check to make sure we captured the entire
subTLV, add checks to make sure the subTLV fits within the TLV.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add tests using the capture files supplied by the reporter(s), modified
so the capture files won't be rejected as an invalid capture.
Update existing tests for changes to IS-IS dissector.
CWE ID: CWE-125 | isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN)
goto trunc;
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN;
len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
| 167,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ReturnsValidPath(int dir_type) {
base::FilePath path;
bool result = PathService::Get(dir_type, &path);
bool check_path_exists = true;
#if defined(OS_POSIX)
if (dir_type == base::DIR_CACHE)
check_path_exists = false;
#endif
#if defined(OS_LINUX)
if (dir_type == base::DIR_USER_DESKTOP)
check_path_exists = false;
#endif
#if defined(OS_WIN)
if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) {
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
wchar_t default_profile_path[MAX_PATH];
DWORD size = arraysize(default_profile_path);
return (result &&
::GetDefaultUserProfileDirectory(default_profile_path, &size) &&
StartsWith(path.value(), default_profile_path, false));
}
} else if (dir_type == base::DIR_TASKBAR_PINS) {
if (base::win::GetVersion() < base::win::VERSION_WIN7)
check_path_exists = false;
}
#endif
#if defined(OS_MAC)
if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE &&
dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) {
if (path.ReferencesParent())
return false;
}
#else
if (path.ReferencesParent())
return false;
#endif
return result && !path.empty() && (!check_path_exists ||
file_util::PathExists(path));
}
Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX.
BUG=163208
TEST=none
Review URL: https://codereview.chromium.org/12829005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ReturnsValidPath(int dir_type) {
base::FilePath path;
bool result = PathService::Get(dir_type, &path);
bool check_path_exists = true;
#if defined(OS_POSIX)
if (dir_type == base::DIR_CACHE)
check_path_exists = false;
#endif
#if defined(OS_LINUX)
if (dir_type == base::DIR_USER_DESKTOP)
check_path_exists = false;
#endif
#if defined(OS_WIN)
if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) {
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
wchar_t default_profile_path[MAX_PATH];
DWORD size = arraysize(default_profile_path);
return (result &&
::GetDefaultUserProfileDirectory(default_profile_path, &size) &&
StartsWith(path.value(), default_profile_path, false));
}
} else if (dir_type == base::DIR_TASKBAR_PINS) {
if (base::win::GetVersion() < base::win::VERSION_WIN7)
check_path_exists = false;
}
#endif
#if defined(OS_MACOSX)
if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE &&
dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) {
if (path.ReferencesParent())
return false;
}
#else
if (path.ReferencesParent())
return false;
#endif
return result && !path.empty() && (!check_path_exists ||
file_util::PathExists(path));
}
| 171,539 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
}
Commit Message: Fix VD-1301 and VD-1302 vulnerabilities
This patch was contributed by Maor Vermucht and Or Peles from
VDOO Connected Trust.
CWE ID: CWE-125 | int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bits = req[offset + 5];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bytes = req[offset + 5];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
}
| 169,581 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VRDisplay::OnPresentChange() {
if (is_presenting_ && !is_valid_device_for_presenting_) {
DVLOG(1) << __FUNCTION__ << ": device not valid, not sending event";
return;
}
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplaypresentchange, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnPresentChange() {
DVLOG(1) << __FUNCTION__ << ": is_presenting_=" << is_presenting_;
if (is_presenting_ && !is_valid_device_for_presenting_) {
DVLOG(1) << __FUNCTION__ << ": device not valid, not sending event";
return;
}
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplaypresentchange, true, false, this, ""));
}
| 171,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageSerializer::serializeFrame(Frame* frame)
{
Document* document = frame->document();
KURL url = document->url();
if (!url.isValid() || url.isBlankURL()) {
url = urlForBlankFrame(frame);
}
if (m_resourceURLs.contains(url)) {
return;
}
if (document->isImageDocument()) {
ImageDocument* imageDocument = toImageDocument(document);
addImageToResources(imageDocument->cachedImage(), imageDocument->imageElement()->renderer(), url);
return;
}
Vector<Node*> nodes;
OwnPtr<SerializerMarkupAccumulator> accumulator;
if (m_URLs)
accumulator = adoptPtr(new LinkChangeSerializerMarkupAccumulator(this, document, &nodes, m_URLs, m_directory));
else
accumulator = adoptPtr(new SerializerMarkupAccumulator(this, document, &nodes));
String text = accumulator->serializeNodes(document, IncludeNode);
WTF::TextEncoding textEncoding(document->charset());
CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables);
m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
m_resourceURLs.add(url);
for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
Node* node = *iter;
if (!node->isElementNode())
continue;
Element* element = toElement(node);
if (element->isStyledElement()) {
retrieveResourcesForProperties(element->inlineStyle(), document);
retrieveResourcesForProperties(element->presentationAttributeStyle(), document);
}
if (element->hasTagName(HTMLNames::imgTag)) {
HTMLImageElement* imageElement = toHTMLImageElement(element);
KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr));
ImageResource* cachedImage = imageElement->cachedImage();
addImageToResources(cachedImage, imageElement->renderer(), url);
} else if (element->hasTagName(HTMLNames::inputTag)) {
HTMLInputElement* inputElement = toHTMLInputElement(element);
if (inputElement->isImageButton() && inputElement->hasImageLoader()) {
KURL url = inputElement->src();
ImageResource* cachedImage = inputElement->imageLoader()->image();
addImageToResources(cachedImage, inputElement->renderer(), url);
}
} else if (element->hasTagName(HTMLNames::linkTag)) {
HTMLLinkElement* linkElement = toHTMLLinkElement(element);
if (CSSStyleSheet* sheet = linkElement->sheet()) {
KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr));
serializeCSSStyleSheet(sheet, url);
ASSERT(m_resourceURLs.contains(url));
}
} else if (element->hasTagName(HTMLNames::styleTag)) {
HTMLStyleElement* styleElement = toHTMLStyleElement(element);
if (CSSStyleSheet* sheet = styleElement->sheet())
serializeCSSStyleSheet(sheet, KURL());
}
}
for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling())
serializeFrame(childFrame);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void PageSerializer::serializeFrame(Frame* frame)
{
Document* document = frame->document();
KURL url = document->url();
if (!url.isValid() || url.isBlankURL()) {
url = urlForBlankFrame(frame);
}
if (m_resourceURLs.contains(url)) {
return;
}
Vector<Node*> nodes;
SerializerMarkupAccumulator accumulator(this, document, &nodes);
WTF::TextEncoding textEncoding(document->charset());
CString data;
if (!textEncoding.isValid()) {
// FIXME: iframes used as images trigger this. We should deal with them correctly.
return;
}
String text = accumulator.serializeNodes(document, IncludeNode);
CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables);
m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
m_resourceURLs.add(url);
for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
Node* node = *iter;
if (!node->isElementNode())
continue;
Element* element = toElement(node);
if (element->isStyledElement())
retrieveResourcesForProperties(element->inlineStyle(), document);
if (element->hasTagName(HTMLNames::imgTag)) {
HTMLImageElement* imageElement = toHTMLImageElement(element);
KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr));
ImageResource* cachedImage = imageElement->cachedImage();
addImageToResources(cachedImage, imageElement->renderer(), url);
} else if (element->hasTagName(HTMLNames::inputTag)) {
HTMLInputElement* inputElement = toHTMLInputElement(element);
if (inputElement->isImageButton() && inputElement->hasImageLoader()) {
KURL url = inputElement->src();
ImageResource* cachedImage = inputElement->imageLoader()->image();
addImageToResources(cachedImage, inputElement->renderer(), url);
}
} else if (element->hasTagName(HTMLNames::linkTag)) {
HTMLLinkElement* linkElement = toHTMLLinkElement(element);
if (CSSStyleSheet* sheet = linkElement->sheet()) {
KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr));
serializeCSSStyleSheet(sheet, url);
ASSERT(m_resourceURLs.contains(url));
}
} else if (element->hasTagName(HTMLNames::styleTag)) {
HTMLStyleElement* styleElement = toHTMLStyleElement(element);
if (CSSStyleSheet* sheet = styleElement->sheet())
serializeCSSStyleSheet(sheet, KURL());
}
}
for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling())
serializeFrame(childFrame);
}
| 171,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct kvec *iov = rqst->rq_iov;
int n_vec = rqst->rq_nvec;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
unsigned int i;
size_t total_len = 0, sent;
struct socket *ssocket = server->ssocket;
int val = 1;
cFYI(1, "Sending smb: smb_len=%u", smb_buf_length);
dump_smb(iov[0].iov_base, iov[0].iov_len);
/* cork the socket */
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
rc = smb_send_kvec(server, iov, n_vec, &sent);
if (rc < 0)
goto uncork;
total_len += sent;
/* now walk the page array and send each page in it */
for (i = 0; i < rqst->rq_npages; i++) {
struct kvec p_iov;
cifs_rqst_page_to_kvec(rqst, i, &p_iov);
rc = smb_send_kvec(server, &p_iov, 1, &sent);
kunmap(rqst->rq_pages[i]);
if (rc < 0)
break;
total_len += sent;
}
uncork:
/* uncork it */
val = 0;
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cFYI(1, "partial send (wanted=%u sent=%zu): terminating "
"session", smb_buf_length + 4, total_len);
/*
* If we have only sent part of an SMB then the next SMB could
* be taken as the remainder of this one. We need to kill the
* socket so the server throws away the partial SMB
*/
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cERROR(1, "Error %d sending data on socket to server", rc);
else
rc = 0;
return rc;
}
Commit Message: cifs: move check for NULL socket into smb_send_rqst
Cai reported this oops:
[90701.616664] BUG: unable to handle kernel NULL pointer dereference at 0000000000000028
[90701.625438] IP: [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.632167] PGD fea319067 PUD 103fda4067 PMD 0
[90701.637255] Oops: 0000 [#1] SMP
[90701.640878] Modules linked in: des_generic md4 nls_utf8 cifs dns_resolver binfmt_misc tun sg igb iTCO_wdt iTCO_vendor_support lpc_ich pcspkr i2c_i801 i2c_core i7core_edac edac_core ioatdma dca mfd_core coretemp kvm_intel kvm crc32c_intel microcode sr_mod cdrom ata_generic sd_mod pata_acpi crc_t10dif ata_piix libata megaraid_sas dm_mirror dm_region_hash dm_log dm_mod
[90701.677655] CPU 10
[90701.679808] Pid: 9627, comm: ls Tainted: G W 3.7.1+ #10 QCI QSSC-S4R/QSSC-S4R
[90701.688950] RIP: 0010:[<ffffffff814a343e>] [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.698383] RSP: 0018:ffff88177b431bb8 EFLAGS: 00010206
[90701.704309] RAX: ffff88177b431fd8 RBX: 00007ffffffff000 RCX: ffff88177b431bec
[90701.712271] RDX: 0000000000000003 RSI: 0000000000000006 RDI: 0000000000000000
[90701.720223] RBP: ffff88177b431bc8 R08: 0000000000000004 R09: 0000000000000000
[90701.728185] R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000001
[90701.736147] R13: ffff88184ef92000 R14: 0000000000000023 R15: ffff88177b431c88
[90701.744109] FS: 00007fd56a1a47c0(0000) GS:ffff88105fc40000(0000) knlGS:0000000000000000
[90701.753137] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[90701.759550] CR2: 0000000000000028 CR3: 000000104f15f000 CR4: 00000000000007e0
[90701.767512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[90701.775465] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[90701.783428] Process ls (pid: 9627, threadinfo ffff88177b430000, task ffff88185ca4cb60)
[90701.792261] Stack:
[90701.794505] 0000000000000023 ffff88177b431c50 ffff88177b431c38 ffffffffa014fcb1
[90701.802809] ffff88184ef921bc 0000000000000000 00000001ffffffff ffff88184ef921c0
[90701.811123] ffff88177b431c08 ffffffff815ca3d9 ffff88177b431c18 ffff880857758000
[90701.819433] Call Trace:
[90701.822183] [<ffffffffa014fcb1>] smb_send_rqst+0x71/0x1f0 [cifs]
[90701.828991] [<ffffffff815ca3d9>] ? schedule+0x29/0x70
[90701.834736] [<ffffffffa014fe6d>] smb_sendv+0x3d/0x40 [cifs]
[90701.841062] [<ffffffffa014fe96>] smb_send+0x26/0x30 [cifs]
[90701.847291] [<ffffffffa015801f>] send_nt_cancel+0x6f/0xd0 [cifs]
[90701.854102] [<ffffffffa015075e>] SendReceive+0x18e/0x360 [cifs]
[90701.860814] [<ffffffffa0134a78>] CIFSFindFirst+0x1a8/0x3f0 [cifs]
[90701.867724] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs]
[90701.875601] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs]
[90701.883477] [<ffffffffa01578e6>] cifs_query_dir_first+0x26/0x30 [cifs]
[90701.890869] [<ffffffffa015480d>] initiate_cifs_search+0xed/0x250 [cifs]
[90701.898354] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.904486] [<ffffffffa01554cb>] cifs_readdir+0x45b/0x8f0 [cifs]
[90701.911288] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.917410] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.923533] [<ffffffff81195970>] ? fillonedir+0x100/0x100
[90701.929657] [<ffffffff81195848>] vfs_readdir+0xb8/0xe0
[90701.935490] [<ffffffff81195b9f>] sys_getdents+0x8f/0x110
[90701.941521] [<ffffffff815d3b99>] system_call_fastpath+0x16/0x1b
[90701.948222] Code: 66 90 55 65 48 8b 04 25 f0 c6 00 00 48 89 e5 53 48 83 ec 08 83 fe 01 48 8b 98 48 e0 ff ff 48 c7 80 48 e0 ff ff ff ff ff ff 74 22 <48> 8b 47 28 ff 50 68 65 48 8b 14 25 f0 c6 00 00 48 89 9a 48 e0
[90701.970313] RIP [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60
[90701.977125] RSP <ffff88177b431bb8>
[90701.981018] CR2: 0000000000000028
[90701.984809] ---[ end trace 24bd602971110a43 ]---
This is likely due to a race vs. a reconnection event.
The current code checks for a NULL socket in smb_send_kvec, but that's
too late. By the time that check is done, the socket will already have
been passed to kernel_setsockopt. Move the check into smb_send_rqst, so
that it's checked earlier.
In truth, this is a bit of a half-assed fix. The -ENOTSOCK error
return here looks like it could bubble back up to userspace. The locking
rules around the ssocket pointer are really unclear as well. There are
cases where the ssocket pointer is changed without holding the srv_mutex,
but I'm not clear whether there's a potential race here yet or not.
This code seems like it could benefit from some fundamental re-think of
how the socket handling should behave. Until then though, this patch
should at least fix the above oops in most cases.
Cc: <[email protected]> # 3.7+
Reported-and-Tested-by: CAI Qian <[email protected]>
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[email protected]>
CWE ID: CWE-362 | smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct kvec *iov = rqst->rq_iov;
int n_vec = rqst->rq_nvec;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
unsigned int i;
size_t total_len = 0, sent;
struct socket *ssocket = server->ssocket;
int val = 1;
if (ssocket == NULL)
return -ENOTSOCK;
cFYI(1, "Sending smb: smb_len=%u", smb_buf_length);
dump_smb(iov[0].iov_base, iov[0].iov_len);
/* cork the socket */
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
rc = smb_send_kvec(server, iov, n_vec, &sent);
if (rc < 0)
goto uncork;
total_len += sent;
/* now walk the page array and send each page in it */
for (i = 0; i < rqst->rq_npages; i++) {
struct kvec p_iov;
cifs_rqst_page_to_kvec(rqst, i, &p_iov);
rc = smb_send_kvec(server, &p_iov, 1, &sent);
kunmap(rqst->rq_pages[i]);
if (rc < 0)
break;
total_len += sent;
}
uncork:
/* uncork it */
val = 0;
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cFYI(1, "partial send (wanted=%u sent=%zu): terminating "
"session", smb_buf_length + 4, total_len);
/*
* If we have only sent part of an SMB then the next SMB could
* be taken as the remainder of this one. We need to kill the
* socket so the server throws away the partial SMB
*/
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cERROR(1, "Error %d sending data on socket to server", rc);
else
rc = 0;
return rc;
}
| 166,026 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan)
{
if (paintingDisabled())
return;
m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle())));
m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, angleSpan);
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan)
{
if (paintingDisabled())
return;
m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle())));
m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, startAngle + angleSpan);
}
| 170,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_devcache_cleanup();
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
| 173,930 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_ && !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
Commit Message: exo: Reduce side-effects of dynamic activation code.
This code exists for clients that need to managed their own system
modal dialogs. Since the addition of the remote surface API we
can limit the impact of this to surfaces created for system modal
container.
BUG=29528396
Review-Url: https://codereview.chromium.org/2084023003
Cr-Commit-Position: refs/heads/master@{#401115}
CWE ID: CWE-416 | void ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_;
// ShellSurfaces in system modal container are only activatable if input
// region is non-empty. See OnCommitSurface() for more details.
if (container_ == ash::kShellWindowId_SystemModalContainer)
activatable &= !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
| 171,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples, i, max, max_w, max_h;
int prec, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm", "wb");
fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);
fclose(icm);
#endif
if (in_prof == NULL) {
return;
}
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = image->comps[0].w;
max_h = image->comps[0].h;
prec = (int)image->comps[0].prec;
if (out_space == cmsSigRgbData) { /* enumCS 16 */
unsigned int i, nr_comp = image->numcomps;
if (nr_comp > 4) {
nr_comp = 4;
}
for (i = 1; i < nr_comp; ++i) { /* AFL test */
if (image->comps[0].dx != image->comps[i].dx) {
break;
}
if (image->comps[0].dy != image->comps[i].dy) {
break;
}
if (image->comps[0].prec != image->comps[i].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[i].sgnd) {
break;
}
}
if (i != nr_comp) {
cmsCloseProfile(in_prof);
return;
}
if (prec <= 8) {
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
} else {
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigGrayData) { /* enumCS 17 */
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__, __LINE__, out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if (out_prof == NULL) {
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,
"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n", __FILE__, __LINE__, image->numcomps, prec,
max_w, max_h, (void*)in_prof, (void*)out_prof);
fprintf(stderr, "\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space >> 24) & 0xff, (in_space >> 16) & 0xff,
(in_space >> 8) & 0xff, in_space & 0xff,
out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff,
in_type, out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (transform == NULL) {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n", __FILE__, __LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if (image->numcomps > 2) { /* RGB, RGBA */
if (prec <= 8) {
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails0;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
*in++ = (unsigned char) * g++;
*in++ = (unsigned char) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails0:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
} else { /* prec > 8 */
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails1;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U ; i < max; ++i) {
*in++ = (unsigned short) * r++;
*in++ = (unsigned short) * g++;
*in++ = (unsigned short) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails1:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
}
} else { /* image->numcomps <= 2 : GRAY, GRAYA */
if (prec <= 8) {
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails2;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails2;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails2:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
} else { /* prec > 8 */
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails3;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails3;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned short) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails3:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (ok) {
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
Commit Message: color_apply_icc_profile: avoid potential heap buffer overflow
Derived from a patch by Thuan Pham
CWE ID: CWE-119 | void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples, i, max, max_w, max_h;
int prec, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm", "wb");
fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);
fclose(icm);
#endif
if (in_prof == NULL) {
return;
}
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = image->comps[0].w;
max_h = image->comps[0].h;
prec = (int)image->comps[0].prec;
if (out_space == cmsSigRgbData) { /* enumCS 16 */
unsigned int i, nr_comp = image->numcomps;
if (nr_comp > 4) {
nr_comp = 4;
}
for (i = 1; i < nr_comp; ++i) { /* AFL test */
if (image->comps[0].dx != image->comps[i].dx) {
break;
}
if (image->comps[0].dy != image->comps[i].dy) {
break;
}
if (image->comps[0].prec != image->comps[i].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[i].sgnd) {
break;
}
}
if (i != nr_comp) {
cmsCloseProfile(in_prof);
return;
}
if (prec <= 8) {
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
} else {
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigGrayData) { /* enumCS 17 */
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__, __LINE__, out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if (out_prof == NULL) {
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,
"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n", __FILE__, __LINE__, image->numcomps, prec,
max_w, max_h, (void*)in_prof, (void*)out_prof);
fprintf(stderr, "\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space >> 24) & 0xff, (in_space >> 16) & 0xff,
(in_space >> 8) & 0xff, in_space & 0xff,
out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff,
in_type, out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (transform == NULL) {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n", __FILE__, __LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if (image->numcomps > 2) { /* RGB, RGBA */
if ((image->comps[0].w == image->comps[1].w &&
image->comps[0].w == image->comps[2].w) &&
(image->comps[0].h == image->comps[1].h &&
image->comps[0].h == image->comps[2].h)) {
if (prec <= 8) {
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails0;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
*in++ = (unsigned char) * g++;
*in++ = (unsigned char) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails0:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
} else { /* prec > 8 */
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails1;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U ; i < max; ++i) {
*in++ = (unsigned short) * r++;
*in++ = (unsigned short) * g++;
*in++ = (unsigned short) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails1:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
}
} else {
fprintf(stderr,
"[ERROR] Image components should have the same width and height\n");
cmsDeleteTransform(transform);
return;
}
} else { /* image->numcomps <= 2 : GRAY, GRAYA */
if (prec <= 8) {
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails2;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails2;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails2:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
} else { /* prec > 8 */
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails3;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails3;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned short) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails3:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (ok) {
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
| 169,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const GURL& frame_url,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const WebKit::WebFrame* frame,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
GURL frame_url = frame->document().url();
GURL page_url = frame->top()->document().url();
// - devtools (chrome-extension:// URLs are loaded into frames of devtools
// to support the devtools extension APIs)
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!(page_url.SchemeIs(chrome::kChromeDevToolsScheme) &&
!extension->devtools_url().is_empty()) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
| 171,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
struct snmp_session *session,
struct objid_query *objid_query)
{
struct snmp_session *ss;
struct snmp_pdu *pdu=NULL, *response;
struct variable_list *vars;
oid root[MAX_NAME_LEN];
size_t rootlen = 0;
int status, count, found;
char buf[2048];
char buf2[2048];
int keepwalking=1;
char *err;
zval *snmpval = NULL;
int snmp_errno;
/* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */
RETVAL_FALSE;
/* reset errno and errstr */
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_NOERROR, "");
if (st & SNMP_CMD_WALK) { /* remember root OID */
memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid));
rootlen = objid_query->vars[0].name_length;
objid_query->offset = objid_query->count;
}
if ((ss = snmp_open(session)) == NULL) {
snmp_error(session, NULL, NULL, &err);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open snmp connection: %s", err);
free(err);
RETVAL_FALSE;
return;
}
if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries");
}
while (keepwalking) {
keepwalking = 0;
if (st & SNMP_CMD_WALK) {
if (session->version == SNMP_VERSION_1) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else {
pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
pdu->non_repeaters = objid_query->non_repeaters;
pdu->max_repetitions = objid_query->max_repetitions;
}
snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length);
} else {
if (st & SNMP_CMD_GET) {
pdu = snmp_pdu_create(SNMP_MSG_GET);
} else if (st & SNMP_CMD_GETNEXT) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else if (st & SNMP_CMD_SET) {
pdu = snmp_pdu_create(SNMP_MSG_SET);
} else {
snmp_close(ss);
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Unknown SNMP command (internals)");
RETVAL_FALSE;
return;
}
for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){
if (st & SNMP_CMD_SET) {
if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) {
snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno));
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
} else {
snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
}
}
if(pdu->variables == NULL){
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
}
retry:
status = snmp_synch_response(ss, pdu, &response);
if (status == STAT_SUCCESS) {
if (response->errstat == SNMP_ERR_NOERROR) {
if (st & SNMP_CMD_SET) {
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
continue;
}
snmp_free_pdu(response);
snmp_close(ss);
RETVAL_TRUE;
return;
}
for (vars = response->variables; vars; vars = vars->next_variable) {
/* do not output errors as values */
if ( vars->type == SNMP_ENDOFMIBVIEW ||
vars->type == SNMP_NOSUCHOBJECT ||
vars->type == SNMP_NOSUCHINSTANCE ) {
if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) {
break;
}
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2);
continue;
}
if ((st & SNMP_CMD_WALK) &&
(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */
if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */
keepwalking = 0;
} else {
/* first fetched OID is out of subtree, fallback to GET query */
st |= SNMP_CMD_GET;
st ^= SNMP_CMD_WALK;
objid_query->offset = 0;
keepwalking = 1;
}
break;
}
MAKE_STD_ZVAL(snmpval);
php_snmp_getvalue(vars, snmpval TSRMLS_CC, objid_query->valueretrieval);
if (objid_query->array_output) {
if (Z_TYPE_P(return_value) == IS_BOOL) {
array_init(return_value);
}
if (st & SNMP_NUMERIC_KEYS) {
add_next_index_zval(return_value, snmpval);
} else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) {
found = 0;
for (count = 0; count < objid_query->count; count++) {
if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) {
found = 1;
objid_query->vars[count].name_length = 0; /* mark this name as used */
break;
}
}
if (found) {
add_assoc_zval(return_value, objid_query->vars[count].oid, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find original OID name for '%s'", buf2);
}
} else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) {
buf2[0] = '\0';
count = rootlen;
while(count < vars->name_length){
sprintf(buf, "%lu.", vars->name[count]);
strcat(buf2, buf);
count++;
}
buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */
}
add_assoc_zval(return_value, buf2, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
add_assoc_zval(return_value, buf2, snmpval);
}
} else {
*return_value = *snmpval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&snmpval);
break;
}
/* OID increase check */
if (st & SNMP_CMD_WALK) {
if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2);
keepwalking = 0;
} else {
memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid));
objid_query->vars[0].name_length = vars->name_length;
keepwalking = 1;
}
}
}
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
}
} else {
if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */
objid_query->max_repetitions /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_BOOL) {
for ( count=1, vars = response->variables;
vars && count != response->errindex;
vars = vars->next_variable, count++);
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */
objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 );
objid_query->step /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (vars) {
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat));
} else {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat));
}
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */
if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) {
snmp_free_pdu(response);
goto retry;
}
}
snmp_free_pdu(response);
snmp_close(ss);
if (objid_query->array_output) {
zval_dtor(return_value);
}
RETVAL_FALSE;
return;
}
}
} else if (status == STAT_TIMEOUT) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
} else { /* status == STAT_ERROR */
snmp_error(ss, NULL, NULL, &err);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err);
free(err);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
}
if (response) {
snmp_free_pdu(response);
}
} /* keepwalking */
snmp_close(ss);
}
Commit Message:
CWE ID: CWE-416 | static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
struct snmp_session *session,
struct objid_query *objid_query)
{
struct snmp_session *ss;
struct snmp_pdu *pdu=NULL, *response;
struct variable_list *vars;
oid root[MAX_NAME_LEN];
size_t rootlen = 0;
int status, count, found;
char buf[2048];
char buf2[2048];
int keepwalking=1;
char *err;
zval *snmpval = NULL;
int snmp_errno;
/* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */
RETVAL_FALSE;
/* reset errno and errstr */
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_NOERROR, "");
if (st & SNMP_CMD_WALK) { /* remember root OID */
memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid));
rootlen = objid_query->vars[0].name_length;
objid_query->offset = objid_query->count;
}
if ((ss = snmp_open(session)) == NULL) {
snmp_error(session, NULL, NULL, &err);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open snmp connection: %s", err);
free(err);
RETVAL_FALSE;
return;
}
if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries");
}
while (keepwalking) {
keepwalking = 0;
if (st & SNMP_CMD_WALK) {
if (session->version == SNMP_VERSION_1) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else {
pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
pdu->non_repeaters = objid_query->non_repeaters;
pdu->max_repetitions = objid_query->max_repetitions;
}
snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length);
} else {
if (st & SNMP_CMD_GET) {
pdu = snmp_pdu_create(SNMP_MSG_GET);
} else if (st & SNMP_CMD_GETNEXT) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else if (st & SNMP_CMD_SET) {
pdu = snmp_pdu_create(SNMP_MSG_SET);
} else {
snmp_close(ss);
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Unknown SNMP command (internals)");
RETVAL_FALSE;
return;
}
for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){
if (st & SNMP_CMD_SET) {
if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) {
snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno));
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
} else {
snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
}
}
if(pdu->variables == NULL){
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
}
retry:
status = snmp_synch_response(ss, pdu, &response);
if (status == STAT_SUCCESS) {
if (response->errstat == SNMP_ERR_NOERROR) {
if (st & SNMP_CMD_SET) {
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
continue;
}
snmp_free_pdu(response);
snmp_close(ss);
RETVAL_TRUE;
return;
}
for (vars = response->variables; vars; vars = vars->next_variable) {
/* do not output errors as values */
if ( vars->type == SNMP_ENDOFMIBVIEW ||
vars->type == SNMP_NOSUCHOBJECT ||
vars->type == SNMP_NOSUCHINSTANCE ) {
if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) {
break;
}
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2);
continue;
}
if ((st & SNMP_CMD_WALK) &&
(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */
if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */
keepwalking = 0;
} else {
/* first fetched OID is out of subtree, fallback to GET query */
st |= SNMP_CMD_GET;
st ^= SNMP_CMD_WALK;
objid_query->offset = 0;
keepwalking = 1;
}
break;
}
MAKE_STD_ZVAL(snmpval);
php_snmp_getvalue(vars, snmpval TSRMLS_CC, objid_query->valueretrieval);
if (objid_query->array_output) {
if (Z_TYPE_P(return_value) == IS_BOOL) {
array_init(return_value);
}
if (st & SNMP_NUMERIC_KEYS) {
add_next_index_zval(return_value, snmpval);
} else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) {
found = 0;
for (count = 0; count < objid_query->count; count++) {
if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) {
found = 1;
objid_query->vars[count].name_length = 0; /* mark this name as used */
break;
}
}
if (found) {
add_assoc_zval(return_value, objid_query->vars[count].oid, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find original OID name for '%s'", buf2);
}
} else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) {
buf2[0] = '\0';
count = rootlen;
while(count < vars->name_length){
sprintf(buf, "%lu.", vars->name[count]);
strcat(buf2, buf);
count++;
}
buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */
}
add_assoc_zval(return_value, buf2, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
add_assoc_zval(return_value, buf2, snmpval);
}
} else {
*return_value = *snmpval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&snmpval);
break;
}
/* OID increase check */
if (st & SNMP_CMD_WALK) {
if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2);
keepwalking = 0;
} else {
memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid));
objid_query->vars[0].name_length = vars->name_length;
keepwalking = 1;
}
}
}
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
}
} else {
if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */
objid_query->max_repetitions /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_BOOL) {
for ( count=1, vars = response->variables;
vars && count != response->errindex;
vars = vars->next_variable, count++);
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */
objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 );
objid_query->step /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (vars) {
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat));
} else {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat));
}
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */
if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) {
snmp_free_pdu(response);
goto retry;
}
}
snmp_free_pdu(response);
snmp_close(ss);
if (objid_query->array_output) {
zval_dtor(return_value);
}
RETVAL_FALSE;
return;
}
}
} else if (status == STAT_TIMEOUT) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
} else { /* status == STAT_ERROR */
snmp_error(ss, NULL, NULL, &err);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err);
free(err);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
}
if (response) {
snmp_free_pdu(response);
}
} /* keepwalking */
snmp_close(ss);
}
| 164,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: __u32 secure_ipv6_id(const __be32 daddr[4])
{
const struct keydata *keyptr;
__u32 hash[4];
keyptr = get_keyptr();
hash[0] = (__force __u32)daddr[0];
hash[1] = (__force __u32)daddr[1];
hash[2] = (__force __u32)daddr[2];
hash[3] = (__force __u32)daddr[3];
return half_md4_transform(hash, keyptr->secret);
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | __u32 secure_ipv6_id(const __be32 daddr[4])
| 165,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 168,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
Commit Message: CVE-2017-13042/HNCP: add DHCPv6-Data bounds checks
hncp_print_rec() validates each HNCP TLV to be within the declared as
well as the on-the-wire packet space. However, dhcpv6_print() in the same
file didn't do the same for the DHCPv6 options within the HNCP
DHCPv6-Data TLV value, which could cause an out-of-bounds read when
decoding an invalid packet. Add missing checks to dhcpv6_print().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
if (i + 4 > length)
return -1;
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
if (i + 4 + optlen > length)
return -1;
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
| 167,833 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ResourceMultiBufferDataProvider::DidReceiveResponse(
const WebURLResponse& response) {
#if DCHECK_IS_ON()
std::string version;
switch (response.HttpVersion()) {
case WebURLResponse::kHTTPVersion_0_9:
version = "0.9";
break;
case WebURLResponse::kHTTPVersion_1_0:
version = "1.0";
break;
case WebURLResponse::kHTTPVersion_1_1:
version = "1.1";
break;
case WebURLResponse::kHTTPVersion_2_0:
version = "2.1";
break;
case WebURLResponse::kHTTPVersionUnknown:
version = "unknown";
break;
}
DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
<< response.HttpStatusCode();
#endif
DCHECK(active_loader_);
scoped_refptr<UrlData> destination_url_data(url_data_);
if (!redirects_to_.is_empty()) {
destination_url_data =
url_data_->url_index()->GetByUrl(redirects_to_, cors_mode_);
redirects_to_ = GURL();
}
base::Time last_modified;
if (base::Time::FromString(
response.HttpHeaderField("Last-Modified").Utf8().data(),
&last_modified)) {
destination_url_data->set_last_modified(last_modified);
}
destination_url_data->set_etag(
response.HttpHeaderField("ETag").Utf8().data());
destination_url_data->set_valid_until(base::Time::Now() +
GetCacheValidUntil(response));
uint32_t reasons = GetReasonsForUncacheability(response);
destination_url_data->set_cacheable(reasons == 0);
UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
int shift = 0;
int max_enum = base::bits::Log2Ceiling(kMaxReason);
while (reasons) {
DCHECK_LT(shift, max_enum); // Sanity check.
if (reasons & 0x1) {
UMA_HISTOGRAM_EXACT_LINEAR("Media.UncacheableReason", shift,
max_enum); // PRESUBMIT_IGNORE_UMA_MAX
}
reasons >>= 1;
++shift;
}
int64_t content_length = response.ExpectedContentLength();
bool end_of_file = false;
bool do_fail = false;
bytes_to_discard_ = 0;
if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
bool partial_response = (response.HttpStatusCode() == kHttpPartialContent);
bool ok_response = (response.HttpStatusCode() == kHttpOK);
std::string accept_ranges =
response.HttpHeaderField("Accept-Ranges").Utf8();
if (accept_ranges.find("bytes") != std::string::npos)
destination_url_data->set_range_supported();
if (partial_response &&
VerifyPartialResponse(response, destination_url_data)) {
destination_url_data->set_range_supported();
} else if (ok_response) {
destination_url_data->set_length(content_length);
bytes_to_discard_ = byte_pos();
} else if (response.HttpStatusCode() == kHttpRangeNotSatisfiable) {
end_of_file = true;
} else {
active_loader_.reset();
do_fail = true;
}
} else {
destination_url_data->set_range_supported();
if (content_length != kPositionNotSpecified) {
destination_url_data->set_length(content_length + byte_pos());
}
}
if (!do_fail) {
destination_url_data =
url_data_->url_index()->TryInsert(destination_url_data);
}
destination_url_data->set_has_opaque_data(
network::cors::IsCORSCrossOriginResponseType(response.GetType()));
if (destination_url_data != url_data_) {
scoped_refptr<UrlData> old_url_data(url_data_);
destination_url_data->Use();
std::unique_ptr<DataProvider> self(
url_data_->multibuffer()->RemoveProvider(this));
url_data_ = destination_url_data.get();
url_data_->multibuffer()->AddProvider(std::move(self));
old_url_data->RedirectTo(destination_url_data);
}
if (do_fail) {
destination_url_data->Fail();
return; // "this" may be deleted now.
}
const GURL& original_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
if (!url_data_->ValidateDataOrigin(original_url.GetOrigin())) {
active_loader_.reset();
url_data_->Fail();
return; // "this" may be deleted now.
}
if (end_of_file) {
fifo_.push_back(DataBuffer::CreateEOSBuffer());
url_data_->multibuffer()->OnDataProviderEvent(this);
}
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | void ResourceMultiBufferDataProvider::DidReceiveResponse(
const WebURLResponse& response) {
#if DCHECK_IS_ON()
std::string version;
switch (response.HttpVersion()) {
case WebURLResponse::kHTTPVersion_0_9:
version = "0.9";
break;
case WebURLResponse::kHTTPVersion_1_0:
version = "1.0";
break;
case WebURLResponse::kHTTPVersion_1_1:
version = "1.1";
break;
case WebURLResponse::kHTTPVersion_2_0:
version = "2.1";
break;
case WebURLResponse::kHTTPVersionUnknown:
version = "unknown";
break;
}
DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
<< response.HttpStatusCode();
#endif
DCHECK(active_loader_);
scoped_refptr<UrlData> destination_url_data(url_data_);
if (!redirects_to_.is_empty()) {
destination_url_data =
url_data_->url_index()->GetByUrl(redirects_to_, cors_mode_);
redirects_to_ = GURL();
}
base::Time last_modified;
if (base::Time::FromString(
response.HttpHeaderField("Last-Modified").Utf8().data(),
&last_modified)) {
destination_url_data->set_last_modified(last_modified);
}
destination_url_data->set_etag(
response.HttpHeaderField("ETag").Utf8().data());
destination_url_data->set_valid_until(base::Time::Now() +
GetCacheValidUntil(response));
uint32_t reasons = GetReasonsForUncacheability(response);
destination_url_data->set_cacheable(reasons == 0);
UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
int shift = 0;
int max_enum = base::bits::Log2Ceiling(kMaxReason);
while (reasons) {
DCHECK_LT(shift, max_enum); // Sanity check.
if (reasons & 0x1) {
UMA_HISTOGRAM_EXACT_LINEAR("Media.UncacheableReason", shift,
max_enum); // PRESUBMIT_IGNORE_UMA_MAX
}
reasons >>= 1;
++shift;
}
int64_t content_length = response.ExpectedContentLength();
bool end_of_file = false;
bool do_fail = false;
// We get the response type here because aborting the loader may change it.
const auto response_type = response.GetType();
bytes_to_discard_ = 0;
if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
bool partial_response = (response.HttpStatusCode() == kHttpPartialContent);
bool ok_response = (response.HttpStatusCode() == kHttpOK);
std::string accept_ranges =
response.HttpHeaderField("Accept-Ranges").Utf8();
if (accept_ranges.find("bytes") != std::string::npos)
destination_url_data->set_range_supported();
if (partial_response &&
VerifyPartialResponse(response, destination_url_data)) {
destination_url_data->set_range_supported();
} else if (ok_response) {
destination_url_data->set_length(content_length);
bytes_to_discard_ = byte_pos();
} else if (response.HttpStatusCode() == kHttpRangeNotSatisfiable) {
end_of_file = true;
} else {
active_loader_.reset();
do_fail = true;
}
} else {
destination_url_data->set_range_supported();
if (content_length != kPositionNotSpecified) {
destination_url_data->set_length(content_length + byte_pos());
}
}
if (!do_fail) {
destination_url_data =
url_data_->url_index()->TryInsert(destination_url_data);
}
// This is vital for security!
destination_url_data->set_is_cors_cross_origin(
network::cors::IsCORSCrossOriginResponseType(response_type));
if (destination_url_data != url_data_) {
scoped_refptr<UrlData> old_url_data(url_data_);
destination_url_data->Use();
std::unique_ptr<DataProvider> self(
url_data_->multibuffer()->RemoveProvider(this));
url_data_ = destination_url_data.get();
url_data_->multibuffer()->AddProvider(std::move(self));
old_url_data->RedirectTo(destination_url_data);
}
if (do_fail) {
destination_url_data->Fail();
return; // "this" may be deleted now.
}
const GURL& original_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
if (!url_data_->ValidateDataOrigin(original_url.GetOrigin())) {
active_loader_.reset();
url_data_->Fail();
return; // "this" may be deleted now.
}
if (end_of_file) {
fifo_.push_back(DataBuffer::CreateEOSBuffer());
url_data_->multibuffer()->OnDataProviderEvent(this);
}
}
| 172,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
| 165,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
{
int totlen;
uint32_t t;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)
{
int totlen;
uint32_t t;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
| 167,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.