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
49 changes: 47 additions & 2 deletions plugins/rest-plugin/src/certs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Error;
use rcgen::{CertificateParams, DistinguishedName, Issuer, KeyPair};
use std::fs;
use std::net::IpAddr;
use std::net::{IpAddr, Ipv6Addr};
use std::path::{Path, PathBuf};

fn write_private_key(path: PathBuf, contents: &[u8]) -> Result<(), Error> {
Expand All @@ -16,6 +16,20 @@ fn write_private_key(path: PathBuf, contents: &[u8]) -> Result<(), Error> {
Ok(())
}

/// The IP address in the `clnrest-host` option, if it is one.
/// An IPv6 address may be given with or without brackets. Brackets are only
/// valid around IPv6, so `[127.0.0.1]` is not accepted.
pub fn host_ip(rest_host: &str) -> Option<IpAddr> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would accept bracketed ipv4 addresses. Suggested fix:

pub fn host_ip(rest_host: &str) -> Option<IpAddr> {
    if let Some(bare) = rest_host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
        bare.parse::<Ipv6Addr>().ok().map(IpAddr::V6)
    } else {
        rest_host.parse::<IpAddr>().ok()
    }
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, I used your version. [127.0.0.1] is refused now, and I added a test for it.

if let Some(bare) = rest_host
.strip_prefix('[')
.and_then(|h| h.strip_suffix(']'))
{
bare.parse::<Ipv6Addr>().ok().map(IpAddr::V6)
} else {
rest_host.parse::<IpAddr>().ok()
}
}

pub fn generate_certificates(certs_path: &PathBuf, rest_host: &str) -> Result<(), Error> {
/* Generate the CA certificate */
let mut ca_params = CertificateParams::new(vec![
Expand Down Expand Up @@ -61,7 +75,7 @@ pub fn generate_certificates(certs_path: &PathBuf, rest_host: &str) -> Result<()
server_params
.distinguished_name
.push(rcgen::DnType::CommonName, "cln rest server");
if let Ok(ip) = rest_host.parse::<IpAddr>() {
if let Some(ip) = host_ip(rest_host) {
server_params
.subject_alt_names
.push(rcgen::SanType::IpAddress(ip));
Expand Down Expand Up @@ -113,3 +127,34 @@ pub fn do_certificates_exist(cert_dir: &Path) -> bool {
path.exists() && path.metadata().map(|m| m.len() > 0).unwrap_or(false)
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn host_ip_ipv4() {
assert_eq!(host_ip("127.0.0.1"), Some("127.0.0.1".parse().unwrap()));
}

#[test]
fn host_ip_ipv6_bare() {
assert_eq!(host_ip("::1"), Some("::1".parse().unwrap()));
}

#[test]
fn host_ip_ipv6_bracketed() {
assert_eq!(host_ip("[::1]"), Some("::1".parse().unwrap()));
}

#[test]
fn host_ip_rejects_bracketed_ipv4() {
assert_eq!(host_ip("[127.0.0.1]"), None);
}

#[test]
fn host_ip_not_an_ip() {
assert_eq!(host_ip("localhost"), None);
assert_eq!(host_ip("[::1"), None);
}
}
66 changes: 53 additions & 13 deletions plugins/rest-plugin/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use tower_http::cors::{Any, CorsLayer};

use crate::{
PluginState,
certs::host_ip,
structs::{ClnrestOptions, ClnrestProtocol},
};

Expand Down Expand Up @@ -67,19 +68,15 @@ pub fn parse_options(
}
};

let address_str = format!("{}:{}", plugin.option(&OPT_CLNREST_HOST)?, port);
let address: SocketAddr = match plugin.option(&OPT_CLNREST_HOST)? {
i if i.eq("localhost") => address_str
.to_socket_addrs()?
.next()
.ok_or(anyhow!("No address found for localhost"))?,
_ => {
if let Ok(addr) = address_str.parse() {
addr
} else {
return Err(anyhow!("`clnrest-host` should be a valid IP."));
}
}
let host = plugin.option(&OPT_CLNREST_HOST)?;
let address = parse_address(&host, port)?;
// Keep `localhost` as given, so the address in the log and the
// certificate name still match. IP literals are printed from the parsed
// address, which puts brackets around IPv6.
let address_str = if host == "localhost" {
format!("{}:{}", host, port)
} else {
address.to_string()
};

let cors = create_cors_layer(&plugin.option(&OPT_CLNREST_CORS)?)?;
Expand Down Expand Up @@ -110,6 +107,20 @@ pub fn parse_options(
})
}

/// Turn the `clnrest-host` option and the port into a socket address.
pub fn parse_address(host: &str, port: u16) -> Result<SocketAddr, anyhow::Error> {
if host == "localhost" {
return format!("{}:{}", host, port)
.to_socket_addrs()?
.next()
.ok_or(anyhow!("No address found for localhost"));
}
match host_ip(host) {
Some(ip) => Ok(SocketAddr::new(ip, port)),
None => Err(anyhow!("`clnrest-host` should be a valid IP.")),
}
}

fn create_cors_layer(allowed_origins: &[String]) -> Result<CorsLayer, anyhow::Error> {
if allowed_origins.is_empty() {
return Err(anyhow!("`clnrest-cors-origins` must not be empty!"));
Expand Down Expand Up @@ -138,3 +149,32 @@ fn create_cors_layer(allowed_origins: &[String]) -> Result<CorsLayer, anyhow::Er
.allow_headers(Any))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn parse_address_ipv4() {
let addr = parse_address("127.0.0.1", 3010).unwrap();
assert_eq!(addr.to_string(), "127.0.0.1:3010");
}

#[test]
fn parse_address_ipv6_bare() {
let addr = parse_address("::1", 3010).unwrap();
assert_eq!(addr.to_string(), "[::1]:3010");
}

#[test]
fn parse_address_ipv6_bracketed() {
let addr = parse_address("[::1]", 3010).unwrap();
assert_eq!(addr.to_string(), "[::1]:3010");
}

#[test]
fn parse_address_rejects_garbage() {
assert!(parse_address("not-an-ip", 3010).is_err());
assert!(parse_address("[::1", 3010).is_err());
}
}
Loading