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

verify checksums on prometheus download #30

Merged
merged 5 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
79 changes: 79 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ clap = { version = "4.2.7", features = ["derive", "env"] }
directories = { version = "5.0.1" }
flate2 = { version = "1.0.26" }
futures-util = { version = "0.3.28", features = ["io"] }
hex = "0.4.3"
http = { version = "0.2.9" }
include_dir = { version = "0.7.3" }
once_cell = { version = "1.17.1" }
remove_dir_all = { version = "0.8.2" }
reqwest = { version = "0.11.18", default-features = false, features = ["json", "rustls-tls", "stream"] }
serde = { version = "1.0.163", features = ["derive"] }
serde_yaml = { version = "0.9.21" }
sha2 = "0.10.6"
tar = { version = "0.4.38" }
tempfile = { version = "3.5.0" }
tokio = { version = "1.28.1", features = ["full"] }
Expand Down
80 changes: 66 additions & 14 deletions src/bin/am/commands/start.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{bail, Context, Result};
use anyhow::{anyhow, bail, Context, Result};
use autometrics_am::prometheus;
use axum::body::{self, Body};
use axum::extract::Path;
Expand All @@ -12,12 +12,15 @@ use futures_util::future::join_all;
use http::{StatusCode, Uri};
use include_dir::{include_dir, Dir};
use once_cell::sync::Lazy;
use sha2::digest::Output;
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{BufWriter, Write};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use std::vec;
use tempfile::NamedTempFile;
use tokio::process;
use tracing::{debug, error, info, trace, warn};
use url::Url;
Expand Down Expand Up @@ -94,6 +97,8 @@ pub async fn handle_command(args: Arguments) -> Result<()> {
info!("Downloading prometheus");
download_prometheus(&prometheus_path, prometheus_version).await?;
info!("Downloaded to: {:?}", &prometheus_path);
} else {
debug!("Found prometheus in {}", prometheus_path.display());
}

let prometheus_config = generate_prom_config(prometheus_args.metrics_endpoints)?;
Expand All @@ -115,27 +120,74 @@ pub async fn handle_command(args: Arguments) -> Result<()> {
/// archive into `prometheus_path`.
async fn download_prometheus(prometheus_path: &PathBuf, prometheus_version: &str) -> Result<()> {
let (os, arch) = determine_os_and_arch()?;
let package = format!("prometheus-{prometheus_version}.{os}-{arch}.tar.gz");

// TODO: Grab the checksum file and retrieve the checksum for the archive
let archive_path = {
let tmp_file = tempfile::NamedTempFile::new()?;
let mut res = CLIENT
.get(format!("https://github.com/prometheus/prometheus/releases/download/v{prometheus_version}/prometheus-{prometheus_version}.{os}-{arch}.tar.gz"))
let destination = NamedTempFile::new()?;

let mut response = CLIENT
.get(format!("https://github.com/prometheus/prometheus/releases/download/v{prometheus_version}/{package}"))
.send()
.await?
.error_for_status()?;

let file = File::create(&tmp_file)?;
let mut buffer = BufWriter::new(file);
let mut hasher = Sha256::new();

while let Some(ref chunk) = res.chunk().await? {
buffer.write_all(chunk)?;
}
let file = File::create(&destination)?;
let mut buffer = BufWriter::new(file);

tmp_file
};
while let Some(ref chunk) = response.chunk().await? {
buffer.write_all(chunk)?;
hasher.update(chunk);
}

if !verify_checksum(hasher.finalize(), prometheus_version, &package).await? {
// drop the temp file now so it gets cleaned up
drop(destination);
bail!("Checksum mismatched, you may be MITM'd right now. Aborting.");
mellowagain marked this conversation as resolved.
Show resolved Hide resolved
}

unpack_prometheus(&destination, prometheus_path, prometheus_version).await
}

async fn verify_checksum(
mellowagain marked this conversation as resolved.
Show resolved Hide resolved
result: Output<Sha256>,
prometheus_version: &str,
package: &str,
) -> Result<bool> {
mellowagain marked this conversation as resolved.
Show resolved Hide resolved
let checksums = CLIENT
.get(format!("https://github.com/prometheus/prometheus/releases/download/v{prometheus_version}/sha256sums.txt"))
.send()
.await?
.error_for_status()?
.text()
.await?;

let checksum_hex = checksums
.lines()
.flat_map(|line| line.split_once(' '))
.find(|(_, pkg)| package == *pkg)
.ok_or_else(|| anyhow!("unable to find checksum for {package} in checksum list"))?
.0;

let checksum = hex::decode(checksum_hex)?;

debug!("Expecting checksum from prometheus: {checksum_hex}");
debug!(
"Calculated checksum for downloaded archive: {}",
hex::encode(result.as_slice())
);

Ok(result.as_slice() == checksum)
}

async fn unpack_prometheus(
archive: &NamedTempFile,
prometheus_path: &PathBuf,
prometheus_version: &str,
) -> Result<()> {
let (os, arch) = determine_os_and_arch()?;

let file = File::open(archive_path)?;
let file = File::open(archive)?;
let tar_file = GzDecoder::new(file);
let mut ar = tar::Archive::new(tar_file);

Expand Down