Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(xlsb): detect xlsb password protected files #393

Merged
merged 1 commit into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/xlsb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub enum XlsbError {
/// value found
val: String,
},
/// Workbook is password protected
Password,
/// Worksheet not found
WorksheetNotFound(String),
}
Expand Down Expand Up @@ -109,6 +111,7 @@ impl std::fmt::Display for XlsbError {
XlsbError::Unrecognized { typ, val } => {
write!(f, "Unrecognized {typ}: {val}")
}
XlsbError::Password => write!(f, "Workbook is password protected"),
XlsbError::WorksheetNotFound(name) => write!(f, "Worksheet '{name}' not found"),
}
}
Expand Down Expand Up @@ -434,7 +437,9 @@ impl<RS: Read + Seek> Xlsb<RS> {
impl<RS: Read + Seek> Reader<RS> for Xlsb<RS> {
type Error = XlsbError;

fn new(reader: RS) -> Result<Self, XlsbError> {
fn new(mut reader: RS) -> Result<Self, XlsbError> {
check_for_password_protected(&mut reader)?;

let mut xlsb = Xlsb {
zip: ZipArchive::new(reader)?,
sheets: Vec::new(),
Expand Down Expand Up @@ -921,3 +926,16 @@ fn cell_format<'a>(formats: &'a [CellFormat], buf: &[u8]) -> Option<&'a CellForm

formats.get(style_ref as usize)
}

fn check_for_password_protected<RS: Read + Seek>(reader: &mut RS) -> Result<(), XlsbError> {
let offset_end = reader.seek(std::io::SeekFrom::End(0))? as usize;
reader.seek(std::io::SeekFrom::Start(0))?;

if let Ok(cfb) = crate::cfb::Cfb::new(reader, offset_end) {
if cfb.has_directory("EncryptedPackage") {
return Err(XlsbError::Password);
}
};

Ok(())
}
Binary file added tests/pass_protected.xlsb
Binary file not shown.
13 changes: 13 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,19 @@ fn issue_385() {
);
}

#[test]
fn pass_protected_xlsb() {
let path = format!("{}/tests/pass_protected.xlsb", env!("CARGO_MANIFEST_DIR"));

assert!(
matches!(
open_workbook::<Xlsb<_>, std::string::String>(path),
Err(calamine::XlsbError::Password)
),
"Is expeced to return XlsbError::Password error"
);
}

#[test]
fn pass_protected_ods() {
let path = format!("{}/tests/pass_protected.ods", env!("CARGO_MANIFEST_DIR"));
Expand Down