Skip to content
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Canonical repository: <https://github.com/Devolutions/psign>.
- `timestamp`: Rust mssign32 core (`SignerTimeStampEx3`/`SignerTimeStampEx2`) plus AppX restrictions.
- `rdp`: Rust port of **`rdpsign.exe`** for `.rdp` files (`SignScope` / `Signature` records, detached PKCS#7 over the secure-settings blob).
- `cert-store`: Portable file-backed certificate store under `~/.psign/cert-store` by default, with Windows-style store/thumbprint selection.
- `portable ...`: Cross-platform digest, verification, trust, signing, package, RFC3161, and remote-hash helpers that avoid Win32 APIs.
- `portable ...`: Cross-platform digest, verification, trust, signing, package, RFC3161, and remote-hash helpers that avoid Win32 APIs, including PE/WinMD signing through Azure Artifact Signing REST without Microsoft client DLLs.

## MSIX parity notes

Expand Down
66 changes: 63 additions & 3 deletions crates/psign-codesigning-rest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use serde_json::Value;
use std::thread;
use std::time::Duration;

pub const DEFAULT_API_VERSION: &str = "2024-06-15";
const DEFAULT_SCOPE: &str = "https://codesigning.azure.net/.default";
const MI_RESOURCE: &str = "https://codesigning.azure.net";

Expand Down Expand Up @@ -41,6 +42,13 @@ pub struct CodesigningSubmitParams {
pub endpoint_base_url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodesigningSignatureResult {
pub signature: Vec<u8>,
pub signing_certificate: Vec<u8>,
pub final_json: Value,
}

fn data_plane_base_url(params: &CodesigningSubmitParams) -> String {
if let Some(ref u) = params.endpoint_base_url {
let t = u.trim().trim_end_matches('/');
Expand All @@ -51,6 +59,17 @@ fn data_plane_base_url(params: &CodesigningSubmitParams) -> String {
format!("https://{}.codesigning.azure.net", params.region.trim())
}

fn operation_location_url(base: &str, location: &str) -> String {
let trimmed = location.trim();
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
return trimmed.to_string();
}
if trimmed.starts_with('/') {
return format!("{}{}", base.trim_end_matches('/'), trimmed);
}
format!("{}/{}", base.trim_end_matches('/'), trimmed)
}

fn normalize_authority(authority: Option<&str>) -> String {
authority
.unwrap_or("https://login.microsoftonline.com")
Expand Down Expand Up @@ -210,7 +229,9 @@ pub fn submit_codesign_hash_blocking(
.map(str::trim)
.filter(|s| !s.is_empty())
{
req = req.header("x-ms-correlation-id", c);
req = req
.header("x-correlation-id", c)
.header("x-ms-correlation-id", c);
}

let rsp = req.send().context("codesign :sign POST")?;
Expand All @@ -234,8 +255,14 @@ pub fn submit_codesign_hash_blocking(
}

let poll_url = if let Some(loc) = op_location {
loc
} else if let Some(id) = accept_json.get("id").and_then(|v| v.as_str()) {
operation_location_url(&base, &loc)
} else if accept_json.get("status").and_then(Value::as_str) == Some("Succeeded") {
return Ok(accept_json);
} else if let Some(id) = accept_json
.get("id")
.or_else(|| accept_json.get("operationId"))
.and_then(Value::as_str)
{
format!(
"{base}/codesigningaccounts/{account}/certificateprofiles/{profile}/sign/{id}?api-version={api}",
)
Expand All @@ -248,6 +275,39 @@ pub fn submit_codesign_hash_blocking(
poll_operation(&http, &token, &poll_url)
}

fn sign_result_object(v: &Value) -> &Value {
v.get("result").unwrap_or(v)
}

fn decode_standard_base64_field(obj: &Value, field: &str) -> Result<Vec<u8>> {
let s = obj
.get(field)
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("codesign result missing {field}"))?;
base64::engine::general_purpose::STANDARD
.decode(s.trim())
.with_context(|| format!("decode codesign result {field}"))
}

pub fn codesign_signature_result_from_json(
final_json: Value,
) -> Result<CodesigningSignatureResult> {
let result = sign_result_object(&final_json);
Ok(CodesigningSignatureResult {
signature: decode_standard_base64_field(result, "signature")?,
signing_certificate: decode_standard_base64_field(result, "signingCertificate")?,
final_json,
})
}

pub fn submit_codesign_hash_signature_blocking(
params: &CodesigningSubmitParams,
debug: impl Fn(&str),
) -> Result<CodesigningSignatureResult> {
let final_json = submit_codesign_hash_blocking(params, debug)?;
codesign_signature_result_from_json(final_json)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
79 changes: 79 additions & 0 deletions crates/psign-codesigning-rest/tests/codesign_rest_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,85 @@ fn submit_sign_sends_x_ms_correlation_id_when_set() {
poll_mock.assert();
}

#[test]
fn submit_sign_sends_stable_x_correlation_id_when_set() {
let mut server = Server::new();
let base = server.url().trim_end_matches('/').to_string();
let poll_url = format!("{base}/operations/corr-stable");

let post_mock = server
.mock(
"POST",
Matcher::Regex(
r"/codesigningaccounts/c/certificateprofiles/p:sign(\?.*)?$".to_string(),
),
)
.match_header("x-correlation-id", "trace-stable")
.with_status(202)
.with_header("Operation-Location", &poll_url)
.with_body("{}")
.create();

let poll_mock = server
.mock(
"GET",
Matcher::Regex(r"/operations/corr-stable(\?.*)?$".to_string()),
)
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"status":"Succeeded"}"#)
.create();

let params = CodesigningSubmitParams {
region: "unused".into(),
account_name: "c".into(),
profile_name: "p".into(),
digest: vec![1, 2, 3],
signature_algorithm: "RS256".into(),
api_version: psign_codesigning_rest::DEFAULT_API_VERSION.into(),
correlation_id: Some("trace-stable".into()),
authority: None,
auth: CodesigningAuth::Bearer("tok".into()),
endpoint_base_url: Some(base),
};

submit_codesign_hash_blocking(&params, |_| {}).expect("submit");
post_mock.assert();
poll_mock.assert();
}

#[test]
fn typed_signature_result_accepts_stable_result_wrapper() {
let sig = vec![0xabu8; 256];
let cert = vec![0x30, 0x82, 0x01, 0x23];
let json = json!({
"status": "Succeeded",
"result": {
"signature": base64::engine::general_purpose::STANDARD.encode(&sig),
"signingCertificate": base64::engine::general_purpose::STANDARD.encode(&cert)
}
});

let parsed = psign_codesigning_rest::codesign_signature_result_from_json(json).expect("parse");
assert_eq!(parsed.signature, sig);
assert_eq!(parsed.signing_certificate, cert);
}

#[test]
fn typed_signature_result_accepts_legacy_top_level_fields() {
let sig = vec![0xcdu8; 256];
let cert = vec![0x30, 0x82, 0x02, 0x34];
let json = json!({
"status": "Succeeded",
"signature": base64::engine::general_purpose::STANDARD.encode(&sig),
"signingCertificate": base64::engine::general_purpose::STANDARD.encode(&cert)
});

let parsed = psign_codesigning_rest::codesign_signature_result_from_json(json).expect("parse");
assert_eq!(parsed.signature, sig);
assert_eq!(parsed.signing_certificate, cert);
}

#[test]
fn submit_poll_failed_status_returns_error() {
let mut server = Server::new();
Expand Down
1 change: 1 addition & 0 deletions crates/psign-digest-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ base64 = { version = "0.22", optional = true }
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"], optional = true }
sha1 = "0.10"
sha2 = "0.10"
x509-cert = "0.2.5"

[dev-dependencies]
assert_cmd = "2"
Expand Down
Loading