Skip to content

Commit

Permalink
make signing packages optional
Browse files Browse the repository at this point in the history
It's no longer validated anyway since DSM 7
  • Loading branch information
publicarray committed Jul 16, 2023
1 parent 7e8098d commit f1e2dd8
Show file tree
Hide file tree
Showing 8 changed files with 101 additions and 131 deletions.
2 changes: 1 addition & 1 deletion server/src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub async fn new_reset(info: web::Json<ResetRequest>, data: web::Data<AppData>)
let user_info = info.into_inner();
debug!("{:?}", user_info);
let mut conn = data.pool.get().expect("couldn't get db connection from pool");
let (user, roles) = web::block(move || User::send_reset_link(&mut conn, &user_info.email))
let (_user, _roles) = web::block(move || User::send_reset_link(&mut conn, &user_info.email))
.await
.map_err(|e| {
debug!("{}", e);
Expand Down
139 changes: 73 additions & 66 deletions server/src/api/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ extern crate serde_qs as qs;
use crate::utils;
use crate::filestorage;
use crate::PGP_KEY_PATH;
use crate::STORAGE_PATH;
use crate::STORAGE_TYPE;


use actix_web_grants::proc_macro::has_any_role;
use async_std::path::Path;
use async_std::{io, prelude::*};
use async_std::{prelude::*};
use async_tar::Archive;
use futures::StreamExt;
use regex::Regex;
Expand Down Expand Up @@ -179,70 +179,77 @@ pub async fn post(
}
}

let tsk = openpgp::Cert::from_file(&*PGP_KEY_PATH)
.context("Failed to read key")
.unwrap();
let p = &crate::openpgp::policy::StandardPolicy::new();
// syno_signature.asc
// let sig_buf = String::new();
//let sig_buf = Vec::new();
//let mut signature_file = std::io::Cursor::new(sig_buf);
let signature_filepath = tmp_dir.path().join("syno_signature.asc");
let mut signature_file = std::fs::File::create("syno_signature.asc")?;
match sign(p, &mut signature_file, &to_sign, &tsk) {
Err(err) => panic!("{:?}", err),
Ok(_sig) => (),
};

//let signature = String::from_utf8(sig_buf).unwrap();
let mut signature = String::new();
let mut sig_file = std::fs::File::open("syno_signature.asc")?;
//signature_file.read_to_string(&mut signature)?;
sig_file.read_to_string(&mut signature)?;

let client = awc::Client::builder()
.connector(awc::Connector::new().rustls(std::sync::Arc::new(utils::rustls_config())))
.finish();

debug!("signature:{}", signature);
let res = client
.post(&*crate::GNUPG_TIMESTAMP_URL)
.insert_header(("User-Agent", "ruspk/1.0"))
.insert_header(("Content-Type", "multipart/form-data; boundary=X-BOUNDARY"))
.send_body(format!(
"{}{}{}",
"--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"file\"; filename=\"syno_signature.asc\"\r\n",
signature,
"\r\n--X-BOUNDARY--\r\n"
))
.await;

debug!("Response: {:?}", res);
if res.is_ok() {
let body = res.unwrap().body().await?;
if body.is_ascii() {
let body_str = std::str::from_utf8(&body).unwrap();
debug!("Response: {}", body_str);
let mut signature_file = std::fs::File::create("syno_signature2.asc")?;
signature_file.write_all(&body)?;

let file1 = std::fs::File::open(filepath.clone())?; // new write file handler
let mut input = tar::Archive::new(file1);

let filepath_tmp = tmp_dir.path().join("temp2.spk");
let file = std::fs::File::create(filepath_tmp.clone())?; // new write file handler
let mut builder = tar::Builder::new(file);
builder.append_archive(&mut input).unwrap();
builder
.append_file(
"syno_signature.asc",
&mut std::fs::File::open("syno_signature2.asc").unwrap(),
)
.unwrap();
builder.finish().unwrap();
debug!("copy archive");
async_std::fs::copy(filepath_tmp, filepath.clone()).await?;
// OpenPGP
// only sign if file at &PGP_KEY_PATH exists
if std::path::Path::new(&*PGP_KEY_PATH).exists() {
debug!("siging..");
let tsk = openpgp::Cert::from_file(&*PGP_KEY_PATH)
.context("Failed to read key")
.unwrap();
let p = &crate::openpgp::policy::StandardPolicy::new();
// syno_signature.asc
// let sig_buf = String::new();
//let sig_buf = Vec::new();
//let mut signature_file = std::io::Cursor::new(sig_buf);
let _signature_filepath = tmp_dir.path().join("syno_signature.asc");
let mut signature_file = std::fs::File::create("syno_signature.asc")?;
match sign(p, &mut signature_file, &to_sign, &tsk) {
Err(err) => panic!("{:?}", err),
Ok(_sig) => (),
};

//let signature = String::from_utf8(sig_buf).unwrap();
let mut signature = String::new();
let mut sig_file = std::fs::File::open("syno_signature.asc")?;
//signature_file.read_to_string(&mut signature)?;
sig_file.read_to_string(&mut signature)?;

let client = awc::Client::builder()
.connector(awc::Connector::new().rustls(std::sync::Arc::new(utils::rustls_config())))
.finish();

debug!("signature:{}", signature);
let res = client
.post(&*crate::GNUPG_TIMESTAMP_URL)
.insert_header(("User-Agent", "ruspk/1.0"))
.insert_header(("Content-Type", "multipart/form-data; boundary=X-BOUNDARY"))
.send_body(format!(
"{}{}{}",
"--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"file\"; filename=\"syno_signature.asc\"\r\n",
signature,
"\r\n--X-BOUNDARY--\r\n"
))
.await;

debug!("Response: {:?}", res);
if res.is_ok() {
let body = res.unwrap().body().await?;
if body.is_ascii() {
let body_str = std::str::from_utf8(&body).unwrap();
debug!("Response: {}", body_str);
let mut signature_file = std::fs::File::create("syno_signature2.asc")?;
signature_file.write_all(&body)?;

let file1 = std::fs::File::open(filepath.clone())?; // new write file handler
let mut input = tar::Archive::new(file1);

let filepath_tmp = tmp_dir.path().join("temp2.spk");
let file = std::fs::File::create(filepath_tmp.clone())?; // new write file handler
let mut builder = tar::Builder::new(file);
builder.append_archive(&mut input).unwrap();
builder
.append_file(
"syno_signature.asc",
&mut std::fs::File::open("syno_signature2.asc").unwrap(),
)
.unwrap();
builder.finish().unwrap();
debug!("copy archive");
async_std::fs::copy(filepath_tmp, filepath.clone()).await?;
}
}
} else {
debug!("Not siging the file, no sining key found!");
}

// convert to booleans hack
Expand Down
2 changes: 1 addition & 1 deletion server/src/filestorage.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::models::*;
use anyhow::{Context, Result};
use anyhow::{Result};
use s3::Region;
// use async_std::path::PathBuf;
use std::path::PathBuf;
Expand Down
76 changes: 18 additions & 58 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ extern crate chrono;
extern crate regex;

extern crate sequoia_openpgp as openpgp;
use openpgp::Cert;
use openpgp::{parse::Parse, serialize::SerializeInto};
use rustls::{Certificate, PrivateKey, ServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys, rsa_private_keys, ec_private_keys};
Expand Down Expand Up @@ -136,7 +137,7 @@ pub struct AppData {
pool: DbPool,
cache_r: evmap::ReadHandle<String, CacheValue>,
cache_w: Arc<Mutex<evmap::WriteHandle<String, CacheValue>>>,
keyring: String,
keyring: Option<String>,
}

#[actix_rt::main]
Expand Down Expand Up @@ -165,63 +166,22 @@ async fn main() -> std::io::Result<()> {
let bind = format!("{}:{}", listen_addr, listen_port);
info!("Starting server at: {}", &bind);

// OpenPGP
//let mut tsk:Option<Cert> = None;
let mut pgp_key:Option<String> = None;
// if file at &PGP_KEY_PATH exists

// get public key / keychain
// let pgp_key_path = std::env::var("PGP_KEY_PATH").unwrap_or_else(|_| "pgpkey.pem".to_string());
// let tsk = openpgp::Cert::from_file(&pgp_key_path).context("Failed to read key").unwrap();
let tsk = openpgp::Cert::from_file(&*PGP_KEY_PATH)
.context("Failed to read key")
.unwrap();

// let mut keys = Vec::new();
// let p = &crate::openpgp::policy::StandardPolicy::new();
// let mut n = 0;
// for key in tsk.keys().with_policy(p, None).alive().revoked(false).for_signing().secret().map(|ka| ka.key()) {
// keys.push({
// let mut key = key.clone();
// if key.secret().is_encrypted() {
// // let password = read_from_sdin (Some(&format!("Please enter password to decrypt {}/{}: ",tsk, key)))?;
// let password = "";
// let algo = key.pk_algo();
// key.secret_mut()
// .decrypt_in_place(algo, &password.into())
// .context("decryption failed").unwrap();
// }
// n += 1;
// key.into_keypair().unwrap();
// });
// }

// if n==0 {
// error!("No valid signing key found");
// }

// let keypair = tsk
// .keys().unencrypted_secret()
// .with_policy(p, None).supported().alive().revoked(false).for_signing()
// .next().unwrap().key().clone().into_keypair().unwrap();

let public_key = String::from_utf8(tsk.armored().to_vec().unwrap()).unwrap();
debug!("Public Key: {}", public_key);
info!("Loaded Key: {}", tsk.fingerprint());
// let ppr = PacketParser::from_file(&pgp_key_path).unwrap();
// let mut public_key = "".to_string();
// for certo in CertParser::from(ppr) {
// match certo {
// Ok(cert) => {
// info!("Key: {}", cert.fingerprint());
// public_key = String::from_utf8(cert.armored().to_vec().unwrap()).unwrap();
// debug!("public Key: {}", public_key);
// for ua in cert.userids() {
// info!(" User ID: {}", ua.userid());
// }
// }
// Err(err) => {
// error!("Error reading keyring: {}", err);
// }
// }
// }
if std::path::Path::new(&*PGP_KEY_PATH).exists() {
let temp_tsk = Cert::from_file(&*PGP_KEY_PATH)
.context("Failed to read signing key")
.unwrap();
let temp_key = String::from_utf8(temp_tsk.armored().to_vec().unwrap()).unwrap();
debug!("Key: {}", temp_key);
info!("Loaded Key: {}", temp_tsk.fingerprint());
//tsk = Some(temp_tsk);
pgp_key = Some(temp_key);
} else {
debug!("No signing key file found at: {}!", &*PGP_KEY_PATH);
}

let (cache_r, raw_cache_w) = evmap::new();
let cache_w = Arc::new(Mutex::new(raw_cache_w));
Expand All @@ -245,7 +205,7 @@ async fn main() -> std::io::Result<()> {
pool: pool.clone(),
cache_r: cache_r.clone(),
cache_w: cache_w.clone(),
keyring: public_key.clone(),
keyring: pgp_key.clone(),
}))
.wrap(middleware::Logger::default())
//.service(web::resource("/hello").route(web::get().to(routes::index)))
Expand Down
3 changes: 2 additions & 1 deletion server/src/models/icon_size_type.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::pg::Pg;
use diesel::serialize::{self, IsNull, Output, ToSql};
Expand Down Expand Up @@ -32,7 +33,7 @@ impl ToSql<IconSize, Pg> for IconSizeEnum {

// https://docs.diesel.rs/diesel/deserialize/trait.FromSql.html
impl FromSql<IconSize, Pg> for IconSizeEnum {
fn from_sql(value: backend::RawValue<'_, Pg>) -> deserialize::Result<Self> {
fn from_sql(value: <Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
let bytes = value.as_bytes();
match bytes {
b"72" => Ok(IconSizeEnum::Icon72),
Expand Down
2 changes: 1 addition & 1 deletion server/src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl User {
username: &Option<String>,
email: &Option<String>,
new_password: &str,
reset_token: &str,
_reset_token: &str,
) -> Result<(UserWithKey, Vec<DbRole>)> {
// let hashed_password = bcrypt::hash(password, 12)?;
// debug!("{:?}", hashed_password);
Expand Down
2 changes: 1 addition & 1 deletion server/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub async fn syno(data: web::Data<AppData>, synorequest: web::Query<SynoRequest>
let response = web::block(move || {
get_packages_for_device_lang(
&mut conn,
&keyring,
keyring.as_deref(),
&synorequest.language,
&synorequest.arch,
synorequest.build,
Expand Down
6 changes: 4 additions & 2 deletions server/src/synopackagelist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Default for Package {

pub fn get_packages_for_device_lang(
conn: &mut DbConn,
keyring: &str,
keyring: Option<&str>,
lang: &str,
arch: &str,
build: Db64,
Expand All @@ -152,7 +152,9 @@ pub fn get_packages_for_device_lang(
packages: Vec::new(),
..Default::default()
};
sr.set_key(keyring);
if let Some(keyring) = keyring {
sr.set_key(keyring);
}

let packages = DbPackage::get_packages(lang, arch, build, beta, major, micro, minor, conn)?;

Expand Down

0 comments on commit f1e2dd8

Please sign in to comment.