Skip to main content

moreinlaw_kernel/
proof.rs

1//! Decides whether an organization really owns the address it claims, so every server proves
2//! organizations the same way. An organization fails when its site answers with another slug or
3//! key, its API sits off its own site, or its signed registration names another key or address.
4//!
5//! This runs when the user opens an organization in the federation list or another organization
6//! is proved. Users would report an organization stuck as "unproved" or "address check failed".
7
8use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
9
10use nostr::{Event, PublicKey};
11use serde::{Deserialize, Serialize};
12
13use crate::registration::{parse_registration, HostRegistration};
14
15const OWN_SITE_ERROR: &str = "API address must be on the organization's own site";
16pub const NO_REGISTRATION_ERROR: &str = "No signed registration found for this key";
17
18/// `GET /api/host_identity`: what a site answers when asked who it is.
19#[derive(Debug, Serialize, Deserialize, PartialEq)]
20pub struct HostIdentityResponse {
21    pub slug: String,
22    pub operator_npub: String,
23    /// The directory name, shown as the organization header in the phone app's pages. Optional so
24    /// an older Host's answer, which has none, still parses during registration checks.
25    #[serde(default)]
26    pub name: Option<String>,
27}
28
29fn is_public_v4(ip: Ipv4Addr) -> bool {
30    let o = ip.octets();
31    let carrier_grade_nat = o[0] == 100 && (o[1] & 0xc0) == 64;
32    let benchmarking = o[0] == 198 && (o[1] & 0xfe) == 18;
33    let protocol_assignments = o[0] == 192 && o[1] == 0 && o[2] == 0;
34    !(ip.is_loopback()
35        || ip.is_private()
36        || ip.is_link_local()
37        || ip.is_broadcast()
38        || ip.is_unspecified()
39        || ip.is_multicast()
40        || ip.is_documentation()
41        || o[0] == 0
42        || o[0] >= 240
43        || carrier_grade_nat
44        || benchmarking
45        || protocol_assignments)
46}
47
48fn is_public_v6(ip: Ipv6Addr) -> bool {
49    if let Some(v4) = ip.to_ipv4_mapped() {
50        return is_public_v4(v4);
51    }
52    let seg = ip.segments();
53    // 64:ff9b::/96 carries an IPv4 address in its last 32 bits.
54    if seg[0] == 0x64 && seg[1] == 0xff9b {
55        let v4 = Ipv4Addr::new(
56            (seg[6] >> 8) as u8,
57            seg[6] as u8,
58            (seg[7] >> 8) as u8,
59            seg[7] as u8,
60        );
61        return is_public_v4(v4);
62    }
63    let unique_local = (seg[0] & 0xfe00) == 0xfc00;
64    let link_local = (seg[0] & 0xffc0) == 0xfe80;
65    let documentation = seg[0] == 0x2001 && seg[1] == 0x0db8;
66    !(ip.is_loopback()
67        || ip.is_unspecified()
68        || ip.is_multicast()
69        || unique_local
70        || link_local
71        || documentation)
72}
73
74/// Whether a connection to this address could only reach the public internet.
75pub fn is_public_ip(ip: IpAddr) -> bool {
76    match ip {
77        IpAddr::V4(v4) => is_public_v4(v4),
78        IpAddr::V6(v6) => is_public_v6(v6),
79    }
80}
81
82/// Compares what a site answered at `/api/host_identity` with what the registration claimed.
83pub fn check_identity(slug: &str, operator_npub: &str, body: &[u8]) -> Result<(), String> {
84    let answered: HostIdentityResponse = serde_json::from_slice(body)
85        .map_err(|_| "the site's identity answer is not the expected JSON".to_string())?;
86    if answered.slug != slug {
87        return Err("the site answered with a different slug".to_string());
88    }
89    if answered.operator_npub != operator_npub {
90        return Err("the site answered with a different operator key".to_string());
91    }
92    Ok(())
93}
94
95/// The API the proof calls must live on the organization's own site: same host, or a subdomain
96/// of it, over https. Otherwise a registration could name a victim's URL and an attacker's API.
97pub fn api_on_own_site(portal_url: &str, api_url: Option<&str>) -> Result<(), String> {
98    let Some(api) = api_url else {
99        return Ok(());
100    };
101    let (portal, api) = match (::url::Url::parse(portal_url), ::url::Url::parse(api)) {
102        (Ok(p), Ok(a)) => (p, a),
103        _ => return Err(OWN_SITE_ERROR.to_string()),
104    };
105    let (Some(ph), Some(ah)) = (portal.host_str(), api.host_str()) else {
106        return Err(OWN_SITE_ERROR.to_string());
107    };
108    let same = ah == ph;
109    let subdomain = ah.ends_with(&format!(".{ph}"));
110    let port_ok = same && api.port_or_known_default() == portal.port_or_known_default();
111    if api.scheme() == "https" && ((same && port_ok) || subdomain) {
112        Ok(())
113    } else {
114        Err(OWN_SITE_ERROR.to_string())
115    }
116}
117
118/// A signed registration is acceptable for (key, slug) if it parses and is from that key.
119pub fn registration_for(
120    event: &Event,
121    pubkey: &PublicKey,
122    slug: &str,
123) -> Result<HostRegistration, String> {
124    let reg = parse_registration(event)?;
125    if &event.pubkey != pubkey || reg.slug != slug {
126        return Err(NO_REGISTRATION_ERROR.to_string());
127    }
128    Ok(reg)
129}
130
131/// ...and for an address too when it also names exactly that portal URL.
132pub fn accept_registration(
133    event: &Event,
134    pubkey: &PublicKey,
135    slug: &str,
136    portal_url: &str,
137) -> Result<HostRegistration, String> {
138    let reg = registration_for(event, pubkey, slug)?;
139    if reg.portal_url != portal_url {
140        return Err(NO_REGISTRATION_ERROR.to_string());
141    }
142    Ok(reg)
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use crate::registration::{build_registration_event, RegistrationInput};
149    use nostr::Keys;
150
151    const NPUB: &str = "npub1m7lzt4jmcutc0c9v0dgk8uzu6ae4xqn6s4sk8thl6nzxw5dyyqksdgansu";
152    const OTHER_NPUB: &str = "npub1juzsrwp5q8hrcawhu2rw4q4m8dsj7fnd2fuxcpmaf5v2z3agdq0q58djak";
153
154    #[test]
155    fn is_public_ip_refuses_every_private_range() {
156        let refused = [
157            "127.0.0.1",
158            "10.0.0.5",
159            "172.16.0.1",
160            "172.31.255.255",
161            "192.168.1.1",
162            "169.254.169.254",
163            "100.64.0.1",
164            "0.0.0.0",
165            "198.18.0.1",
166            "224.0.0.1",
167            "255.255.255.255",
168            "::1",
169            "::",
170            "fe80::1",
171            "fc00::1",
172            "fd12:3456::1",
173            "ff02::1",
174            "::ffff:127.0.0.1",
175            "::ffff:10.0.0.1",
176        ];
177        for ip in refused {
178            assert!(!is_public_ip(ip.parse().unwrap()), "{ip} must be refused");
179        }
180        for ip in ["8.8.8.8", "9.9.9.9", "172.32.0.1", "2606:4700:4700::1111"] {
181            assert!(is_public_ip(ip.parse().unwrap()), "{ip} must be allowed");
182        }
183    }
184
185    #[test]
186    fn check_identity_accepts_matching_slug_and_key() {
187        let body = format!(r#"{{"slug":"main-org","operator_npub":"{NPUB}"}}"#);
188        assert!(check_identity("main-org", NPUB, body.as_bytes()).is_ok());
189    }
190
191    #[test]
192    fn check_identity_rejects_wrong_key_wrong_slug_and_garbage() {
193        let wrong_key = format!(r#"{{"slug":"main-org","operator_npub":"{OTHER_NPUB}"}}"#);
194        assert!(check_identity("main-org", NPUB, wrong_key.as_bytes()).is_err());
195        let wrong_slug = format!(r#"{{"slug":"other","operator_npub":"{NPUB}"}}"#);
196        assert!(check_identity("main-org", NPUB, wrong_slug.as_bytes()).is_err());
197        assert!(check_identity("main-org", NPUB, b"<html>not json</html>").is_err());
198    }
199
200    #[test]
201    fn host_identity_without_name_parses() {
202        let body = format!(r#"{{"slug":"main-org","operator_npub":"{NPUB}"}}"#);
203        let answered: HostIdentityResponse = serde_json::from_str(&body).unwrap();
204        assert_eq!(answered.name, None);
205    }
206
207    #[test]
208    fn api_must_live_on_the_organizations_own_site() {
209        let portal = "https://morein.ph";
210        let ok = |api: &str| api_on_own_site(portal, Some(api)).is_ok();
211        assert!(api_on_own_site(portal, None).is_ok());
212        assert!(ok("https://morein.ph/backend"), "same host");
213        assert!(ok("https://api.morein.ph"), "subdomain");
214        assert!(
215            ok("https://api.morein.ph:8443/backend"),
216            "subdomain, other port"
217        );
218        assert!(!ok("https://api.attacker.com/backend"), "other site");
219        assert!(!ok("https://evilmorein.ph"), "suffix trick");
220        assert!(
221            !ok("https://morein.ph:8443/backend"),
222            "same host, other port"
223        );
224        assert!(!ok("http://morein.ph/backend"), "not https");
225        assert!(!ok("https://morein.ph.attacker.com"), "prefix trick");
226        assert!(
227            api_on_own_site("https://morein.ph:8443", Some("https://morein.ph:8443/b")).is_ok()
228        );
229    }
230
231    #[test]
232    fn a_registration_counts_only_for_its_own_key_slug_and_url() {
233        let keys = Keys::generate();
234        let input = RegistrationInput {
235            slug: "alpha-law".into(),
236            name: "Alpha".into(),
237            portal_url: "https://alpha.example".into(),
238            api_url: None,
239            relays: vec!["wss://nos.lol".into()],
240            geohash: None,
241            picture: None,
242        };
243        let ev = build_registration_event(&keys, &input).unwrap();
244        let pk = keys.public_key();
245        assert!(accept_registration(&ev, &pk, "alpha-law", "https://alpha.example").is_ok());
246        assert!(accept_registration(&ev, &pk, "alpha-law", "https://victim.ph").is_err());
247        assert!(accept_registration(&ev, &pk, "other-law", "https://alpha.example").is_err());
248        let stranger = Keys::generate().public_key();
249        assert!(accept_registration(&ev, &stranger, "alpha-law", "https://alpha.example").is_err());
250    }
251}