aboutsummaryrefslogtreecommitdiff
path: root/src/wg/peer.rs
blob: ed77911740791510d8bf39d4e0322142844cb0a9 (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
use std::net::Ipv4Addr;
use std::fs::{read_to_string, self, File};
use std::fmt::Write;
use std::path::{Path};
use std::process::{Command, Stdio};
use std::io::Write as ioWrite;

use anyhow::{Context, Result, anyhow};

use super::config::WireguardConfig;

#[derive(Debug)]
pub struct Peer {
    pub name: String,
    pub public_key: String,
    pub ip: Ipv4Addr
}

impl Peer {
    pub fn new(name: String, ip: Ipv4Addr) -> Result<Peer> {
        let private = Command::new("wg")
            .arg("genkey")
            .output()
            .context("Could not generate a private key. Is 'wg' installed?")?;

        let mut public = Command::new("wg")
            .arg("pubkey")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .context("Could not run 'wg'")?;

        let private_clone = private.stdout.clone();

        let mut stdin = public.stdin.take().context("could not open wg stdin")?;
        std::thread::spawn(move || {
            stdin.write_all(&private.stdout).unwrap();
        });

        let output = public.wait_with_output().context("could not read from 'wg pubkey'")?;
    
        let private_key = String::from_utf8(private_clone).context("could not decode private key")?;
        let public_key = String::from_utf8(output.stdout).context("could not decode public key")?;

        let private_key = private_key.trim();
        let public_key = public_key.trim();

        let p = Peer{
            name,
            ip,
            public_key: String::from(public_key)
        };

        let pk_path = p.private_key_path()?;
        let mut f = File::create(pk_path.clone()).context(format!("could not create file {}", pk_path))?;
        write!(f, "{}", private_key).context("could not write private key to file")?;


        Ok(p)
    }

    fn private_key_folder(&self) -> Result<String> {
        let pk_folder = String::from("/etc/wireguard/private_keys/");

        let pk_path = Path::new(pk_folder.as_str());
        if !pk_path.exists() {
            fs::create_dir(pk_path).context(format!("creating {} folder", pk_folder))?;
        }

        if !pk_path.is_dir() {
            return Err(anyhow!("Error: the private key folder exists but is not a directory"));
        }

        Ok(pk_folder)
    }

    pub fn private_key_path(&self) -> Result<String> {
        let folder_name = self.private_key_folder()?;
        let pk_folder = Path::new(folder_name.as_str());
        let pk_path = pk_folder.join(self.name.clone());

        Ok(String::from(pk_path.to_str().unwrap()))
    }

    pub fn private_key(&self) -> Result<String> {
        let pk_path = self.private_key_path()?;
        let pk = read_to_string(pk_path)?;

        Ok(pk)
    }

    pub fn gen_config(&self, wg_conf: &WireguardConfig, dns: Option<String>, endpoint: String, port: Option<u32>, is_full: bool) -> Result<String>{
        let mut res = String::new();
        
        writeln!(res, "[Interface]")?;
        writeln!(res, "PrivateKey = {}", self.private_key()?)?;
        writeln!(res, "Address = {}/32", self.ip)?;

        if let Some(s) = dns {
            writeln!(res, "DNS = {}", s)?;
        }
        
        writeln!(res, "")?;
        writeln!(res, "[Peer]")?;
        writeln!(res, "PublicKey = {}", wg_conf.public_key().context("error getting server public key")?)?;

        let allowed_ips = match is_full { 
            true => String::from("0.0.0.0/0"), 
            false => wg_conf.network.to_string()
        };
        writeln!(res, "AllowedIPs = {}", allowed_ips)?;

        let port = match port {
            Some(p) => p,
            None => 51820,
        };
        writeln!(res, "Endpoint = {}:{}", endpoint, port)?;
        writeln!(res, "PersistentKeepAlive = 25")?;

        Ok(res)
    }
}

impl PartialOrd for Peer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        return self.ip.partial_cmp(&other.ip)
    }

    fn ge(&self, other: &Self) -> bool {
        return self.ip.ge(&other.ip)
    }

    fn gt(&self, other: &Self) -> bool {
        return self.ip.gt(&other.ip)
    }

    fn le(&self, other: &Self) -> bool {
        return self.ip.le(&other.ip)
    }

    fn lt(&self, other: &Self) -> bool {
        return self.ip.lt(&other.ip)
    }
}

impl PartialEq for Peer {
    fn eq(&self, other: &Self) -> bool {
        return self.ip.eq(&other.ip)
    }

    fn ne(&self, other: &Self) -> bool {
        return self.ip.ne(&other.ip)
    }
}