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 pn_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct sk_buff *skb = NULL;
struct sockaddr_pn sa;
int rval = -EOPNOTSUPP;
int copylen;
if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
goto out_nofree;
if (addr_len)
*addr_len = sizeof(sa);
skb = skb_recv_datagram(sk, flags, noblock, &rval);
if (skb == NULL)
goto out_nofree;
pn_skb_get_src_sockaddr(skb, &sa);
copylen = skb->len;
if (len < copylen) {
msg->msg_flags |= MSG_TRUNC;
copylen = len;
}
rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);
if (rval) {
rval = -EFAULT;
goto out;
}
rval = (flags & MSG_TRUNC) ? skb->len : copylen;
if (msg->msg_name != NULL)
memcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));
out:
skb_free_datagram(sk, skb);
out_nofree:
return rval;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct sk_buff *skb = NULL;
struct sockaddr_pn sa;
int rval = -EOPNOTSUPP;
int copylen;
if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
goto out_nofree;
skb = skb_recv_datagram(sk, flags, noblock, &rval);
if (skb == NULL)
goto out_nofree;
pn_skb_get_src_sockaddr(skb, &sa);
copylen = skb->len;
if (len < copylen) {
msg->msg_flags |= MSG_TRUNC;
copylen = len;
}
rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);
if (rval) {
rval = -EFAULT;
goto out;
}
rval = (flags & MSG_TRUNC) ? skb->len : copylen;
if (msg->msg_name != NULL) {
memcpy(msg->msg_name, &sa, sizeof(sa));
*addr_len = sizeof(sa);
}
out:
skb_free_datagram(sk, skb);
out_nofree:
return rval;
}
| 166,483 |
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: file_continue(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr pscratch = esp - 2;
file_enum *pfen = r_ptr(esp - 1, file_enum);
int devlen = esp[-3].value.intval;
gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);
uint len = r_size(pscratch);
uint code;
if (len < devlen)
return_error(gs_error_rangecheck); /* not even room for device len */
do {
memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);
code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,
len - devlen);
if (code == ~(uint) 0) { /* all done */
esp -= 5; /* pop proc, pfen, devlen, iodev , mark */
return o_pop_estack;
} else if (code > len) /* overran string */
return_error(gs_error_rangecheck);
else if (iodev != iodev_default(imemory)
|| (check_file_permissions_reduced(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, iodev, "PermitFileReading")) == 0) {
push(1);
ref_assign(op, pscratch);
r_set_size(op, code + devlen);
push_op_estack(file_continue); /* come again */
*++esp = pscratch[2]; /* proc */
return o_push_estack;
}
} while(1);
}
Commit Message:
CWE ID: CWE-200 | file_continue(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr pscratch = esp - 2;
file_enum *pfen = r_ptr(esp - 1, file_enum);
int devlen = esp[-3].value.intval;
gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);
uint len = r_size(pscratch);
uint code;
if (len < devlen)
return_error(gs_error_rangecheck); /* not even room for device len */
do {
memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);
code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,
len - devlen);
if (code == ~(uint) 0) { /* all done */
esp -= 5; /* pop proc, pfen, devlen, iodev , mark */
return o_pop_estack;
} else if (code > len) /* overran string */
return_error(gs_error_rangecheck);
else if (iodev != iodev_default(imemory)
|| (check_file_permissions(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, iodev, "PermitFileReading")) == 0) {
push(1);
ref_assign(op, pscratch);
r_set_size(op, code + devlen);
push_op_estack(file_continue); /* come again */
*++esp = pscratch[2]; /* proc */
return o_push_estack;
}
} while(1);
}
| 165,389 |
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 ExtensionServiceBackend::OnExtensionInstalled(
const scoped_refptr<const Extension>& extension) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (frontend_.get())
frontend_->OnExtensionInstalled(extension);
}
Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension
with plugins.
First landing broke some browser tests.
BUG=83273
TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog.
TBR=mihaip
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionServiceBackend::OnExtensionInstalled(
void ExtensionServiceBackend::OnLoadSingleExtension(
const scoped_refptr<const Extension>& extension) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (frontend_.get())
frontend_->OnLoadSingleExtension(extension);
}
| 170,408 |
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: ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)));
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), canvas->buffer() ? ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)) : nullptr);
}
| 171,394 |
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 diff_bytes_c(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w){
long i;
#if !HAVE_FAST_UNALIGNED
if((long)src2 & (sizeof(long)-1)){
for(i=0; i+7<w; i+=8){
dst[i+0] = src1[i+0]-src2[i+0];
dst[i+1] = src1[i+1]-src2[i+1];
dst[i+2] = src1[i+2]-src2[i+2];
dst[i+3] = src1[i+3]-src2[i+3];
dst[i+4] = src1[i+4]-src2[i+4];
dst[i+5] = src1[i+5]-src2[i+5];
dst[i+6] = src1[i+6]-src2[i+6];
dst[i+7] = src1[i+7]-src2[i+7];
}
}else
#endif
for(i=0; i<=w-sizeof(long); i+=sizeof(long)){
long a = *(long*)(src1+i);
long b = *(long*)(src2+i);
*(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80);
}
for(; i<w; i++)
dst[i+0] = src1[i+0]-src2[i+0];
}
Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-189 | static void diff_bytes_c(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w){
long i;
#if !HAVE_FAST_UNALIGNED
if((long)src2 & (sizeof(long)-1)){
for(i=0; i+7<w; i+=8){
dst[i+0] = src1[i+0]-src2[i+0];
dst[i+1] = src1[i+1]-src2[i+1];
dst[i+2] = src1[i+2]-src2[i+2];
dst[i+3] = src1[i+3]-src2[i+3];
dst[i+4] = src1[i+4]-src2[i+4];
dst[i+5] = src1[i+5]-src2[i+5];
dst[i+6] = src1[i+6]-src2[i+6];
dst[i+7] = src1[i+7]-src2[i+7];
}
}else
#endif
for(i=0; i<=w-(int)sizeof(long); i+=sizeof(long)){
long a = *(long*)(src1+i);
long b = *(long*)(src2+i);
*(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80);
}
for(; i<w; i++)
dst[i+0] = src1[i+0]-src2[i+0];
}
| 165,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 AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) {
DCHECK(entries_.find(url) == entries_.end());
entries_.insert(EntryMap::value_type(url, entry));
cache_size_ += entry.response_size();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) {
DCHECK(entries_.find(url) == entries_.end());
entries_.insert(EntryMap::value_type(url, entry));
cache_size_ += entry.response_size();
padding_size_ += entry.padding_size();
}
| 172,967 |
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: xps_select_font_encoding(xps_font_t *font, int idx)
{
byte *cmapdata, *entry;
int pid, eid;
if (idx < 0 || idx >= font->cmapsubcount)
return;
cmapdata = font->data + font->cmaptable;
entry = cmapdata + 4 + idx * 8;
pid = u16(entry + 0);
eid = u16(entry + 2);
font->cmapsubtable = font->cmaptable + u32(entry + 4);
font->usepua = (pid == 3 && eid == 0);
}
Commit Message:
CWE ID: CWE-125 | xps_select_font_encoding(xps_font_t *font, int idx)
{
byte *cmapdata, *entry;
int pid, eid;
if (idx < 0 || idx >= font->cmapsubcount)
return 0;
cmapdata = font->data + font->cmaptable;
entry = cmapdata + 4 + idx * 8;
pid = u16(entry + 0);
eid = u16(entry + 2);
font->cmapsubtable = font->cmaptable + u32(entry + 4);
if (font->cmapsubtable >= font->length) {
font->cmapsubtable = 0;
return 0;
}
font->usepua = (pid == 3 && eid == 0);
return 1;
}
| 164,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: PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
: PrintingContext(app_locale) {
#else
: PrintingContext(app_locale),
print_dialog_(NULL) {
#endif
}
PrintingContextCairo::~PrintingContextCairo() {
ReleaseContext();
#if !defined(OS_CHROMEOS)
if (print_dialog_)
print_dialog_->ReleaseDialog();
#endif
}
#if !defined(OS_CHROMEOS)
void PrintingContextCairo::SetCreatePrintDialogFunction(
PrintDialogGtkInterface* (*create_dialog_func)(
PrintingContextCairo* context)) {
DCHECK(create_dialog_func);
DCHECK(!create_dialog_func_);
create_dialog_func_ = create_dialog_func;
}
void PrintingContextCairo::PrintDocument(const Metafile* metafile) {
DCHECK(print_dialog_);
DCHECK(metafile);
print_dialog_->PrintDocument(metafile, document_name_);
}
#endif // !defined(OS_CHROMEOS)
void PrintingContextCairo::AskUserForSettings(
gfx::NativeView parent_view,
int max_pages,
bool has_selection,
PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
callback->Run(OK);
#else
print_dialog_->ShowDialog(callback);
#endif // defined(OS_CHROMEOS)
}
PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
DCHECK(!in_print_job_);
ResetSettings();
#if defined(OS_CHROMEOS)
int dpi = 300;
gfx::Size physical_size_device_units;
gfx::Rect printable_area_device_units;
int32_t width = 0;
int32_t height = 0;
UErrorCode error = U_ZERO_ERROR;
ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
if (error != U_ZERO_ERROR) {
LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
<< error;
width = static_cast<int>(8.5 * dpi);
height = static_cast<int>(11 * dpi);
} else {
width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
}
physical_size_device_units.SetSize(width, height);
printable_area_device_units.SetRect(
static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
height - (PrintSettingsInitializerGtk::kTopMarginInInch +
PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);
settings_.set_dpi(dpi);
settings_.SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
#else
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
print_dialog_->UseDefaultSettings();
#endif // defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
PrintingContext::Result PrintingContextCairo::InitWithSettings(
const PrintSettings& settings) {
DCHECK(!in_print_job_);
settings_ = settings;
return OK;
}
PrintingContext::Result PrintingContextCairo::NewDocument(
const string16& document_name) {
DCHECK(!in_print_job_);
in_print_job_ = true;
#if !defined(OS_CHROMEOS)
document_name_ = document_name;
#endif // !defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::NewPage() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::PageDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::DocumentDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
ResetSettings();
return OK;
}
void PrintingContextCairo::Cancel() {
abort_printing_ = true;
in_print_job_ = false;
}
void PrintingContextCairo::ReleaseContext() {
}
gfx::NativeDrawingContext PrintingContextCairo::context() const {
return NULL;
}
} // namespace printing
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
: PrintingContext(app_locale) {
#else
: PrintingContext(app_locale),
print_dialog_(NULL) {
#endif
}
PrintingContextCairo::~PrintingContextCairo() {
ReleaseContext();
#if !defined(OS_CHROMEOS)
if (print_dialog_)
print_dialog_->ReleaseDialog();
#endif
}
#if !defined(OS_CHROMEOS)
void PrintingContextCairo::SetCreatePrintDialogFunction(
PrintDialogGtkInterface* (*create_dialog_func)(
PrintingContextCairo* context)) {
DCHECK(create_dialog_func);
DCHECK(!create_dialog_func_);
create_dialog_func_ = create_dialog_func;
}
void PrintingContextCairo::PrintDocument(const Metafile* metafile) {
DCHECK(print_dialog_);
DCHECK(metafile);
print_dialog_->PrintDocument(metafile, document_name_);
}
#endif // !defined(OS_CHROMEOS)
void PrintingContextCairo::AskUserForSettings(
gfx::NativeView parent_view,
int max_pages,
bool has_selection,
PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
callback->Run(OK);
#else
print_dialog_->ShowDialog(callback);
#endif // defined(OS_CHROMEOS)
}
PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
DCHECK(!in_print_job_);
ResetSettings();
#if defined(OS_CHROMEOS)
int dpi = 300;
gfx::Size physical_size_device_units;
gfx::Rect printable_area_device_units;
int32_t width = 0;
int32_t height = 0;
UErrorCode error = U_ZERO_ERROR;
ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
if (error != U_ZERO_ERROR) {
LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
<< error;
width = static_cast<int>(8.5 * dpi);
height = static_cast<int>(11 * dpi);
} else {
width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
}
physical_size_device_units.SetSize(width, height);
printable_area_device_units.SetRect(
static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
height - (PrintSettingsInitializerGtk::kTopMarginInInch +
PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);
settings_.set_dpi(dpi);
settings_.SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
#else
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
print_dialog_->UseDefaultSettings();
#endif // defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
PrintingContext::Result PrintingContextCairo::InitWithSettings(
const PrintSettings& settings) {
DCHECK(!in_print_job_);
settings_ = settings;
return OK;
}
PrintingContext::Result PrintingContextCairo::NewDocument(
const string16& document_name) {
DCHECK(!in_print_job_);
in_print_job_ = true;
#if !defined(OS_CHROMEOS)
document_name_ = document_name;
#endif // !defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::NewPage() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::PageDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::DocumentDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
ResetSettings();
return OK;
}
void PrintingContextCairo::Cancel() {
abort_printing_ = true;
in_print_job_ = false;
}
void PrintingContextCairo::ReleaseContext() {
}
gfx::NativeDrawingContext PrintingContextCairo::context() const {
return NULL;
}
} // namespace printing
| 170,266 |
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 ion_handle_put(struct ion_handle *handle)
{
struct ion_client *client = handle->client;
int ret;
mutex_lock(&client->lock);
ret = kref_put(&handle->ref, ion_handle_destroy);
mutex_unlock(&client->lock);
return ret;
}
Commit Message: staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <[email protected]>
Reviewed-by: Laura Abbott <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-416 | static int ion_handle_put(struct ion_handle *handle)
static int ion_handle_put_nolock(struct ion_handle *handle)
{
int ret;
ret = kref_put(&handle->ref, ion_handle_destroy);
return ret;
}
int ion_handle_put(struct ion_handle *handle)
{
struct ion_client *client = handle->client;
int ret;
mutex_lock(&client->lock);
ret = ion_handle_put_nolock(handle);
mutex_unlock(&client->lock);
return ret;
}
| 166,898 |
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 ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
if (WARN_ON(ret < match32->match_size))
return -EINVAL;
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-787 | static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
if (WARN_ON(ret < match32->match_size))
return -EINVAL;
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
if (WARN_ON(type == EBT_COMPAT_TARGET && size_left))
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
| 169,357 |
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: validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
Commit Message:
CWE ID: CWE-20 | validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen < 0 || screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
| 165,270 |
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 RenderWidgetHostViewAura::InsertSyncPointAndACK(
int32 route_id, int gpu_host_id, bool presented,
ui::Compositor* compositor) {
uint32 sync_point = 0;
if (compositor) {
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
sync_point = factory->InsertSyncPoint();
}
RenderWidgetHostImpl::AcknowledgeBufferPresent(
route_id, gpu_host_id, presented, sync_point);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::InsertSyncPointAndACK(
const BufferPresentedParams& params) {
uint32 sync_point = 0;
// If we produced a texture, we have to synchronize with the consumer of
// that texture.
if (params.texture_to_produce) {
params.texture_to_produce->Produce();
sync_point = ImageTransportFactory::GetInstance()->InsertSyncPoint();
}
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, params.gpu_host_id, params.surface_handle, sync_point);
}
| 171,379 |
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 const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,
RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,
const RBinDwarfCompUnitHdr *hdr,
const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf;
const ut8 *buf_end = obuf + obuf_len;
size_t j;
if (!spec || !value || !hdr || !obuf || obuf_len < 0) {
return NULL;
}
value->form = spec->attr_form;
value->name = spec->attr_name;
value->encoding.block.data = NULL;
value->encoding.str_struct.string = NULL;
value->encoding.str_struct.offset = 0;
switch (spec->attr_form) {
case DW_FORM_addr:
switch (hdr->pointer_size) {
case 1:
value->encoding.address = READ (buf, ut8);
break;
case 2:
value->encoding.address = READ (buf, ut16);
break;
case 4:
value->encoding.address = READ (buf, ut32);
break;
case 8:
value->encoding.address = READ (buf, ut64);
break;
default:
eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size);
return NULL;
}
break;
case DW_FORM_block2:
value->encoding.block.length = READ (buf, ut16);
if (value->encoding.block.length > 0) {
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block4:
value->encoding.block.length = READ (buf, ut32);
if (value->encoding.block.length > 0) {
ut8 *data = calloc (sizeof (ut8), value->encoding.block.length);
if (data) {
for (j = 0; j < value->encoding.block.length; j++) {
data[j] = READ (buf, ut8);
}
}
value->encoding.block.data = data;
}
break;
//// This causes segfaults to happen
case DW_FORM_data2:
value->encoding.data = READ (buf, ut16);
break;
case DW_FORM_data4:
value->encoding.data = READ (buf, ut32);
break;
case DW_FORM_data8:
value->encoding.data = READ (buf, ut64);
break;
case DW_FORM_string:
value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;
buf += (strlen ((const char*)buf) + 1);
break;
case DW_FORM_block:
buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);
if (!buf) {
return NULL;
}
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_block1:
value->encoding.block.length = READ (buf, ut8);
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_flag:
value->encoding.flag = READ (buf, ut8);
break;
case DW_FORM_sdata:
buf = r_leb128 (buf, &value->encoding.sdata);
break;
case DW_FORM_strp:
value->encoding.str_struct.offset = READ (buf, ut32);
if (debug_str && value->encoding.str_struct.offset < debug_str_len) {
value->encoding.str_struct.string = strdup (
(const char *)(debug_str +
value->encoding.str_struct.offset));
} else {
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_udata:
{
ut64 ndata = 0;
const ut8 *data = (const ut8*)&ndata;
buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);
memcpy (&value->encoding.data, data, sizeof (value->encoding.data));
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_ref_addr:
value->encoding.reference = READ (buf, ut64); // addr size of machine
break;
case DW_FORM_ref1:
value->encoding.reference = READ (buf, ut8);
break;
case DW_FORM_ref2:
value->encoding.reference = READ (buf, ut16);
break;
case DW_FORM_ref4:
value->encoding.reference = READ (buf, ut32);
break;
case DW_FORM_ref8:
value->encoding.reference = READ (buf, ut64);
break;
case DW_FORM_data1:
value->encoding.data = READ (buf, ut8);
break;
default:
eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form);
value->encoding.data = 0;
return NULL;
}
return buf;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125 | static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,
RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,
const RBinDwarfCompUnitHdr *hdr,
const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf;
const ut8 *buf_end = obuf + obuf_len;
size_t j;
if (!spec || !value || !hdr || !obuf || obuf_len < 1) {
return NULL;
}
value->form = spec->attr_form;
value->name = spec->attr_name;
value->encoding.block.data = NULL;
value->encoding.str_struct.string = NULL;
value->encoding.str_struct.offset = 0;
switch (spec->attr_form) {
case DW_FORM_addr:
switch (hdr->pointer_size) {
case 1:
value->encoding.address = READ (buf, ut8);
break;
case 2:
value->encoding.address = READ (buf, ut16);
break;
case 4:
value->encoding.address = READ (buf, ut32);
break;
case 8:
value->encoding.address = READ (buf, ut64);
break;
default:
eprintf ("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size);
return NULL;
}
break;
case DW_FORM_block2:
value->encoding.block.length = READ (buf, ut16);
if (value->encoding.block.length > 0) {
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block4:
value->encoding.block.length = READ (buf, ut32);
if (value->encoding.block.length > 0) {
ut8 *data = calloc (sizeof (ut8), value->encoding.block.length);
if (data) {
for (j = 0; j < value->encoding.block.length; j++) {
data[j] = READ (buf, ut8);
}
}
value->encoding.block.data = data;
}
break;
#if 0
//// This causes segfaults to happen
case DW_FORM_data2:
value->encoding.data = READ (buf, ut16);
break;
case DW_FORM_data4:
value->encoding.data = READ (buf, ut32);
break;
case DW_FORM_data8:
value->encoding.data = READ (buf, ut64);
break;
#endif
case DW_FORM_string:
value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;
buf += (strlen ((const char*)buf) + 1);
break;
case DW_FORM_block:
buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);
if (!buf) {
return NULL;
}
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length);
if (value->encoding.block.data) {
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block1:
value->encoding.block.length = READ (buf, ut8);
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);
if (value->encoding.block.data) {
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_flag:
value->encoding.flag = READ (buf, ut8);
break;
case DW_FORM_sdata:
buf = r_leb128 (buf, &value->encoding.sdata);
break;
case DW_FORM_strp:
value->encoding.str_struct.offset = READ (buf, ut32);
if (debug_str && value->encoding.str_struct.offset < debug_str_len) {
value->encoding.str_struct.string = strdup (
(const char *)(debug_str +
value->encoding.str_struct.offset));
} else {
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_udata:
{
ut64 ndata = 0;
const ut8 *data = (const ut8*)&ndata;
buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);
memcpy (&value->encoding.data, data, sizeof (value->encoding.data));
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_ref_addr:
value->encoding.reference = READ (buf, ut64); // addr size of machine
break;
case DW_FORM_ref1:
value->encoding.reference = READ (buf, ut8);
break;
case DW_FORM_ref2:
value->encoding.reference = READ (buf, ut16);
break;
case DW_FORM_ref4:
value->encoding.reference = READ (buf, ut32);
break;
case DW_FORM_ref8:
value->encoding.reference = READ (buf, ut64);
break;
case DW_FORM_data1:
value->encoding.data = READ (buf, ut8);
break;
default:
eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form);
value->encoding.data = 0;
return NULL;
}
return buf;
}
| 167,669 |
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: seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
struct stream packet = *s;
if (!s_check(s))
{
rdp_protocol_error("seamless_process(), stream is in unstable state", &packet);
}
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
| 169,808 |
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 bool elementCanUseSimpleDefaultStyle(Element* e)
{
return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e);
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static inline bool elementCanUseSimpleDefaultStyle(Element* e)
| 171,578 |
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_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
struct zip *intern;
zval *self = getThis();
struct zip_stat sb;
struct zip_file *zf;
zend_long index = -1;
zend_long flags = 0;
zend_long len = 0;
zend_string *filename;
zend_string *buffer;
int n = 0;
if (!self) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, self);
if (type == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_INDEX(intern, index, 0, sb);
}
if (sb.size < 1) {
RETURN_EMPTY_STRING();
}
if (len < 1) {
len = sb.size;
}
if (index >= 0) {
zf = zip_fopen_index(intern, index, flags);
} else {
zf = zip_fopen(intern, ZSTR_VAL(filename), flags);
}
if (zf == NULL) {
RETURN_FALSE;
}
buffer = zend_string_alloc(len, 0);
n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer));
if (n < 1) {
zend_string_free(buffer);
RETURN_EMPTY_STRING();
}
zip_fclose(zf);
ZSTR_VAL(buffer)[n] = '\0';
ZSTR_LEN(buffer) = n;
RETURN_NEW_STR(buffer);
}
/* }}} */
Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom*
CWE ID: CWE-190 | static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
struct zip *intern;
zval *self = getThis();
struct zip_stat sb;
struct zip_file *zf;
zend_long index = -1;
zend_long flags = 0;
zend_long len = 0;
zend_string *filename;
zend_string *buffer;
int n = 0;
if (!self) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, self);
if (type == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) {
return;
}
PHP_ZIP_STAT_INDEX(intern, index, 0, sb);
}
if (sb.size < 1) {
RETURN_EMPTY_STRING();
}
if (len < 1) {
len = sb.size;
}
if (index >= 0) {
zf = zip_fopen_index(intern, index, flags);
} else {
zf = zip_fopen(intern, ZSTR_VAL(filename), flags);
}
if (zf == NULL) {
RETURN_FALSE;
}
buffer = zend_string_safe_alloc(1, len, 0, 0);
n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer));
if (n < 1) {
zend_string_free(buffer);
RETURN_EMPTY_STRING();
}
zip_fclose(zf);
ZSTR_VAL(buffer)[n] = '\0';
ZSTR_LEN(buffer) = n;
RETURN_NEW_STR(buffer);
}
/* }}} */
| 167,381 |
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 SocketStream::set_context(URLRequestContext* context) {
const URLRequestContext* prev_context = context_.get();
if (context) {
context_ = context->AsWeakPtr();
} else {
context_.reset();
}
if (prev_context != context) {
if (prev_context && pac_request_) {
prev_context->proxy_service()->CancelPacRequest(pac_request_);
pac_request_ = NULL;
}
net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
net_log_ = BoundNetLog();
if (context) {
net_log_ = BoundNetLog::Make(
context->net_log(),
NetLog::SOURCE_SOCKET_STREAM);
net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
}
}
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void SocketStream::set_context(URLRequestContext* context) {
const URLRequestContext* prev_context = context_;
context_ = context;
if (prev_context != context) {
if (prev_context && pac_request_) {
prev_context->proxy_service()->CancelPacRequest(pac_request_);
pac_request_ = NULL;
}
net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
net_log_ = BoundNetLog();
if (context) {
net_log_ = BoundNetLog::Make(
context->net_log(),
NetLog::SOURCE_SOCKET_STREAM);
net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
}
}
}
| 171,257 |
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 sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_setbindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_REUSEPORT:
sk->sk_reuseport = valbool;
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check_tx = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) ||
ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
if (val & SOF_TIMESTAMPING_OPT_ID &&
!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
if ((1 << sk->sk_state) &
(TCPF_CLOSE | TCPF_LISTEN)) {
ret = -EINVAL;
break;
}
sk->sk_tskey = tcp_sk(sk)->snd_una;
} else {
sk->sk_tskey = 0;
}
}
sk->sk_tsflags = val;
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_BPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_attach_bpf(ufd, sk);
}
break;
case SO_ATTACH_REUSEPORT_CBPF:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_reuseport_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_REUSEPORT_EBPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_reuseport_attach_bpf(ufd, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_LOCK_FILTER:
if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
ret = -EPERM;
else
sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
ret = sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
case SO_SELECT_ERR_QUEUE:
sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
break;
#ifdef CONFIG_NET_RX_BUSY_POLL
case SO_BUSY_POLL:
/* allow unprivileged users to decrease the value */
if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
ret = -EPERM;
else {
if (val < 0)
ret = -EINVAL;
else
sk->sk_ll_usec = val;
}
break;
#endif
case SO_MAX_PACING_RATE:
sk->sk_max_pacing_rate = val;
sk->sk_pacing_rate = min(sk->sk_pacing_rate,
sk->sk_max_pacing_rate);
break;
case SO_INCOMING_CPU:
sk->sk_incoming_cpu = val;
break;
case SO_CNX_ADVICE:
if (val == 1)
dst_negative_advice(sk);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
Commit Message: net: avoid signed overflows for SO_{SND|RCV}BUFFORCE
CAP_NET_ADMIN users should not be allowed to set negative
sk_sndbuf or sk_rcvbuf values, as it can lead to various memory
corruptions, crashes, OOM...
Note that before commit 82981930125a ("net: cleanups in
sock_setsockopt()"), the bug was even more serious, since SO_SNDBUF
and SO_RCVBUF were vulnerable.
This needs to be backported to all known linux kernels.
Again, many thanks to syzkaller team for discovering this gem.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_setbindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_REUSEPORT:
sk->sk_reuseport = valbool;
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check_tx = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) ||
ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
if (val & SOF_TIMESTAMPING_OPT_ID &&
!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
if ((1 << sk->sk_state) &
(TCPF_CLOSE | TCPF_LISTEN)) {
ret = -EINVAL;
break;
}
sk->sk_tskey = tcp_sk(sk)->snd_una;
} else {
sk->sk_tskey = 0;
}
}
sk->sk_tsflags = val;
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_BPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_attach_bpf(ufd, sk);
}
break;
case SO_ATTACH_REUSEPORT_CBPF:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_reuseport_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_REUSEPORT_EBPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_reuseport_attach_bpf(ufd, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_LOCK_FILTER:
if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
ret = -EPERM;
else
sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
ret = sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
case SO_SELECT_ERR_QUEUE:
sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
break;
#ifdef CONFIG_NET_RX_BUSY_POLL
case SO_BUSY_POLL:
/* allow unprivileged users to decrease the value */
if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
ret = -EPERM;
else {
if (val < 0)
ret = -EINVAL;
else
sk->sk_ll_usec = val;
}
break;
#endif
case SO_MAX_PACING_RATE:
sk->sk_max_pacing_rate = val;
sk->sk_pacing_rate = min(sk->sk_pacing_rate,
sk->sk_max_pacing_rate);
break;
case SO_INCOMING_CPU:
sk->sk_incoming_cpu = val;
break;
case SO_CNX_ADVICE:
if (val == 1)
dst_negative_advice(sk);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
| 166,846 |
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 skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_skcipher_setkey(private, key, keylen);
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
CWE ID: CWE-476 | static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
struct skcipher_tfm *tfm = private;
int err;
err = crypto_skcipher_setkey(tfm->skcipher, key, keylen);
tfm->has_key = !err;
return err;
}
| 167,457 |
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: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
Commit Message: Fail expression lookup on invalid atoms
If we fail atom lookup, then we should not claim that we successfully
looked up the expression.
Signed-off-by: Daniel Stone <[email protected]>
CWE ID: CWE-476 | ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return (*elem_rtrn != NULL && *field_rtrn != NULL);
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
if (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)
return false;
if (*field_rtrn == NULL)
return false;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
| 169,091 |
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: my_object_emit_signals (MyObject *obj, GError **error)
{
GValue val = {0, };
g_signal_emit (obj, signals[SIG0], 0, "foo", 22, "moo");
g_value_init (&val, G_TYPE_STRING);
g_value_set_string (&val, "bar");
g_signal_emit (obj, signals[SIG1], 0, "baz", &val);
g_value_unset (&val);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_emit_signals (MyObject *obj, GError **error)
| 165,096 |
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: DECLAREcpFunc(cpDecodedStrips)
{
tsize_t stripsize = TIFFStripSize(in);
tdata_t buf = _TIFFmalloc(stripsize);
(void) imagewidth; (void) spp;
if (buf) {
tstrip_t s, ns = TIFFNumberOfStrips(in);
uint32 row = 0;
_TIFFmemset(buf, 0, stripsize);
for (s = 0; s < ns; s++) {
tsize_t cc = (row + rowsperstrip > imagelength) ?
TIFFVStripSize(in, imagelength - row) : stripsize;
if (TIFFReadEncodedStrip(in, s, buf, cc) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu",
(unsigned long) s);
goto bad;
}
if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %lu",
(unsigned long) s);
goto bad;
}
row += rowsperstrip;
}
_TIFFfree(buf);
return 1;
} else {
TIFFError(TIFFFileName(in),
"Error, can't allocate memory buffer of size %lu "
"to read strips", (unsigned long) stripsize);
return 0;
}
bad:
_TIFFfree(buf);
return 0;
}
Commit Message: * tools/tiffcp.c: avoid uint32 underflow in cpDecodedStrips that
can cause various issues, such as buffer overflows in the library.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2598
CWE ID: CWE-191 | DECLAREcpFunc(cpDecodedStrips)
{
tsize_t stripsize = TIFFStripSize(in);
tdata_t buf = _TIFFmalloc(stripsize);
(void) imagewidth; (void) spp;
if (buf) {
tstrip_t s, ns = TIFFNumberOfStrips(in);
uint32 row = 0;
_TIFFmemset(buf, 0, stripsize);
for (s = 0; s < ns && row < imagelength; s++) {
tsize_t cc = (row + rowsperstrip > imagelength) ?
TIFFVStripSize(in, imagelength - row) : stripsize;
if (TIFFReadEncodedStrip(in, s, buf, cc) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu",
(unsigned long) s);
goto bad;
}
if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %lu",
(unsigned long) s);
goto bad;
}
row += rowsperstrip;
}
_TIFFfree(buf);
return 1;
} else {
TIFFError(TIFFFileName(in),
"Error, can't allocate memory buffer of size %lu "
"to read strips", (unsigned long) stripsize);
return 0;
}
bad:
_TIFFfree(buf);
return 0;
}
| 168,467 |
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: WORD32 ih264d_cavlc_4x4res_block_totalcoeff_11to16(UWORD32 u4_isdc,
UWORD32 u4_total_coeff_trail_one, /*!<TotalCoefficients<<16+trailingones*/
dec_bit_stream_t *ps_bitstrm )
{
UWORD32 u4_total_zeroes;
WORD32 i;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF;
UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16;
WORD16 i2_level_arr[16];
tu_sblk4x4_coeff_data_t *ps_tu_4x4;
WORD16 *pi2_coeff_data;
dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle;
ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data;
ps_tu_4x4->u2_sig_coeff_map = 0;
pi2_coeff_data = &ps_tu_4x4->ai2_level[0];
i = u4_total_coeff - 1;
if(u4_trailing_ones)
{
/*********************************************************************/
/* Decode Trailing Ones */
/* read the sign of T1's and put them in level array */
/*********************************************************************/
UWORD32 u4_signs, u4_cnt = u4_trailing_ones;
WORD16 (*ppi2_trlone_lkup)[3] =
(WORD16 (*)[3])gai2_ih264d_trailing_one_level;
WORD16 *pi2_trlone_lkup;
GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt);
pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs];
while(u4_cnt--)
i2_level_arr[i--] = *pi2_trlone_lkup++;
}
/****************************************************************/
/* Decoding Levels Begins */
/****************************************************************/
if(i >= 0)
{
/****************************************************************/
/* First level is decoded outside the loop as it has lot of */
/* special cases. */
/****************************************************************/
UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size;
UWORD16 u2_lev_code, u2_abs_value;
UWORD32 u4_lev_prefix;
if(u4_trailing_ones < 3)
{
/*********************************************************/
/* u4_suffix_len = 1 */
/*********************************************************/
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : 1;
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = 2 + (MIN(u4_lev_prefix,15) << 1) + u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
}
else
{
/*********************************************************/
/*u4_suffix_len = 0 */
/*********************************************************/
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
/*********************************************************/
/* Special decoding case when trailing ones are 3 */
/*********************************************************/
u2_lev_code = MIN(15, u4_lev_prefix);
u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2);
if(14 == u4_lev_prefix)
u4_lev_suffix_size = 4;
else if(15 <= u4_lev_prefix)
{
u2_lev_code += 15;
u4_lev_suffix_size = (u4_lev_prefix - 3);
}
else
u4_lev_suffix_size = 0;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
if(u4_lev_suffix_size)
{
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code += u4_lev_suffix;
}
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
u4_suffix_len = (u2_abs_value > 3) ? 2 : 1;
/*********************************************************/
/* Now loop over the remaining levels */
/*********************************************************/
while(i >= 0)
{
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ?
(u4_lev_prefix - 3) : u4_suffix_len;
/*********************************************************/
/* Compute level code using prefix and suffix */
/*********************************************************/
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len)
+ u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] =
(u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
/*********************************************************/
/* Increment suffix length if required */
/*********************************************************/
u4_suffix_len +=
(u4_suffix_len < 6) ?
(u2_abs_value
> (3
<< (u4_suffix_len
- 1))) :
0;
}
/****************************************************************/
/* Decoding Levels Ends */
/****************************************************************/
}
if(u4_total_coeff < (16 - u4_isdc))
{
UWORD32 u4_index;
const UWORD8 (*ppu1_total_zero_lkup)[16] =
(const UWORD8 (*)[16])gau1_ih264d_table_total_zero_11to15;
NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 4);
u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 11][u4_index];
FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4));
u4_total_zeroes &= 0xf;
}
else
u4_total_zeroes = 0;
/**************************************************************/
/* Decode the runs and form the coefficient buffer */
/**************************************************************/
{
const UWORD8 *pu1_table_runbefore;
UWORD32 u4_run;
WORD32 k;
UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc;
WORD32 u4_zeroes_left = u4_total_zeroes;
k = u4_total_coeff - 1;
/**************************************************************/
/* Decoding Runs for 0 < zeros left <=6 */
/**************************************************************/
pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before;
while((u4_zeroes_left > 0) && k)
{
UWORD32 u4_code;
NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3);
u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)];
u4_run = u4_code >> 2;
FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03));
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[k--];
u4_zeroes_left -= u4_run;
u4_scan_pos -= (u4_run + 1);
}
/**************************************************************/
/* Decoding Runs End */
/**************************************************************/
/**************************************************************/
/* Copy the remaining coefficients */
/**************************************************************/
if(u4_zeroes_left < 0)
return -1;
while(k >= 0)
{
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[k--];
u4_scan_pos--;
}
}
{
WORD32 offset;
offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4;
offset = ALIGN4(offset);
ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset);
}
ps_bitstrm->u4_ofst = u4_bitstream_offset;
return 0;
}
Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions
Bug: 26399350
Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e
CWE ID: CWE-119 | WORD32 ih264d_cavlc_4x4res_block_totalcoeff_11to16(UWORD32 u4_isdc,
UWORD32 u4_total_coeff_trail_one, /*!<TotalCoefficients<<16+trailingones*/
dec_bit_stream_t *ps_bitstrm )
{
UWORD32 u4_total_zeroes;
WORD32 i;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF;
UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16;
// To avoid error check at 4x4 level, allocating for 3 extra levels(16+3)
// since u4_trailing_ones can at the max be 3. This will be required when
// u4_total_coeff is less than u4_trailing_ones
WORD16 ai2_level_arr[19];//
WORD16 *i2_level_arr = &ai2_level_arr[3];
tu_sblk4x4_coeff_data_t *ps_tu_4x4;
WORD16 *pi2_coeff_data;
dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle;
ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data;
ps_tu_4x4->u2_sig_coeff_map = 0;
pi2_coeff_data = &ps_tu_4x4->ai2_level[0];
i = u4_total_coeff - 1;
if(u4_trailing_ones)
{
/*********************************************************************/
/* Decode Trailing Ones */
/* read the sign of T1's and put them in level array */
/*********************************************************************/
UWORD32 u4_signs, u4_cnt = u4_trailing_ones;
WORD16 (*ppi2_trlone_lkup)[3] =
(WORD16 (*)[3])gai2_ih264d_trailing_one_level;
WORD16 *pi2_trlone_lkup;
GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt);
pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs];
while(u4_cnt--)
i2_level_arr[i--] = *pi2_trlone_lkup++;
}
/****************************************************************/
/* Decoding Levels Begins */
/****************************************************************/
if(i >= 0)
{
/****************************************************************/
/* First level is decoded outside the loop as it has lot of */
/* special cases. */
/****************************************************************/
UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size;
UWORD16 u2_lev_code, u2_abs_value;
UWORD32 u4_lev_prefix;
if(u4_trailing_ones < 3)
{
/*********************************************************/
/* u4_suffix_len = 1 */
/*********************************************************/
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : 1;
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = 2 + (MIN(u4_lev_prefix,15) << 1) + u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
}
else
{
/*********************************************************/
/*u4_suffix_len = 0 */
/*********************************************************/
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
/*********************************************************/
/* Special decoding case when trailing ones are 3 */
/*********************************************************/
u2_lev_code = MIN(15, u4_lev_prefix);
u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2);
if(14 == u4_lev_prefix)
u4_lev_suffix_size = 4;
else if(15 <= u4_lev_prefix)
{
u2_lev_code += 15;
u4_lev_suffix_size = (u4_lev_prefix - 3);
}
else
u4_lev_suffix_size = 0;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
if(u4_lev_suffix_size)
{
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code += u4_lev_suffix;
}
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
u4_suffix_len = (u2_abs_value > 3) ? 2 : 1;
/*********************************************************/
/* Now loop over the remaining levels */
/*********************************************************/
while(i >= 0)
{
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ?
(u4_lev_prefix - 3) : u4_suffix_len;
/*********************************************************/
/* Compute level code using prefix and suffix */
/*********************************************************/
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len)
+ u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] =
(u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
/*********************************************************/
/* Increment suffix length if required */
/*********************************************************/
u4_suffix_len +=
(u4_suffix_len < 6) ?
(u2_abs_value
> (3
<< (u4_suffix_len
- 1))) :
0;
}
/****************************************************************/
/* Decoding Levels Ends */
/****************************************************************/
}
if(u4_total_coeff < (16 - u4_isdc))
{
UWORD32 u4_index;
const UWORD8 (*ppu1_total_zero_lkup)[16] =
(const UWORD8 (*)[16])gau1_ih264d_table_total_zero_11to15;
NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 4);
u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 11][u4_index];
FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4));
u4_total_zeroes &= 0xf;
}
else
u4_total_zeroes = 0;
/**************************************************************/
/* Decode the runs and form the coefficient buffer */
/**************************************************************/
{
const UWORD8 *pu1_table_runbefore;
UWORD32 u4_run;
WORD32 k;
UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc;
WORD32 u4_zeroes_left = u4_total_zeroes;
k = u4_total_coeff - 1;
/**************************************************************/
/* Decoding Runs for 0 < zeros left <=6 */
/**************************************************************/
pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before;
while((u4_zeroes_left > 0) && k)
{
UWORD32 u4_code;
NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3);
u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)];
u4_run = u4_code >> 2;
FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03));
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[k--];
u4_zeroes_left -= u4_run;
u4_scan_pos -= (u4_run + 1);
}
/**************************************************************/
/* Decoding Runs End */
/**************************************************************/
/**************************************************************/
/* Copy the remaining coefficients */
/**************************************************************/
if(u4_zeroes_left < 0)
return -1;
while(k >= 0)
{
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[k--];
u4_scan_pos--;
}
}
{
WORD32 offset;
offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4;
offset = ALIGN4(offset);
ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset);
}
ps_bitstrm->u4_ofst = u4_bitstream_offset;
return 0;
}
| 173,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: my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error)
{
if (str[0] == '\0' || !g_ascii_isdigit (str[0])) {
g_value_init (value, G_TYPE_STRING);
g_value_set_string (value, str);
} else {
g_value_init (value, G_TYPE_INT);
g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10));
}
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error)
| 165,125 |
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 Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
latency_info_.Clear();
}
| 171,203 |
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: xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
/*
* Is there any DTD definition ?
*/
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
NEXT;
/*
* Parse the succession of Markup declarations and
* PEReferences.
* Subsequence (markupdecl | PEReference | S)*
*/
while (RAW != ']') {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
break;
}
}
if (RAW == ']') {
NEXT;
SKIP_BLANKS;
}
}
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
/*
* Is there any DTD definition ?
*/
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
NEXT;
/*
* Parse the succession of Markup declarations and
* PEReferences.
* Subsequence (markupdecl | PEReference | S)*
*/
while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
break;
}
}
if (RAW == ']') {
NEXT;
SKIP_BLANKS;
}
}
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
| 171,293 |
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 ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
| 170,979 |
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: DefragIPv4NoDataTest(void)
{
DefragContext *dc = NULL;
Packet *p = NULL;
int id = 12;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
/* This packet has an offset > 0, more frags set to 0 and no data. */
p = BuildTestPacket(id, 1, 0, 'A', 0);
if (p == NULL)
goto end;
/* We do not expect a packet returned. */
if (Defrag(NULL, NULL, p, NULL) != NULL)
goto end;
/* The fragment should have been ignored so no fragments should
* have been allocated from the pool. */
if (dc->frag_pool->outstanding != 0)
return 0;
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p != NULL)
SCFree(p);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragIPv4NoDataTest(void)
{
DefragContext *dc = NULL;
Packet *p = NULL;
int id = 12;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
/* This packet has an offset > 0, more frags set to 0 and no data. */
p = BuildTestPacket(IPPROTO_ICMP, id, 1, 0, 'A', 0);
if (p == NULL)
goto end;
/* We do not expect a packet returned. */
if (Defrag(NULL, NULL, p, NULL) != NULL)
goto end;
/* The fragment should have been ignored so no fragments should
* have been allocated from the pool. */
if (dc->frag_pool->outstanding != 0)
return 0;
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p != NULL)
SCFree(p);
DefragDestroy();
return ret;
}
| 168,296 |
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: HistogramBase* SparseHistogram::FactoryGet(const std::string& name,
int32_t flags) {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
if (!histogram) {
PersistentMemoryAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
SPARSE_HISTOGRAM, name, 0, 0, nullptr, flags, &histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags &= ~HistogramBase::kIsPersistent;
tentative_histogram.reset(new SparseHistogram(name));
tentative_histogram->SetFlags(flags);
}
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
DCHECK_EQ(SPARSE_HISTOGRAM, histogram->GetHistogramType());
return histogram;
}
Commit Message: Convert DCHECKs to CHECKs for histogram types
When a histogram is looked up by name, there is currently a DCHECK that
verifies the type of the stored histogram matches the expected type.
A mismatch represents a significant problem because the returned
HistogramBase is cast to a Histogram in ValidateRangeChecksum,
potentially causing a crash.
This CL converts the DCHECK to a CHECK to prevent the possibility of
type confusion in release builds.
BUG=651443
[email protected]
Review-Url: https://codereview.chromium.org/2381893003
Cr-Commit-Position: refs/heads/master@{#421929}
CWE ID: CWE-476 | HistogramBase* SparseHistogram::FactoryGet(const std::string& name,
int32_t flags) {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
if (!histogram) {
PersistentMemoryAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
SPARSE_HISTOGRAM, name, 0, 0, nullptr, flags, &histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags &= ~HistogramBase::kIsPersistent;
tentative_histogram.reset(new SparseHistogram(name));
tentative_histogram->SetFlags(flags);
}
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
CHECK_EQ(SPARSE_HISTOGRAM, histogram->GetHistogramType());
return histogram;
}
| 172,494 |
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 long Chapters::Atom::GetStartTimecode() const
{
return m_start_timecode;
}
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 | long long Chapters::Atom::GetStartTimecode() const
| 174,356 |
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 call_console_drivers(unsigned start, unsigned end)
{
unsigned cur_index, start_print;
static int msg_level = -1;
BUG_ON(((int)(start - end)) > 0);
cur_index = start;
start_print = start;
while (cur_index != end) {
if (msg_level < 0 && ((end - cur_index) > 2)) {
/* strip log prefix */
cur_index += log_prefix(&LOG_BUF(cur_index), &msg_level, NULL);
start_print = cur_index;
}
while (cur_index != end) {
char c = LOG_BUF(cur_index);
cur_index++;
if (c == '\n') {
if (msg_level < 0) {
/*
* printk() has already given us loglevel tags in
* the buffer. This code is here in case the
* log buffer has wrapped right round and scribbled
* on those tags
*/
msg_level = default_message_loglevel;
}
_call_console_drivers(start_print, cur_index, msg_level);
msg_level = -1;
start_print = cur_index;
break;
}
}
}
_call_console_drivers(start_print, end, msg_level);
}
Commit Message: printk: fix buffer overflow when calling log_prefix function from call_console_drivers
This patch corrects a buffer overflow in kernels from 3.0 to 3.4 when calling
log_prefix() function from call_console_drivers().
This bug existed in previous releases but has been revealed with commit
162a7e7500f9664636e649ba59defe541b7c2c60 (2.6.39 => 3.0) that made changes
about how to allocate memory for early printk buffer (use of memblock_alloc).
It disappears with commit 7ff9554bb578ba02166071d2d487b7fc7d860d62 (3.4 => 3.5)
that does a refactoring of printk buffer management.
In log_prefix(), the access to "p[0]", "p[1]", "p[2]" or
"simple_strtoul(&p[1], &endp, 10)" may cause a buffer overflow as this
function is called from call_console_drivers by passing "&LOG_BUF(cur_index)"
where the index must be masked to do not exceed the buffer's boundary.
The trick is to prepare in call_console_drivers() a buffer with the necessary
data (PRI field of syslog message) to be safely evaluated in log_prefix().
This patch can be applied to stable kernel branches 3.0.y, 3.2.y and 3.4.y.
Without this patch, one can freeze a server running this loop from shell :
$ export DUMMY=`cat /dev/urandom | tr -dc '12345AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn' | head -c255`
$ while true do ; echo $DUMMY > /dev/kmsg ; done
The "server freeze" depends on where memblock_alloc does allocate printk buffer :
if the buffer overflow is inside another kernel allocation the problem may not
be revealed, else the server may hangs up.
Signed-off-by: Alexandre SIMON <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | static void call_console_drivers(unsigned start, unsigned end)
{
unsigned cur_index, start_print;
static int msg_level = -1;
BUG_ON(((int)(start - end)) > 0);
cur_index = start;
start_print = start;
while (cur_index != end) {
if (msg_level < 0 && ((end - cur_index) > 2)) {
/*
* prepare buf_prefix, as a contiguous array,
* to be processed by log_prefix function
*/
char buf_prefix[SYSLOG_PRI_MAX_LENGTH+1];
unsigned i;
for (i = 0; i < ((end - cur_index)) && (i < SYSLOG_PRI_MAX_LENGTH); i++) {
buf_prefix[i] = LOG_BUF(cur_index + i);
}
buf_prefix[i] = '\0'; /* force '\0' as last string character */
/* strip log prefix */
cur_index += log_prefix((const char *)&buf_prefix, &msg_level, NULL);
start_print = cur_index;
}
while (cur_index != end) {
char c = LOG_BUF(cur_index);
cur_index++;
if (c == '\n') {
if (msg_level < 0) {
/*
* printk() has already given us loglevel tags in
* the buffer. This code is here in case the
* log buffer has wrapped right round and scribbled
* on those tags
*/
msg_level = default_message_loglevel;
}
_call_console_drivers(start_print, cur_index, msg_level);
msg_level = -1;
start_print = cur_index;
break;
}
}
}
_call_console_drivers(start_print, end, msg_level);
}
| 166,126 |
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: horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
return 1;
}
| 166,887 |
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 __u32 dccp_v6_init_sequence(struct sk_buff *skb)
{
return secure_dccpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32,
ipv6_hdr(skb)->saddr.s6_addr32,
dccp_hdr(skb)->dccph_dport,
dccp_hdr(skb)->dccph_sport );
}
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: | static inline __u32 dccp_v6_init_sequence(struct sk_buff *skb)
static inline __u64 dccp_v6_init_sequence(struct sk_buff *skb)
{
return secure_dccpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32,
ipv6_hdr(skb)->saddr.s6_addr32,
dccp_hdr(skb)->dccph_dport,
dccp_hdr(skb)->dccph_sport );
}
| 165,771 |
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 tls1_change_cipher_state(SSL *s, int which)
{
static const unsigned char empty[]="";
unsigned char *p,*mac_secret;
unsigned char *exp_label;
unsigned char tmp1[EVP_MAX_KEY_LENGTH];
unsigned char tmp2[EVP_MAX_KEY_LENGTH];
unsigned char iv1[EVP_MAX_IV_LENGTH*2];
unsigned char iv2[EVP_MAX_IV_LENGTH*2];
unsigned char *ms,*key,*iv;
int client_write;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
const SSL_COMP *comp;
#endif
const EVP_MD *m;
int mac_type;
int *mac_secret_size;
EVP_MD_CTX *mac_ctx;
EVP_PKEY *mac_key;
int is_export,n,i,j,k,exp_label_len,cl;
int reuse_dd = 0;
is_export=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
c=s->s3->tmp.new_sym_enc;
m=s->s3->tmp.new_hash;
mac_type = s->s3->tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp=s->s3->tmp.new_compression;
#endif
#ifdef KSSL_DEBUG
printf("tls1_change_cipher_state(which= %d) w/\n", which);
printf("\talg= %ld/%ld, comp= %p\n",
s->s3->tmp.new_cipher->algorithm_mkey,
s->s3->tmp.new_cipher->algorithm_auth,
comp);
printf("\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c);
printf("\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n",
c->nid,c->block_size,c->key_len,c->iv_len);
printf("\tkey_block: len= %d, data= ", s->s3->tmp.key_block_length);
{
int i;
for (i=0; i<s->s3->tmp.key_block_length; i++)
printf("%02x", s->s3->tmp.key_block[i]); printf("\n");
}
#endif /* KSSL_DEBUG */
if (which & SSL3_CC_READ)
{
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
goto err;
else
/* make sure it's intialized in case we exit later with an error */
EVP_CIPHER_CTX_init(s->enc_read_ctx);
dd= s->enc_read_ctx;
mac_ctx=ssl_replace_hash(&s->read_hash,NULL);
#ifndef OPENSSL_NO_COMP
if (s->expand != NULL)
{
COMP_CTX_free(s->expand);
s->expand=NULL;
}
if (comp != NULL)
{
s->expand=COMP_CTX_new(comp->method);
if (s->expand == NULL)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
if (s->s3->rrec.comp == NULL)
s->s3->rrec.comp=(unsigned char *)
OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
if (s->s3->rrec.comp == NULL)
goto err;
}
#endif
/* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
if (s->version != DTLS1_VERSION)
memset(&(s->s3->read_sequence[0]),0,8);
mac_secret= &(s->s3->read_mac_secret[0]);
mac_secret_size=&(s->s3->read_mac_secret_size);
}
else
{
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->enc_write_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
goto err;
else
/* make sure it's intialized in case we exit later with an error */
EVP_CIPHER_CTX_init(s->enc_write_ctx);
dd= s->enc_write_ctx;
mac_ctx = ssl_replace_hash(&s->write_hash,NULL);
#ifndef OPENSSL_NO_COMP
if (s->compress != NULL)
{
s->compress=COMP_CTX_new(comp->method);
if (s->compress == NULL)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
if (s->version != DTLS1_VERSION)
memset(&(s->s3->write_sequence[0]),0,8);
mac_secret= &(s->s3->write_mac_secret[0]);
mac_secret_size = &(s->s3->write_mac_secret_size);
}
if (reuse_dd)
EVP_CIPHER_CTX_cleanup(dd);
p=s->s3->tmp.key_block;
i=*mac_secret_size=s->s3->tmp.new_mac_secret_size;
cl=EVP_CIPHER_key_length(c);
j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
/* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
/* If GCM mode only part of IV comes from PRF */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
k = EVP_GCM_TLS_FIXED_IV_LEN;
else
k=EVP_CIPHER_iv_length(c);
if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ))
{
ms= &(p[ 0]); n=i+i;
key= &(p[ n]); n+=j+j;
iv= &(p[ n]); n+=k+k;
exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST;
exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
client_write=1;
}
else
{
n=i;
ms= &(p[ n]); n+=i+j;
key= &(p[ n]); n+=j+k;
iv= &(p[ n]); n+=k;
exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST;
exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
client_write=0;
}
if (n > s->s3->tmp.key_block_length)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret,ms,i);
if (!(EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER))
{
mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
mac_secret,*mac_secret_size);
EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key);
EVP_PKEY_free(mac_key);
}
#ifdef TLS_DEBUG
printf("which = %04X\nmac key=",which);
{ int z; for (z=0; z<i; z++) printf("%02X%c",ms[z],((z+1)%16)?' ':'\n'); }
#endif
if (is_export)
{
/* In here I set both the read and write key/iv to the
* same value since only the correct one will be used :-).
*/
if (!tls1_PRF(ssl_get_algorithm2(s),
exp_label,exp_label_len,
s->s3->client_random,SSL3_RANDOM_SIZE,
s->s3->server_random,SSL3_RANDOM_SIZE,
NULL,0,NULL,0,
key,j,tmp1,tmp2,EVP_CIPHER_key_length(c)))
goto err2;
key=tmp1;
if (k > 0)
{
if (!tls1_PRF(ssl_get_algorithm2(s),
TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE,
s->s3->client_random,SSL3_RANDOM_SIZE,
s->s3->server_random,SSL3_RANDOM_SIZE,
NULL,0,NULL,0,
empty,0,iv1,iv2,k*2))
goto err2;
if (client_write)
iv=iv1;
else
iv= &(iv1[k]);
}
}
s->session->key_arg_length=0;
#ifdef KSSL_DEBUG
{
int i;
printf("EVP_CipherInit_ex(dd,c,key=,iv=,which)\n");
printf("\tkey= "); for (i=0; i<c->key_len; i++) printf("%02x", key[i]);
printf("\n");
printf("\t iv= "); for (i=0; i<c->iv_len; i++) printf("%02x", iv[i]);
printf("\n");
}
#endif /* KSSL_DEBUG */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
{
EVP_CipherInit_ex(dd,c,NULL,key,NULL,(which & SSL3_CC_WRITE));
EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv);
}
else
EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE));
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size)
EVP_CIPHER_CTX_ctrl(dd,EVP_CTRL_AEAD_SET_MAC_KEY,
*mac_secret_size,mac_secret);
#ifdef TLS_DEBUG
printf("which = %04X\nkey=",which);
{ int z; for (z=0; z<EVP_CIPHER_key_length(c); z++) printf("%02X%c",key[z],((z+1)%16)?' ':'\n'); }
printf("\niv=");
{ int z; for (z=0; z<k; z++) printf("%02X%c",iv[z],((z+1)%16)?' ':'\n'); }
printf("\n");
#endif
OPENSSL_cleanse(tmp1,sizeof(tmp1));
OPENSSL_cleanse(tmp2,sizeof(tmp1));
OPENSSL_cleanse(iv1,sizeof(iv1));
OPENSSL_cleanse(iv2,sizeof(iv2));
return(1);
err:
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_MALLOC_FAILURE);
err2:
return(0);
}
Commit Message:
CWE ID: CWE-310 | int tls1_change_cipher_state(SSL *s, int which)
{
static const unsigned char empty[]="";
unsigned char *p,*mac_secret;
unsigned char *exp_label;
unsigned char tmp1[EVP_MAX_KEY_LENGTH];
unsigned char tmp2[EVP_MAX_KEY_LENGTH];
unsigned char iv1[EVP_MAX_IV_LENGTH*2];
unsigned char iv2[EVP_MAX_IV_LENGTH*2];
unsigned char *ms,*key,*iv;
int client_write;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
const SSL_COMP *comp;
#endif
const EVP_MD *m;
int mac_type;
int *mac_secret_size;
EVP_MD_CTX *mac_ctx;
EVP_PKEY *mac_key;
int is_export,n,i,j,k,exp_label_len,cl;
int reuse_dd = 0;
is_export=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
c=s->s3->tmp.new_sym_enc;
m=s->s3->tmp.new_hash;
mac_type = s->s3->tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp=s->s3->tmp.new_compression;
#endif
#ifdef KSSL_DEBUG
printf("tls1_change_cipher_state(which= %d) w/\n", which);
printf("\talg= %ld/%ld, comp= %p\n",
s->s3->tmp.new_cipher->algorithm_mkey,
s->s3->tmp.new_cipher->algorithm_auth,
comp);
printf("\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c);
printf("\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n",
c->nid,c->block_size,c->key_len,c->iv_len);
printf("\tkey_block: len= %d, data= ", s->s3->tmp.key_block_length);
{
int i;
for (i=0; i<s->s3->tmp.key_block_length; i++)
printf("%02x", s->s3->tmp.key_block[i]); printf("\n");
}
#endif /* KSSL_DEBUG */
if (which & SSL3_CC_READ)
{
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
goto err;
else
/* make sure it's intialized in case we exit later with an error */
EVP_CIPHER_CTX_init(s->enc_read_ctx);
dd= s->enc_read_ctx;
mac_ctx=ssl_replace_hash(&s->read_hash,NULL);
#ifndef OPENSSL_NO_COMP
if (s->expand != NULL)
{
COMP_CTX_free(s->expand);
s->expand=NULL;
}
if (comp != NULL)
{
s->expand=COMP_CTX_new(comp->method);
if (s->expand == NULL)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
if (s->s3->rrec.comp == NULL)
s->s3->rrec.comp=(unsigned char *)
OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
if (s->s3->rrec.comp == NULL)
goto err;
}
#endif
/* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
if (s->version != DTLS1_VERSION)
memset(&(s->s3->read_sequence[0]),0,8);
mac_secret= &(s->s3->read_mac_secret[0]);
mac_secret_size=&(s->s3->read_mac_secret_size);
}
else
{
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
reuse_dd = 1;
else if ((s->enc_write_ctx=EVP_CIPHER_CTX_new()) == NULL)
goto err;
dd= s->enc_write_ctx;
if (SSL_IS_DTLS(s))
{
mac_ctx = EVP_MD_CTX_create();
if (!mac_ctx)
goto err;
s->write_hash = mac_ctx;
}
else
mac_ctx = ssl_replace_hash(&s->write_hash,NULL);
#ifndef OPENSSL_NO_COMP
if (s->compress != NULL)
{
s->compress=COMP_CTX_new(comp->method);
if (s->compress == NULL)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
if (s->version != DTLS1_VERSION)
memset(&(s->s3->write_sequence[0]),0,8);
mac_secret= &(s->s3->write_mac_secret[0]);
mac_secret_size = &(s->s3->write_mac_secret_size);
}
if (reuse_dd)
EVP_CIPHER_CTX_cleanup(dd);
p=s->s3->tmp.key_block;
i=*mac_secret_size=s->s3->tmp.new_mac_secret_size;
cl=EVP_CIPHER_key_length(c);
j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
/* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
/* If GCM mode only part of IV comes from PRF */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
k = EVP_GCM_TLS_FIXED_IV_LEN;
else
k=EVP_CIPHER_iv_length(c);
if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ))
{
ms= &(p[ 0]); n=i+i;
key= &(p[ n]); n+=j+j;
iv= &(p[ n]); n+=k+k;
exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST;
exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
client_write=1;
}
else
{
n=i;
ms= &(p[ n]); n+=i+j;
key= &(p[ n]); n+=j+k;
iv= &(p[ n]); n+=k;
exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST;
exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
client_write=0;
}
if (n > s->s3->tmp.key_block_length)
{
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret,ms,i);
if (!(EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER))
{
mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
mac_secret,*mac_secret_size);
EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key);
EVP_PKEY_free(mac_key);
}
#ifdef TLS_DEBUG
printf("which = %04X\nmac key=",which);
{ int z; for (z=0; z<i; z++) printf("%02X%c",ms[z],((z+1)%16)?' ':'\n'); }
#endif
if (is_export)
{
/* In here I set both the read and write key/iv to the
* same value since only the correct one will be used :-).
*/
if (!tls1_PRF(ssl_get_algorithm2(s),
exp_label,exp_label_len,
s->s3->client_random,SSL3_RANDOM_SIZE,
s->s3->server_random,SSL3_RANDOM_SIZE,
NULL,0,NULL,0,
key,j,tmp1,tmp2,EVP_CIPHER_key_length(c)))
goto err2;
key=tmp1;
if (k > 0)
{
if (!tls1_PRF(ssl_get_algorithm2(s),
TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE,
s->s3->client_random,SSL3_RANDOM_SIZE,
s->s3->server_random,SSL3_RANDOM_SIZE,
NULL,0,NULL,0,
empty,0,iv1,iv2,k*2))
goto err2;
if (client_write)
iv=iv1;
else
iv= &(iv1[k]);
}
}
s->session->key_arg_length=0;
#ifdef KSSL_DEBUG
{
int i;
printf("EVP_CipherInit_ex(dd,c,key=,iv=,which)\n");
printf("\tkey= "); for (i=0; i<c->key_len; i++) printf("%02x", key[i]);
printf("\n");
printf("\t iv= "); for (i=0; i<c->iv_len; i++) printf("%02x", iv[i]);
printf("\n");
}
#endif /* KSSL_DEBUG */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
{
EVP_CipherInit_ex(dd,c,NULL,key,NULL,(which & SSL3_CC_WRITE));
EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv);
}
else
EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE));
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size)
EVP_CIPHER_CTX_ctrl(dd,EVP_CTRL_AEAD_SET_MAC_KEY,
*mac_secret_size,mac_secret);
#ifdef TLS_DEBUG
printf("which = %04X\nkey=",which);
{ int z; for (z=0; z<EVP_CIPHER_key_length(c); z++) printf("%02X%c",key[z],((z+1)%16)?' ':'\n'); }
printf("\niv=");
{ int z; for (z=0; z<k; z++) printf("%02X%c",iv[z],((z+1)%16)?' ':'\n'); }
printf("\n");
#endif
OPENSSL_cleanse(tmp1,sizeof(tmp1));
OPENSSL_cleanse(tmp2,sizeof(tmp1));
OPENSSL_cleanse(iv1,sizeof(iv1));
OPENSSL_cleanse(iv2,sizeof(iv2));
return(1);
err:
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_MALLOC_FAILURE);
err2:
return(0);
}
| 165,335 |
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: main (int argc, char **argv)
{
char const *val;
bool somefailed = false;
struct outstate outstate;
struct stat tmpoutst;
char numbuf[LINENUM_LENGTH_BOUND + 1];
bool written_to_rejname = false;
bool apply_empty_patch = false;
mode_t file_type;
int outfd = -1;
bool have_git_diff = false;
exit_failure = 2;
set_program_name (argv[0]);
init_time ();
setbuf(stderr, serrbuf);
bufsize = 8 * 1024;
buf = xmalloc (bufsize);
strippath = -1;
val = getenv ("QUOTING_STYLE");
{
int i = val ? argmatch (val, quoting_style_args, 0, 0) : -1;
set_quoting_style ((struct quoting_options *) 0,
i < 0 ? shell_quoting_style : (enum quoting_style) i);
}
posixly_correct = getenv ("POSIXLY_CORRECT") != 0;
backup_if_mismatch = ! posixly_correct;
patch_get = ((val = getenv ("PATCH_GET"))
? numeric_string (val, true, "PATCH_GET value")
: 0);
val = getenv ("SIMPLE_BACKUP_SUFFIX");
simple_backup_suffix = val && *val ? val : ".orig";
if ((version_control = getenv ("PATCH_VERSION_CONTROL")))
version_control_context = "$PATCH_VERSION_CONTROL";
else if ((version_control = getenv ("VERSION_CONTROL")))
version_control_context = "$VERSION_CONTROL";
init_backup_hash_table ();
init_files_to_delete ();
init_files_to_output ();
/* parse switches */
Argc = argc;
Argv = argv;
get_some_switches();
/* Make get_date() assume that context diff headers use UTC. */
if (set_utc)
setenv ("TZ", "UTC", 1);
if (make_backups | backup_if_mismatch)
backup_type = get_version (version_control_context, version_control);
init_output (&outstate);
if (outfile)
outstate.ofp = open_outfile (outfile);
/* Make sure we clean up in case of disaster. */
set_signals (false);
if (inname && outfile)
{
/* When an input and an output filename is given and the patch is
empty, copy the input file to the output file. In this case, the
input file must be a regular file (i.e., symlinks cannot be copied
this way). */
apply_empty_patch = true;
file_type = S_IFREG;
inerrno = -1;
}
for (
open_patch_file (patchname);
there_is_another_patch (! (inname || posixly_correct), &file_type)
|| apply_empty_patch;
reinitialize_almost_everything(),
apply_empty_patch = false
) { /* for each patch in patch file */
int hunk = 0;
int failed = 0;
bool mismatch = false;
char const *outname = NULL;
if (have_git_diff != pch_git_diff ())
{
if (have_git_diff)
}
have_git_diff = ! have_git_diff;
}
if (TMPREJNAME_needs_removal)
{
if (rejfp)
{
fclose (rejfp);
rejfp = NULL;
}
remove_if_needed (TMPREJNAME, &TMPREJNAME_needs_removal);
}
if (TMPOUTNAME_needs_removal)
{
if (outfd != -1)
{
close (outfd);
outfd = -1;
}
remove_if_needed (TMPOUTNAME, &TMPOUTNAME_needs_removal);
}
if (! skip_rest_of_patch && ! file_type)
{
say ("File %s: can't change file type from 0%o to 0%o.\n",
quotearg (inname),
pch_mode (reverse) & S_IFMT,
pch_mode (! reverse) & S_IFMT);
skip_rest_of_patch = true;
somefailed = true;
}
if (! skip_rest_of_patch)
{
if (outfile)
outname = outfile;
else if (pch_copy () || pch_rename ())
outname = pch_name (! strcmp (inname, pch_name (OLD)));
else
outname = inname;
}
if (pch_git_diff () && ! skip_rest_of_patch)
{
struct stat outstat;
int outerrno = 0;
/* Try to recognize concatenated git diffs based on the SHA1 hashes
in the headers. Will not always succeed for patches that rename
or copy files. */
if (! strcmp (inname, outname))
{
if (inerrno == -1)
inerrno = stat_file (inname, &instat);
outstat = instat;
outerrno = inerrno;
}
else
outerrno = stat_file (outname, &outstat);
if (! outerrno)
{
if (has_queued_output (&outstat))
{
output_files (&outstat);
outerrno = stat_file (outname, &outstat);
inerrno = -1;
}
if (! outerrno)
set_queued_output (&outstat, true);
}
}
if (! skip_rest_of_patch)
{
if (! get_input_file (inname, outname, file_type))
{
skip_rest_of_patch = true;
somefailed = true;
}
}
if (read_only_behavior != RO_IGNORE
&& ! inerrno && ! S_ISLNK (instat.st_mode)
&& access (inname, W_OK) != 0)
{
say ("File %s is read-only; ", quotearg (inname));
if (read_only_behavior == RO_WARN)
say ("trying to patch anyway\n");
else
{
say ("refusing to patch\n");
skip_rest_of_patch = true;
somefailed = true;
}
}
tmpoutst.st_size = -1;
outfd = make_tempfile (&TMPOUTNAME, 'o', outname,
O_WRONLY | binary_transput,
instat.st_mode & S_IRWXUGO);
TMPOUTNAME_needs_removal = true;
if (diff_type == ED_DIFF) {
outstate.zero_output = false;
somefailed |= skip_rest_of_patch;
do_ed_script (inname, TMPOUTNAME, &TMPOUTNAME_needs_removal,
outstate.ofp);
if (! dry_run && ! outfile && ! skip_rest_of_patch)
{
if (fstat (outfd, &tmpoutst) != 0)
pfatal ("%s", TMPOUTNAME);
outstate.zero_output = tmpoutst.st_size == 0;
}
close (outfd);
outfd = -1;
} else {
int got_hunk;
bool apply_anyway = merge; /* don't try to reverse when merging */
if (! skip_rest_of_patch && diff_type == GIT_BINARY_DIFF) {
say ("File %s: git binary diffs are not supported.\n",
quotearg (outname));
skip_rest_of_patch = true;
somefailed = true;
}
/* initialize the patched file */
if (! skip_rest_of_patch && ! outfile)
{
init_output (&outstate);
outstate.ofp = fdopen(outfd, binary_transput ? "wb" : "w");
if (! outstate.ofp)
pfatal ("%s", TMPOUTNAME);
}
/* find out where all the lines are */
if (!skip_rest_of_patch) {
scan_input (inname, file_type);
if (verbosity != SILENT)
{
bool renamed = strcmp (inname, outname);
say ("%s %s %s%c",
dry_run ? "checking" : "patching",
S_ISLNK (file_type) ? "symbolic link" : "file",
quotearg (outname), renamed ? ' ' : '\n');
if (renamed)
say ("(%s from %s)\n",
pch_copy () ? "copied" :
(pch_rename () ? "renamed" : "read"),
inname);
if (verbosity == VERBOSE)
say ("Using Plan %s...\n", using_plan_a ? "A" : "B");
}
}
/* from here on, open no standard i/o files, because malloc */
/* might misfire and we can't catch it easily */
/* apply each hunk of patch */
while (0 < (got_hunk = another_hunk (diff_type, reverse)))
{
lin where = 0; /* Pacify 'gcc -Wall'. */
lin newwhere;
lin fuzz = 0;
lin mymaxfuzz;
if (merge)
{
/* When in merge mode, don't apply with fuzz. */
mymaxfuzz = 0;
}
else
{
lin prefix_context = pch_prefix_context ();
lin suffix_context = pch_suffix_context ();
lin context = (prefix_context < suffix_context
? suffix_context : prefix_context);
mymaxfuzz = (maxfuzz < context ? maxfuzz : context);
}
hunk++;
if (!skip_rest_of_patch) {
do {
where = locate_hunk(fuzz);
if (! where || fuzz || in_offset)
mismatch = true;
if (hunk == 1 && ! where && ! (force | apply_anyway)
&& reverse == reverse_flag_specified) {
/* dwim for reversed patch? */
if (!pch_swap()) {
say (
"Not enough memory to try swapped hunk! Assuming unswapped.\n");
continue;
}
/* Try again. */
where = locate_hunk (fuzz);
if (where
&& (ok_to_reverse
("%s patch detected!",
(reverse
? "Unreversed"
: "Reversed (or previously applied)"))))
reverse = ! reverse;
else
{
/* Put it back to normal. */
if (! pch_swap ())
fatal ("lost hunk on alloc error!");
if (where)
{
apply_anyway = true;
fuzz--; /* Undo '++fuzz' below. */
where = 0;
}
}
}
} while (!skip_rest_of_patch && !where
&& ++fuzz <= mymaxfuzz);
if (skip_rest_of_patch) { /* just got decided */
if (outstate.ofp && ! outfile)
{
fclose (outstate.ofp);
outstate.ofp = 0;
outfd = -1;
}
}
}
newwhere = (where ? where : pch_first()) + out_offset;
if (skip_rest_of_patch
|| (merge && ! merge_hunk (hunk, &outstate, where,
&somefailed))
|| (! merge
&& ((where == 1 && pch_says_nonexistent (reverse) == 2
&& instat.st_size)
|| ! where
|| ! apply_hunk (&outstate, where))))
{
abort_hunk (outname, ! failed, reverse);
failed++;
if (verbosity == VERBOSE ||
(! skip_rest_of_patch && verbosity != SILENT))
say ("Hunk #%d %s at %s%s.\n", hunk,
skip_rest_of_patch ? "ignored" : "FAILED",
format_linenum (numbuf, newwhere),
! skip_rest_of_patch && check_line_endings (newwhere)
? " (different line endings)" : "");
}
else if (! merge &&
(verbosity == VERBOSE
|| (verbosity != SILENT && (fuzz || in_offset))))
{
say ("Hunk #%d succeeded at %s", hunk,
format_linenum (numbuf, newwhere));
if (fuzz)
say (" with fuzz %s", format_linenum (numbuf, fuzz));
if (in_offset)
say (" (offset %s line%s)",
format_linenum (numbuf, in_offset),
"s" + (in_offset == 1));
say (".\n");
}
}
if (!skip_rest_of_patch)
{
if (got_hunk < 0 && using_plan_a)
{
if (outfile)
fatal ("out of memory using Plan A");
say ("\n\nRan out of memory using Plan A -- trying again...\n\n");
if (outstate.ofp)
{
fclose (outstate.ofp);
outstate.ofp = 0;
}
continue;
}
/* Finish spewing out the new file. */
if (! spew_output (&outstate, &tmpoutst))
{
say ("Skipping patch.\n");
skip_rest_of_patch = true;
}
}
}
/* and put the output where desired */
ignore_signals ();
if (! skip_rest_of_patch && ! outfile) {
bool backup = make_backups
|| (backup_if_mismatch && (mismatch | failed));
if (outstate.zero_output
&& (remove_empty_files
|| (pch_says_nonexistent (! reverse) == 2
&& ! posixly_correct)
|| S_ISLNK (file_type)))
{
if (! dry_run)
output_file (NULL, NULL, NULL, outname,
(inname == outname) ? &instat : NULL,
file_type | 0, backup);
}
else
{
if (! outstate.zero_output
&& pch_says_nonexistent (! reverse) == 2
&& (remove_empty_files || ! posixly_correct)
&& ! (merge && somefailed))
{
mismatch = true;
somefailed = true;
if (verbosity != SILENT)
say ("Not deleting file %s as content differs from patch\n",
quotearg (outname));
}
if (! dry_run)
{
mode_t old_mode = pch_mode (reverse);
mode_t new_mode = pch_mode (! reverse);
bool set_mode = new_mode && old_mode != new_mode;
/* Avoid replacing files when nothing has changed. */
if (failed < hunk || diff_type == ED_DIFF || set_mode
|| pch_copy () || pch_rename ())
{
enum file_attributes attr = 0;
struct timespec new_time = pch_timestamp (! reverse);
mode_t mode = file_type |
((new_mode ? new_mode : instat.st_mode) & S_IRWXUGO);
if ((set_time | set_utc) && new_time.tv_sec != -1)
{
struct timespec old_time = pch_timestamp (reverse);
if (! force && ! inerrno
&& pch_says_nonexistent (reverse) != 2
&& old_time.tv_sec != -1
&& timespec_cmp (old_time,
get_stat_mtime (&instat)))
say ("Not setting time of file %s "
"(time mismatch)\n",
quotearg (outname));
else if (! force && (mismatch | failed))
say ("Not setting time of file %s "
"(contents mismatch)\n",
quotearg (outname));
else
attr |= FA_TIMES;
}
if (inerrno)
set_file_attributes (TMPOUTNAME, attr, NULL, NULL,
mode, &new_time);
else
{
attr |= FA_IDS | FA_MODE | FA_XATTRS;
set_file_attributes (TMPOUTNAME, attr, inname, &instat,
mode, &new_time);
}
output_file (TMPOUTNAME, &TMPOUTNAME_needs_removal,
&tmpoutst, outname, NULL, mode, backup);
if (pch_rename ())
output_file (NULL, NULL, NULL, inname, &instat,
mode, backup);
}
else
output_file (outname, NULL, &tmpoutst, NULL, NULL,
file_type | 0, backup);
}
}
}
if (diff_type != ED_DIFF) {
struct stat rejst;
if (failed) {
if (fstat (fileno (rejfp), &rejst) != 0 || fclose (rejfp) != 0)
write_fatal ();
rejfp = NULL;
somefailed = true;
say ("%d out of %d hunk%s %s", failed, hunk, "s" + (hunk == 1),
skip_rest_of_patch ? "ignored" : "FAILED");
if (outname && (! rejname || strcmp (rejname, "-") != 0)) {
char *rej = rejname;
if (!rejname) {
/* FIXME: This should really be done differently! */
const char *s = simple_backup_suffix;
size_t len;
simple_backup_suffix = ".rej";
rej = find_backup_file_name (outname, simple_backups);
len = strlen (rej);
if (rej[len - 1] == '~')
rej[len - 1] = '#';
simple_backup_suffix = s;
}
if (! dry_run)
{
say (" -- saving rejects to file %s\n", quotearg (rej));
if (rejname)
{
if (! written_to_rejname)
{
copy_file (TMPREJNAME, rejname, 0, 0,
S_IFREG | 0666, true);
written_to_rejname = true;
}
else
append_to_file (TMPREJNAME, rejname);
}
else
{
struct stat oldst;
int olderrno;
olderrno = stat_file (rej, &oldst);
if (olderrno && olderrno != ENOENT)
write_fatal ();
if (! olderrno && lookup_file_id (&oldst) == CREATED)
append_to_file (TMPREJNAME, rej);
else
move_file (TMPREJNAME, &TMPREJNAME_needs_removal,
&rejst, rej, S_IFREG | 0666, false);
}
}
else
say ("\n");
if (!rejname)
free (rej);
} else
say ("\n");
}
}
set_signals (true);
}
Commit Message:
CWE ID: CWE-22 | main (int argc, char **argv)
{
char const *val;
bool somefailed = false;
struct outstate outstate;
struct stat tmpoutst;
char numbuf[LINENUM_LENGTH_BOUND + 1];
bool written_to_rejname = false;
bool apply_empty_patch = false;
mode_t file_type;
int outfd = -1;
bool have_git_diff = false;
exit_failure = 2;
set_program_name (argv[0]);
init_time ();
setbuf(stderr, serrbuf);
bufsize = 8 * 1024;
buf = xmalloc (bufsize);
strippath = -1;
val = getenv ("QUOTING_STYLE");
{
int i = val ? argmatch (val, quoting_style_args, 0, 0) : -1;
set_quoting_style ((struct quoting_options *) 0,
i < 0 ? shell_quoting_style : (enum quoting_style) i);
}
posixly_correct = getenv ("POSIXLY_CORRECT") != 0;
backup_if_mismatch = ! posixly_correct;
patch_get = ((val = getenv ("PATCH_GET"))
? numeric_string (val, true, "PATCH_GET value")
: 0);
val = getenv ("SIMPLE_BACKUP_SUFFIX");
simple_backup_suffix = val && *val ? val : ".orig";
if ((version_control = getenv ("PATCH_VERSION_CONTROL")))
version_control_context = "$PATCH_VERSION_CONTROL";
else if ((version_control = getenv ("VERSION_CONTROL")))
version_control_context = "$VERSION_CONTROL";
init_backup_hash_table ();
init_files_to_delete ();
init_files_to_output ();
/* parse switches */
Argc = argc;
Argv = argv;
get_some_switches();
/* Make get_date() assume that context diff headers use UTC. */
if (set_utc)
setenv ("TZ", "UTC", 1);
if (make_backups | backup_if_mismatch)
backup_type = get_version (version_control_context, version_control);
init_output (&outstate);
if (outfile)
outstate.ofp = open_outfile (outfile);
/* Make sure we clean up in case of disaster. */
set_signals (false);
if (inname && outfile)
{
/* When an input and an output filename is given and the patch is
empty, copy the input file to the output file. In this case, the
input file must be a regular file (i.e., symlinks cannot be copied
this way). */
apply_empty_patch = true;
file_type = S_IFREG;
inerrno = -1;
}
for (
open_patch_file (patchname);
there_is_another_patch (! (inname || posixly_correct), &file_type)
|| apply_empty_patch;
reinitialize_almost_everything(),
apply_empty_patch = false
) { /* for each patch in patch file */
int hunk = 0;
int failed = 0;
bool mismatch = false;
char const *outname = NULL;
if (skip_rest_of_patch)
somefailed = true;
if (have_git_diff != pch_git_diff ())
{
if (have_git_diff)
}
have_git_diff = ! have_git_diff;
}
if (TMPREJNAME_needs_removal)
{
if (rejfp)
{
fclose (rejfp);
rejfp = NULL;
}
remove_if_needed (TMPREJNAME, &TMPREJNAME_needs_removal);
}
if (TMPOUTNAME_needs_removal)
{
if (outfd != -1)
{
close (outfd);
outfd = -1;
}
remove_if_needed (TMPOUTNAME, &TMPOUTNAME_needs_removal);
}
if (! skip_rest_of_patch && ! file_type)
{
say ("File %s: can't change file type from 0%o to 0%o.\n",
quotearg (inname),
pch_mode (reverse) & S_IFMT,
pch_mode (! reverse) & S_IFMT);
skip_rest_of_patch = true;
somefailed = true;
}
if (! skip_rest_of_patch)
{
if (outfile)
outname = outfile;
else if (pch_copy () || pch_rename ())
outname = pch_name (! strcmp (inname, pch_name (OLD)));
else
outname = inname;
}
if (pch_git_diff () && ! skip_rest_of_patch)
{
struct stat outstat;
int outerrno = 0;
/* Try to recognize concatenated git diffs based on the SHA1 hashes
in the headers. Will not always succeed for patches that rename
or copy files. */
if (! strcmp (inname, outname))
{
if (inerrno == -1)
inerrno = stat_file (inname, &instat);
outstat = instat;
outerrno = inerrno;
}
else
outerrno = stat_file (outname, &outstat);
if (! outerrno)
{
if (has_queued_output (&outstat))
{
output_files (&outstat);
outerrno = stat_file (outname, &outstat);
inerrno = -1;
}
if (! outerrno)
set_queued_output (&outstat, true);
}
}
if (! skip_rest_of_patch)
{
if (! get_input_file (inname, outname, file_type))
{
skip_rest_of_patch = true;
somefailed = true;
}
}
if (read_only_behavior != RO_IGNORE
&& ! inerrno && ! S_ISLNK (instat.st_mode)
&& access (inname, W_OK) != 0)
{
say ("File %s is read-only; ", quotearg (inname));
if (read_only_behavior == RO_WARN)
say ("trying to patch anyway\n");
else
{
say ("refusing to patch\n");
skip_rest_of_patch = true;
somefailed = true;
}
}
tmpoutst.st_size = -1;
outfd = make_tempfile (&TMPOUTNAME, 'o', outname,
O_WRONLY | binary_transput,
instat.st_mode & S_IRWXUGO);
TMPOUTNAME_needs_removal = true;
if (diff_type == ED_DIFF) {
outstate.zero_output = false;
somefailed |= skip_rest_of_patch;
do_ed_script (inname, TMPOUTNAME, &TMPOUTNAME_needs_removal,
outstate.ofp);
if (! dry_run && ! outfile && ! skip_rest_of_patch)
{
if (fstat (outfd, &tmpoutst) != 0)
pfatal ("%s", TMPOUTNAME);
outstate.zero_output = tmpoutst.st_size == 0;
}
close (outfd);
outfd = -1;
} else {
int got_hunk;
bool apply_anyway = merge; /* don't try to reverse when merging */
if (! skip_rest_of_patch && diff_type == GIT_BINARY_DIFF) {
say ("File %s: git binary diffs are not supported.\n",
quotearg (outname));
skip_rest_of_patch = true;
somefailed = true;
}
/* initialize the patched file */
if (! skip_rest_of_patch && ! outfile)
{
init_output (&outstate);
outstate.ofp = fdopen(outfd, binary_transput ? "wb" : "w");
if (! outstate.ofp)
pfatal ("%s", TMPOUTNAME);
}
/* find out where all the lines are */
if (!skip_rest_of_patch) {
scan_input (inname, file_type);
if (verbosity != SILENT)
{
bool renamed = strcmp (inname, outname);
say ("%s %s %s%c",
dry_run ? "checking" : "patching",
S_ISLNK (file_type) ? "symbolic link" : "file",
quotearg (outname), renamed ? ' ' : '\n');
if (renamed)
say ("(%s from %s)\n",
pch_copy () ? "copied" :
(pch_rename () ? "renamed" : "read"),
inname);
if (verbosity == VERBOSE)
say ("Using Plan %s...\n", using_plan_a ? "A" : "B");
}
}
/* from here on, open no standard i/o files, because malloc */
/* might misfire and we can't catch it easily */
/* apply each hunk of patch */
while (0 < (got_hunk = another_hunk (diff_type, reverse)))
{
lin where = 0; /* Pacify 'gcc -Wall'. */
lin newwhere;
lin fuzz = 0;
lin mymaxfuzz;
if (merge)
{
/* When in merge mode, don't apply with fuzz. */
mymaxfuzz = 0;
}
else
{
lin prefix_context = pch_prefix_context ();
lin suffix_context = pch_suffix_context ();
lin context = (prefix_context < suffix_context
? suffix_context : prefix_context);
mymaxfuzz = (maxfuzz < context ? maxfuzz : context);
}
hunk++;
if (!skip_rest_of_patch) {
do {
where = locate_hunk(fuzz);
if (! where || fuzz || in_offset)
mismatch = true;
if (hunk == 1 && ! where && ! (force | apply_anyway)
&& reverse == reverse_flag_specified) {
/* dwim for reversed patch? */
if (!pch_swap()) {
say (
"Not enough memory to try swapped hunk! Assuming unswapped.\n");
continue;
}
/* Try again. */
where = locate_hunk (fuzz);
if (where
&& (ok_to_reverse
("%s patch detected!",
(reverse
? "Unreversed"
: "Reversed (or previously applied)"))))
reverse = ! reverse;
else
{
/* Put it back to normal. */
if (! pch_swap ())
fatal ("lost hunk on alloc error!");
if (where)
{
apply_anyway = true;
fuzz--; /* Undo '++fuzz' below. */
where = 0;
}
}
}
} while (!skip_rest_of_patch && !where
&& ++fuzz <= mymaxfuzz);
if (skip_rest_of_patch) { /* just got decided */
if (outstate.ofp && ! outfile)
{
fclose (outstate.ofp);
outstate.ofp = 0;
outfd = -1;
}
}
}
newwhere = (where ? where : pch_first()) + out_offset;
if (skip_rest_of_patch
|| (merge && ! merge_hunk (hunk, &outstate, where,
&somefailed))
|| (! merge
&& ((where == 1 && pch_says_nonexistent (reverse) == 2
&& instat.st_size)
|| ! where
|| ! apply_hunk (&outstate, where))))
{
abort_hunk (outname, ! failed, reverse);
failed++;
if (verbosity == VERBOSE ||
(! skip_rest_of_patch && verbosity != SILENT))
say ("Hunk #%d %s at %s%s.\n", hunk,
skip_rest_of_patch ? "ignored" : "FAILED",
format_linenum (numbuf, newwhere),
! skip_rest_of_patch && check_line_endings (newwhere)
? " (different line endings)" : "");
}
else if (! merge &&
(verbosity == VERBOSE
|| (verbosity != SILENT && (fuzz || in_offset))))
{
say ("Hunk #%d succeeded at %s", hunk,
format_linenum (numbuf, newwhere));
if (fuzz)
say (" with fuzz %s", format_linenum (numbuf, fuzz));
if (in_offset)
say (" (offset %s line%s)",
format_linenum (numbuf, in_offset),
"s" + (in_offset == 1));
say (".\n");
}
}
if (!skip_rest_of_patch)
{
if (got_hunk < 0 && using_plan_a)
{
if (outfile)
fatal ("out of memory using Plan A");
say ("\n\nRan out of memory using Plan A -- trying again...\n\n");
if (outstate.ofp)
{
fclose (outstate.ofp);
outstate.ofp = 0;
}
continue;
}
/* Finish spewing out the new file. */
if (! spew_output (&outstate, &tmpoutst))
{
say ("Skipping patch.\n");
skip_rest_of_patch = true;
}
}
}
/* and put the output where desired */
ignore_signals ();
if (! skip_rest_of_patch && ! outfile) {
bool backup = make_backups
|| (backup_if_mismatch && (mismatch | failed));
if (outstate.zero_output
&& (remove_empty_files
|| (pch_says_nonexistent (! reverse) == 2
&& ! posixly_correct)
|| S_ISLNK (file_type)))
{
if (! dry_run)
output_file (NULL, NULL, NULL, outname,
(inname == outname) ? &instat : NULL,
file_type | 0, backup);
}
else
{
if (! outstate.zero_output
&& pch_says_nonexistent (! reverse) == 2
&& (remove_empty_files || ! posixly_correct)
&& ! (merge && somefailed))
{
mismatch = true;
somefailed = true;
if (verbosity != SILENT)
say ("Not deleting file %s as content differs from patch\n",
quotearg (outname));
}
if (! dry_run)
{
mode_t old_mode = pch_mode (reverse);
mode_t new_mode = pch_mode (! reverse);
bool set_mode = new_mode && old_mode != new_mode;
/* Avoid replacing files when nothing has changed. */
if (failed < hunk || diff_type == ED_DIFF || set_mode
|| pch_copy () || pch_rename ())
{
enum file_attributes attr = 0;
struct timespec new_time = pch_timestamp (! reverse);
mode_t mode = file_type |
((new_mode ? new_mode : instat.st_mode) & S_IRWXUGO);
if ((set_time | set_utc) && new_time.tv_sec != -1)
{
struct timespec old_time = pch_timestamp (reverse);
if (! force && ! inerrno
&& pch_says_nonexistent (reverse) != 2
&& old_time.tv_sec != -1
&& timespec_cmp (old_time,
get_stat_mtime (&instat)))
say ("Not setting time of file %s "
"(time mismatch)\n",
quotearg (outname));
else if (! force && (mismatch | failed))
say ("Not setting time of file %s "
"(contents mismatch)\n",
quotearg (outname));
else
attr |= FA_TIMES;
}
if (inerrno)
set_file_attributes (TMPOUTNAME, attr, NULL, NULL,
mode, &new_time);
else
{
attr |= FA_IDS | FA_MODE | FA_XATTRS;
set_file_attributes (TMPOUTNAME, attr, inname, &instat,
mode, &new_time);
}
output_file (TMPOUTNAME, &TMPOUTNAME_needs_removal,
&tmpoutst, outname, NULL, mode, backup);
if (pch_rename ())
output_file (NULL, NULL, NULL, inname, &instat,
mode, backup);
}
else
output_file (outname, NULL, &tmpoutst, NULL, NULL,
file_type | 0, backup);
}
}
}
if (diff_type != ED_DIFF) {
struct stat rejst;
if (failed) {
if (fstat (fileno (rejfp), &rejst) != 0 || fclose (rejfp) != 0)
write_fatal ();
rejfp = NULL;
somefailed = true;
say ("%d out of %d hunk%s %s", failed, hunk, "s" + (hunk == 1),
skip_rest_of_patch ? "ignored" : "FAILED");
if (outname && (! rejname || strcmp (rejname, "-") != 0)) {
char *rej = rejname;
if (!rejname) {
/* FIXME: This should really be done differently! */
const char *s = simple_backup_suffix;
size_t len;
simple_backup_suffix = ".rej";
rej = find_backup_file_name (outname, simple_backups);
len = strlen (rej);
if (rej[len - 1] == '~')
rej[len - 1] = '#';
simple_backup_suffix = s;
}
if (! dry_run)
{
say (" -- saving rejects to file %s\n", quotearg (rej));
if (rejname)
{
if (! written_to_rejname)
{
copy_file (TMPREJNAME, rejname, 0, 0,
S_IFREG | 0666, true);
written_to_rejname = true;
}
else
append_to_file (TMPREJNAME, rejname);
}
else
{
struct stat oldst;
int olderrno;
olderrno = stat_file (rej, &oldst);
if (olderrno && olderrno != ENOENT)
write_fatal ();
if (! olderrno && lookup_file_id (&oldst) == CREATED)
append_to_file (TMPREJNAME, rej);
else
move_file (TMPREJNAME, &TMPREJNAME_needs_removal,
&rejst, rej, S_IFREG | 0666, false);
}
}
else
say ("\n");
if (!rejname)
free (rej);
} else
say ("\n");
}
}
set_signals (true);
}
| 165,396 |
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 wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
Commit Message: Fix bug #72860: wddx_deserialize use-after-free
CWE ID: CWE-416 | static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data
&& ((st_entry *)stack->elements[i])->type != ST_FIELD) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
| 166,936 |
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 *ReadIPLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
/*
Declare variables.
*/
Image *image;
MagickBooleanType status;
register PixelPacket *q;
unsigned char magick[12], *pixels;
ssize_t count;
ssize_t y;
size_t t_count=0;
size_t length;
IPLInfo
ipl_info;
QuantumFormatType
quantum_format;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
/*
Open Image
*/
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);
}
/*
Read IPL image
*/
/*
Determine endianness
If we get back "iiii", we have LSB,"mmmm", MSB
*/
count=ReadBlob(image,4,magick);
(void) count;
if((LocaleNCompare((char *) magick,"iiii",4) == 0))
image->endian=LSBEndian;
else{
if((LocaleNCompare((char *) magick,"mmmm",4) == 0))
image->endian=MSBEndian;
else{
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
}
}
/* Skip o'er the next 8 bytes (garbage) */
count=ReadBlob(image, 8, magick);
/*
Excellent, now we read the header unimpeded.
*/
count=ReadBlob(image,4,magick);
if((LocaleNCompare((char *) magick,"data",4) != 0))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
ipl_info.size=ReadBlobLong(image);
ipl_info.width=ReadBlobLong(image);
ipl_info.height=ReadBlobLong(image);
if((ipl_info.width == 0UL) || (ipl_info.height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ipl_info.colors=ReadBlobLong(image);
if(ipl_info.colors == 3){ SetImageColorspace(image,sRGBColorspace);}
else { image->colorspace = GRAYColorspace; }
ipl_info.z=ReadBlobLong(image);
ipl_info.time=ReadBlobLong(image);
ipl_info.byteType=ReadBlobLong(image);
/* Initialize Quantum Info */
switch (ipl_info.byteType) {
case 0:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 1:
ipl_info.depth=16;
quantum_format = SignedQuantumFormat;
break;
case 2:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 3:
ipl_info.depth=32;
quantum_format = SignedQuantumFormat;
break;
case 4: ipl_info.depth=32;
quantum_format = FloatingPointQuantumFormat;
break;
case 5:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 6:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 10:
ipl_info.depth=64;
quantum_format = FloatingPointQuantumFormat;
break;
default:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
}
/*
Set number of scenes of image
*/
SetHeaderFromIPL(image, &ipl_info);
/* Thats all we need if we are pinging. */
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
length=image->columns;
quantum_type=GetQuantumType(image,exception);
do
{
SetHeaderFromIPL(image, &ipl_info);
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
printf("Length: %.20g, Memory size: %.20g\n", (double) length,(double)
image->depth);
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,quantum_format);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if(image->columns != ipl_info.width){
/*
printf("Columns not set correctly! Wanted: %.20g, got: %.20g\n",
(double) ipl_info.width, (double) image->columns);
*/
}
/*
Covert IPL binary to pixel packets
*/
if(ipl_info.colors == 1){
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else{
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RedQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
t_count++;
quantum_info = DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if(t_count < ipl_info.z * ipl_info.time){
/*
Proceed to next image.
*/
AcquireNextImage(image_info, image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (t_count < ipl_info.z*ipl_info.time);
CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadIPLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
/*
Declare variables.
*/
Image *image;
MagickBooleanType status;
register PixelPacket *q;
unsigned char magick[12], *pixels;
ssize_t count;
ssize_t y;
size_t t_count=0;
size_t length;
IPLInfo
ipl_info;
QuantumFormatType
quantum_format;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
/*
Open Image
*/
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);
}
/*
Read IPL image
*/
/*
Determine endianness
If we get back "iiii", we have LSB,"mmmm", MSB
*/
count=ReadBlob(image,4,magick);
(void) count;
if((LocaleNCompare((char *) magick,"iiii",4) == 0))
image->endian=LSBEndian;
else{
if((LocaleNCompare((char *) magick,"mmmm",4) == 0))
image->endian=MSBEndian;
else{
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
}
}
/* Skip o'er the next 8 bytes (garbage) */
count=ReadBlob(image, 8, magick);
/*
Excellent, now we read the header unimpeded.
*/
count=ReadBlob(image,4,magick);
if((LocaleNCompare((char *) magick,"data",4) != 0))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
ipl_info.size=ReadBlobLong(image);
ipl_info.width=ReadBlobLong(image);
ipl_info.height=ReadBlobLong(image);
if((ipl_info.width == 0UL) || (ipl_info.height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ipl_info.colors=ReadBlobLong(image);
if(ipl_info.colors == 3){ SetImageColorspace(image,sRGBColorspace);}
else { image->colorspace = GRAYColorspace; }
ipl_info.z=ReadBlobLong(image);
ipl_info.time=ReadBlobLong(image);
ipl_info.byteType=ReadBlobLong(image);
/* Initialize Quantum Info */
switch (ipl_info.byteType) {
case 0:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 1:
ipl_info.depth=16;
quantum_format = SignedQuantumFormat;
break;
case 2:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 3:
ipl_info.depth=32;
quantum_format = SignedQuantumFormat;
break;
case 4: ipl_info.depth=32;
quantum_format = FloatingPointQuantumFormat;
break;
case 5:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 6:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 10:
ipl_info.depth=64;
quantum_format = FloatingPointQuantumFormat;
break;
default:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
}
/*
Set number of scenes of image
*/
SetHeaderFromIPL(image, &ipl_info);
/* Thats all we need if we are pinging. */
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
length=image->columns;
quantum_type=GetQuantumType(image,exception);
do
{
SetHeaderFromIPL(image, &ipl_info);
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
printf("Length: %.20g, Memory size: %.20g\n", (double) length,(double)
image->depth);
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,quantum_format);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if(image->columns != ipl_info.width){
/*
printf("Columns not set correctly! Wanted: %.20g, got: %.20g\n",
(double) ipl_info.width, (double) image->columns);
*/
}
/*
Covert IPL binary to pixel packets
*/
if(ipl_info.colors == 1){
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else{
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RedQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
t_count++;
quantum_info = DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if(t_count < ipl_info.z * ipl_info.time){
/*
Proceed to next image.
*/
AcquireNextImage(image_info, image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (t_count < ipl_info.z*ipl_info.time);
CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,573 |
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 ImageLoader::updateFromElement()
{
Document* document = m_element->document();
if (!document->renderer())
return;
AtomicString attr = m_element->imageSourceURL();
if (attr == m_failedLoadURL)
return;
CachedResourceHandle<CachedImage> newImage = 0;
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
CachedResourceRequest request(ResourceRequest(document->completeURL(sourceURI(attr))));
request.setInitiator(element());
String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
}
if (m_loadManually) {
bool autoLoadOtherImages = document->cachedResourceLoader()->autoLoadImages();
document->cachedResourceLoader()->setAutoLoadImages(false);
newImage = new CachedImage(request.resourceRequest());
newImage->setLoading(true);
newImage->setOwningCachedResourceLoader(document->cachedResourceLoader());
document->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get());
document->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages);
} else
newImage = document->cachedResourceLoader()->requestImage(request);
if (!newImage && !pageIsBeingDismissed(document)) {
m_failedLoadURL = attr;
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
} else
clearFailedLoadURL();
} else if (!attr.isNull()) {
m_element->dispatchEvent(Event::create(eventNames().errorEvent, false, false));
}
CachedImage* oldImage = m_image.get();
if (newImage != oldImage) {
if (m_hasPendingBeforeLoadEvent) {
beforeLoadEventSender().cancelEvent(this);
m_hasPendingBeforeLoadEvent = false;
}
if (m_hasPendingLoadEvent) {
loadEventSender().cancelEvent(this);
m_hasPendingLoadEvent = false;
}
if (m_hasPendingErrorEvent && newImage) {
errorEventSender().cancelEvent(this);
m_hasPendingErrorEvent = false;
}
m_image = newImage;
m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage;
m_hasPendingLoadEvent = newImage;
m_imageComplete = !newImage;
if (newImage) {
if (!m_element->document()->isImageDocument()) {
if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER))
dispatchPendingBeforeLoadEvent();
else
beforeLoadEventSender().dispatchEventSoon(this);
} else
updateRenderer();
newImage->addClient(this);
}
if (oldImage)
oldImage->removeClient(this);
}
if (RenderImageResource* imageResource = renderImageResource())
imageResource->resetAnimation();
updatedHasPendingEvent();
}
Commit Message: Error event was fired synchronously blowing away the input element from underneath. Remove the FIXME and fire it asynchronously using errorEventSender().
BUG=240124
Review URL: https://chromiumcodereview.appspot.com/14741011
git-svn-id: svn://svn.chromium.org/blink/trunk@150232 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416 | void ImageLoader::updateFromElement()
{
Document* document = m_element->document();
if (!document->renderer())
return;
AtomicString attr = m_element->imageSourceURL();
if (attr == m_failedLoadURL)
return;
CachedResourceHandle<CachedImage> newImage = 0;
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
CachedResourceRequest request(ResourceRequest(document->completeURL(sourceURI(attr))));
request.setInitiator(element());
String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
}
if (m_loadManually) {
bool autoLoadOtherImages = document->cachedResourceLoader()->autoLoadImages();
document->cachedResourceLoader()->setAutoLoadImages(false);
newImage = new CachedImage(request.resourceRequest());
newImage->setLoading(true);
newImage->setOwningCachedResourceLoader(document->cachedResourceLoader());
document->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get());
document->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages);
} else
newImage = document->cachedResourceLoader()->requestImage(request);
if (!newImage && !pageIsBeingDismissed(document)) {
m_failedLoadURL = attr;
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
} else
clearFailedLoadURL();
} else if (!attr.isNull()) {
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
}
CachedImage* oldImage = m_image.get();
if (newImage != oldImage) {
if (m_hasPendingBeforeLoadEvent) {
beforeLoadEventSender().cancelEvent(this);
m_hasPendingBeforeLoadEvent = false;
}
if (m_hasPendingLoadEvent) {
loadEventSender().cancelEvent(this);
m_hasPendingLoadEvent = false;
}
if (m_hasPendingErrorEvent && newImage) {
errorEventSender().cancelEvent(this);
m_hasPendingErrorEvent = false;
}
m_image = newImage;
m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage;
m_hasPendingLoadEvent = newImage;
m_imageComplete = !newImage;
if (newImage) {
if (!m_element->document()->isImageDocument()) {
if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER))
dispatchPendingBeforeLoadEvent();
else
beforeLoadEventSender().dispatchEventSoon(this);
} else
updateRenderer();
newImage->addClient(this);
}
if (oldImage)
oldImage->removeClient(this);
}
if (RenderImageResource* imageResource = renderImageResource())
imageResource->resetAnimation();
updatedHasPendingEvent();
}
| 171,319 |
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: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
Commit Message: Avoid sharing process for blob URLs with null origin.
Previously, when a frame with a unique origin, such as from a data
URL, created a blob URL, the blob URL looked like blob:null/guid and
resulted in a site URL of "blob:" when navigated to. This incorrectly
allowed all such blob URLs to share a process, even if they were
created by different sites.
This CL changes the site URL assigned in such cases to be the full
blob URL, which includes the GUID. This avoids process sharing for
all blob URLs with unique origins.
This fix is conservative in the sense that it would also isolate
different blob URLs created by the same unique origin from each other.
This case isn't expected to be common, so it's unlikely to affect
process count. There's ongoing work to maintain a GUID for unique
origins, so longer-term, we could try using that to track down the
creator and potentially use that GUID in the site URL instead of the
blob URL's GUID, to avoid unnecessary process isolation in scenarios
like this.
Note that as part of this, we discovered a bug where data URLs aren't
able to script blob URLs that they create: https://crbug.com/865254.
This scripting bug should be fixed independently of this CL, and as
far as we can tell, this CL doesn't regress scripting cases like this
further.
Bug: 863623
Change-Id: Ib50407adbba3d5ee0cf6d72d3df7f8d8f24684ee
Reviewed-on: https://chromium-review.googlesource.com/1142389
Commit-Queue: Alex Moshchuk <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#576318}
CWE ID: CWE-285 | GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
// cover blob:file: and filesystem:file: URIs (see also
// https://crbug.com/697111).
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
// In some cases, it is not safe to use just the scheme as a site URL, as
// that might allow two URLs created by different sites to to share a
// process. See https://crbug.com/863623.
//
// TODO(alexmos,creis): This should eventually be expanded to certain other
// schemes, such as data: and file:.
if (url.SchemeIsBlob()) {
// We get here for blob URLs of form blob:null/guid. Use the full URL
// with the guid in that case, which isolates all blob URLs with unique
// origins from each other. Remove hash from the URL, since
// same-document navigations shouldn't use a different site URL.
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
| 173,184 |
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: xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 171,297 |
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: vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
unsigned long tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas Bellinger <[email protected]>
CWE ID: CWE-119 | vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
u16 tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtou16(name + 5, 10, &tpgt) || tpgt >= VHOST_SCSI_MAX_TARGET)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
| 166,615 |
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: TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) {
const int shmkey = shmget(IPC_PRIVATE, size, 0666);
if (shmkey == -1) {
DLOG(ERROR) << "Failed to create SysV shared memory region"
<< " errno:" << errno;
return NULL;
}
void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */);
shmctl(shmkey, IPC_RMID, 0);
if (address == kInvalidAddress)
return NULL;
TransportDIB* dib = new TransportDIB;
dib->key_.shmkey = shmkey;
dib->address_ = address;
dib->size_ = size;
return dib;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) {
const int shmkey = shmget(IPC_PRIVATE, size, 0600);
if (shmkey == -1) {
DLOG(ERROR) << "Failed to create SysV shared memory region"
<< " errno:" << errno;
return NULL;
} else {
VLOG(1) << "Created SysV shared memory region " << shmkey;
}
void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */);
shmctl(shmkey, IPC_RMID, 0);
if (address == kInvalidAddress)
return NULL;
TransportDIB* dib = new TransportDIB;
dib->key_.shmkey = shmkey;
dib->address_ = address;
dib->size_ = size;
return dib;
}
| 171,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: void BrowserCommandController::RemoveInterstitialObservers(
TabContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents->web_contents()));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserCommandController::RemoveInterstitialObservers(
WebContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents));
}
| 171,510 |
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 BluetoothDeviceChromeOS::Cancel() {
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Cancel";
DCHECK(pairing_delegate_);
pairing_delegate_->DismissDisplayOrConfirm();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::Cancel() {
| 171,218 |
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: gfx::Size CardUnmaskPromptViews::GetPreferredSize() const {
const int kWidth = 375;
return gfx::Size(kWidth, GetHeightForWidth(kWidth));
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | gfx::Size CardUnmaskPromptViews::GetPreferredSize() const {
// Must hardcode a width so the label knows where to wrap.
const int kWidth = 375;
return gfx::Size(kWidth, GetHeightForWidth(kWidth));
}
| 171,142 |
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: SecurityContext::SecurityContext()
: m_mayDisplaySeamlesslyWithParent(false)
, m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | SecurityContext::SecurityContext()
: m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
| 170,700 |
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 bool unconditional(const struct arpt_arp *arp)
{
static const struct arpt_arp uncond;
return memcmp(arp, &uncond, sizeof(uncond)) == 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static inline bool unconditional(const struct arpt_arp *arp)
static inline bool unconditional(const struct arpt_entry *e)
{
static const struct arpt_arp uncond;
return e->target_offset == sizeof(struct arpt_entry) &&
memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;
}
| 167,366 |
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: ContentUtilityClient* ShellMainDelegate::CreateContentUtilityClient() {
utility_client_.reset(new ShellContentUtilityClient);
return utility_client_.get();
}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <[email protected]>
Commit-Queue: John Abd-El-Malek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264 | ContentUtilityClient* ShellMainDelegate::CreateContentUtilityClient() {
utility_client_.reset(new ShellContentUtilityClient(is_browsertest_));
return utility_client_.get();
}
| 172,120 |
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 ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[20];
sprintf(key, "a=framesize:%lu", PT);
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
Commit Message: Fix corruption via buffer overflow in mediaserver
change unbound sprintf() to snprintf() so network-provided values
can't overflow the buffers.
Applicable to all K/L/M/N branches.
Bug: 25747670
Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6
CWE ID: CWE-284 | bool ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[33];
snprintf(key, sizeof(key), "a=framesize:%lu", PT);
if (PT > 9999999) {
android_errorWriteLog(0x534e4554, "25747670");
}
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
| 173,410 |
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: _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
if (rc)
return rc;
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_addm (sum, hash, dr, skey->E.n); /* sum = hash + (d*r) mod n */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
}
Commit Message:
CWE ID: CWE-200 | _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
gcry_mpi_t b; /* Random number needed for blinding. */
gcry_mpi_t bi; /* multiplicative inverse of B. */
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
if (rc)
return rc;
b = mpi_snew (qbits);
bi = mpi_snew (qbits);
do
{
_gcry_mpi_randomize (b, qbits, GCRY_WEAK_RANDOM);
mpi_mod (b, b, skey->E.n);
}
while (!mpi_invm (bi, b, skey->E.n));
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_addm (sum, hash, dr, skey->E.n); /* sum = hash + (d*r) mod n */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
}
| 165,348 |
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: parse(struct magic_set *ms, struct magic_entry *me, const char *line,
size_t lineno, int action)
{
#ifdef ENABLE_CONDITIONALS
static uint32_t last_cont_level = 0;
#endif
size_t i;
struct magic *m;
const char *l = line;
char *t;
int op;
uint32_t cont_level;
int32_t diff;
cont_level = 0;
/*
* Parse the offset.
*/
while (*l == '>') {
++l; /* step over */
cont_level++;
}
#ifdef ENABLE_CONDITIONALS
if (cont_level == 0 || cont_level > last_cont_level)
if (file_check_mem(ms, cont_level) == -1)
return -1;
last_cont_level = cont_level;
#endif
if (cont_level != 0) {
if (me->mp == NULL) {
file_magerror(ms, "No current entry for continuation");
return -1;
}
if (me->cont_count == 0) {
file_magerror(ms, "Continuations present with 0 count");
return -1;
}
m = &me->mp[me->cont_count - 1];
diff = (int32_t)cont_level - (int32_t)m->cont_level;
if (diff > 1)
file_magwarn(ms, "New continuation level %u is more "
"than one larger than current level %u", cont_level,
m->cont_level);
if (me->cont_count == me->max_count) {
struct magic *nm;
size_t cnt = me->max_count + ALLOC_CHUNK;
if ((nm = CAST(struct magic *, realloc(me->mp,
sizeof(*nm) * cnt))) == NULL) {
file_oomem(ms, sizeof(*nm) * cnt);
return -1;
}
me->mp = m = nm;
me->max_count = CAST(uint32_t, cnt);
}
m = &me->mp[me->cont_count++];
(void)memset(m, 0, sizeof(*m));
m->cont_level = cont_level;
} else {
static const size_t len = sizeof(*m) * ALLOC_CHUNK;
if (me->mp != NULL)
return 1;
if ((m = CAST(struct magic *, malloc(len))) == NULL) {
file_oomem(ms, len);
return -1;
}
me->mp = m;
me->max_count = ALLOC_CHUNK;
(void)memset(m, 0, sizeof(*m));
m->factor_op = FILE_FACTOR_OP_NONE;
m->cont_level = 0;
me->cont_count = 1;
}
m->lineno = CAST(uint32_t, lineno);
if (*l == '&') { /* m->cont_level == 0 checked below. */
++l; /* step over */
m->flag |= OFFADD;
}
if (*l == '(') {
++l; /* step over */
m->flag |= INDIR;
if (m->flag & OFFADD)
m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
if (*l == '&') { /* m->cont_level == 0 checked below */
++l; /* step over */
m->flag |= OFFADD;
}
}
/* Indirect offsets are not valid at level 0. */
if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "relative offset at level 0");
/* get offset, then skip over it */
m->offset = (uint32_t)strtoul(l, &t, 0);
if (l == t)
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "offset `%s' invalid", l);
l = t;
if (m->flag & INDIR) {
m->in_type = FILE_LONG;
m->in_offset = 0;
/*
* read [.lbs][+-]nnnnn)
*/
if (*l == '.') {
l++;
switch (*l) {
case 'l':
m->in_type = FILE_LELONG;
break;
case 'L':
m->in_type = FILE_BELONG;
break;
case 'm':
m->in_type = FILE_MELONG;
break;
case 'h':
case 's':
m->in_type = FILE_LESHORT;
break;
case 'H':
case 'S':
m->in_type = FILE_BESHORT;
break;
case 'c':
case 'b':
case 'C':
case 'B':
m->in_type = FILE_BYTE;
break;
case 'e':
case 'f':
case 'g':
m->in_type = FILE_LEDOUBLE;
break;
case 'E':
case 'F':
case 'G':
m->in_type = FILE_BEDOUBLE;
break;
case 'i':
m->in_type = FILE_LEID3;
break;
case 'I':
m->in_type = FILE_BEID3;
break;
default:
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"indirect offset type `%c' invalid",
*l);
break;
}
l++;
}
m->in_op = 0;
if (*l == '~') {
m->in_op |= FILE_OPINVERSE;
l++;
}
if ((op = get_op(*l)) != -1) {
m->in_op |= op;
l++;
}
if (*l == '(') {
m->in_op |= FILE_OPINDIRECT;
l++;
}
if (isdigit((unsigned char)*l) || *l == '-') {
m->in_offset = (int32_t)strtol(l, &t, 0);
if (l == t)
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"in_offset `%s' invalid", l);
l = t;
}
if (*l++ != ')' ||
((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"missing ')' in indirect offset");
}
EATAB;
#ifdef ENABLE_CONDITIONALS
m->cond = get_cond(l, &l);
if (check_cond(ms, m->cond, cont_level) == -1)
return -1;
EATAB;
#endif
/*
* Parse the type.
*/
if (*l == 'u') {
/*
* Try it as a keyword type prefixed by "u"; match what
* follows the "u". If that fails, try it as an SUS
* integer type.
*/
m->type = get_type(type_tbl, l + 1, &l);
if (m->type == FILE_INVALID) {
/*
* Not a keyword type; parse it as an SUS type,
* 'u' possibly followed by a number or C/S/L.
*/
m->type = get_standard_integer_type(l, &l);
}
/* It's unsigned. */
if (m->type != FILE_INVALID)
m->flag |= UNSIGNED;
} else {
/*
* Try it as a keyword type. If that fails, try it as
* an SUS integer type if it begins with "d" or as an
* SUS string type if it begins with "s". In any case,
* it's not unsigned.
*/
m->type = get_type(type_tbl, l, &l);
if (m->type == FILE_INVALID) {
/*
* Not a keyword type; parse it as an SUS type,
* either 'd' possibly followed by a number or
* C/S/L, or just 's'.
*/
if (*l == 'd')
m->type = get_standard_integer_type(l, &l);
else if (*l == 's' && !isalpha((unsigned char)l[1])) {
m->type = FILE_STRING;
++l;
}
}
}
if (m->type == FILE_INVALID) {
/* Not found - try it as a special keyword. */
m->type = get_type(special_tbl, l, &l);
}
if (m->type == FILE_INVALID) {
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "type `%s' invalid", l);
return -1;
}
/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
m->mask_op = 0;
if (*l == '~') {
if (!IS_STRING(m->type))
m->mask_op |= FILE_OPINVERSE;
else if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "'~' invalid for string types");
++l;
}
m->str_range = 0;
m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
if ((op = get_op(*l)) != -1) {
if (!IS_STRING(m->type)) {
uint64_t val;
++l;
m->mask_op |= op;
val = (uint64_t)strtoull(l, &t, 0);
l = t;
m->num_mask = file_signextend(ms, m, val);
eatsize(&l);
}
else if (op == FILE_OPDIVIDE) {
int have_range = 0;
while (!isspace((unsigned char)*++l)) {
switch (*l) {
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9':
if (have_range &&
(ms->flags & MAGIC_CHECK))
file_magwarn(ms,
"multiple ranges");
have_range = 1;
m->str_range = CAST(uint32_t,
strtoul(l, &t, 0));
if (m->str_range == 0)
file_magwarn(ms,
"zero range");
l = t - 1;
break;
case CHAR_COMPACT_WHITESPACE:
m->str_flags |=
STRING_COMPACT_WHITESPACE;
break;
case CHAR_COMPACT_OPTIONAL_WHITESPACE:
m->str_flags |=
STRING_COMPACT_OPTIONAL_WHITESPACE;
break;
case CHAR_IGNORE_LOWERCASE:
m->str_flags |= STRING_IGNORE_LOWERCASE;
break;
case CHAR_IGNORE_UPPERCASE:
m->str_flags |= STRING_IGNORE_UPPERCASE;
break;
case CHAR_REGEX_OFFSET_START:
m->str_flags |= REGEX_OFFSET_START;
break;
case CHAR_BINTEST:
m->str_flags |= STRING_BINTEST;
break;
case CHAR_TEXTTEST:
m->str_flags |= STRING_TEXTTEST;
break;
case CHAR_TRIM:
m->str_flags |= STRING_TRIM;
break;
case CHAR_PSTRING_1_LE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_1_LE;
break;
case CHAR_PSTRING_2_BE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_2_BE;
break;
case CHAR_PSTRING_2_LE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_2_LE;
break;
case CHAR_PSTRING_4_BE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_4_BE;
break;
case CHAR_PSTRING_4_LE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_4_LE;
break;
case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
break;
default:
bad:
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"string extension `%c' "
"invalid", *l);
return -1;
}
/* allow multiple '/' for readability */
if (l[1] == '/' &&
!isspace((unsigned char)l[2]))
l++;
}
if (string_modifier_check(ms, m) == -1)
return -1;
}
else {
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "invalid string op: %c", *t);
return -1;
}
}
/*
* We used to set mask to all 1's here, instead let's just not do
* anything if mask = 0 (unless you have a better idea)
*/
EATAB;
switch (*l) {
case '>':
case '<':
m->reln = *l;
++l;
if (*l == '=') {
if (ms->flags & MAGIC_CHECK) {
file_magwarn(ms, "%c= not supported",
m->reln);
return -1;
}
++l;
}
break;
/* Old-style anding: "0 byte &0x80 dynamically linked" */
case '&':
case '^':
case '=':
m->reln = *l;
++l;
if (*l == '=') {
/* HP compat: ignore &= etc. */
++l;
}
break;
case '!':
m->reln = *l;
++l;
break;
default:
m->reln = '='; /* the default relation */
if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
isspace((unsigned char)l[1])) || !l[1])) {
m->reln = *l;
++l;
}
break;
}
/*
* Grab the value part, except for an 'x' reln.
*/
if (m->reln != 'x' && getvalue(ms, m, &l, action))
return -1;
/*
* TODO finish this macro and start using it!
* #define offsetcheck {if (offset > HOWMANY-1)
* magwarn("offset too big"); }
*/
/*
* Now get last part - the description
*/
EATAB;
if (l[0] == '\b') {
++l;
m->flag |= NOSPACE;
} else if ((l[0] == '\\') && (l[1] == 'b')) {
++l;
++l;
m->flag |= NOSPACE;
}
for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
continue;
if (i == sizeof(m->desc)) {
m->desc[sizeof(m->desc) - 1] = '\0';
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "description `%s' truncated", m->desc);
}
/*
* We only do this check while compiling, or if any of the magic
* files were not compiled.
*/
if (ms->flags & MAGIC_CHECK) {
if (check_format(ms, m) == -1)
return -1;
}
#ifndef COMPILE_ONLY
if (action == FILE_CHECK) {
file_mdump(m);
}
#endif
m->mimetype[0] = '\0'; /* initialise MIME type to none */
return 0;
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | parse(struct magic_set *ms, struct magic_entry *me, const char *line,
size_t lineno, int action)
{
#ifdef ENABLE_CONDITIONALS
static uint32_t last_cont_level = 0;
#endif
size_t i;
struct magic *m;
const char *l = line;
char *t;
int op;
uint32_t cont_level;
int32_t diff;
cont_level = 0;
/*
* Parse the offset.
*/
while (*l == '>') {
++l; /* step over */
cont_level++;
}
#ifdef ENABLE_CONDITIONALS
if (cont_level == 0 || cont_level > last_cont_level)
if (file_check_mem(ms, cont_level) == -1)
return -1;
last_cont_level = cont_level;
#endif
if (cont_level != 0) {
if (me->mp == NULL) {
file_magerror(ms, "No current entry for continuation");
return -1;
}
if (me->cont_count == 0) {
file_magerror(ms, "Continuations present with 0 count");
return -1;
}
m = &me->mp[me->cont_count - 1];
diff = (int32_t)cont_level - (int32_t)m->cont_level;
if (diff > 1)
file_magwarn(ms, "New continuation level %u is more "
"than one larger than current level %u", cont_level,
m->cont_level);
if (me->cont_count == me->max_count) {
struct magic *nm;
size_t cnt = me->max_count + ALLOC_CHUNK;
if ((nm = CAST(struct magic *, realloc(me->mp,
sizeof(*nm) * cnt))) == NULL) {
file_oomem(ms, sizeof(*nm) * cnt);
return -1;
}
me->mp = m = nm;
me->max_count = CAST(uint32_t, cnt);
}
m = &me->mp[me->cont_count++];
(void)memset(m, 0, sizeof(*m));
m->cont_level = cont_level;
} else {
static const size_t len = sizeof(*m) * ALLOC_CHUNK;
if (me->mp != NULL)
return 1;
if ((m = CAST(struct magic *, malloc(len))) == NULL) {
file_oomem(ms, len);
return -1;
}
me->mp = m;
me->max_count = ALLOC_CHUNK;
(void)memset(m, 0, sizeof(*m));
m->factor_op = FILE_FACTOR_OP_NONE;
m->cont_level = 0;
me->cont_count = 1;
}
m->lineno = CAST(uint32_t, lineno);
if (*l == '&') { /* m->cont_level == 0 checked below. */
++l; /* step over */
m->flag |= OFFADD;
}
if (*l == '(') {
++l; /* step over */
m->flag |= INDIR;
if (m->flag & OFFADD)
m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
if (*l == '&') { /* m->cont_level == 0 checked below */
++l; /* step over */
m->flag |= OFFADD;
}
}
/* Indirect offsets are not valid at level 0. */
if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "relative offset at level 0");
/* get offset, then skip over it */
m->offset = (uint32_t)strtoul(l, &t, 0);
if (l == t)
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "offset `%s' invalid", l);
l = t;
if (m->flag & INDIR) {
m->in_type = FILE_LONG;
m->in_offset = 0;
/*
* read [.lbs][+-]nnnnn)
*/
if (*l == '.') {
l++;
switch (*l) {
case 'l':
m->in_type = FILE_LELONG;
break;
case 'L':
m->in_type = FILE_BELONG;
break;
case 'm':
m->in_type = FILE_MELONG;
break;
case 'h':
case 's':
m->in_type = FILE_LESHORT;
break;
case 'H':
case 'S':
m->in_type = FILE_BESHORT;
break;
case 'c':
case 'b':
case 'C':
case 'B':
m->in_type = FILE_BYTE;
break;
case 'e':
case 'f':
case 'g':
m->in_type = FILE_LEDOUBLE;
break;
case 'E':
case 'F':
case 'G':
m->in_type = FILE_BEDOUBLE;
break;
case 'i':
m->in_type = FILE_LEID3;
break;
case 'I':
m->in_type = FILE_BEID3;
break;
default:
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"indirect offset type `%c' invalid",
*l);
break;
}
l++;
}
m->in_op = 0;
if (*l == '~') {
m->in_op |= FILE_OPINVERSE;
l++;
}
if ((op = get_op(*l)) != -1) {
m->in_op |= op;
l++;
}
if (*l == '(') {
m->in_op |= FILE_OPINDIRECT;
l++;
}
if (isdigit((unsigned char)*l) || *l == '-') {
m->in_offset = (int32_t)strtol(l, &t, 0);
if (l == t)
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"in_offset `%s' invalid", l);
l = t;
}
if (*l++ != ')' ||
((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"missing ')' in indirect offset");
}
EATAB;
#ifdef ENABLE_CONDITIONALS
m->cond = get_cond(l, &l);
if (check_cond(ms, m->cond, cont_level) == -1)
return -1;
EATAB;
#endif
/*
* Parse the type.
*/
if (*l == 'u') {
/*
* Try it as a keyword type prefixed by "u"; match what
* follows the "u". If that fails, try it as an SUS
* integer type.
*/
m->type = get_type(type_tbl, l + 1, &l);
if (m->type == FILE_INVALID) {
/*
* Not a keyword type; parse it as an SUS type,
* 'u' possibly followed by a number or C/S/L.
*/
m->type = get_standard_integer_type(l, &l);
}
/* It's unsigned. */
if (m->type != FILE_INVALID)
m->flag |= UNSIGNED;
} else {
/*
* Try it as a keyword type. If that fails, try it as
* an SUS integer type if it begins with "d" or as an
* SUS string type if it begins with "s". In any case,
* it's not unsigned.
*/
m->type = get_type(type_tbl, l, &l);
if (m->type == FILE_INVALID) {
/*
* Not a keyword type; parse it as an SUS type,
* either 'd' possibly followed by a number or
* C/S/L, or just 's'.
*/
if (*l == 'd')
m->type = get_standard_integer_type(l, &l);
else if (*l == 's' && !isalpha((unsigned char)l[1])) {
m->type = FILE_STRING;
++l;
}
}
}
if (m->type == FILE_INVALID) {
/* Not found - try it as a special keyword. */
m->type = get_type(special_tbl, l, &l);
}
if (m->type == FILE_INVALID) {
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "type `%s' invalid", l);
return -1;
}
/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
m->mask_op = 0;
if (*l == '~') {
if (!IS_STRING(m->type))
m->mask_op |= FILE_OPINVERSE;
else if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "'~' invalid for string types");
++l;
}
m->str_range = 0;
m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
if ((op = get_op(*l)) != -1) {
if (!IS_STRING(m->type)) {
uint64_t val;
++l;
m->mask_op |= op;
val = (uint64_t)strtoull(l, &t, 0);
l = t;
m->num_mask = file_signextend(ms, m, val);
eatsize(&l);
}
else if (op == FILE_OPDIVIDE) {
int have_range = 0;
while (!isspace((unsigned char)*++l)) {
switch (*l) {
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9':
if (have_range &&
(ms->flags & MAGIC_CHECK))
file_magwarn(ms,
"multiple ranges");
have_range = 1;
m->str_range = CAST(uint32_t,
strtoul(l, &t, 0));
if (m->str_range == 0)
file_magwarn(ms,
"zero range");
l = t - 1;
break;
case CHAR_COMPACT_WHITESPACE:
m->str_flags |=
STRING_COMPACT_WHITESPACE;
break;
case CHAR_COMPACT_OPTIONAL_WHITESPACE:
m->str_flags |=
STRING_COMPACT_OPTIONAL_WHITESPACE;
break;
case CHAR_IGNORE_LOWERCASE:
m->str_flags |= STRING_IGNORE_LOWERCASE;
break;
case CHAR_IGNORE_UPPERCASE:
m->str_flags |= STRING_IGNORE_UPPERCASE;
break;
case CHAR_REGEX_OFFSET_START:
m->str_flags |= REGEX_OFFSET_START;
break;
case CHAR_BINTEST:
m->str_flags |= STRING_BINTEST;
break;
case CHAR_TEXTTEST:
m->str_flags |= STRING_TEXTTEST;
break;
case CHAR_TRIM:
m->str_flags |= STRING_TRIM;
break;
case CHAR_PSTRING_1_LE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_1_LE;
break;
case CHAR_PSTRING_2_BE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_2_BE;
break;
case CHAR_PSTRING_2_LE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_2_LE;
break;
case CHAR_PSTRING_4_BE:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_4_BE;
break;
case CHAR_PSTRING_4_LE:
switch (m->type) {
case FILE_PSTRING:
case FILE_REGEX:
break;
default:
goto bad;
}
m->str_flags = (m->str_flags & ~PSTRING_LEN) | PSTRING_4_LE;
break;
case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
if (m->type != FILE_PSTRING)
goto bad;
m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
break;
default:
bad:
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms,
"string extension `%c' "
"invalid", *l);
return -1;
}
/* allow multiple '/' for readability */
if (l[1] == '/' &&
!isspace((unsigned char)l[2]))
l++;
}
if (string_modifier_check(ms, m) == -1)
return -1;
}
else {
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "invalid string op: %c", *t);
return -1;
}
}
/*
* We used to set mask to all 1's here, instead let's just not do
* anything if mask = 0 (unless you have a better idea)
*/
EATAB;
switch (*l) {
case '>':
case '<':
m->reln = *l;
++l;
if (*l == '=') {
if (ms->flags & MAGIC_CHECK) {
file_magwarn(ms, "%c= not supported",
m->reln);
return -1;
}
++l;
}
break;
/* Old-style anding: "0 byte &0x80 dynamically linked" */
case '&':
case '^':
case '=':
m->reln = *l;
++l;
if (*l == '=') {
/* HP compat: ignore &= etc. */
++l;
}
break;
case '!':
m->reln = *l;
++l;
break;
default:
m->reln = '='; /* the default relation */
if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
isspace((unsigned char)l[1])) || !l[1])) {
m->reln = *l;
++l;
}
break;
}
/*
* Grab the value part, except for an 'x' reln.
*/
if (m->reln != 'x' && getvalue(ms, m, &l, action))
return -1;
/*
* TODO finish this macro and start using it!
* #define offsetcheck {if (offset > HOWMANY-1)
* magwarn("offset too big"); }
*/
/*
* Now get last part - the description
*/
EATAB;
if (l[0] == '\b') {
++l;
m->flag |= NOSPACE;
} else if ((l[0] == '\\') && (l[1] == 'b')) {
++l;
++l;
m->flag |= NOSPACE;
}
for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
continue;
if (i == sizeof(m->desc)) {
m->desc[sizeof(m->desc) - 1] = '\0';
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "description `%s' truncated", m->desc);
}
/*
* We only do this check while compiling, or if any of the magic
* files were not compiled.
*/
if (ms->flags & MAGIC_CHECK) {
if (check_format(ms, m) == -1)
return -1;
}
#ifndef COMPILE_ONLY
if (action == FILE_CHECK) {
file_mdump(m);
}
#endif
m->mimetype[0] = '\0'; /* initialise MIME type to none */
return 0;
}
| 166,355 |
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 perf_syscall_enter(void *ignore, struct pt_regs *regs, long id)
{
struct syscall_metadata *sys_data;
struct syscall_trace_enter *rec;
struct hlist_head *head;
int syscall_nr;
int rctx;
int size;
syscall_nr = trace_get_syscall_nr(current, regs);
if (syscall_nr < 0)
return;
if (!test_bit(syscall_nr, enabled_perf_enter_syscalls))
return;
sys_data = syscall_nr_to_meta(syscall_nr);
if (!sys_data)
return;
head = this_cpu_ptr(sys_data->enter_event->perf_events);
if (hlist_empty(head))
return;
/* get the size after alignment with the u32 buffer size field */
size = sizeof(unsigned long) * sys_data->nb_args + sizeof(*rec);
size = ALIGN(size + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
rec = (struct syscall_trace_enter *)perf_trace_buf_prepare(size,
sys_data->enter_event->event.type, regs, &rctx);
if (!rec)
return;
rec->nr = syscall_nr;
syscall_get_arguments(current, regs, 0, sys_data->nb_args,
(unsigned long *)&rec->args);
perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);
}
Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range
ARM has some private syscalls (for example, set_tls(2)) which lie
outside the range of NR_syscalls. If any of these are called while
syscall tracing is being performed, out-of-bounds array access will
occur in the ftrace and perf sys_{enter,exit} handlers.
# trace-cmd record -e raw_syscalls:* true && trace-cmd report
...
true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0)
true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264
true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1)
true-653 [000] 384.675988: sys_exit: NR 983045 = 0
...
# trace-cmd record -e syscalls:* true
[ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace
[ 17.289590] pgd = 9e71c000
[ 17.289696] [aaaaaace] *pgd=00000000
[ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM
[ 17.290169] Modules linked in:
[ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21
[ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000
[ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8
[ 17.290866] LR is at syscall_trace_enter+0x124/0x184
Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers.
Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
added the check for less than zero, but it should have also checked
for greater than NR_syscalls.
Link: http://lkml.kernel.org/p/[email protected]
Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
Cc: [email protected] # 2.6.33+
Signed-off-by: Rabin Vincent <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID: CWE-264 | static void perf_syscall_enter(void *ignore, struct pt_regs *regs, long id)
{
struct syscall_metadata *sys_data;
struct syscall_trace_enter *rec;
struct hlist_head *head;
int syscall_nr;
int rctx;
int size;
syscall_nr = trace_get_syscall_nr(current, regs);
if (syscall_nr < 0 || syscall_nr >= NR_syscalls)
return;
if (!test_bit(syscall_nr, enabled_perf_enter_syscalls))
return;
sys_data = syscall_nr_to_meta(syscall_nr);
if (!sys_data)
return;
head = this_cpu_ptr(sys_data->enter_event->perf_events);
if (hlist_empty(head))
return;
/* get the size after alignment with the u32 buffer size field */
size = sizeof(unsigned long) * sys_data->nb_args + sizeof(*rec);
size = ALIGN(size + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
rec = (struct syscall_trace_enter *)perf_trace_buf_prepare(size,
sys_data->enter_event->event.type, regs, &rctx);
if (!rec)
return;
rec->nr = syscall_nr;
syscall_get_arguments(current, regs, 0, sys_data->nb_args,
(unsigned long *)&rec->args);
perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);
}
| 166,256 |
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: xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) {
return retval;
} else if (retval == -EEXIST) {
if (args->flags & ATTR_CREATE)
return retval;
retval = xfs_attr_shortform_remove(args);
ASSERT(retval == 0);
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return -ENOSPC;
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return -ENOSPC;
xfs_attr_shortform_add(args, forkoff);
return 0;
}
Commit Message: xfs: don't fail when converting shortform attr to long form during ATTR_REPLACE
Kanda Motohiro reported that expanding a tiny xattr into a large xattr
fails on XFS because we remove the tiny xattr from a shortform fork and
then try to re-add it after converting the fork to extents format having
not removed the ATTR_REPLACE flag. This fails because the attr is no
longer present, causing a fs shutdown.
This is derived from the patch in his bug report, but we really
shouldn't ignore a nonzero retval from the remove call.
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199119
Reported-by: [email protected]
Reviewed-by: Dave Chinner <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Darrick J. Wong <[email protected]>
CWE ID: CWE-754 | xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) {
return retval;
} else if (retval == -EEXIST) {
if (args->flags & ATTR_CREATE)
return retval;
retval = xfs_attr_shortform_remove(args);
if (retval)
return retval;
/*
* Since we have removed the old attr, clear ATTR_REPLACE so
* that the leaf format add routine won't trip over the attr
* not being around.
*/
args->flags &= ~ATTR_REPLACE;
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return -ENOSPC;
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return -ENOSPC;
xfs_attr_shortform_add(args, forkoff);
return 0;
}
| 169,000 |
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: file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
{
int i;
for (i = 0; attrs[i]; i++)
{
MAPI_Attr* a = attrs[i];
if (a->num_values)
{
switch (a->name)
{
case MAPI_ATTACH_LONG_FILENAME:
if (file->name) XFREE(file->name);
file->name = strdup( (char*)a->values[0].data.buf );
break;
case MAPI_ATTACH_DATA_OBJ:
file->len = a->values[0].len;
if (file->data) XFREE (file->data);
file->data = CHECKED_XMALLOC (unsigned char, file->len);
memmove (file->data, a->values[0].data.buf, file->len);
break;
case MAPI_ATTACH_MIME_TAG:
if (file->mime_type) XFREE (file->mime_type);
file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
break;
case MAPI_ATTACH_CONTENT_ID:
if (file->content_id) XFREE(file->content_id);
file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
break;
default:
break;
}
}
}
}
Commit Message: Check types to avoid invalid reads/writes.
CWE ID: CWE-125 | file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
{
int i;
for (i = 0; attrs[i]; i++)
{
MAPI_Attr* a = attrs[i];
if (a->num_values)
{
switch (a->name)
{
case MAPI_ATTACH_LONG_FILENAME:
assert(a->type == szMAPI_STRING);
if (file->name) XFREE(file->name);
file->name = strdup( (char*)a->values[0].data.buf );
break;
case MAPI_ATTACH_DATA_OBJ:
assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT));
file->len = a->values[0].len;
if (file->data) XFREE (file->data);
file->data = CHECKED_XMALLOC (unsigned char, file->len);
memmove (file->data, a->values[0].data.buf, file->len);
break;
case MAPI_ATTACH_MIME_TAG:
assert(a->type == szMAPI_STRING);
if (file->mime_type) XFREE (file->mime_type);
file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
break;
case MAPI_ATTACH_CONTENT_ID:
assert(a->type == szMAPI_STRING);
if (file->content_id) XFREE(file->content_id);
file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
break;
default:
break;
}
}
}
}
| 168,351 |
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 validation_muldiv(int count, int argc, char **argv)
{
int tested = 0;
int overflow = 0;
int error = 0;
int error64 = 0;
int passed = 0;
int randbits = 0;
png_uint_32 randbuffer;
png_fixed_point a;
png_int_32 times, div;
while (--argc > 0)
{
fprintf(stderr, "unknown argument %s\n", *++argv);
return 1;
}
/* Find out about the random number generator. */
randbuffer = RAND_MAX;
while (randbuffer != 0) ++randbits, randbuffer >>= 1;
printf("Using random number generator that makes %d bits\n", randbits);
for (div=0; div<32; div += randbits)
randbuffer = (randbuffer << randbits) ^ rand();
a = 0;
times = div = 0;
do
{
png_fixed_point result;
/* NOTE: your mileage may vary, a type is required below that can
* hold 64 bits or more, if floating point is used a 64 bit or
* better mantissa is required.
*/
long long int fp, fpround;
unsigned long hi, lo;
int ok;
/* Check the values, png_64bit_product can only handle positive
* numbers, so correct for that here.
*/
{
long u1, u2;
int n = 0;
if (a < 0) u1 = -a, n = 1; else u1 = a;
if (times < 0) u2 = -times, n = !n; else u2 = times;
png_64bit_product(u1, u2, &hi, &lo);
if (n)
{
/* -x = ~x+1 */
lo = ((~lo) + 1) & 0xffffffff;
hi = ~hi;
if (lo == 0) ++hi;
}
}
fp = a;
fp *= times;
if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
{
fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
a, times, hi, lo, fp);
++error64;
}
if (div != 0)
{
/* Round - this is C round to zero. */
if ((fp < 0) != (div < 0))
fp -= div/2;
else
fp += div/2;
fp /= div;
fpround = fp;
/* Assume 2's complement here: */
ok = fpround <= PNG_UINT_31_MAX &&
fpround >= -1-(long long int)PNG_UINT_31_MAX;
if (!ok) ++overflow;
}
else
ok = 0, ++overflow, fpround = fp/*misleading*/;
if (verbose)
fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n", a, times, div,
fp, ok ? "ok" : "overflow");
++tested;
if (png_muldiv(&result, a, times, div) != ok)
{
++error;
if (ok)
fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n", a,
times, div, fp);
else
fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n", a,
times, div, result, fp);
}
else if (ok && result != fpround)
{
++error;
fprintf(stderr, "%d * %d / %d -> %d not %lld\n", a, times, div, result,
fp);
}
else
++passed;
/* Generate three new values, this uses rand() and rand() only returns
* up to RAND_MAX.
*/
/* CRUDE */
a += times;
times += div;
div = randbuffer;
randbuffer = (randbuffer << randbits) ^ rand();
}
while (--count > 0);
printf("%d tests including %d overflows, %d passed, %d failed (%d 64 bit "
"errors)\n", tested, overflow, passed, error, error64);
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int validation_muldiv(int count, int argc, char **argv)
{
int tested = 0;
int overflow = 0;
int error = 0;
int error64 = 0;
int passed = 0;
int randbits = 0;
png_uint_32 randbuffer;
png_fixed_point a;
png_int_32 times, div;
while (--argc > 0)
{
fprintf(stderr, "unknown argument %s\n", *++argv);
return 1;
}
/* Find out about the random number generator. */
randbuffer = RAND_MAX;
while (randbuffer != 0) ++randbits, randbuffer >>= 1;
printf("Using random number generator that makes %d bits\n", randbits);
for (div=0; div<32; div += randbits)
randbuffer = (randbuffer << randbits) ^ rand();
a = 0;
times = div = 0;
do
{
png_fixed_point result;
/* NOTE: your mileage may vary, a type is required below that can
* hold 64 bits or more, if floating point is used a 64-bit or
* better mantissa is required.
*/
long long int fp, fpround;
unsigned long hi, lo;
int ok;
/* Check the values, png_64bit_product can only handle positive
* numbers, so correct for that here.
*/
{
long u1, u2;
int n = 0;
if (a < 0) u1 = -a, n = 1; else u1 = a;
if (times < 0) u2 = -times, n = !n; else u2 = times;
png_64bit_product(u1, u2, &hi, &lo);
if (n)
{
/* -x = ~x+1 */
lo = ((~lo) + 1) & 0xffffffff;
hi = ~hi;
if (lo == 0) ++hi;
}
}
fp = a;
fp *= times;
if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
{
fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
a, times, hi, lo, fp);
++error64;
}
if (div != 0)
{
/* Round - this is C round to zero. */
if ((fp < 0) != (div < 0))
fp -= div/2;
else
fp += div/2;
fp /= div;
fpround = fp;
/* Assume 2's complement here: */
ok = fpround <= PNG_UINT_31_MAX &&
fpround >= -1-(long long int)PNG_UINT_31_MAX;
if (!ok) ++overflow;
}
else
ok = 0, ++overflow, fpround = fp/*misleading*/;
if (verbose)
fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n", a, times, div,
fp, ok ? "ok" : "overflow");
++tested;
if (png_muldiv(&result, a, times, div) != ok)
{
++error;
if (ok)
fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n", a,
times, div, fp);
else
fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n", a,
times, div, result, fp);
}
else if (ok && result != fpround)
{
++error;
fprintf(stderr, "%d * %d / %d -> %d not %lld\n", a, times, div, result,
fp);
}
else
++passed;
/* Generate three new values, this uses rand() and rand() only returns
* up to RAND_MAX.
*/
/* CRUDE */
a += times;
times += div;
div = randbuffer;
randbuffer = (randbuffer << randbits) ^ rand();
}
while (--count > 0);
printf("%d tests including %d overflows, %d passed, %d failed (%d 64-bit "
"errors)\n", tested, overflow, passed, error, error64);
return 0;
}
| 173,721 |
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: WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
Commit Message:
CWE ID: CWE-20 | WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
WebContext* WebContext::FromBrowserContext(BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
| 165,411 |
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: mark_trusted_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
MarkTrustedJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
mark_desktop_file_trusted (common,
cancellable,
job->file,
job->interactive);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | mark_trusted_task_thread_func (GTask *task,
mark_desktop_file_executable_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
MarkTrustedJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
mark_desktop_file_executable (common,
cancellable,
job->file,
job->interactive);
}
| 167,750 |
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 nw_buf_free(nw_buf_pool *pool, nw_buf *buf)
{
if (pool->free < pool->free_total) {
pool->free_arr[pool->free++] = buf;
} else {
uint32_t new_free_total = pool->free_total * 2;
void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *));
if (new_arr) {
pool->free_total = new_free_total;
pool->free_arr = new_arr;
pool->free_arr[pool->free++] = buf;
} else {
free(buf);
}
}
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190 | void nw_buf_free(nw_buf_pool *pool, nw_buf *buf)
{
if (pool->free < pool->free_total) {
pool->free_arr[pool->free++] = buf;
} else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) {
uint32_t new_free_total = pool->free_total * 2;
void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *));
if (new_arr) {
pool->free_total = new_free_total;
pool->free_arr = new_arr;
pool->free_arr[pool->free++] = buf;
} else {
free(buf);
}
} else {
free(buf);
}
}
| 169,015 |
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 install_process_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->process_keyring)
return -EEXIST;
keyring = keyring_alloc("_pid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->process_keyring = keyring;
return 0;
}
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: [email protected] # 2.6.29+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-404 | int install_process_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->process_keyring)
return 0;
keyring = keyring_alloc("_pid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->process_keyring = keyring;
return 0;
}
| 168,275 |
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_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
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_header(wStream* s, NTLM_MESSAGE_HEADER* header)
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
| 169,278 |
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 AutofillManager::OnQueryFormFieldAutofillImpl(
int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& transformed_box,
bool autoselect_first_suggestion) {
external_delegate_->OnQuery(query_id, form, field, transformed_box);
std::vector<Suggestion> suggestions;
SuggestionsContext context;
GetAvailableSuggestions(form, field, &suggestions, &context);
if (context.is_autofill_available) {
switch (context.suppress_reason) {
case SuppressReason::kNotSuppressed:
break;
case SuppressReason::kCreditCardsAblation:
enable_ablation_logging_ = true;
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion);
return;
case SuppressReason::kAutocompleteOff:
return;
}
if (!suggestions.empty()) {
if (context.is_filling_credit_card) {
AutofillMetrics::LogIsQueriedCreditCardFormSecure(
context.is_context_secure);
}
if (!has_logged_address_suggestions_count_ &&
!context.section_has_autofilled_field) {
AutofillMetrics::LogAddressSuggestionsCount(suggestions.size());
has_logged_address_suggestions_count_ = true;
}
}
}
if (suggestions.empty() && !ShouldShowCreditCardSigninPromo(form, field) &&
field.should_autocomplete &&
!(context.focused_field &&
(IsCreditCardExpirationType(
context.focused_field->Type().GetStorableType()) ||
context.focused_field->Type().html_type() == HTML_TYPE_UNRECOGNIZED ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_NUMBER ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_VERIFICATION_CODE))) {
autocomplete_history_manager_->OnGetAutocompleteSuggestions(
query_id, field.name, field.value, field.form_control_type);
return;
}
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion,
context.is_all_server_suggestions);
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <[email protected]>
Commit-Queue: Sebastien Seguin-Gagnon <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID: | void AutofillManager::OnQueryFormFieldAutofillImpl(
int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& transformed_box,
bool autoselect_first_suggestion) {
external_delegate_->OnQuery(query_id, form, field, transformed_box);
std::vector<Suggestion> suggestions;
SuggestionsContext context;
GetAvailableSuggestions(form, field, &suggestions, &context);
if (context.is_autofill_available) {
switch (context.suppress_reason) {
case SuppressReason::kNotSuppressed:
break;
case SuppressReason::kCreditCardsAblation:
enable_ablation_logging_ = true;
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion);
return;
case SuppressReason::kAutocompleteOff:
return;
}
if (!suggestions.empty()) {
if (context.is_filling_credit_card) {
AutofillMetrics::LogIsQueriedCreditCardFormSecure(
context.is_context_secure);
}
if (!has_logged_address_suggestions_count_) {
AutofillMetrics::LogAddressSuggestionsCount(suggestions.size());
has_logged_address_suggestions_count_ = true;
}
}
}
if (suggestions.empty() && !ShouldShowCreditCardSigninPromo(form, field) &&
field.should_autocomplete &&
!(context.focused_field &&
(IsCreditCardExpirationType(
context.focused_field->Type().GetStorableType()) ||
context.focused_field->Type().html_type() == HTML_TYPE_UNRECOGNIZED ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_NUMBER ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_VERIFICATION_CODE))) {
autocomplete_history_manager_->OnGetAutocompleteSuggestions(
query_id, field.name, field.value, field.form_control_type);
return;
}
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion,
context.is_all_server_suggestions);
}
| 173,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: void PageInfo::OnWhitelistPasswordReuseButtonPressed(
content::WebContents* web_contents) {
#if defined(FULL_SAFE_BROWSING)
DCHECK(password_protection_service_);
DCHECK(safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE ||
safe_browsing_status_ ==
SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE);
password_protection_service_->OnUserAction(
web_contents,
safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE
? PasswordReuseEvent::SIGN_IN_PASSWORD
: PasswordReuseEvent::ENTERPRISE_PASSWORD,
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::MARK_AS_LEGITIMATE);
#endif
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311 | void PageInfo::OnWhitelistPasswordReuseButtonPressed(
content::WebContents* web_contents) {
#if defined(FULL_SAFE_BROWSING)
DCHECK(password_protection_service_);
DCHECK(site_identity_status_ == SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE ||
site_identity_status_ ==
SITE_IDENTITY_STATUS_ENTERPRISE_PASSWORD_REUSE);
password_protection_service_->OnUserAction(
web_contents,
site_identity_status_ == SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE
? PasswordReuseEvent::SIGN_IN_PASSWORD
: PasswordReuseEvent::ENTERPRISE_PASSWORD,
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::MARK_AS_LEGITIMATE);
#endif
}
| 172,437 |
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: gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
mem_free(gr.gr_ctx.value,
sizeof(gss_union_ctx_id_desc));
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc));
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
Commit Message: Fix gssrpc data leakage [CVE-2014-9423]
[MITKRB5-SA-2015-001] In svcauth_gss_accept_sec_context(), do not copy
bytes from the union context into the handle field we send to the
client. We do not use this handle field, so just supply a fixed
string of "xxxx".
In gss_union_ctx_id_struct, remove the unused "interposer" field which
was causing part of the union context to remain uninitialized.
ticket: 8058 (new)
target_version: 1.13.1
tags: pullup
CWE ID: CWE-200 | gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
| 166,787 |
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: pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
goto cleanup;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
Commit Message: PKINIT null pointer deref [CVE-2013-1415]
Don't dereference a null pointer when cleaning up.
The KDC plugin for PKINIT can dereference a null pointer when a
malformed packet causes processing to terminate early, leading to
a crash of the KDC process. An attacker would need to have a valid
PKINIT certificate or have observed a successful PKINIT authentication,
or an unauthenticated attacker could execute the attack if anonymous
PKINIT is enabled.
CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C
This is a minimal commit for pullup; style fixes in a followup.
[[email protected]: reformat and edit commit message]
(cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed)
ticket: 7570
version_fixed: 1.11.1
status: resolved
CWE ID: | pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
return retval;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
retval = 0;
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
| 166,133 |
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: explicit RemoveDownloadsTester(TestingProfile* testing_profile)
: download_manager_(new content::MockDownloadManager()),
chrome_download_manager_delegate_(testing_profile) {
content::BrowserContext::SetDownloadManagerForTesting(
testing_profile, base::WrapUnique(download_manager_));
EXPECT_EQ(download_manager_,
content::BrowserContext::GetDownloadManager(testing_profile));
EXPECT_CALL(*download_manager_, GetDelegate())
.WillOnce(Return(&chrome_download_manager_delegate_));
EXPECT_CALL(*download_manager_, Shutdown());
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125 | explicit RemoveDownloadsTester(TestingProfile* testing_profile)
: download_manager_(new content::MockDownloadManager()) {
content::BrowserContext::SetDownloadManagerForTesting(
testing_profile, base::WrapUnique(download_manager_));
std::unique_ptr<ChromeDownloadManagerDelegate> delegate =
std::make_unique<ChromeDownloadManagerDelegate>(testing_profile);
chrome_download_manager_delegate_ = delegate.get();
service_ =
DownloadCoreServiceFactory::GetForBrowserContext(testing_profile);
service_->SetDownloadManagerDelegateForTesting(std::move(delegate));
EXPECT_CALL(*download_manager_, GetBrowserContext())
.WillRepeatedly(Return(testing_profile));
EXPECT_CALL(*download_manager_, Shutdown());
}
| 173,167 |
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 rpza_decode_stream(RpzaContext *s)
{
int width = s->avctx->width;
int stride = s->frame.linesize[0] / 2;
int row_inc = stride - 4;
int stream_ptr = 0;
int chunk_size;
unsigned char opcode;
int n_blocks;
unsigned short colorA = 0, colorB;
unsigned short color4[4];
unsigned char index, idx;
unsigned short ta, tb;
unsigned short *pixels = (unsigned short *)s->frame.data[0];
int row_ptr = 0;
int pixel_ptr = 0;
int block_ptr;
int pixel_x, pixel_y;
int total_blocks;
/* First byte is always 0xe1. Warn if it's different */
if (s->buf[stream_ptr] != 0xe1)
av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",
s->buf[stream_ptr]);
/* Get chunk size, ingnoring first byte */
chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;
stream_ptr += 4;
/* If length mismatch use size from MOV file and try to decode anyway */
if (chunk_size != s->size)
av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");
chunk_size = s->size;
/* Number of 4x4 blocks in frame. */
total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);
/* Process chunk data */
while (stream_ptr < chunk_size) {
opcode = s->buf[stream_ptr++]; /* Get opcode */
n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */
/* If opcode MSbit is 0, we need more data to decide what to do */
if ((opcode & 0x80) == 0) {
colorA = (opcode << 8) | (s->buf[stream_ptr++]);
opcode = 0;
if ((s->buf[stream_ptr] & 0x80) != 0) {
/* Must behave as opcode 110xxxxx, using colorA computed
* above. Use fake opcode 0x20 to enter switch block at
* the right place */
opcode = 0x20;
n_blocks = 1;
}
}
switch (opcode & 0xe0) {
/* Skip blocks */
case 0x80:
while (n_blocks--) {
ADVANCE_BLOCK();
}
break;
/* Fill blocks with one color */
case 0xa0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill blocks with 4 colors */
case 0xc0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
case 0x20:
colorB = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
/* sort out the colors */
color4[0] = colorB;
color4[1] = 0;
color4[2] = 0;
color4[3] = colorA;
/* red components */
ta = (colorA >> 10) & 0x1F;
tb = (colorB >> 10) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;
/* green components */
ta = (colorA >> 5) & 0x1F;
tb = (colorB >> 5) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;
/* blue components */
ta = colorA & 0x1F;
tb = colorB & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5);
color4[2] |= ((21 * ta + 11 * tb) >> 5);
if (s->size - stream_ptr < n_blocks * 4)
return;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
index = s->buf[stream_ptr++];
for (pixel_x = 0; pixel_x < 4; pixel_x++){
idx = (index >> (2 * (3 - pixel_x))) & 0x03;
pixels[block_ptr] = color4[idx];
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill block with 16 colors */
case 0x00:
if (s->size - stream_ptr < 16)
return;
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
/* We already have color of upper left pixel */
if ((pixel_y != 0) || (pixel_x !=0)) {
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
}
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
break;
/* Unknown opcode */
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."
" Skip remaining %d bytes of chunk data.\n", opcode,
chunk_size - stream_ptr);
return;
} /* Opcode switch */
}
}
Commit Message: avcodec/rpza: Perform pointer advance and checks before using the pointers
Fixes out of array accesses
Fixes Ticket2850
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static void rpza_decode_stream(RpzaContext *s)
{
int width = s->avctx->width;
int stride = s->frame.linesize[0] / 2;
int row_inc = stride - 4;
int stream_ptr = 0;
int chunk_size;
unsigned char opcode;
int n_blocks;
unsigned short colorA = 0, colorB;
unsigned short color4[4];
unsigned char index, idx;
unsigned short ta, tb;
unsigned short *pixels = (unsigned short *)s->frame.data[0];
int row_ptr = 0;
int pixel_ptr = -4;
int block_ptr;
int pixel_x, pixel_y;
int total_blocks;
/* First byte is always 0xe1. Warn if it's different */
if (s->buf[stream_ptr] != 0xe1)
av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",
s->buf[stream_ptr]);
/* Get chunk size, ingnoring first byte */
chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;
stream_ptr += 4;
/* If length mismatch use size from MOV file and try to decode anyway */
if (chunk_size != s->size)
av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");
chunk_size = s->size;
/* Number of 4x4 blocks in frame. */
total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);
/* Process chunk data */
while (stream_ptr < chunk_size) {
opcode = s->buf[stream_ptr++]; /* Get opcode */
n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */
/* If opcode MSbit is 0, we need more data to decide what to do */
if ((opcode & 0x80) == 0) {
colorA = (opcode << 8) | (s->buf[stream_ptr++]);
opcode = 0;
if ((s->buf[stream_ptr] & 0x80) != 0) {
/* Must behave as opcode 110xxxxx, using colorA computed
* above. Use fake opcode 0x20 to enter switch block at
* the right place */
opcode = 0x20;
n_blocks = 1;
}
}
switch (opcode & 0xe0) {
/* Skip blocks */
case 0x80:
while (n_blocks--) {
ADVANCE_BLOCK();
}
break;
/* Fill blocks with one color */
case 0xa0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
while (n_blocks--) {
ADVANCE_BLOCK()
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
}
break;
/* Fill blocks with 4 colors */
case 0xc0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
case 0x20:
colorB = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
/* sort out the colors */
color4[0] = colorB;
color4[1] = 0;
color4[2] = 0;
color4[3] = colorA;
/* red components */
ta = (colorA >> 10) & 0x1F;
tb = (colorB >> 10) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;
/* green components */
ta = (colorA >> 5) & 0x1F;
tb = (colorB >> 5) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;
/* blue components */
ta = colorA & 0x1F;
tb = colorB & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5);
color4[2] |= ((21 * ta + 11 * tb) >> 5);
if (s->size - stream_ptr < n_blocks * 4)
return;
while (n_blocks--) {
ADVANCE_BLOCK();
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
index = s->buf[stream_ptr++];
for (pixel_x = 0; pixel_x < 4; pixel_x++){
idx = (index >> (2 * (3 - pixel_x))) & 0x03;
pixels[block_ptr] = color4[idx];
block_ptr++;
}
block_ptr += row_inc;
}
}
break;
/* Fill block with 16 colors */
case 0x00:
if (s->size - stream_ptr < 16)
return;
ADVANCE_BLOCK();
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
/* We already have color of upper left pixel */
if ((pixel_y != 0) || (pixel_x !=0)) {
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
}
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
break;
/* Unknown opcode */
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."
" Skip remaining %d bytes of chunk data.\n", opcode,
chunk_size - stream_ptr);
return;
} /* Opcode switch */
}
}
| 165,931 |
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: sd2_parse_rsrc_fork (SF_PRIVATE *psf)
{ SD2_RSRC rsrc ;
int k, marker, error = 0 ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.rsrc_len = psf_get_filelen (psf) ;
psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ;
if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header))
{ rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ;
rsrc.need_to_free_rsrc_data = SF_TRUE ;
}
else
{
rsrc.rsrc_data = psf->header ;
rsrc.need_to_free_rsrc_data = SF_FALSE ;
} ;
/* Read in the whole lot. */
psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
/* Reset the header storage because we have changed to the rsrcdes. */
psf->headindex = psf->headend = rsrc.rsrc_len ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0) ;
rsrc.map_offset = read_rsrc_int (&rsrc, 4) ;
rsrc.data_length = read_rsrc_int (&rsrc, 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 12) ;
if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000)
{ psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ;
rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ;
rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ;
} ;
psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n"
" data length : 0x%04X\n map length : 0x%04X\n",
rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ;
if (rsrc.data_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ;
error = SFE_SD2_BAD_DATA_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ;
error = SFE_SD2_BAD_MAP_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_length > len\n") ;
error = SFE_SD2_BAD_DATA_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_length > len\n") ;
error = SFE_SD2_BAD_MAP_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset + 28 >= rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ;
if (rsrc.string_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_offset = rsrc.map_offset + 30 ;
rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ;
if (rsrc.type_count < 1)
{ psf_log_printf (psf, "Bad type count.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.str_index = -1 ;
for (k = 0 ; k < rsrc.type_count ; k ++)
{ marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ;
if (marker == STR_MARKER)
{ rsrc.str_index = k ;
rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ;
error = parse_str_rsrc (psf, &rsrc) ;
goto parse_rsrc_fork_cleanup ;
} ;
} ;
psf_log_printf (psf, "No 'STR ' resource.\n") ;
error = SFE_SD2_BAD_RSRC ;
parse_rsrc_fork_cleanup :
psf_use_rsrc (psf, SF_FALSE) ;
if (rsrc.need_to_free_rsrc_data)
free (rsrc.rsrc_data) ;
return error ;
} /* sd2_parse_rsrc_fork */
Commit Message: src/sd2.c : Fix two potential buffer read overflows.
Closes: https://github.com/erikd/libsndfile/issues/93
CWE ID: CWE-119 | sd2_parse_rsrc_fork (SF_PRIVATE *psf)
{ SD2_RSRC rsrc ;
int k, marker, error = 0 ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.rsrc_len = psf_get_filelen (psf) ;
psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ;
if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header))
{ rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ;
rsrc.need_to_free_rsrc_data = SF_TRUE ;
}
else
{
rsrc.rsrc_data = psf->header ;
rsrc.need_to_free_rsrc_data = SF_FALSE ;
} ;
/* Read in the whole lot. */
psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
/* Reset the header storage because we have changed to the rsrcdes. */
psf->headindex = psf->headend = rsrc.rsrc_len ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0) ;
rsrc.map_offset = read_rsrc_int (&rsrc, 4) ;
rsrc.data_length = read_rsrc_int (&rsrc, 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 12) ;
if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000)
{ psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ;
rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ;
rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ;
} ;
psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n"
" data length : 0x%04X\n map length : 0x%04X\n",
rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ;
if (rsrc.data_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ;
error = SFE_SD2_BAD_DATA_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ;
error = SFE_SD2_BAD_MAP_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_length > len\n") ;
error = SFE_SD2_BAD_DATA_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_length > len\n") ;
error = SFE_SD2_BAD_MAP_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset + 28 >= rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ;
if (rsrc.string_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_offset = rsrc.map_offset + 30 ;
if (rsrc.map_offset + 28 > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset.\n") ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ;
if (rsrc.type_count < 1)
{ psf_log_printf (psf, "Bad type count.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.str_index = -1 ;
for (k = 0 ; k < rsrc.type_count ; k ++)
{ if (rsrc.type_offset + k * 8 > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad rsrc marker.\n") ;
goto parse_rsrc_fork_cleanup ;
} ;
marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ;
if (marker == STR_MARKER)
{ rsrc.str_index = k ;
rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ;
error = parse_str_rsrc (psf, &rsrc) ;
goto parse_rsrc_fork_cleanup ;
} ;
} ;
psf_log_printf (psf, "No 'STR ' resource.\n") ;
error = SFE_SD2_BAD_RSRC ;
parse_rsrc_fork_cleanup :
psf_use_rsrc (psf, SF_FALSE) ;
if (rsrc.need_to_free_rsrc_data)
free (rsrc.rsrc_data) ;
return error ;
} /* sd2_parse_rsrc_fork */
| 166,784 |
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 Automation::InitWithBrowserPath(const FilePath& browser_exe,
const CommandLine& options,
Error** error) {
if (!file_util::PathExists(browser_exe)) {
std::string message = base::StringPrintf(
"Could not find Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
*error = new Error(kUnknownError, message);
return;
}
CommandLine command(browser_exe);
command.AppendSwitch(switches::kDisableHangMonitor);
command.AppendSwitch(switches::kDisablePromptOnRepost);
command.AppendSwitch(switches::kDomAutomationController);
command.AppendSwitch(switches::kFullMemoryCrashReport);
command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL);
command.AppendSwitch(switches::kNoDefaultBrowserCheck);
command.AppendSwitch(switches::kNoFirstRun);
command.AppendSwitchASCII(switches::kTestType, "webdriver");
command.AppendArguments(options, false);
launcher_.reset(new AnonymousProxyLauncher(false));
ProxyLauncher::LaunchState launch_props = {
false, // clear_profile
FilePath(), // template_user_data
ProxyLauncher::DEFAULT_THEME,
command,
true, // include_testing_id
true // show_window
};
std::string chrome_details = base::StringPrintf(
"Using Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
VLOG(1) << chrome_details;
if (!launcher_->LaunchBrowserAndServer(launch_props, true)) {
*error = new Error(
kUnknownError,
"Unable to either launch or connect to Chrome. Please check that "
"ChromeDriver is up-to-date. " + chrome_details);
return;
}
launcher_->automation()->set_action_timeout_ms(base::kNoTimeout);
VLOG(1) << "Chrome launched successfully. Version: "
<< automation()->server_version();
bool has_automation_version = false;
*error = CompareVersion(730, 0, &has_automation_version);
if (*error)
return;
chrome_details += ", version (" + automation()->server_version() + ")";
if (has_automation_version) {
int version = 0;
std::string error_msg;
if (!SendGetChromeDriverAutomationVersion(
automation(), &version, &error_msg)) {
*error = new Error(kUnknownError, error_msg + " " + chrome_details);
return;
}
if (version > automation::kChromeDriverAutomationVersion) {
*error = new Error(
kUnknownError,
"ChromeDriver is not compatible with this version of Chrome. " +
chrome_details);
return;
}
}
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void Automation::InitWithBrowserPath(const FilePath& browser_exe,
const CommandLine& options,
Error** error) {
if (!file_util::PathExists(browser_exe)) {
std::string message = base::StringPrintf(
"Could not find Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
*error = new Error(kUnknownError, message);
return;
}
CommandLine command(browser_exe);
command.AppendSwitch(switches::kDisableHangMonitor);
command.AppendSwitch(switches::kDisablePromptOnRepost);
command.AppendSwitch(switches::kDomAutomationController);
command.AppendSwitch(switches::kFullMemoryCrashReport);
command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL);
command.AppendSwitch(switches::kNoDefaultBrowserCheck);
command.AppendSwitch(switches::kNoFirstRun);
command.AppendSwitchASCII(switches::kTestType, "webdriver");
command.AppendArguments(options, false);
launcher_.reset(new AnonymousProxyLauncher(false));
ProxyLauncher::LaunchState launch_props = {
false, // clear_profile
FilePath(), // template_user_data
ProxyLauncher::DEFAULT_THEME,
command,
true, // include_testing_id
true // show_window
};
std::string chrome_details = base::StringPrintf(
"Using Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
LOG(INFO) << chrome_details;
if (!launcher_->LaunchBrowserAndServer(launch_props, true)) {
*error = new Error(
kUnknownError,
"Unable to either launch or connect to Chrome. Please check that "
"ChromeDriver is up-to-date. " + chrome_details);
return;
}
launcher_->automation()->set_action_timeout_ms(base::kNoTimeout);
LOG(INFO) << "Chrome launched successfully. Version: "
<< automation()->server_version();
bool has_automation_version = false;
*error = CompareVersion(730, 0, &has_automation_version);
if (*error)
return;
chrome_details += ", version (" + automation()->server_version() + ")";
if (has_automation_version) {
int version = 0;
std::string error_msg;
if (!SendGetChromeDriverAutomationVersion(
automation(), &version, &error_msg)) {
*error = new Error(kUnknownError, error_msg + " " + chrome_details);
return;
}
if (version > automation::kChromeDriverAutomationVersion) {
*error = new Error(
kUnknownError,
"ChromeDriver is not compatible with this version of Chrome. " +
chrome_details);
return;
}
}
}
| 170,452 |
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 zend_object_value php_snmp_object_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
zend_object_value retval;
php_snmp_object *intern;
/* Allocate memory for it */
intern = emalloc(sizeof(php_snmp_object));
memset(&intern->zo, 0, sizeof(php_snmp_object));
zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
object_properties_init(&intern->zo, class_type);
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) php_snmp_object_free_storage, NULL TSRMLS_CC);
retval.handlers = (zend_object_handlers *) &php_snmp_object_handlers;
return retval;
}
/* {{{ php_snmp_error
*
* Record last SNMP-related error in object
*
*/
static void php_snmp_error(zval *object, const char *docref TSRMLS_DC, int type, const char *format, ...)
{
va_list args;
php_snmp_object *snmp_object = NULL;
if (object) {
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (type == PHP_SNMP_ERRNO_NOERROR) {
memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr));
} else {
va_start(args, format);
vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args);
va_end(args);
}
snmp_object->snmp_errno = type;
}
if (type == PHP_SNMP_ERRNO_NOERROR) {
return;
}
if (object && (snmp_object->exceptions_enabled & type)) {
zend_throw_exception_ex(php_snmp_exception_ce, type TSRMLS_CC, "%s", snmp_object->snmp_errstr);
} else {
va_start(args, format);
php_verror(docref, "", E_WARNING, format, args TSRMLS_CC);
va_end(args);
}
}
/* }}} */
/* {{{ php_snmp_getvalue
*
* SNMP value to zval converter
*
*/
static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval)
{
zval *val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
MAKE_STD_ZVAL(val);
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(val, buf, 1);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
default:
ZVAL_STRING(val, "Unknown value type", 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(val, buf, 1);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", val);
} else {
*snmpval = *val;
zval_copy_ctor(snmpval);
}
zval_ptr_dtor(&val);
if(dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
/* }}} */
/* {{{ php_snmp_internal
*
* SNMP object fetcher/setter for all SNMP versions
*
*/
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);
}
/* }}} */
/* {{{ php_snmp_parse_oid
*
* OID parser (and type, value for SNMP_SET command)
*/
static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
/* }}} */
/* {{{ netsnmp_session_init
allocates memory for session and session->peername, caller should free it manually using netsnmp_session_free() and efree()
*/
static int netsnmp_session_init(php_snmp_session **session_p, int version, char *hostname, char *community, int timeout, int retries TSRMLS_DC)
{
php_snmp_session *session;
char *pptr, *host_ptr;
int force_ipv6 = FALSE;
int n;
struct sockaddr **psal;
struct sockaddr **res;
*session_p = (php_snmp_session *)emalloc(sizeof(php_snmp_session));
session = *session_p;
if (session == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed allocating session");
return (-1);
}
memset(session, 0, sizeof(php_snmp_session));
snmp_sess_init(session);
session->version = version;
session->remote_port = SNMP_PORT;
session->peername = emalloc(MAX_NAME_LEN);
if (session->peername == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while copying hostname");
return (-1);
}
/* we copy original hostname for further processing */
strlcpy(session->peername, hostname, MAX_NAME_LEN);
host_ptr = session->peername;
/* Reading the hostname and its optional non-default port number */
if (*host_ptr == '[') { /* IPv6 address */
force_ipv6 = TRUE;
host_ptr++;
if ((pptr = strchr(host_ptr, ']'))) {
if (pptr[1] == ':') {
session->remote_port = atoi(pptr + 2);
}
*pptr = '\0';
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "malformed IPv6 address, closing square bracket missing");
return (-1);
}
} else { /* IPv4 address */
if ((pptr = strchr(host_ptr, ':'))) {
session->remote_port = atoi(pptr + 1);
*pptr = '\0';
}
}
/* since Net-SNMP library requires 'udp6:' prefix for all IPv6 addresses (in FQDN form too) we need to
perform possible name resolution before running any SNMP queries */
if ((n = php_network_getaddresses(host_ptr, SOCK_DGRAM, &psal, NULL TSRMLS_CC)) == 0) { /* some resolver error */
/* warnings sent, bailing out */
return (-1);
}
/* we have everything we need in psal, flush peername and fill it properly */
*(session->peername) = '\0';
res = psal;
while (n-- > 0) {
pptr = session->peername;
#if HAVE_GETADDRINFO && HAVE_IPV6 && HAVE_INET_NTOP
if (force_ipv6 && (*res)->sa_family != AF_INET6) {
res++;
continue;
}
if ((*res)->sa_family == AF_INET6) {
strcpy(session->peername, "udp6:[");
pptr = session->peername + strlen(session->peername);
inet_ntop((*res)->sa_family, &(((struct sockaddr_in6*)(*res))->sin6_addr), pptr, MAX_NAME_LEN);
strcat(pptr, "]");
} else if ((*res)->sa_family == AF_INET) {
inet_ntop((*res)->sa_family, &(((struct sockaddr_in*)(*res))->sin_addr), pptr, MAX_NAME_LEN);
} else {
res++;
continue;
}
#else
if ((*res)->sa_family != AF_INET) {
res++;
continue;
}
strcat(pptr, inet_ntoa(((struct sockaddr_in*)(*res))->sin_addr));
#endif
break;
}
if (strlen(session->peername) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown failure while resolving '%s'", hostname);
return (-1);
}
/* XXX FIXME
There should be check for non-empty session->peername!
*/
/* put back non-standard SNMP port */
if (session->remote_port != SNMP_PORT) {
pptr = session->peername + strlen(session->peername);
sprintf(pptr, ":%d", session->remote_port);
}
php_network_freeaddresses(psal);
if (version == SNMP_VERSION_3) {
/* Setting the security name. */
session->securityName = estrdup(community);
session->securityNameLen = strlen(session->securityName);
} else {
session->authenticator = NULL;
session->community = (u_char *)estrdup(community);
session->community_len = strlen(community);
}
session->retries = retries;
session->timeout = timeout;
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
Set the security level in the snmpv3 session */
static int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
{
if (!strcasecmp(level, "noAuthNoPriv") || !strcasecmp(level, "nanp")) {
s->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
} else if (!strcasecmp(level, "authNoPriv") || !strcasecmp(level, "anp")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
} else if (!strcasecmp(level, "authPriv") || !strcasecmp(level, "ap")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
} else {
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot)
Set the authentication protocol in the snmpv3 session */
static int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot TSRMLS_DC)
{
if (!strcasecmp(prot, "MD5")) {
s->securityAuthProto = usmHMACMD5AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
} else if (!strcasecmp(prot, "SHA")) {
s->securityAuthProto = usmHMACSHA1AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown authentication protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot)
Set the security protocol in the snmpv3 session */
static int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot TSRMLS_DC)
{
if (!strcasecmp(prot, "DES")) {
s->securityPrivProto = usmDESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
#ifdef HAVE_AES
} else if (!strcasecmp(prot, "AES128") || !strcasecmp(prot, "AES")) {
s->securityPrivProto = usmAESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown security protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass TSRMLS_DC)
{
int snmp_errno;
s->securityAuthKeyLen = USM_AUTH_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *) pass, strlen(pass),
s->securityAuthKey, &(s->securityAuthKeyLen)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error generating a key for authentication pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_sec_key(struct snmp_session *s, u_char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_sec_key(struct snmp_session *s, char *pass TSRMLS_DC)
{
int snmp_errno;
s->securityPrivKeyLen = USM_PRIV_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *)pass, strlen(pass),
s->securityPrivKey, &(s->securityPrivKeyLen)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error generating a key for privacy pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-2);
}
return (0);
}
/* }}} */
/* {{{ in netsnmp_session_set_contextEngineID(struct snmp_session *s, u_char * contextEngineID)
Set context Engine Id in the snmpv3 session */
static int netsnmp_session_set_contextEngineID(struct snmp_session *s, char * contextEngineID TSRMLS_DC)
{
size_t ebuf_len = 32, eout_len = 0;
u_char *ebuf = (u_char *) emalloc(ebuf_len);
if (ebuf == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "malloc failure setting contextEngineID");
return (-1);
}
if (!snmp_hex_to_binary(&ebuf, &ebuf_len, &eout_len, 1, contextEngineID)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad engine ID value '%s'", contextEngineID);
efree(ebuf);
return (-1);
}
if (s->contextEngineID) {
efree(s->contextEngineID);
}
s->contextEngineID = ebuf;
s->contextEngineIDLen = eout_len;
return (0);
}
/* }}} */
/* {{{ php_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID)
Set all snmpv3-related security options */
static int netsnmp_session_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID TSRMLS_DC)
{
/* Setting the security level. */
if (netsnmp_session_set_sec_level(session, sec_level)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid security level '%s'", sec_level);
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the authentication protocol. */
if (netsnmp_session_set_auth_protocol(session, auth_protocol TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the authentication passphrase. */
if (netsnmp_session_gen_auth_key(session, auth_passphrase TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the security protocol. */
if (netsnmp_session_set_sec_protocol(session, priv_protocol TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the security protocol passphrase. */
if (netsnmp_session_gen_sec_key(session, priv_passphrase TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
}
}
/* Setting contextName if specified */
if (contextName) {
session->contextName = contextName;
session->contextNameLen = strlen(contextName);
}
/* Setting contextEngineIS if specified */
if (contextEngineID && strlen(contextEngineID) && netsnmp_session_set_contextEngineID(session, contextEngineID TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
return (0);
}
/* }}} */
/* {{{ php_snmp
*
* Generic SNMP handler for all versions.
* This function makes use of the internal SNMP object fetcher.
* Used both in old (non-OO) and OO API
*
*/
static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version)
{
zval **oid, **value, **type;
char *a1, *a2, *a3, *a4, *a5, *a6, *a7;
int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len;
zend_bool use_orignames = 0, suffix_keys = 0;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
int argc = ZEND_NUM_ARGS();
struct objid_query objid_query;
php_snmp_session *session;
int session_less_mode = (getThis() == NULL);
php_snmp_object *snmp_object;
php_snmp_object glob_snmp_object;
objid_query.max_repetitions = -1;
objid_query.non_repeaters = 0;
objid_query.valueretrieval = SNMP_G(valueretrieval);
objid_query.oid_increasing_check = TRUE;
if (session_less_mode) {
if (version == SNMP_VERSION_3) {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) {
RETURN_FALSE;
}
} else if (st & SNMP_CMD_WALK) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) {
RETURN_FALSE;
}
if (suffix_keys) {
st |= SNMP_USE_SUFFIX_AS_KEYS;
}
} else if (st & SNMP_CMD_GET) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) {
RETURN_FALSE;
}
if (use_orignames) {
st |= SNMP_ORIGINAL_NAMES_AS_KEYS;
}
} else {
/* SNMP_CMD_GETNEXT
*/
if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) {
RETURN_FALSE;
}
}
}
if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) {
RETURN_FALSE;
}
if (session_less_mode) {
if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
RETURN_FALSE;
}
if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
} else {
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
session = snmp_object->session;
if (!session) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object");
efree(objid_query.vars);
RETURN_FALSE;
}
if (snmp_object->max_oids > 0) {
objid_query.step = snmp_object->max_oids;
if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */
objid_query.max_repetitions = snmp_object->max_oids;
}
}
objid_query.oid_increasing_check = snmp_object->oid_increasing_check;
objid_query.valueretrieval = snmp_object->valueretrieval;
glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print);
glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print);
glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format);
}
if (objid_query.max_repetitions < 0) {
objid_query.max_repetitions = 20; /* provide correct default value */
}
php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query);
efree(objid_query.vars);
if (session_less_mode) {
netsnmp_session_free(&session);
} else {
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format);
}
}
/* }}} */
/* {{{ proto mixed snmpget(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpget)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpgetnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpgetnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmpwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmprealwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmprealwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmpset(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmpset)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmp_get_quick_print(void)
Return the current status of quick_print */
PHP_FUNCTION(snmp_get_quick_print)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT));
}
/* }}} */
/* {{{ proto bool snmp_set_quick_print(int quick_print)
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmp_set_quick_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, (int)a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_enum_print(int enum_print)
Return all values that are enums with their enum value instead of the raw integer */
PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_oid_output_format(int oid_format)
Set the OID output format. */
PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto mixed snmp2_get(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_getnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmp2_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_real_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmp2_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto bool snmp2_set(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmp2_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp_set_valueretrieval(int method)
Specify the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_set_valueretrieval)
{
long method;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) {
RETURN_FALSE;
}
if (method >= 0 && method <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) {
SNMP_G(valueretrieval) = method;
RETURN_TRUE;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP value retrieval method '%ld'", method);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int snmp_get_valueretrieval()
Return the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_get_valueretrieval)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
RETURN_LONG(SNMP_G(valueretrieval));
}
/* }}} */
/* {{{ proto bool snmp_read_mib(string filename)
Reads and parses a MIB file into the active MIB tree. */
PHP_FUNCTION(snmp_read_mib)
{
char *filename;
int filename_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) {
RETURN_FALSE;
}
if (!read_mib(filename)) {
char *error = strerror(errno);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading MIB file '%s': %s", filename, error);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto SNMP SNMP::__construct(int version, string hostname, string community|securityName [, long timeout [, long retries]])
Creates a new SNMP session to specified host. */
PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
int a1_len, a2_len;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
zend_error_handling error_handling;
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
switch(version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
/* }}} */
/* {{{ proto bool SNMP::close()
Close SNMP session */
PHP_METHOD(snmp, close)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
netsnmp_session_free(&(snmp_object->session));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed SNMP::get(mixed object_id [, bool preserve_keys])
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::getnext(mixed object_id)
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::walk(mixed object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters]])
Return all objects including their respective object id withing the specified one as array of oid->value pairs */
PHP_METHOD(snmp, walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, (-1));
}
/* }}} */
/* {{{ proto bool SNMP::set(mixed object_id, mixed type, mixed value)
Set the value of a SNMP object */
PHP_METHOD(snmp, set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, (-1));
}
/* {{{ proto bool SNMP::setSecurity(string sec_level, [ string auth_protocol, string auth_passphrase [, string priv_protocol, string priv_passphrase [, string contextName [, string contextEngineID]]]])
Set SNMPv3 security-related session parameters */
PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto long SNMP::getErrno()
Get last error code number */
PHP_METHOD(snmp, getErrno)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
RETVAL_LONG(snmp_object->snmp_errno);
return;
}
/* }}} */
/* {{{ proto long SNMP::getError()
Get last error message */
PHP_METHOD(snmp, getError)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
RETVAL_STRING(snmp_object->snmp_errstr, 1);
return;
}
/* }}} */
/* {{{ */
void php_snmp_add_property(HashTable *h, const char *name, size_t name_length, php_snmp_read_t read_func, php_snmp_write_t write_func TSRMLS_DC)
{
php_snmp_prop_handler p;
p.name = (char*) name;
p.name_length = name_length;
p.read_func = (read_func) ? read_func : NULL;
p.write_func = (write_func) ? write_func : NULL;
zend_hash_add(h, (char *)name, name_length + 1, &p, sizeof(php_snmp_prop_handler), NULL);
}
/* }}} */
/* {{{ php_snmp_read_property(zval *object, zval *member, int type[, const zend_literal *key])
Generic object property reader */
zval *php_snmp_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC)
{
zval tmp_member;
zval *retval;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
int ret;
ret = FAILURE;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
if (Z_TYPE_P(member) != IS_STRING) {
tmp_member = *member;
zval_copy_ctor(&tmp_member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
ret = zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, (void **) &hnd);
if (ret == SUCCESS && hnd->read_func) {
ret = hnd->read_func(obj, &retval TSRMLS_CC);
if (ret == SUCCESS) {
/* ensure we're creating a temporary variable */
Z_SET_REFCOUNT_P(retval, 0);
} else {
retval = EG(uninitialized_zval_ptr);
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
retval = std_hnd->read_property(object, member, type, key TSRMLS_CC);
}
if (member == &tmp_member) {
zval_dtor(member);
}
return(retval);
}
/* }}} */
/* {{{ php_snmp_write_property(zval *object, zval *member, zval *value[, const zend_literal *key])
Generic object property writer */
void php_snmp_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC)
{
zval tmp_member;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
int ret;
if (Z_TYPE_P(member) != IS_STRING) {
tmp_member = *member;
zval_copy_ctor(&tmp_member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
ret = FAILURE;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
ret = zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, (void **) &hnd);
if (ret == SUCCESS && hnd->write_func) {
hnd->write_func(obj, value TSRMLS_CC);
if (! PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) == 0) {
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
std_hnd->write_property(object, member, value, key TSRMLS_CC);
}
if (member == &tmp_member) {
zval_dtor(member);
}
}
/* }}} */
/* {{{ php_snmp_has_property(zval *object, zval *member, int has_set_exists[, const zend_literal *key])
Generic object property checker */
static int php_snmp_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC)
{
php_snmp_prop_handler *hnd;
int ret = 0;
if (zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, (void **)&hnd) == SUCCESS) {
switch (has_set_exists) {
case 2:
ret = 1;
break;
case 0: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, key TSRMLS_CC);
if (value != EG(uninitialized_zval_ptr)) {
ret = Z_TYPE_P(value) != IS_NULL? 1:0;
/* refcount is 0 */
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
break;
}
default: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, key TSRMLS_CC);
if (value != EG(uninitialized_zval_ptr)) {
convert_to_boolean(value);
ret = Z_BVAL_P(value)? 1:0;
/* refcount is 0 */
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
break;
}
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
ret = std_hnd->has_property(object, member, has_set_exists, key TSRMLS_CC);
}
return ret;
}
/* }}} */
/* {{{ php_snmp_get_properties(zval *object)
Returns all object properties. Injects SNMP properties into object on first call */
static HashTable *php_snmp_get_properties(zval *object TSRMLS_DC)
ulong num_key;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
props = zend_std_get_properties(object TSRMLS_CC);
zend_hash_internal_pointer_reset_ex(&php_snmp_properties, &pos);
while (zend_hash_get_current_data_ex(&php_snmp_properties, (void**)&hnd, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_snmp_properties, &key, &key_len, &num_key, 0, &pos);
if (!hnd->read_func || hnd->read_func(obj, &val TSRMLS_CC) != SUCCESS) {
val = EG(uninitialized_zval_ptr);
Z_ADDREF_P(val);
}
zend_hash_update(props, key, key_len, (void *)&val, sizeof(zval *), NULL);
zend_hash_move_forward_ex(&php_snmp_properties, &pos);
}
return obj->zo.properties;
}
/* }}} */
/* {{{ */
static int php_snmp_read_info(php_snmp_object *snmp_object, zval **retval TSRMLS_DC)
{
zval *val;
MAKE_STD_ZVAL(*retval);
array_init(*retval);
if (snmp_object->session == NULL) {
return SUCCESS;
}
MAKE_STD_ZVAL(val);
ZVAL_STRINGL(val, snmp_object->session->peername, strlen(snmp_object->session->peername), 1);
add_assoc_zval(*retval, "hostname", val);
if (snmp_object->session == NULL) {
return SUCCESS;
}
MAKE_STD_ZVAL(val);
ZVAL_STRINGL(val, snmp_object->session->peername, strlen(snmp_object->session->peername), 1);
add_assoc_zval(*retval, "hostname", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->remote_port);
add_assoc_zval(*retval, "port", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->timeout);
add_assoc_zval(*retval, "timeout", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->retries);
add_assoc_zval(*retval, "retries", val);
return SUCCESS;
}
/* }}} */
ZVAL_NULL(*retval);
}
return SUCCESS;
}
/* }}} */
Commit Message:
CWE ID: CWE-416 | static zend_object_value php_snmp_object_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
zend_object_value retval;
php_snmp_object *intern;
/* Allocate memory for it */
intern = emalloc(sizeof(php_snmp_object));
memset(&intern->zo, 0, sizeof(php_snmp_object));
zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
object_properties_init(&intern->zo, class_type);
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) php_snmp_object_free_storage, NULL TSRMLS_CC);
retval.handlers = (zend_object_handlers *) &php_snmp_object_handlers;
return retval;
}
/* {{{ php_snmp_error
*
* Record last SNMP-related error in object
*
*/
static void php_snmp_error(zval *object, const char *docref TSRMLS_DC, int type, const char *format, ...)
{
va_list args;
php_snmp_object *snmp_object = NULL;
if (object) {
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (type == PHP_SNMP_ERRNO_NOERROR) {
memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr));
} else {
va_start(args, format);
vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args);
va_end(args);
}
snmp_object->snmp_errno = type;
}
if (type == PHP_SNMP_ERRNO_NOERROR) {
return;
}
if (object && (snmp_object->exceptions_enabled & type)) {
zend_throw_exception_ex(php_snmp_exception_ce, type TSRMLS_CC, "%s", snmp_object->snmp_errstr);
} else {
va_start(args, format);
php_verror(docref, "", E_WARNING, format, args TSRMLS_CC);
va_end(args);
}
}
/* }}} */
/* {{{ php_snmp_getvalue
*
* SNMP value to zval converter
*
*/
static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval)
{
zval *val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
MAKE_STD_ZVAL(val);
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(val, buf, 1);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
default:
ZVAL_STRING(val, "Unknown value type", 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(val, buf, 1);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", val);
} else {
*snmpval = *val;
zval_copy_ctor(snmpval);
}
zval_ptr_dtor(&val);
if(dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
/* }}} */
/* {{{ php_snmp_internal
*
* SNMP object fetcher/setter for all SNMP versions
*
*/
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);
}
/* }}} */
/* {{{ php_snmp_parse_oid
*
* OID parser (and type, value for SNMP_SET command)
*/
static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
/* }}} */
/* {{{ netsnmp_session_init
allocates memory for session and session->peername, caller should free it manually using netsnmp_session_free() and efree()
*/
static int netsnmp_session_init(php_snmp_session **session_p, int version, char *hostname, char *community, int timeout, int retries TSRMLS_DC)
{
php_snmp_session *session;
char *pptr, *host_ptr;
int force_ipv6 = FALSE;
int n;
struct sockaddr **psal;
struct sockaddr **res;
*session_p = (php_snmp_session *)emalloc(sizeof(php_snmp_session));
session = *session_p;
if (session == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed allocating session");
return (-1);
}
memset(session, 0, sizeof(php_snmp_session));
snmp_sess_init(session);
session->version = version;
session->remote_port = SNMP_PORT;
session->peername = emalloc(MAX_NAME_LEN);
if (session->peername == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while copying hostname");
return (-1);
}
/* we copy original hostname for further processing */
strlcpy(session->peername, hostname, MAX_NAME_LEN);
host_ptr = session->peername;
/* Reading the hostname and its optional non-default port number */
if (*host_ptr == '[') { /* IPv6 address */
force_ipv6 = TRUE;
host_ptr++;
if ((pptr = strchr(host_ptr, ']'))) {
if (pptr[1] == ':') {
session->remote_port = atoi(pptr + 2);
}
*pptr = '\0';
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "malformed IPv6 address, closing square bracket missing");
return (-1);
}
} else { /* IPv4 address */
if ((pptr = strchr(host_ptr, ':'))) {
session->remote_port = atoi(pptr + 1);
*pptr = '\0';
}
}
/* since Net-SNMP library requires 'udp6:' prefix for all IPv6 addresses (in FQDN form too) we need to
perform possible name resolution before running any SNMP queries */
if ((n = php_network_getaddresses(host_ptr, SOCK_DGRAM, &psal, NULL TSRMLS_CC)) == 0) { /* some resolver error */
/* warnings sent, bailing out */
return (-1);
}
/* we have everything we need in psal, flush peername and fill it properly */
*(session->peername) = '\0';
res = psal;
while (n-- > 0) {
pptr = session->peername;
#if HAVE_GETADDRINFO && HAVE_IPV6 && HAVE_INET_NTOP
if (force_ipv6 && (*res)->sa_family != AF_INET6) {
res++;
continue;
}
if ((*res)->sa_family == AF_INET6) {
strcpy(session->peername, "udp6:[");
pptr = session->peername + strlen(session->peername);
inet_ntop((*res)->sa_family, &(((struct sockaddr_in6*)(*res))->sin6_addr), pptr, MAX_NAME_LEN);
strcat(pptr, "]");
} else if ((*res)->sa_family == AF_INET) {
inet_ntop((*res)->sa_family, &(((struct sockaddr_in*)(*res))->sin_addr), pptr, MAX_NAME_LEN);
} else {
res++;
continue;
}
#else
if ((*res)->sa_family != AF_INET) {
res++;
continue;
}
strcat(pptr, inet_ntoa(((struct sockaddr_in*)(*res))->sin_addr));
#endif
break;
}
if (strlen(session->peername) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown failure while resolving '%s'", hostname);
return (-1);
}
/* XXX FIXME
There should be check for non-empty session->peername!
*/
/* put back non-standard SNMP port */
if (session->remote_port != SNMP_PORT) {
pptr = session->peername + strlen(session->peername);
sprintf(pptr, ":%d", session->remote_port);
}
php_network_freeaddresses(psal);
if (version == SNMP_VERSION_3) {
/* Setting the security name. */
session->securityName = estrdup(community);
session->securityNameLen = strlen(session->securityName);
} else {
session->authenticator = NULL;
session->community = (u_char *)estrdup(community);
session->community_len = strlen(community);
}
session->retries = retries;
session->timeout = timeout;
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
Set the security level in the snmpv3 session */
static int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
{
if (!strcasecmp(level, "noAuthNoPriv") || !strcasecmp(level, "nanp")) {
s->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
} else if (!strcasecmp(level, "authNoPriv") || !strcasecmp(level, "anp")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
} else if (!strcasecmp(level, "authPriv") || !strcasecmp(level, "ap")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
} else {
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot)
Set the authentication protocol in the snmpv3 session */
static int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot TSRMLS_DC)
{
if (!strcasecmp(prot, "MD5")) {
s->securityAuthProto = usmHMACMD5AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
} else if (!strcasecmp(prot, "SHA")) {
s->securityAuthProto = usmHMACSHA1AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown authentication protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot)
Set the security protocol in the snmpv3 session */
static int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot TSRMLS_DC)
{
if (!strcasecmp(prot, "DES")) {
s->securityPrivProto = usmDESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
#ifdef HAVE_AES
} else if (!strcasecmp(prot, "AES128") || !strcasecmp(prot, "AES")) {
s->securityPrivProto = usmAESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown security protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass TSRMLS_DC)
{
int snmp_errno;
s->securityAuthKeyLen = USM_AUTH_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *) pass, strlen(pass),
s->securityAuthKey, &(s->securityAuthKeyLen)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error generating a key for authentication pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_sec_key(struct snmp_session *s, u_char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_sec_key(struct snmp_session *s, char *pass TSRMLS_DC)
{
int snmp_errno;
s->securityPrivKeyLen = USM_PRIV_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *)pass, strlen(pass),
s->securityPrivKey, &(s->securityPrivKeyLen)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error generating a key for privacy pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-2);
}
return (0);
}
/* }}} */
/* {{{ in netsnmp_session_set_contextEngineID(struct snmp_session *s, u_char * contextEngineID)
Set context Engine Id in the snmpv3 session */
static int netsnmp_session_set_contextEngineID(struct snmp_session *s, char * contextEngineID TSRMLS_DC)
{
size_t ebuf_len = 32, eout_len = 0;
u_char *ebuf = (u_char *) emalloc(ebuf_len);
if (ebuf == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "malloc failure setting contextEngineID");
return (-1);
}
if (!snmp_hex_to_binary(&ebuf, &ebuf_len, &eout_len, 1, contextEngineID)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad engine ID value '%s'", contextEngineID);
efree(ebuf);
return (-1);
}
if (s->contextEngineID) {
efree(s->contextEngineID);
}
s->contextEngineID = ebuf;
s->contextEngineIDLen = eout_len;
return (0);
}
/* }}} */
/* {{{ php_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID)
Set all snmpv3-related security options */
static int netsnmp_session_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID TSRMLS_DC)
{
/* Setting the security level. */
if (netsnmp_session_set_sec_level(session, sec_level)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid security level '%s'", sec_level);
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the authentication protocol. */
if (netsnmp_session_set_auth_protocol(session, auth_protocol TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the authentication passphrase. */
if (netsnmp_session_gen_auth_key(session, auth_passphrase TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the security protocol. */
if (netsnmp_session_set_sec_protocol(session, priv_protocol TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the security protocol passphrase. */
if (netsnmp_session_gen_sec_key(session, priv_passphrase TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
}
}
/* Setting contextName if specified */
if (contextName) {
session->contextName = contextName;
session->contextNameLen = strlen(contextName);
}
/* Setting contextEngineIS if specified */
if (contextEngineID && strlen(contextEngineID) && netsnmp_session_set_contextEngineID(session, contextEngineID TSRMLS_CC)) {
/* Warning message sent already, just bail out */
return (-1);
}
return (0);
}
/* }}} */
/* {{{ php_snmp
*
* Generic SNMP handler for all versions.
* This function makes use of the internal SNMP object fetcher.
* Used both in old (non-OO) and OO API
*
*/
static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version)
{
zval **oid, **value, **type;
char *a1, *a2, *a3, *a4, *a5, *a6, *a7;
int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len;
zend_bool use_orignames = 0, suffix_keys = 0;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
int argc = ZEND_NUM_ARGS();
struct objid_query objid_query;
php_snmp_session *session;
int session_less_mode = (getThis() == NULL);
php_snmp_object *snmp_object;
php_snmp_object glob_snmp_object;
objid_query.max_repetitions = -1;
objid_query.non_repeaters = 0;
objid_query.valueretrieval = SNMP_G(valueretrieval);
objid_query.oid_increasing_check = TRUE;
if (session_less_mode) {
if (version == SNMP_VERSION_3) {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) {
RETURN_FALSE;
}
} else if (st & SNMP_CMD_WALK) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) {
RETURN_FALSE;
}
if (suffix_keys) {
st |= SNMP_USE_SUFFIX_AS_KEYS;
}
} else if (st & SNMP_CMD_GET) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) {
RETURN_FALSE;
}
if (use_orignames) {
st |= SNMP_ORIGINAL_NAMES_AS_KEYS;
}
} else {
/* SNMP_CMD_GETNEXT
*/
if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) {
RETURN_FALSE;
}
}
}
if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) {
RETURN_FALSE;
}
if (session_less_mode) {
if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
RETURN_FALSE;
}
if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
} else {
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
session = snmp_object->session;
if (!session) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object");
efree(objid_query.vars);
RETURN_FALSE;
}
if (snmp_object->max_oids > 0) {
objid_query.step = snmp_object->max_oids;
if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */
objid_query.max_repetitions = snmp_object->max_oids;
}
}
objid_query.oid_increasing_check = snmp_object->oid_increasing_check;
objid_query.valueretrieval = snmp_object->valueretrieval;
glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print);
glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print);
glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format);
}
if (objid_query.max_repetitions < 0) {
objid_query.max_repetitions = 20; /* provide correct default value */
}
php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query);
efree(objid_query.vars);
if (session_less_mode) {
netsnmp_session_free(&session);
} else {
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format);
}
}
/* }}} */
/* {{{ proto mixed snmpget(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpget)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpgetnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpgetnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmpwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmprealwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmprealwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmpset(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmpset)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmp_get_quick_print(void)
Return the current status of quick_print */
PHP_FUNCTION(snmp_get_quick_print)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT));
}
/* }}} */
/* {{{ proto bool snmp_set_quick_print(int quick_print)
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmp_set_quick_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, (int)a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_enum_print(int enum_print)
Return all values that are enums with their enum value instead of the raw integer */
PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_oid_output_format(int oid_format)
Set the OID output format. */
PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto mixed snmp2_get(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_getnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmp2_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_real_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id withing the specified one */
PHP_FUNCTION(snmp2_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto bool snmp2_set(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmp2_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp_set_valueretrieval(int method)
Specify the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_set_valueretrieval)
{
long method;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) {
RETURN_FALSE;
}
if (method >= 0 && method <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) {
SNMP_G(valueretrieval) = method;
RETURN_TRUE;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP value retrieval method '%ld'", method);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int snmp_get_valueretrieval()
Return the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_get_valueretrieval)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
RETURN_LONG(SNMP_G(valueretrieval));
}
/* }}} */
/* {{{ proto bool snmp_read_mib(string filename)
Reads and parses a MIB file into the active MIB tree. */
PHP_FUNCTION(snmp_read_mib)
{
char *filename;
int filename_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) {
RETURN_FALSE;
}
if (!read_mib(filename)) {
char *error = strerror(errno);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading MIB file '%s': %s", filename, error);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto SNMP SNMP::__construct(int version, string hostname, string community|securityName [, long timeout [, long retries]])
Creates a new SNMP session to specified host. */
PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
int a1_len, a2_len;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
zend_error_handling error_handling;
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
switch(version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
/* }}} */
/* {{{ proto bool SNMP::close()
Close SNMP session */
PHP_METHOD(snmp, close)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
netsnmp_session_free(&(snmp_object->session));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed SNMP::get(mixed object_id [, bool preserve_keys])
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::getnext(mixed object_id)
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::walk(mixed object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters]])
Return all objects including their respective object id withing the specified one as array of oid->value pairs */
PHP_METHOD(snmp, walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, (-1));
}
/* }}} */
/* {{{ proto bool SNMP::set(mixed object_id, mixed type, mixed value)
Set the value of a SNMP object */
PHP_METHOD(snmp, set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, (-1));
}
/* {{{ proto bool SNMP::setSecurity(string sec_level, [ string auth_protocol, string auth_passphrase [, string priv_protocol, string priv_passphrase [, string contextName [, string contextEngineID]]]])
Set SNMPv3 security-related session parameters */
PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto long SNMP::getErrno()
Get last error code number */
PHP_METHOD(snmp, getErrno)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
RETVAL_LONG(snmp_object->snmp_errno);
return;
}
/* }}} */
/* {{{ proto long SNMP::getError()
Get last error message */
PHP_METHOD(snmp, getError)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
RETVAL_STRING(snmp_object->snmp_errstr, 1);
return;
}
/* }}} */
/* {{{ */
void php_snmp_add_property(HashTable *h, const char *name, size_t name_length, php_snmp_read_t read_func, php_snmp_write_t write_func TSRMLS_DC)
{
php_snmp_prop_handler p;
p.name = (char*) name;
p.name_length = name_length;
p.read_func = (read_func) ? read_func : NULL;
p.write_func = (write_func) ? write_func : NULL;
zend_hash_add(h, (char *)name, name_length + 1, &p, sizeof(php_snmp_prop_handler), NULL);
}
/* }}} */
/* {{{ php_snmp_read_property(zval *object, zval *member, int type[, const zend_literal *key])
Generic object property reader */
zval *php_snmp_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC)
{
zval tmp_member;
zval *retval;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
int ret;
ret = FAILURE;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
if (Z_TYPE_P(member) != IS_STRING) {
tmp_member = *member;
zval_copy_ctor(&tmp_member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
ret = zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, (void **) &hnd);
if (ret == SUCCESS && hnd->read_func) {
ret = hnd->read_func(obj, &retval TSRMLS_CC);
if (ret == SUCCESS) {
/* ensure we're creating a temporary variable */
Z_SET_REFCOUNT_P(retval, 0);
} else {
retval = EG(uninitialized_zval_ptr);
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
retval = std_hnd->read_property(object, member, type, key TSRMLS_CC);
}
if (member == &tmp_member) {
zval_dtor(member);
}
return(retval);
}
/* }}} */
/* {{{ php_snmp_write_property(zval *object, zval *member, zval *value[, const zend_literal *key])
Generic object property writer */
void php_snmp_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC)
{
zval tmp_member;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
int ret;
if (Z_TYPE_P(member) != IS_STRING) {
tmp_member = *member;
zval_copy_ctor(&tmp_member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
ret = FAILURE;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
ret = zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, (void **) &hnd);
if (ret == SUCCESS && hnd->write_func) {
hnd->write_func(obj, value TSRMLS_CC);
if (! PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) == 0) {
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
std_hnd->write_property(object, member, value, key TSRMLS_CC);
}
if (member == &tmp_member) {
zval_dtor(member);
}
}
/* }}} */
/* {{{ php_snmp_has_property(zval *object, zval *member, int has_set_exists[, const zend_literal *key])
Generic object property checker */
static int php_snmp_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC)
{
php_snmp_prop_handler *hnd;
int ret = 0;
if (zend_hash_find(&php_snmp_properties, Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, (void **)&hnd) == SUCCESS) {
switch (has_set_exists) {
case 2:
ret = 1;
break;
case 0: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, key TSRMLS_CC);
if (value != EG(uninitialized_zval_ptr)) {
ret = Z_TYPE_P(value) != IS_NULL? 1:0;
/* refcount is 0 */
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
break;
}
default: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, key TSRMLS_CC);
if (value != EG(uninitialized_zval_ptr)) {
convert_to_boolean(value);
ret = Z_BVAL_P(value)? 1:0;
/* refcount is 0 */
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
break;
}
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
ret = std_hnd->has_property(object, member, has_set_exists, key TSRMLS_CC);
}
return ret;
}
/* }}} */
static HashTable *php_snmp_get_gc(zval *object, zval ***gc_data, int *gc_data_count TSRMLS_DC) /* {{{ */
{
*gc_data = NULL;
*gc_data_count = 0;
return zend_std_get_properties(object TSRMLS_CC);
}
/* }}} */
/* {{{ php_snmp_get_properties(zval *object)
Returns all object properties. Injects SNMP properties into object on first call */
static HashTable *php_snmp_get_properties(zval *object TSRMLS_DC)
ulong num_key;
obj = (php_snmp_object *)zend_objects_get_address(object TSRMLS_CC);
props = zend_std_get_properties(object TSRMLS_CC);
zend_hash_internal_pointer_reset_ex(&php_snmp_properties, &pos);
while (zend_hash_get_current_data_ex(&php_snmp_properties, (void**)&hnd, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_snmp_properties, &key, &key_len, &num_key, 0, &pos);
if (!hnd->read_func || hnd->read_func(obj, &val TSRMLS_CC) != SUCCESS) {
val = EG(uninitialized_zval_ptr);
Z_ADDREF_P(val);
}
zend_hash_update(props, key, key_len, (void *)&val, sizeof(zval *), NULL);
zend_hash_move_forward_ex(&php_snmp_properties, &pos);
}
return obj->zo.properties;
}
/* }}} */
/* {{{ */
static int php_snmp_read_info(php_snmp_object *snmp_object, zval **retval TSRMLS_DC)
{
zval *val;
MAKE_STD_ZVAL(*retval);
array_init(*retval);
if (snmp_object->session == NULL) {
return SUCCESS;
}
MAKE_STD_ZVAL(val);
ZVAL_STRINGL(val, snmp_object->session->peername, strlen(snmp_object->session->peername), 1);
add_assoc_zval(*retval, "hostname", val);
if (snmp_object->session == NULL) {
return SUCCESS;
}
MAKE_STD_ZVAL(val);
ZVAL_STRINGL(val, snmp_object->session->peername, strlen(snmp_object->session->peername), 1);
add_assoc_zval(*retval, "hostname", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->remote_port);
add_assoc_zval(*retval, "port", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->timeout);
add_assoc_zval(*retval, "timeout", val);
MAKE_STD_ZVAL(val);
ZVAL_LONG(val, snmp_object->session->retries);
add_assoc_zval(*retval, "retries", val);
return SUCCESS;
}
/* }}} */
ZVAL_NULL(*retval);
}
return SUCCESS;
}
/* }}} */
| 164,978 |
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 WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1612
CWE ID: CWE-119 | static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 170,202 |
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: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64,
gint base64_len)
{
GstBuffer *img;
guchar *img_data;
gsize img_len;
guint save = 0;
gint state = 0;
if (base64_len < 2)
goto not_enough_data;
img_data = g_try_malloc0 (base64_len * 3 / 4);
if (img_data == NULL)
goto alloc_failed;
img_len = g_base64_decode_step (img_data_base64, base64_len, img_data,
&state, &save);
if (img_len == 0)
goto decode_failed;
img = gst_tag_image_data_to_image_buffer (img_data, img_len,
GST_TAG_IMAGE_TYPE_NONE);
if (img == NULL)
gst_tag_list_add (tags, GST_TAG_MERGE_APPEND,
GST_TAG_PREVIEW_IMAGE, img, NULL);
GST_TAG_PREVIEW_IMAGE, img, NULL);
gst_buffer_unref (img);
g_free (img_data);
return;
/* ERRORS */
{
GST_WARNING ("COVERART tag with too little base64-encoded data");
GST_WARNING ("COVERART tag with too little base64-encoded data");
return;
}
alloc_failed:
{
GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag");
return;
}
decode_failed:
{
GST_WARNING ("Couldn't decode bas64 image data from COVERART tag");
g_free (img_data);
return;
}
convert_failed:
{
GST_WARNING ("Couldn't extract image or image type from COVERART tag");
g_free (img_data);
return;
}
}
Commit Message:
CWE ID: CWE-189 | gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64,
gst_vorbis_tag_add_coverart (GstTagList * tags, gchar * img_data_base64,
gint base64_len)
{
GstBuffer *img;
gsize img_len;
guchar *out;
guint save = 0;
gint state = 0;
if (base64_len < 2)
goto not_enough_data;
/* img_data_base64 points to a temporary copy of the base64 encoded data, so
* it's safe to do inpace decoding here
* TODO: glib 2.20 and later provides g_base64_decode_inplace, so change this
* to use glib's API instead once it's in wider use:
* http://bugzilla.gnome.org/show_bug.cgi?id=564728
* http://svn.gnome.org/viewvc/glib?view=revision&revision=7807 */
out = (guchar *) img_data_base64;
img_len = g_base64_decode_step (img_data_base64, base64_len,
out, &state, &save);
if (img_len == 0)
goto decode_failed;
img = gst_tag_image_data_to_image_buffer (out, img_len,
GST_TAG_IMAGE_TYPE_NONE);
if (img == NULL)
gst_tag_list_add (tags, GST_TAG_MERGE_APPEND,
GST_TAG_PREVIEW_IMAGE, img, NULL);
GST_TAG_PREVIEW_IMAGE, img, NULL);
gst_buffer_unref (img);
return;
/* ERRORS */
{
GST_WARNING ("COVERART tag with too little base64-encoded data");
GST_WARNING ("COVERART tag with too little base64-encoded data");
return;
}
decode_failed:
{
GST_WARNING ("Couldn't decode base64 image data from COVERART tag");
return;
}
convert_failed:
{
GST_WARNING ("Couldn't extract image or image type from COVERART tag");
return;
}
}
| 164,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 void command_port_read_callback(struct urb *urb)
{
struct usb_serial_port *command_port = urb->context;
struct whiteheat_command_private *command_info;
int status = urb->status;
unsigned char *data = urb->transfer_buffer;
int result;
command_info = usb_get_serial_port_data(command_port);
if (!command_info) {
dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status);
if (status != -ENOENT)
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
return;
}
usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data);
if (data[0] == WHITEHEAT_CMD_COMPLETE) {
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_CMD_FAILURE) {
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_EVENT) {
/* These are unsolicited reports from the firmware, hence no
waiting command to wakeup */
dev_dbg(&urb->dev->dev, "%s - event received\n", __func__);
} else if (data[0] == WHITEHEAT_GET_DTR_RTS) {
memcpy(command_info->result_buffer, &data[1],
urb->actual_length - 1);
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else
dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__);
/* Continue trying to always read */
result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC);
if (result)
dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n",
__func__, result);
}
Commit Message: USB: whiteheat: Added bounds checking for bulk command response
This patch fixes a potential security issue in the whiteheat USB driver
which might allow a local attacker to cause kernel memory corrpution. This
is due to an unchecked memcpy into a fixed size buffer (of 64 bytes). On
EHCI and XHCI busses it's possible to craft responses greater than 64
bytes leading a buffer overflow.
Signed-off-by: James Forshaw <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | static void command_port_read_callback(struct urb *urb)
{
struct usb_serial_port *command_port = urb->context;
struct whiteheat_command_private *command_info;
int status = urb->status;
unsigned char *data = urb->transfer_buffer;
int result;
command_info = usb_get_serial_port_data(command_port);
if (!command_info) {
dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__);
return;
}
if (!urb->actual_length) {
dev_dbg(&urb->dev->dev, "%s - empty response, exiting.\n", __func__);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status);
if (status != -ENOENT)
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
return;
}
usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data);
if (data[0] == WHITEHEAT_CMD_COMPLETE) {
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_CMD_FAILURE) {
command_info->command_finished = WHITEHEAT_CMD_FAILURE;
wake_up(&command_info->wait_command);
} else if (data[0] == WHITEHEAT_EVENT) {
/* These are unsolicited reports from the firmware, hence no
waiting command to wakeup */
dev_dbg(&urb->dev->dev, "%s - event received\n", __func__);
} else if ((data[0] == WHITEHEAT_GET_DTR_RTS) &&
(urb->actual_length - 1 <= sizeof(command_info->result_buffer))) {
memcpy(command_info->result_buffer, &data[1],
urb->actual_length - 1);
command_info->command_finished = WHITEHEAT_CMD_COMPLETE;
wake_up(&command_info->wait_command);
} else
dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__);
/* Continue trying to always read */
result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC);
if (result)
dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n",
__func__, result);
}
| 166,369 |
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: validate_entries( bool ignore_invalid_entry ) {
HASHITER it = hash_iter_begin( ConfigTab, TABLESIZE );
unsigned int invalid_entries = 0;
MyString tmp;
MyString output = "The following configuration macros appear to contain default values that must be changed before Condor will run. These macros are:\n";
while( ! hash_iter_done(it) ) {
char * val = hash_iter_value(it);
if( strstr(val, FORBIDDEN_CONFIG_VAL) ) {
char * name = hash_iter_key(it);
MyString filename;
int line_number;
param_get_location(name, filename, line_number);
tmp.sprintf(" %s (found on line %d of %s)\n", name, line_number, filename.Value());
output += tmp;
invalid_entries++;
}
hash_iter_next(it);
}
hash_iter_delete(&it);
if(invalid_entries > 0) {
if(ignore_invalid_entry) {
dprintf(D_ALWAYS, "%s", output.Value());
} else {
EXCEPT(output.Value());
}
}
}
Commit Message:
CWE ID: CWE-134 | validate_entries( bool ignore_invalid_entry ) {
HASHITER it = hash_iter_begin( ConfigTab, TABLESIZE );
unsigned int invalid_entries = 0;
MyString tmp;
MyString output = "The following configuration macros appear to contain default values that must be changed before Condor will run. These macros are:\n";
while( ! hash_iter_done(it) ) {
char * val = hash_iter_value(it);
if( strstr(val, FORBIDDEN_CONFIG_VAL) ) {
char * name = hash_iter_key(it);
MyString filename;
int line_number;
param_get_location(name, filename, line_number);
tmp.sprintf(" %s (found on line %d of %s)\n", name, line_number, filename.Value());
output += tmp;
invalid_entries++;
}
hash_iter_next(it);
}
hash_iter_delete(&it);
if(invalid_entries > 0) {
if(ignore_invalid_entry) {
dprintf(D_ALWAYS, "%s", output.Value());
} else {
EXCEPT("%s", output.Value());
}
}
}
| 165,382 |
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: png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
/* Note: this does not properly handle chunks that are > 64K under DOS */
{
png_byte compression_type;
png_bytep pC;
png_charp profile;
png_uint_32 skip = 0;
png_uint_32 profile_size, profile_length;
png_size_t slength, prefix_length, data_length;
png_debug(1, "in png_handle_iCCP");
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before iCCP");
else if (png_ptr->mode & PNG_HAVE_IDAT)
{
png_warning(png_ptr, "Invalid iCCP after IDAT");
png_crc_finish(png_ptr, length);
return;
}
else if (png_ptr->mode & PNG_HAVE_PLTE)
/* Should be an error, but we can cope with it */
png_warning(png_ptr, "Out of place iCCP chunk");
if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
{
png_warning(png_ptr, "Duplicate iCCP chunk");
png_crc_finish(png_ptr, length);
return;
}
#ifdef PNG_MAX_MALLOC_64K
if (length > (png_uint_32)65535L)
{
png_warning(png_ptr, "iCCP chunk too large to fit in memory");
skip = length - (png_uint_32)65535L;
length = (png_uint_32)65535L;
}
#endif
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
slength = (png_size_t)length;
png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
if (png_crc_finish(png_ptr, skip))
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
return;
}
png_ptr->chunkdata[slength] = 0x00;
for (profile = png_ptr->chunkdata; *profile; profile++)
/* Empty loop to find end of name */ ;
++profile;
/* There should be at least one zero (the compression type byte)
* following the separator, and we should be on it
*/
if ( profile >= png_ptr->chunkdata + slength - 1)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Malformed iCCP chunk");
return;
}
/* Compression_type should always be zero */
compression_type = *profile++;
if (compression_type)
{
png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
wrote nonzero) */
}
prefix_length = profile - png_ptr->chunkdata;
png_decompress_chunk(png_ptr, compression_type,
slength, prefix_length, &data_length);
profile_length = data_length - prefix_length;
if ( prefix_length > data_length || profile_length < 4)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Profile size field missing from iCCP chunk");
return;
}
/* Check the profile_size recorded in the first 32 bits of the ICC profile */
pC = (png_bytep)(png_ptr->chunkdata + prefix_length);
profile_size = ((*(pC ))<<24) |
((*(pC + 1))<<16) |
((*(pC + 2))<< 8) |
((*(pC + 3)) );
if (profile_size < profile_length)
profile_length = profile_size;
if (profile_size > profile_length)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Ignoring truncated iCCP profile.");
return;
}
png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata,
compression_type, png_ptr->chunkdata + prefix_length, profile_length);
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
/* Note: this does not properly handle chunks that are > 64K under DOS */
{
png_byte compression_type;
png_bytep pC;
png_charp profile;
png_uint_32 skip = 0;
png_uint_32 profile_size, profile_length;
png_size_t slength, prefix_length, data_length;
png_debug(1, "in png_handle_iCCP");
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before iCCP");
else if (png_ptr->mode & PNG_HAVE_IDAT)
{
png_warning(png_ptr, "Invalid iCCP after IDAT");
png_crc_finish(png_ptr, length);
return;
}
else if (png_ptr->mode & PNG_HAVE_PLTE)
/* Should be an error, but we can cope with it */
png_warning(png_ptr, "Out of place iCCP chunk");
if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
{
png_warning(png_ptr, "Duplicate iCCP chunk");
png_crc_finish(png_ptr, length);
return;
}
#ifdef PNG_MAX_MALLOC_64K
if (length > (png_uint_32)65535L)
{
png_warning(png_ptr, "iCCP chunk too large to fit in memory");
skip = length - (png_uint_32)65535L;
length = (png_uint_32)65535L;
}
#endif
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
slength = (png_size_t)length;
png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
if (png_crc_finish(png_ptr, skip))
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
return;
}
png_ptr->chunkdata[slength] = 0x00;
for (profile = png_ptr->chunkdata; *profile; profile++)
/* Empty loop to find end of name */ ;
++profile;
/* There should be at least one zero (the compression type byte)
* following the separator, and we should be on it
*/
if ( profile >= png_ptr->chunkdata + slength - 1)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Malformed iCCP chunk");
return;
}
/* Compression_type should always be zero */
compression_type = *profile++;
if (compression_type)
{
png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
wrote nonzero) */
}
prefix_length = profile - png_ptr->chunkdata;
png_decompress_chunk(png_ptr, compression_type,
slength, prefix_length, &data_length);
profile_length = data_length - prefix_length;
if ( prefix_length > data_length || profile_length < 4)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Profile size field missing from iCCP chunk");
return;
}
/* Check the profile_size recorded in the first 32 bits of the ICC profile */
pC = (png_bytep)(png_ptr->chunkdata + prefix_length);
profile_size = ((png_uint_32) (*(pC )<<24)) |
((png_uint_32) (*(pC + 1)<<16)) |
((png_uint_32) (*(pC + 2)<< 8)) |
((png_uint_32) (*(pC + 3) ));
if (profile_size < profile_length)
profile_length = profile_size;
if (profile_size > profile_length)
{
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
png_warning(png_ptr, "Ignoring truncated iCCP profile.");
return;
}
png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata,
compression_type, png_ptr->chunkdata + prefix_length, profile_length);
png_free(png_ptr, png_ptr->chunkdata);
png_ptr->chunkdata = NULL;
}
| 172,178 |
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 parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)
{
/* OpenSc Operation values for each command operation-type */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
u8 bValue;
int i;
int iKeyRef = 0;
int iMethod;
int iPinCount;
int iOffset = 0;
int iOperation;
const int* p_idx;
/* Check all sub-AC definitions within the total AC */
while (len > 1) { /* minimum length = 2 */
int iACLen = buf[iOffset] & 0x0F;
iPinCount = -1; /* default no pin required */
iMethod = SC_AC_NONE; /* default no authentication required */
if (buf[iOffset] & 0X80) { /* AC in adaptive coding */
/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */
int iParmLen = 1; /* command-byte is always present */
int iKeyLen = 0; /* Encryption key is optional */
if (buf[iOffset] & 0x20) iKeyLen++;
if (buf[iOffset+1] & 0x40) iParmLen++;
if (buf[iOffset+1] & 0x20) iParmLen++;
if (buf[iOffset+1] & 0x10) iParmLen++;
if (buf[iOffset+1] & 0x08) iParmLen++;
/* Get KeyNumber if available */
if(iKeyLen) {
int iSC = buf[iOffset+iACLen];
switch( (iSC>>5) & 0x03 ){
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
}
/* Get PinNumber if available */
if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */
iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */
iMethod = SC_AC_CHV;
}
/* Convert SETCOS command to OpenSC command group */
switch(buf[iOffset+2]){
case 0x2A: /* crypto operation */
iOperation = SC_AC_OP_CRYPTO;
break;
case 0x46: /* key-generation operation */
iOperation = SC_AC_OP_UPDATE;
break;
default:
iOperation = SC_AC_OP_SELECT;
break;
}
sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);
}
else { /* AC in simple coding */
/* Initial AC is treated as an operational AC */
/* Get specific Cmd groups for specified file-type */
switch (file->type) {
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* EF */
p_idx = ef_idx;
break;
}
/* Encryption key present ? */
iPinCount = iACLen - 1;
if (buf[iOffset] & 0x20) {
int iSC = buf[iOffset + iACLen];
switch( (iSC>>5) & 0x03 ) {
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
iPinCount--; /* one byte used for keyReference */
}
/* Pin present ? */
if ( iPinCount > 0 ) {
iKeyRef = buf[iOffset + 2]; /* pin ref */
iMethod = SC_AC_CHV;
}
/* Add AC for each command-operationType into OpenSc structure */
bValue = buf[iOffset + 1];
for (i = 0; i < 8; i++) {
if((bValue & 1) && (p_idx[i] >= 0))
sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);
bValue >>= 1;
}
}
/* Current field treated, get next AC sub-field */
iOffset += iACLen +1; /* AC + PTL-byte */
len -= iACLen +1;
}
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)
{
/* OpenSc Operation values for each command operation-type */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
u8 bValue;
int i;
int iKeyRef = 0;
int iMethod;
int iPinCount;
int iOffset = 0;
int iOperation;
const int* p_idx;
/* Check all sub-AC definitions within the total AC */
while (len > 1) { /* minimum length = 2 */
int iACLen = buf[iOffset] & 0x0F;
if ((size_t) iACLen > len)
break;
iPinCount = -1; /* default no pin required */
iMethod = SC_AC_NONE; /* default no authentication required */
if (buf[iOffset] & 0X80) { /* AC in adaptive coding */
/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */
int iParmLen = 1; /* command-byte is always present */
int iKeyLen = 0; /* Encryption key is optional */
if (buf[iOffset] & 0x20) iKeyLen++;
if (buf[iOffset+1] & 0x40) iParmLen++;
if (buf[iOffset+1] & 0x20) iParmLen++;
if (buf[iOffset+1] & 0x10) iParmLen++;
if (buf[iOffset+1] & 0x08) iParmLen++;
/* Get KeyNumber if available */
if(iKeyLen) {
int iSC;
if (len < 1+iACLen)
break;
iSC = buf[iOffset+iACLen];
switch( (iSC>>5) & 0x03 ){
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
}
/* Get PinNumber if available */
if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */
if (len < 1+1+1+iParmLen)
break;
iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */
iMethod = SC_AC_CHV;
}
/* Convert SETCOS command to OpenSC command group */
if (len < 1+2)
break;
switch(buf[iOffset+2]){
case 0x2A: /* crypto operation */
iOperation = SC_AC_OP_CRYPTO;
break;
case 0x46: /* key-generation operation */
iOperation = SC_AC_OP_UPDATE;
break;
default:
iOperation = SC_AC_OP_SELECT;
break;
}
sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);
}
else { /* AC in simple coding */
/* Initial AC is treated as an operational AC */
/* Get specific Cmd groups for specified file-type */
switch (file->type) {
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* EF */
p_idx = ef_idx;
break;
}
/* Encryption key present ? */
iPinCount = iACLen - 1;
if (buf[iOffset] & 0x20) {
int iSC;
if (len < 1 + iACLen)
break;
iSC = buf[iOffset + iACLen];
switch( (iSC>>5) & 0x03 ) {
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
iPinCount--; /* one byte used for keyReference */
}
/* Pin present ? */
if ( iPinCount > 0 ) {
if (len < 1 + 2)
break;
iKeyRef = buf[iOffset + 2]; /* pin ref */
iMethod = SC_AC_CHV;
}
/* Add AC for each command-operationType into OpenSc structure */
bValue = buf[iOffset + 1];
for (i = 0; i < 8; i++) {
if((bValue & 1) && (p_idx[i] >= 0))
sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);
bValue >>= 1;
}
}
/* Current field treated, get next AC sub-field */
iOffset += iACLen +1; /* AC + PTL-byte */
len -= iACLen +1;
}
}
| 169,064 |
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 MediaStreamDispatcherHost::BindRequest(
mojom::MediaStreamDispatcherHostRequest request) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
bindings_.AddBinding(this, std::move(request));
}
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 | void MediaStreamDispatcherHost::BindRequest(
void MediaStreamDispatcherHost::Create(
int render_process_id,
int render_frame_id,
MediaStreamManager* media_stream_manager,
mojom::MediaStreamDispatcherHostRequest request) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
mojo::MakeStrongBinding(
std::make_unique<MediaStreamDispatcherHost>(
render_process_id, render_frame_id, media_stream_manager),
std::move(request));
}
| 173,091 |
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: SPL_METHOD(SplFileObject, getMaxLineLen)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG((long)intern->u.file.max_line_len);
} /* }}} */
/* {{{ proto bool SplFileObject::hasChildren()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, getMaxLineLen)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG((long)intern->u.file.max_line_len);
} /* }}} */
/* {{{ proto bool SplFileObject::hasChildren()
| 167,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: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder.
CWE ID: CWE-476 | jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
image = 0;
info = 0;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
goto error;
//return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
//return 0;
goto error;
}
JAS_DBGLOG(1,
("BMP information: len %ld; width %ld; height %ld; numplanes %d; "
"depth %d; enctype %ld; siz %ld; hres %ld; vres %ld; numcolors %ld; "
"mincolors %ld\n", JAS_CAST(long, info->len),
JAS_CAST(long, info->width), JAS_CAST(long, info->height),
JAS_CAST(long, info->numplanes), JAS_CAST(long, info->depth),
JAS_CAST(long, info->enctype), JAS_CAST(long, info->siz),
JAS_CAST(long, info->hres), JAS_CAST(long, info->vres),
JAS_CAST(long, info->numcolors), JAS_CAST(long, info->mincolors)));
if (info->width < 0 || info->height < 0 || info->numplanes < 0 ||
info->depth < 0 || info->siz < 0 || info->hres < 0 || info->vres < 0) {
jas_eprintf("corrupt bit stream\n");
goto error;
}
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
//bmp_info_destroy(info);
//return 0;
goto error;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
goto error;
//return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
//bmp_info_destroy(info);
//return 0;
goto error;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
//bmp_info_destroy(info);
//return 0;
goto error;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
//bmp_info_destroy(info);
//jas_image_destroy(image);
//return 0;
goto error;
}
bmp_info_destroy(info);
return image;
error:
if (info) {
bmp_info_destroy(info);
}
if (image) {
jas_image_destroy(image);
}
return 0;
}
| 168,756 |
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_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
Commit Message: Extend build-id reporting to 8-byte IDs that lld can generate (Ed Maste)
CWE ID: CWE-119 | do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
| 170,010 |
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 msg_cache_check(const char *id, struct BodyCache *bcache, void *data)
{
struct Context *ctx = (struct Context *) data;
if (!ctx)
return -1;
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return -1;
#ifdef USE_HCACHE
/* keep hcache file if hcache == bcache */
if (strcmp(HC_FNAME "." HC_FEXT, id) == 0)
return 0;
#endif
for (int i = 0; i < ctx->msgcount; i++)
{
/* if the id we get is known for a header: done (i.e. keep in cache) */
if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))
return 0;
}
/* message not found in context -> remove it from cache
* return the result of bcache, so we stop upon its first error
*/
return mutt_bcache_del(bcache, id);
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22 | static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data)
{
struct Context *ctx = (struct Context *) data;
if (!ctx)
return -1;
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return -1;
#ifdef USE_HCACHE
/* keep hcache file if hcache == bcache */
if (strcmp(HC_FNAME "." HC_FEXT, id) == 0)
return 0;
#endif
for (int i = 0; i < ctx->msgcount; i++)
{
/* if the id we get is known for a header: done (i.e. keep in cache) */
if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))
return 0;
}
/* message not found in context -> remove it from cache
* return the result of bcache, so we stop upon its first error
*/
return mutt_bcache_del(bcache, cache_id(id));
}
| 169,120 |
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 enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_EXT_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else {
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
}
return 0;
}
| 169,069 |
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 install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
Commit Message: KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: | int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
| 169,376 |
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 *ReadTEXTImage(const ImageInfo *image_info,Image *image,
char *text,ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p;
DrawInfo
*draw_info;
Image
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,offset,image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
char *text,ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p;
DrawInfo
*draw_info;
Image
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,offset,image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,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: InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType(
const Resource& cached_resource) {
switch (cached_resource.GetType()) {
case Resource::kImage:
return InspectorPageAgent::kImageResource;
case Resource::kFont:
return InspectorPageAgent::kFontResource;
case Resource::kMedia:
return InspectorPageAgent::kMediaResource;
case Resource::kManifest:
return InspectorPageAgent::kManifestResource;
case Resource::kTextTrack:
return InspectorPageAgent::kTextTrackResource;
case Resource::kCSSStyleSheet:
case Resource::kXSLStyleSheet:
return InspectorPageAgent::kStylesheetResource;
case Resource::kScript:
return InspectorPageAgent::kScriptResource;
case Resource::kImportResource:
case Resource::kMainResource:
return InspectorPageAgent::kDocumentResource;
default:
break;
}
return InspectorPageAgent::kOtherResource;
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType(
InspectorPageAgent::ResourceType InspectorPageAgent::ToResourceType(
const Resource::Type resource_type) {
switch (resource_type) {
case Resource::kImage:
return InspectorPageAgent::kImageResource;
case Resource::kFont:
return InspectorPageAgent::kFontResource;
case Resource::kMedia:
return InspectorPageAgent::kMediaResource;
case Resource::kManifest:
return InspectorPageAgent::kManifestResource;
case Resource::kTextTrack:
return InspectorPageAgent::kTextTrackResource;
case Resource::kCSSStyleSheet:
case Resource::kXSLStyleSheet:
return InspectorPageAgent::kStylesheetResource;
case Resource::kScript:
return InspectorPageAgent::kScriptResource;
case Resource::kImportResource:
case Resource::kMainResource:
return InspectorPageAgent::kDocumentResource;
default:
break;
}
return InspectorPageAgent::kOtherResource;
}
| 172,469 |
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 struct page *alloc_huge_page(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct hstate *h = hstate_vma(vma);
struct page *page;
struct address_space *mapping = vma->vm_file->f_mapping;
struct inode *inode = mapping->host;
long chg;
/*
* Processes that did not create the mapping will have no reserves and
* will not have accounted against quota. Check that the quota can be
* made before satisfying the allocation
* MAP_NORESERVE mappings may also need pages and quota allocated
* if no reserve mapping overlaps.
*/
chg = vma_needs_reservation(h, vma, addr);
if (chg < 0)
return ERR_PTR(-VM_FAULT_OOM);
if (chg)
if (hugetlb_get_quota(inode->i_mapping, chg))
return ERR_PTR(-VM_FAULT_SIGBUS);
spin_lock(&hugetlb_lock);
page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);
spin_unlock(&hugetlb_lock);
if (!page) {
page = alloc_buddy_huge_page(h, NUMA_NO_NODE);
if (!page) {
hugetlb_put_quota(inode->i_mapping, chg);
return ERR_PTR(-VM_FAULT_SIGBUS);
}
}
set_page_private(page, (unsigned long) mapping);
vma_commit_reservation(h, vma, addr);
return page;
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static struct page *alloc_huge_page(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct hugepage_subpool *spool = subpool_vma(vma);
struct hstate *h = hstate_vma(vma);
struct page *page;
long chg;
/*
* Processes that did not create the mapping will have no
* reserves and will not have accounted against subpool
* limit. Check that the subpool limit can be made before
* satisfying the allocation MAP_NORESERVE mappings may also
* need pages and subpool limit allocated allocated if no reserve
* mapping overlaps.
*/
chg = vma_needs_reservation(h, vma, addr);
if (chg < 0)
return ERR_PTR(-VM_FAULT_OOM);
if (chg)
if (hugepage_subpool_get_pages(spool, chg))
return ERR_PTR(-VM_FAULT_SIGBUS);
spin_lock(&hugetlb_lock);
page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);
spin_unlock(&hugetlb_lock);
if (!page) {
page = alloc_buddy_huge_page(h, NUMA_NO_NODE);
if (!page) {
hugepage_subpool_put_pages(spool, chg);
return ERR_PTR(-VM_FAULT_SIGBUS);
}
}
set_page_private(page, (unsigned long)spool);
vma_commit_reservation(h, vma, addr);
return page;
}
| 165,608 |
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: GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
renderer_process_(base::kNullProcessHandle),
renderer_pid_(base::kNullProcessId),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
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: | GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
| 170,931 |
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 impeg2d_flush_ext_and_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | void impeg2d_flush_ext_and_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while((u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
| 173,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: SPL_METHOD(RecursiveDirectoryIterator, getChildren)
{
zval *zpath, *zflags;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_object *subdir;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
MAKE_STD_ZVAL(zflags);
MAKE_STD_ZVAL(zpath);
ZVAL_LONG(zflags, intern->flags);
ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);
zval_ptr_dtor(&zpath);
zval_ptr_dtor(&zflags);
subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);
if (subdir) {
if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {
subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
} else {
subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);
subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);
}
subdir->info_class = intern->info_class;
subdir->file_class = intern->file_class;
subdir->oth = intern->oth;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(RecursiveDirectoryIterator, getChildren)
{
zval *zpath, *zflags;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_object *subdir;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
MAKE_STD_ZVAL(zflags);
MAKE_STD_ZVAL(zpath);
ZVAL_LONG(zflags, intern->flags);
ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);
zval_ptr_dtor(&zpath);
zval_ptr_dtor(&zflags);
subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);
if (subdir) {
if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {
subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
} else {
subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);
subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);
}
subdir->info_class = intern->info_class;
subdir->file_class = intern->file_class;
subdir->oth = intern->oth;
}
}
| 167,045 |
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: shared_memory_handle(const gfx::GpuMemoryBufferHandle& handle) {
if (handle.type != gfx::SHARED_MEMORY_BUFFER &&
handle.type != gfx::DXGI_SHARED_HANDLE &&
handle.type != gfx::ANDROID_HARDWARE_BUFFER)
return mojo::ScopedSharedBufferHandle();
return mojo::WrapSharedMemoryHandle(handle.handle, handle.handle.GetSize(),
false);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;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: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | shared_memory_handle(const gfx::GpuMemoryBufferHandle& handle) {
if (handle.type != gfx::SHARED_MEMORY_BUFFER &&
handle.type != gfx::DXGI_SHARED_HANDLE &&
handle.type != gfx::ANDROID_HARDWARE_BUFFER)
return mojo::ScopedSharedBufferHandle();
return mojo::WrapSharedMemoryHandle(
handle.handle, handle.handle.GetSize(),
mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite);
}
| 172,886 |
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: ospf6_print_lshdr(netdissect_options *ndo,
register const struct lsa6_hdr *lshp, const u_char *dataend)
{
if ((const u_char *)(lshp + 1) > dataend)
goto trunc;
ND_TCHECK(lshp->ls_type);
ND_TCHECK(lshp->ls_seq);
ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u",
ipaddr_string(ndo, &lshp->ls_router),
EXTRACT_32BITS(&lshp->ls_seq),
EXTRACT_16BITS(&lshp->ls_age),
EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr)));
ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid);
return (0);
trunc:
return (1);
}
Commit Message: (for 4.9.3) CVE-2018-14880/OSPFv3: Fix a bounds check
Need to test bounds check for the last field of the structure lsa6_hdr.
No need to test other fields.
Include Security working under the Mozilla SOS program had independently
identified this vulnerability in 2018 by means of code audit.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | ospf6_print_lshdr(netdissect_options *ndo,
register const struct lsa6_hdr *lshp, const u_char *dataend)
{
if ((const u_char *)(lshp + 1) > dataend)
goto trunc;
ND_TCHECK(lshp->ls_length); /* last field of struct lsa6_hdr */
ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u",
ipaddr_string(ndo, &lshp->ls_router),
EXTRACT_32BITS(&lshp->ls_seq),
EXTRACT_16BITS(&lshp->ls_age),
EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr)));
ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid);
return (0);
trunc:
return (1);
}
| 169,834 |
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: XcursorImageCreate (int width, int height)
{
XcursorImage *image;
image = malloc (sizeof (XcursorImage) +
width * height * sizeof (XcursorPixel));
if (!image)
image->height = height;
image->delay = 0;
return image;
}
Commit Message:
CWE ID: CWE-190 | XcursorImageCreate (int width, int height)
{
XcursorImage *image;
if (width < 0 || height < 0)
return NULL;
if (width > XCURSOR_IMAGE_MAX_SIZE || height > XCURSOR_IMAGE_MAX_SIZE)
return NULL;
image = malloc (sizeof (XcursorImage) +
width * height * sizeof (XcursorPixel));
if (!image)
image->height = height;
image->delay = 0;
return image;
}
| 164,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: static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
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);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
(void) fputc(c,file);
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199
CWE ID: CWE-20 | static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
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);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
if (fputc(c,file) != c)
break;
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 169,040 |
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 LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
factory_.reset(new FakeURLFetcherFactory());
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
integration_factory_.reset(new URLFetcherFactory());
factory_.reset(new FakeURLFetcherFactory(integration_factory_.get()));
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
| 170,430 |
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: lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump, ret;
u_int offset;
u_int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
if (tlen < sizeof(const struct lmp_common_header)) {
ND_PRINT((ndo, " (too short)"));
return;
}
if (tlen > len) {
ND_PRINT((ndo, " (too long)"));
tlen = len;
}
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
if (lmp_obj_len < 4) {
ND_PRINT((ndo, " (too short)"));
return;
}
if ((lmp_obj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
return;
}
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
if (obj_tlen != 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
break;
case LMP_CTYPE_UNMD:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)"
"\n\t Remote Link-ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
case LMP_CTYPE_IPV6:
if (obj_tlen < 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
case LMP_CTYPE_UNMD:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)"
"\n\t Remote Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 20) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
/* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */
while (offset+20 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));
offset+=20;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
while (offset+16 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=16;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
link_type = EXTRACT_8BITS(obj_tptr);
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
switch (link_type) {
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 2))));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 7))));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
Commit Message: (for 4.9.3) LMP: Add some missing bounds checks
In lmp_print_data_link_subobjs(), these problems were identified
through code review.
Moreover:
Add and use tstr[].
Update two tests outputs accordingly.
CWE ID: CWE-20 | lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump, ret;
u_int offset;
u_int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
if (tlen < sizeof(const struct lmp_common_header)) {
ND_PRINT((ndo, " (too short)"));
return;
}
if (tlen > len) {
ND_PRINT((ndo, " (too long)"));
tlen = len;
}
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
if (lmp_obj_len < 4) {
ND_PRINT((ndo, " (too short)"));
return;
}
if ((lmp_obj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
return;
}
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
if (obj_tlen != 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
break;
case LMP_CTYPE_UNMD:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)"
"\n\t Remote Link-ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
case LMP_CTYPE_IPV6:
if (obj_tlen < 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
case LMP_CTYPE_UNMD:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)"
"\n\t Remote Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12);
if (ret == -1)
goto trunc;
if (ret == TRUE)
hexdump=TRUE;
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 20) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
/* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */
while (offset+20 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));
offset+=20;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
while (offset+16 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=16;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
link_type = EXTRACT_8BITS(obj_tptr);
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
switch (link_type) {
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 2))));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 7))));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 169,537 |
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 struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
br_write_lock(&vfsmount_lock);
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
br_write_unlock(&vfsmount_lock);
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
free_vfsmnt(mnt);
return ERR_PTR(err);
}
Commit Message: vfs: Carefully propogate mounts across user namespaces
As a matter of policy MNT_READONLY should not be changable if the
original mounter had more privileges than creator of the mount
namespace.
Add the flag CL_UNPRIVILEGED to note when we are copying a mount from
a mount namespace that requires more privileges to a mount namespace
that requires fewer privileges.
When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT
if any of the mnt flags that should never be changed are set.
This protects both mount propagation and the initial creation of a less
privileged mount namespace.
Cc: [email protected]
Acked-by: Serge Hallyn <[email protected]>
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD;
/* Don't allow unprivileged users to change mount flags */
if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY))
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
br_write_lock(&vfsmount_lock);
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
br_write_unlock(&vfsmount_lock);
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
free_vfsmnt(mnt);
return ERR_PTR(err);
}
| 166,094 |
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: png_get_mmx_bitdepth_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0: 0);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_mmx_bitdepth_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,166 |
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: virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
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 | virtual const ImePropertyList& current_ime_properties() const {
virtual const input_method::ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
| 170,511 |
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 ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb;
unsigned int maxfraglen, fragheaderlen;
int exthdrlen;
int hh_len;
int mtu;
int copy;
int err;
int offset = 0;
int csummode = CHECKSUM_NONE;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kmalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
sk->sk_sndmsg_page = NULL;
sk->sk_sndmsg_off = 0;
exthdrlen = rt->dst.header_len + (opt ? opt->opt_flen : 0) -
rt->rt6i_nfheader_len;
length += exthdrlen;
transhdrlen += exthdrlen;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM) {
err = sock_tx_timestamp(sk, &tx_flags);
if (err)
goto error;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
struct sk_buff *skb_prev;
alloc_new_skb:
skb_prev = skb;
/* There's no room in the current skb */
if (skb_prev)
fraggap = skb_prev->len - maxfraglen;
else
fraggap = 0;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen;
fraglen = datalen + fragheaderlen;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
/*
* The last fragment gets additional space at tail.
* Note: we overallocate on fragments with MSG_MODE
* because we have no idea if we're the last one.
*/
if (datalen == length + fraggap)
alloclen += rt->dst.trailer_len;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation */
skb_reserve(skb, hh_len+sizeof(struct frag_hdr));
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
csummode = CHECKSUM_NONE;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i-1];
struct page *page = sk->sk_sndmsg_page;
int off = sk->sk_sndmsg_off;
unsigned int left;
if (page && (left = PAGE_SIZE - off) > 0) {
if (copy >= left)
copy = left;
if (page != frag->page) {
if (i == MAX_SKB_FRAGS) {
err = -EMSGSIZE;
goto error;
}
get_page(page);
skb_fill_page_desc(skb, i, page, sk->sk_sndmsg_off, 0);
frag = &skb_shinfo(skb)->frags[i];
}
} else if(i < MAX_SKB_FRAGS) {
if (copy > PAGE_SIZE)
copy = PAGE_SIZE;
page = alloc_pages(sk->sk_allocation, 0);
if (page == NULL) {
err = -ENOMEM;
goto error;
}
sk->sk_sndmsg_page = page;
sk->sk_sndmsg_off = 0;
skb_fill_page_desc(skb, i, page, 0, 0);
frag = &skb_shinfo(skb)->frags[i];
} else {
err = -EMSGSIZE;
goto error;
}
if (getfrag(from, page_address(frag->page)+frag->page_offset+frag->size, offset, copy, skb->len, skb) < 0) {
err = -EFAULT;
goto error;
}
sk->sk_sndmsg_off += copy;
frag->size += copy;
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb;
unsigned int maxfraglen, fragheaderlen;
int exthdrlen;
int hh_len;
int mtu;
int copy;
int err;
int offset = 0;
int csummode = CHECKSUM_NONE;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kmalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
sk->sk_sndmsg_page = NULL;
sk->sk_sndmsg_off = 0;
exthdrlen = rt->dst.header_len + (opt ? opt->opt_flen : 0) -
rt->rt6i_nfheader_len;
length += exthdrlen;
transhdrlen += exthdrlen;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM) {
err = sock_tx_timestamp(sk, &tx_flags);
if (err)
goto error;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
struct sk_buff *skb_prev;
alloc_new_skb:
skb_prev = skb;
/* There's no room in the current skb */
if (skb_prev)
fraggap = skb_prev->len - maxfraglen;
else
fraggap = 0;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen;
fraglen = datalen + fragheaderlen;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
/*
* The last fragment gets additional space at tail.
* Note: we overallocate on fragments with MSG_MODE
* because we have no idea if we're the last one.
*/
if (datalen == length + fraggap)
alloclen += rt->dst.trailer_len;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation */
skb_reserve(skb, hh_len+sizeof(struct frag_hdr));
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
csummode = CHECKSUM_NONE;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i-1];
struct page *page = sk->sk_sndmsg_page;
int off = sk->sk_sndmsg_off;
unsigned int left;
if (page && (left = PAGE_SIZE - off) > 0) {
if (copy >= left)
copy = left;
if (page != frag->page) {
if (i == MAX_SKB_FRAGS) {
err = -EMSGSIZE;
goto error;
}
get_page(page);
skb_fill_page_desc(skb, i, page, sk->sk_sndmsg_off, 0);
frag = &skb_shinfo(skb)->frags[i];
}
} else if(i < MAX_SKB_FRAGS) {
if (copy > PAGE_SIZE)
copy = PAGE_SIZE;
page = alloc_pages(sk->sk_allocation, 0);
if (page == NULL) {
err = -ENOMEM;
goto error;
}
sk->sk_sndmsg_page = page;
sk->sk_sndmsg_off = 0;
skb_fill_page_desc(skb, i, page, 0, 0);
frag = &skb_shinfo(skb)->frags[i];
} else {
err = -EMSGSIZE;
goto error;
}
if (getfrag(from, page_address(frag->page)+frag->page_offset+frag->size, offset, copy, skb->len, skb) < 0) {
err = -EFAULT;
goto error;
}
sk->sk_sndmsg_off += copy;
frag->size += copy;
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
| 165,851 |
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 inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
if (S_ISDIR(mode))
mode |= S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
Commit Message: Fix up non-directory creation in SGID directories
sgid directories have special semantics, making newly created files in
the directory belong to the group of the directory, and newly created
subdirectories will also become sgid. This is historically used for
group-shared directories.
But group directories writable by non-group members should not imply
that such non-group members can magically join the group, so make sure
to clear the sgid bit on non-directories for non-members (but remember
that sgid without group execute means "mandatory locking", just to
confuse things even more).
Reported-by: Jann Horn <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-269 | void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
/* Directories are special, and always inherit S_ISGID */
if (S_ISDIR(mode))
mode |= S_ISGID;
else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) &&
!in_group_p(inode->i_gid) &&
!capable_wrt_inode_uidgid(dir, CAP_FSETID))
mode &= ~S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
| 169,153 |
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 AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)
{
PadContext *s = inlink->dst->priv;
AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],
w + (s->w - s->in_w),
h + (s->h - s->in_h));
int plane;
if (!frame)
return NULL;
frame->width = w;
frame->height = h;
for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
int hsub = s->draw.hsub[plane];
int vsub = s->draw.vsub[plane];
frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +
(s->y >> vsub) * frame->linesize[plane];
}
return frame;
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)
{
PadContext *s = inlink->dst->priv;
AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],
w + (s->w - s->in_w),
h + (s->h - s->in_h));
int plane;
if (!frame)
return NULL;
frame->width = w;
frame->height = h;
for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
int hsub = s->draw.hsub[plane];
int vsub = s->draw.vsub[plane];
frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +
(s->y >> vsub) * frame->linesize[plane];
}
return frame;
}
| 166,006 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.