From f9b1dbe2ac3da4ed87647ea27d9060879acc20fe Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Tue, 15 Feb 2022 11:48:09 +0000 Subject: [PATCH] imgcodecs: add runtime checks to validate input --- modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.cpp | 2 +- modules/imgcodecs/src/grfmt_pam.cpp | 8 ++++++++ modules/imgcodecs/src/grfmt_tiff.cpp | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.cpp b/modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.cpp index 73d49282d7..c5b1a292cc 100644 --- a/modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.cpp +++ b/modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.cpp @@ -545,7 +545,7 @@ bool Jpeg2KOpjDecoderBase::readHeader() */ bool hasAlpha = false; const int numcomps = image_->numcomps; - CV_Assert(numcomps >= 1); + CV_Check(numcomps, numcomps >= 1 && numcomps <= 4, "Unsupported number of components"); for (int i = 0; i < numcomps; i++) { const opj_image_comp_t& comp = image_->comps[i]; diff --git a/modules/imgcodecs/src/grfmt_pam.cpp b/modules/imgcodecs/src/grfmt_pam.cpp index 0c59702c41..1c8f8476a5 100644 --- a/modules/imgcodecs/src/grfmt_pam.cpp +++ b/modules/imgcodecs/src/grfmt_pam.cpp @@ -470,7 +470,11 @@ bool PAMDecoder::readHeader() selected_fmt = IMWRITE_PAM_FORMAT_GRAYSCALE; else if (m_channels == 3 && m_maxval < 256) selected_fmt = IMWRITE_PAM_FORMAT_RGB; + else + CV_Error(Error::StsError, "Can't determine selected_fmt (IMWRITE_PAM_FORMAT_NULL)"); } + CV_CheckDepth(m_sampledepth, m_sampledepth == CV_8U || m_sampledepth == CV_16U, ""); + CV_Check(m_channels, m_channels >= 1 && m_channels <= 4, "Unsupported number of channels"); m_type = CV_MAKETYPE(m_sampledepth, m_channels); m_offset = m_strm.getPos(); @@ -567,6 +571,10 @@ bool PAMDecoder::readData(Mat& img) FillColorRow1( data, src, m_width, palette ); } } + else + { + CV_Error(Error::StsError, cv::format("Unsupported value of target_channels: %d", target_channels)); + } } else { for (int y = 0; y < m_height; y++, data += imp_stride) { diff --git a/modules/imgcodecs/src/grfmt_tiff.cpp b/modules/imgcodecs/src/grfmt_tiff.cpp index cb4afb9f25..36cf17e1e3 100644 --- a/modules/imgcodecs/src/grfmt_tiff.cpp +++ b/modules/imgcodecs/src/grfmt_tiff.cpp @@ -149,8 +149,8 @@ bool TiffDecoder::checkSignature( const String& signature ) const int TiffDecoder::normalizeChannelsNumber(int channels) const { - CV_Assert(channels <= 4); - return channels > 4 ? 4 : channels; + CV_Check(channels, channels >= 1 && channels <= 4, "Unsupported number of channels"); + return channels; } ImageDecoder TiffDecoder::newDecoder() const