Skip to main content

gossan_cloud/
azure.rs

1//! Azure Blob Storage probe.
2//!
3//! Azure storage account names are 3–24 lowercase alphanumeric chars (no hyphens).
4//! Containers are probed by name — common names and the special `$web` container
5//! (used for static website hosting) are checked.
6//!
7//! URL format: `https://{account}.blob.core.windows.net/{container}/`
8
9use async_trait::async_trait;
10use gossan_core::Target;
11use secfinding::{Evidence, Finding, Severity};
12use serde::Deserialize;
13use std::sync::OnceLock;
14
15use crate::provider::CloudProvider;
16
17/// Azure container definition from TOML.
18#[derive(Debug, Clone, Deserialize)]
19struct AzureContainer {
20    name: String,
21    #[allow(dead_code)]
22    description: String,
23    #[allow(dead_code)]
24    #[serde(rename = "severity_if_exposed")]
25    severity: String,
26}
27
28/// TOML file containing Azure container definitions.
29#[derive(Debug, Deserialize)]
30struct AzureContainersFile {
31    container: Vec<AzureContainer>,
32}
33
34/// Built-in azure.toml content (embedded at compile time).
35const BUILTIN_AZURE: &str = include_str!("../rules/azure.toml");
36
37/// Global cache for built-in Azure containers.
38static AZURE_CONTAINERS: OnceLock<Vec<AzureContainer>> = OnceLock::new();
39
40/// Initialize and return the built-in Azure containers.
41fn builtin_azure_containers() -> &'static Vec<AzureContainer> {
42    AZURE_CONTAINERS.get_or_init(|| {
43        match toml::from_str::<AzureContainersFile>(BUILTIN_AZURE) {
44            Ok(file) => file.container,
45            Err(e) => {
46                tracing::error!(error = %e, "failed to parse built-in azure.toml");
47                // Fallback to minimal hardcoded list only on parse failure
48                vec![
49                    AzureContainer {
50                        name: "$web".to_string(),
51                        description: "static website hosting".to_string(),
52                        severity: "critical".to_string(),
53                    },
54                ]
55            }
56        }
57    })
58}
59
60/// Get container names from TOML configuration.
61fn container_names() -> &'static [AzureContainer] {
62    builtin_azure_containers()
63}
64/// Azure Blob Storage container enumeration.
65pub struct AzureProvider;
66
67#[async_trait]
68impl CloudProvider for AzureProvider {
69    fn name(&self) -> &'static str {
70        "azure"
71    }
72
73    fn endpoint(&self, name: &str) -> String {
74        format!("https://{}.blob.core.windows.net/", name)
75    }
76
77    async fn probe(
78        &self,
79        client: &reqwest::Client,
80        name: &str,
81        target: &Target,
82    ) -> anyhow::Result<Vec<Finding>> {
83        // Azure account names: 3–24 lowercase alphanumeric only
84        let account: String = name
85            .chars()
86            .filter(|c| c.is_ascii_alphanumeric())
87            .collect::<String>()
88            .to_lowercase();
89        if account.len() < 3 || account.len() > 24 {
90            return Ok(vec![]);
91        }
92
93        let base_endpoint = self.endpoint(&account);
94        let mut findings = Vec::new();
95        let mut account_confirmed = false;
96
97        for container in container_names() {
98            let container_name = &container.name;
99            let url = format!("{}{}/", base_endpoint, container_name);
100            let resp = match client.get(&url).send().await {
101                Ok(r) => r,
102                Err(_) => continue,
103            };
104            let status = resp.status().as_u16();
105
106            match status {
107                200 => {
108                    let body = gossan_core::net::bounded_text(resp, 4 * 1024 * 1024).await.unwrap_or_default();
109                    let is_web = container_name == "$web";
110                    gossan_core::try_push_finding(crate::finding_builder(target, Severity::Critical,
111                            format!("Azure Blob container public: {}/{}", account, container_name),
112                            if is_web {
113                                format!(
114                                    "https://{}.blob.core.windows.net/$web is the static website \
115                                     hosting container and is publicly readable — all files accessible.",
116                                    account
117                                )
118                            } else {
119                                format!(
120                                    "https://{}.blob.core.windows.net/{} is publicly accessible \
121                                     and returns a directory listing.",
122                                    account, container_name
123                                )
124                            })
125                        .evidence(Evidence::HttpResponse {
126                            status,
127                            headers: vec![("url".into(), url.clone().into())],
128                            body_excerpt: Some(body.chars().take(300).collect::<String>().into()),
129                        })
130                        .tag("azure").tag("cloud").tag("exposure"), &mut findings);
131                    return Ok(findings); // one public container is enough to report
132                }
133                403 | 404 if !account_confirmed => {
134                    // 403 = container exists but private; 404 on a valid account
135                    // still confirms the account exists
136                    if status == 403 {
137                        account_confirmed = true;
138                        gossan_core::try_push_finding(crate::finding_builder(target, Severity::Low,
139                                format!("Azure storage account exists: {}", account),
140                                format!(
141                                    "https://{}.blob.core.windows.net exists — account name confirmed \
142                                     via HTTP 403 on container probe.",
143                                    account
144                                ))
145                            .evidence(Evidence::HttpResponse {
146                                status,
147                                headers: vec![("url".into(), url.clone().into())],
148                                body_excerpt: None,
149                            })
150                            .tag("azure").tag("cloud"), &mut findings);
151                    }
152                }
153                _ => {}
154            }
155        }
156
157        Ok(findings)
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn azure_containers_load_from_toml() {
167        let containers = container_names();
168        assert!(!containers.is_empty(), "should have Azure containers from TOML");
169        
170        // Check for critical $web container
171        assert!(
172            containers.iter().any(|c| c.name == "$web"),
173            "should include $web container"
174        );
175    }
176
177    #[test]
178    fn azure_containers_have_required_fields() {
179        for container in container_names() {
180            assert!(!container.name.is_empty(), "container name should not be empty");
181            assert!(!container.severity.is_empty(), "severity should not be empty");
182        }
183    }
184
185    #[test]
186    fn azure_containers_include_common_names() {
187        let names: Vec<_> = container_names().iter().map(|c| c.name.clone()).collect();
188        for expected in ["$web", "public", "assets", "backup"] {
189            assert!(names.contains(&expected.to_string()), "missing container: {}", expected);
190        }
191    }
192}