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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::{
    borrow::Cow,
    collections::HashSet,
    net::{IpAddr, SocketAddr},
    path::{Path, PathBuf},
    sync::Arc,
};

use crate::error::BootstrapError;
use massa_logging::massa_trace;
use parking_lot::RwLock;
use tracing::{info, warn};

use crate::tools::to_canonical;

/// A wrapper around the white/black lists that allows efficient sharing between threads
// TODO: don't clone the path-bufs...
#[derive(Clone, Debug)]
pub struct SharedWhiteBlackList<'a> {
    inner: Arc<RwLock<WhiteBlackListInner>>,
    white_path: Cow<'a, Path>,
    black_path: Cow<'a, Path>,
}

impl SharedWhiteBlackList<'_> {
    pub(crate) fn new(white_path: PathBuf, black_path: PathBuf) -> Result<Self, BootstrapError> {
        let (white_list, black_list) = WhiteBlackListInner::init_list(&white_path, &black_path)?;
        Ok(Self {
            inner: Arc::new(RwLock::new(WhiteBlackListInner {
                white_list,
                black_list,
            })),
            white_path: Cow::from(white_path),
            black_path: Cow::from(black_path),
        })
    }

    /// get the white list
    pub fn get_white_list(&self) -> Option<HashSet<IpAddr>> {
        self.inner.read().white_list.clone()
    }

    /// get the black list
    pub fn get_black_list(&self) -> Option<HashSet<IpAddr>> {
        self.inner.read().black_list.clone()
    }

    /// Add IP address to the black list
    pub fn add_ips_to_blacklist(&self, ips: Vec<IpAddr>) -> Result<(), BootstrapError> {
        // Canonicalize on insert so the in-memory list matches the canonical
        // form used by `is_ip_allowed` (and by `load_list` on reload). Otherwise
        // a non-canonical entry such as `::ffff:a.b.c.d` would fail to block the
        // equivalent IPv4 peer until the next file reload.
        let ips = ips.into_iter().map(to_canonical).collect::<Vec<_>>();
        let mut write_lock = self.inner.write();
        if let Some(black_list) = &mut write_lock.black_list {
            black_list.extend(ips);
        } else {
            write_lock.black_list = Some(HashSet::from_iter(ips));
        };
        self.write_to_file(&self.black_path, write_lock.black_list.as_ref().unwrap())?;
        Ok(())
    }

    /// Remove IPs address from the black list
    pub fn remove_ips_from_blacklist(&self, ips: Vec<IpAddr>) -> Result<(), BootstrapError> {
        let ips = ips.into_iter().map(to_canonical).collect::<Vec<_>>();
        let mut write_lock = self.inner.write();
        if let Some(black_list) = &mut write_lock.black_list {
            for ip in ips {
                black_list.remove(&ip);
            }
            self.write_to_file(&self.black_path, black_list)?;
        }
        Ok(())
    }

    /// Add IP address to the white list
    pub fn add_ips_to_whitelist(&self, ips: Vec<IpAddr>) -> Result<(), BootstrapError> {
        // See `add_ips_to_blacklist`: canonicalize on insert for consistency
        // with the canonicalized membership check in `is_ip_allowed`.
        let ips = ips.into_iter().map(to_canonical).collect::<Vec<_>>();
        let mut write_lock = self.inner.write();
        if let Some(white_list) = &mut write_lock.white_list {
            white_list.extend(ips);
        } else {
            write_lock.white_list = Some(HashSet::from_iter(ips));
        };
        self.write_to_file(&self.white_path, write_lock.white_list.as_ref().unwrap())?;
        Ok(())
    }

    /// Remove IPs address from the white list
    pub fn remove_ips_from_whitelist(&self, ips: Vec<IpAddr>) -> Result<(), BootstrapError> {
        let ips = ips.into_iter().map(to_canonical).collect::<Vec<_>>();
        let mut write_lock = self.inner.write();
        if let Some(white_list) = &mut write_lock.white_list {
            for ip in ips {
                white_list.remove(&ip);
            }
            self.write_to_file(&self.white_path, white_list)?;
        }
        Ok(())
    }

    /// write list to file
    fn write_to_file(
        &self,
        file_path: &Path,
        data: &HashSet<IpAddr>,
    ) -> Result<(), BootstrapError> {
        let list = serde_json::to_string(data).map_err(|e| {
            warn!(error = ?e, "failed to serialize list");
            BootstrapError::SerializationError(e.to_string())
        })?;
        std::fs::write(file_path, list).map_err(|e| {
            warn!(error = ?e, "failed to write list to file");
            BootstrapError::IoError(e)
        })?;
        Ok(())
    }

    /// Checks if the white/black list is up to date with a read-lock
    /// Creates a new list, and replaces the old one in a write-lock
    pub(crate) fn update(&mut self) -> Result<(), BootstrapError> {
        let read_lock = self.inner.read();
        let (new_white_file, new_black_file) =
            WhiteBlackListInner::update_list(&self.white_path, &self.black_path)?;
        let white_delta = new_white_file != read_lock.white_list;
        let black_delta = new_black_file != read_lock.black_list;
        if white_delta || black_delta {
            // Ideally this scope would be atomic
            let mut mut_inner = {
                drop(read_lock);
                self.inner.write()
            };

            if white_delta {
                info!("whitelist has updated !");
                mut_inner.white_list = new_white_file;
            }
            if black_delta {
                info!("blacklist has updated !");
                mut_inner.black_list = new_black_file;
            }
        }
        Ok(())
    }

    pub(crate) fn is_ip_allowed(&self, remote_addr: &SocketAddr) -> Result<(), BootstrapError> {
        let ip = to_canonical(remote_addr.ip());
        // whether the peer IP address is blacklisted
        let read = self.inner.read();
        if let Some(ip_list) = &read.black_list {
            if ip_list.contains(&ip) {
                massa_trace!("bootstrap.lib.run.select.accept.refuse_blacklisted", {"remote_addr": remote_addr});
                return Err(BootstrapError::BlackListed(ip.to_string()));
            }
            // whether the peer IP address is not present in the whitelist
        }
        if let Some(ip_list) = &read.white_list {
            if !ip_list.contains(&ip) {
                massa_trace!("bootstrap.lib.run.select.accept.refuse_not_whitelisted", {"remote_addr": remote_addr});
                return Err(BootstrapError::WhiteListed(ip.to_string()));
            }
        }
        Ok(())
    }
}

impl WhiteBlackListInner {
    #[allow(clippy::type_complexity)]
    fn update_list(
        whitelist_path: &Path,
        blacklist_path: &Path,
    ) -> Result<(Option<HashSet<IpAddr>>, Option<HashSet<IpAddr>>), BootstrapError> {
        Ok((
            Self::load_list(whitelist_path, false)?,
            Self::load_list(blacklist_path, false)?,
        ))
    }

    #[allow(clippy::type_complexity)]
    fn init_list(
        whitelist_path: &Path,
        blacklist_path: &Path,
    ) -> Result<(Option<HashSet<IpAddr>>, Option<HashSet<IpAddr>>), BootstrapError> {
        Ok((
            Self::load_list(whitelist_path, true)?,
            Self::load_list(blacklist_path, true)?,
        ))
    }

    fn load_list(
        list_path: &Path,
        is_init: bool,
    ) -> Result<Option<HashSet<IpAddr>>, BootstrapError> {
        match std::fs::read_to_string(list_path) {
            Err(e) => {
                if is_init {
                    warn!(
                        "error on load whitelist/blacklist file : {} | {}",
                        list_path.to_str().unwrap_or(" "),
                        e
                    );
                }
                Ok(None)
            }
            Ok(list) => {
                let res = Some(
                    serde_json::from_str::<HashSet<IpAddr>>(list.as_str())
                        .map_err(|e| {
                            BootstrapError::InitListError(format!(
                                "Failed to parse bootstrap whitelist : {}",
                                e
                            ))
                        })?
                        .into_iter()
                        .map(to_canonical)
                        .collect(),
                );
                Ok(res)
            }
        }
    }
}

#[derive(Default, Debug)]
pub(crate) struct WhiteBlackListInner {
    white_list: Option<HashSet<IpAddr>>,
    black_list: Option<HashSet<IpAddr>>,
}

#[cfg(test)]
mod tests {
    use super::SharedWhiteBlackList;
    use crate::error::BootstrapError;
    use std::net::{IpAddr, SocketAddr};
    use tempfile::TempDir;

    #[test]
    fn blacklisting_mapped_ipv6_blocks_equivalent_ipv4_immediately() {
        let dir = TempDir::new().unwrap();
        let white = dir.path().join("whitelist.json");
        let black = dir.path().join("blacklist.json");
        let list = SharedWhiteBlackList::new(white, black).unwrap();

        // Add the IPv4-mapped IPv6 form of 127.0.0.2 through the private API.
        let mapped: IpAddr = "::ffff:127.0.0.2".parse().unwrap();
        list.add_ips_to_blacklist(vec![mapped]).unwrap();

        // The equivalent plain IPv4 peer must be blocked right away, without
        // waiting for a file reload to canonicalize the stored entry.
        let peer = SocketAddr::new("127.0.0.2".parse().unwrap(), 12345);
        assert!(matches!(
            list.is_ip_allowed(&peer),
            Err(BootstrapError::BlackListed(_))
        ));
    }
}