summaryrefslogtreecommitdiffhomepage
path: root/mullvad-cli/src/cmds/personal_vpn.rs
blob: f131426f837e69d65eea75482abb2e4816703a92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#![cfg(feature = "personal-vpn")]

use anyhow::{Context, Result};
use clap::Subcommand;
use ipnetwork::IpNetwork;
use mullvad_management_interface::MullvadProxyClient;
use std::{
    fs,
    io::{self, Read},
    net::IpAddr,
    str::FromStr,
};
use talpid_types::net::wireguard;
use talpid_types::net::wireguard::{
    PersonalVpnTunnelConfig, UnresolvedPersonalVpnConfig, UnresolvedPersonalVpnPeerConfig,
};

use super::BooleanOption;

#[derive(Subcommand, Debug)]
pub enum PersonalVpn {
    /// Show current personal VPN configuration and enabled state
    Get,

    /// Set the personal WireGuard VPN configuration (requires all fields)
    Set {
        /// Base64-encoded WireGuard private key for the tunnel interface
        #[arg(long, value_parser = wireguard::PrivateKey::from_base64)]
        private_key: wireguard::PrivateKey,

        /// IP address for the tunnel interface
        #[arg(long)]
        tunnel_ip: IpAddr,

        /// Base64-encoded WireGuard public key of the VPN peer
        #[arg(long, value_parser = wireguard::PublicKey::from_base64)]
        peer_pubkey: wireguard::PublicKey,

        /// IP network to route through the VPN peer, in CIDR notation (e.g. 0.0.0.0/0)
        #[arg(long)]
        allowed_ip: Vec<IpNetwork>,

        /// Endpoint of the VPN peer as `<host>:<port>` (host may be an IP or
        /// DNS name, e.g. `1.2.3.4:51820` or `vpn.example.com:51820`)
        #[arg(long)]
        endpoint: String,
    },

    /// Enable or disable the personal VPN
    Enable { state: BooleanOption },

    /// Remove the personal VPN configuration
    Unset,

    /// Import a WireGuard config file.
    /// If PATH is "-", read from standard input.
    Import {
        /// Path to the config file, or "-" for stdin
        path: String,
    },
}

impl PersonalVpn {
    pub async fn handle(self) -> Result<()> {
        match self {
            PersonalVpn::Get => Self::get().await,
            PersonalVpn::Set {
                private_key,
                tunnel_ip,
                peer_pubkey,
                allowed_ip,
                endpoint,
            } => Self::set(private_key, tunnel_ip, peer_pubkey, allowed_ip, endpoint).await,
            PersonalVpn::Enable { state } => Self::enable(state).await,
            PersonalVpn::Unset => Self::unset().await,
            PersonalVpn::Import { path } => Self::import(path).await,
        }
    }

    async fn get() -> Result<()> {
        let mut rpc = MullvadProxyClient::new().await?;
        let settings = rpc.get_settings().await?;
        let enabled = BooleanOption::from(settings.personal_vpn_enabled);
        println!("Personal VPN: {enabled}");
        match settings.personal_vpn_config {
            None => println!("Configuration: none"),
            Some(config) => {
                // TODO: Do not print?
                println!(
                    "Tunnel private key: {}",
                    config.tunnel.private_key.to_base64()
                );
                println!("Tunnel IP:          {}", config.tunnel.ip);
                println!("Peer public key:    {}", config.peer.public_key.to_base64());
                for allowed_ip in &config.peer.allowed_ip {
                    println!("Allowed IP:         {allowed_ip}");
                }
                println!("Endpoint:           {}", config.peer.endpoint);
            }
        }
        Ok(())
    }

    async fn set(
        private_key: wireguard::PrivateKey,
        tunnel_ip: IpAddr,
        peer_pubkey: wireguard::PublicKey,
        allowed_ip: Vec<IpNetwork>,
        endpoint: String,
    ) -> Result<()> {
        let config = UnresolvedPersonalVpnConfig {
            tunnel: PersonalVpnTunnelConfig {
                private_key,
                ip: tunnel_ip,
            },
            peer: UnresolvedPersonalVpnPeerConfig {
                public_key: peer_pubkey,
                allowed_ip,
                endpoint,
            },
        };
        let mut rpc = MullvadProxyClient::new().await?;
        let error = rpc.set_personal_vpn_config(Some(config)).await?;
        if !error.is_empty() {
            anyhow::bail!("Daemon returned error: {error}");
        }
        println!("Personal VPN configuration updated");
        Ok(())
    }

    async fn enable(state: BooleanOption) -> Result<()> {
        let mut rpc = MullvadProxyClient::new().await?;
        rpc.set_personal_vpn_config_status(*state).await?;
        println!("Personal VPN: {state}");
        Ok(())
    }

    async fn unset() -> Result<()> {
        let mut rpc = MullvadProxyClient::new().await?;
        let error = rpc.set_personal_vpn_config(None).await?;
        if !error.is_empty() {
            anyhow::bail!("Daemon returned error: {error}");
        }
        println!("Personal VPN configuration removed");
        Ok(())
    }

    /// Blocking: reads the entire file or stdin before returning.
    async fn import(path: String) -> Result<()> {
        let config_str = tokio::task::spawn_blocking(move || -> Result<String> {
            if path == "-" {
                let mut buf = String::new();
                io::stdin()
                    .read_to_string(&mut buf)
                    .context("Failed to read from stdin")?;
                Ok(buf)
            } else {
                fs::read_to_string(&path).with_context(|| format!("Failed to read {path}"))
            }
        })
        .await??;

        let config = UnresolvedPersonalVpnConfig::from_str(&config_str)
            .context("Failed to parse WireGuard config")?;

        let mut rpc = MullvadProxyClient::new().await?;
        let error = rpc.set_personal_vpn_config(Some(config)).await?;
        if !error.is_empty() {
            anyhow::bail!("Daemon returned error: {error}");
        }
        println!("Personal VPN configuration imported");
        Ok(())
    }
}