Skip to content

Commit

Permalink
Refactoring code for file write and setting restricted permissions.
Browse files Browse the repository at this point in the history
  • Loading branch information
mchf committed Jun 6, 2024
1 parent 77c4e1c commit db47621
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions rust/agama-server/src/cert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa;
use openssl::x509::extension::{BasicConstraints, SubjectAlternativeName, SubjectKeyIdentifier};
use openssl::x509::{X509NameBuilder, X509};
use std::{fs, io::Write, os::unix::fs::OpenOptionsExt, path::Path};
use std::{
fs,
io::{self, Write},
os::unix::fs::OpenOptionsExt,
path::Path,
};

const DEFAULT_CERT_DIR: &str = "/etc/agama.d/ssl";

Expand All @@ -27,17 +32,10 @@ impl Certificate {
}

if let Ok(bytes) = self.cert.to_pem() {
fs::write(Path::new(DEFAULT_CERT_DIR).join("cert.pem"), bytes)?;
write_and_restrict(Path::new(DEFAULT_CERT_DIR).join("cert.pem"), &bytes)?;
}
if let Ok(bytes) = self.key.private_key_to_pem_pkcs8() {
let path = Path::new(DEFAULT_CERT_DIR).join("key.pem");
let mut file = fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o400)
.open(path)?;
file.write_all(&bytes)?;
write_and_restrict(Path::new(DEFAULT_CERT_DIR).join("key.pem"), &bytes)?;
}

Ok(())
Expand Down Expand Up @@ -114,3 +112,17 @@ impl Certificate {
})
}
}

/// Writes buf into a file at path and sets the file permissions for the root only access
fn write_and_restrict<T: AsRef<Path>>(path: T, buf: &[u8]) -> io::Result<()> {
let mut file = fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o400)
.open(path)?;

file.write_all(buf)?;

Ok(())
}

0 comments on commit db47621

Please sign in to comment.