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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! `alog` is a simple log file anonymizer.
//!
//! ## About
//!
//! In fact `alog` just replaces the first *word*[^1] on every line of any input stream with a
//! customizable string.
//!
//! So "log file anonymizer" might be a bit of an overstatement, but `alog` can be used to (very
//! efficiently) replace the $remote_addr part in many access log formats, e.g. Nginx' default
//! combined log format:
//!
//! ```text
//! log_format combined '$remote_addr - $remote_user [$time_local] '
//!                     '"$request" $status $body_bytes_sent '
//!                     '"$http_referer" "$http_user_agent"';
//! ```
//!
//! By default any parseable $remote_addr is replaced by it's *localhost* representation,
//!
//! * any valid IPv4 address is replaced by '127.0.0.1',
//! * any valid IPv6 address is replaced by '::1' and
//! * any String (what might be a domain name) with 'localhost'.
//!
//! Lines without a $remote_addr part will remain unchanged (but can be skipped with
//! [`alog::Config::set_skip()`] set to `true`).
//!
//! [^1]: Any first substring separated by a `b' '` (Space) from the remainder of the line.
//!
//! ### Personal data in server logs
//!
//! The default configuration of popular web servers including Apache Web Server and Nginx collect
//! and store at least two of the following three types of logs:
//!
//! 1. access logs
//! 2. error logs (including processing-language logs like PHP)
//! 3. security audit logs
//!
//! All of these logs contain personal information by default. IP addresses are specifically
//! defined as personal data by the [GDPR].  The logs can also contain usernames if your web
//! service uses them as part of their URL structure, and even the referral information that’s
//! logged by default **can** contain personal information (or other sensitive data).
//!
//! So keep in mind, just removing the IP / `$remote_addr` part might not be enough to fully
//! anonymize any given log file.
//!
//! [GDPR]: https://gdpr.eu/article-4-definitions/
//! [`alog::Config::set_skip()`]: ./struct.Config.html#method.set_skip

use std::fs::File;
use std::fs::OpenOptions;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::net;
use std::path::Path;
use std::process;

/// INPUT / OUTPUT config
#[derive(Debug)]
pub struct IOConfig<'a> {
    /// List of input paths / files, e.g. Some(["/tmp/test1.log", "/tmp/test2.log"])
    pub input: Option<Vec<&'a str>>,
    /// Single output path / file
    pub output: Option<&'a str>,
}

/// Collection of replacement strings / config flags
#[derive(Debug)]
pub struct Config<'a> {
    /// IPv4-parseable $remote_addr replacement string
    pub ipv4: &'a str,
    /// IPv6-parseable $remote_addr replacement string
    pub ipv6: &'a str,
    /// $remote_addr replacement string
    pub host: &'a str,
    /// Skip lines w/o a $remote_addr part / first word
    pub skip: bool,
    /// Flush output after each line
    pub flush: bool,
}

/// defaults to `None` for both input and output
impl<'a> Default for IOConfig<'a> {
    fn default() -> Self {
        IOConfig {
            input: None,
            output: None,
        }
    }
}

/// defaults to an equivalent of *localhost*
impl<'a> Default for Config<'a> {
    fn default() -> Self {
        Config {
            ipv4: "127.0.0.1",
            ipv6: "::1",
            host: "localhost",
            skip: false,
            flush: false,
        }
    }
}

impl<'a> Config<'a> {
    /// Get IPv4 replacement value
    pub fn get_ipv4_value(&self) -> &'a str {
        &self.ipv4
    }

    /// Get IPv6 replacement value
    pub fn get_ipv6_value(&self) -> &'a str {
        &self.ipv6
    }

    /// Get string replacement value
    pub fn get_host_value(&self) -> &'a str {
        &self.host
    }

    /// Get `skip` value
    pub fn get_skip(&self) -> bool {
        self.skip
    }

    /// Get `flush` value
    pub fn get_flush(&self) -> bool {
        self.flush
    }

    /// Set IPv4 replacement `String`
    pub fn set_ipv4_value(&mut self, ipv4: &'a str) {
        self.ipv4 = ipv4;
    }

    /// Set IPv6 replacement `String`
    pub fn set_ipv6_value(&mut self, ipv6: &'a str) {
        self.ipv6 = ipv6;
    }

    /// Set `hostname` replacement `String`
    pub fn set_host_value(&mut self, host: &'a str) {
        self.host = host;
    }

    /// Set `flush` field
    pub fn set_flush(&mut self, b: bool) {
        self.flush = b;
    }

    /// Set `skip` field
    pub fn set_skip(&mut self, b: bool) {
        self.skip = b;
    }
}

impl<'a> IOConfig<'a> {
    /// Get input / reader names, if any (defaults to `None`)
    pub fn get_input(&self) -> Option<&Vec<&'a str>> {
        self.input.as_ref()
    }

    /// Get output / writer name (defaults to `None`)
    pub fn get_output(&self) -> Option<&'a str> {
        self.output
    }

    /// Add input `Path`
    pub fn push_input(&mut self, i: &'a str) {
        if let Some(input) = &mut self.input {
            input.push(i);
        } else {
            self.input = Some(vec![]);
            self.push_input(i);
        }
    }

    /// Set output `Path`
    pub fn set_output(&mut self, output: &'a str) {
        self.output = Some(output);
    }
}

/// Reads lines from `reader`, if there is a '*first word*' (any String separated from the
/// remainder of the line by a b' ' (Space) byte) this word will be replaced
///
/// Any word, that can be parsed as
/// * [`std::net::Ipv4Addr`] will be replaced with [`alog::Config::get_ipv4_value()`],
/// * [`std::net::Ipv6Addr`] will be replaced with [`alog::Config::get_ipv6_value()`],
/// * any other *word* will be replaced with [`alog::Config::get_host_value()`].
///
/// Any line without a 'first word' will be written as is if [`alog::Config::get_skip()`] returns
/// `false` (default), or will be skipped otherwise.
///
/// ## Errors
///
/// This function will return an I/O error if the underlying reader or writer returns an error.
///
/// [`alog::Config::get_ipv4_value()`]: ./struct.Config.html#method.get_ipv4_value
/// [`alog::Config::get_ipv6_value()`]: ./struct.Config.html#method.get_ipv6_value
/// [`alog::Config::get_host_value()`]: ./struct.Config.html#method.get_host_value
fn replace_remote_address<R: BufRead, W: Write>(
    config: &Config,
    mut reader: R,
    mut writer: W,
) -> Result<(), std::io::Error> {
    let mut buf = vec![];

    'lines: loop {
        buf.clear();
        let bytes_read = reader.read_until(b'\n', &mut buf)?;
        match bytes_read {
            0 => break,
            _ => {
                for (i, byte) in buf.iter().enumerate() {
                    if *byte == b' ' {
                        if let Ok(_) = String::from_utf8_lossy(&buf[..i]).parse::<net::Ipv4Addr>() {
                            write!(&mut writer, "{}", config.get_ipv4_value())?;
                        } else if let Ok(_) =
                            String::from_utf8_lossy(&buf[..i]).parse::<net::Ipv6Addr>()
                        {
                            write!(&mut writer, "{}", config.get_ipv6_value())?;
                        } else {
                            write!(&mut writer, "{}", config.get_host_value())?;
                        }
                        writer.write(&buf[i..])?;
                        if config.get_flush() == true {
                            writer.flush()?;
                        }
                        continue 'lines;
                    }
                }
                if config.get_skip() != true {
                    writer.write(&buf)?;
                    if config.get_flush() == true {
                        writer.flush()?;
                    }
                }
            }
        };
    }
    writer.flush()?;
    Ok(())
}

/// Creates a reader (defaults to [`std::io::Stdin`]) and writer (defaults to [`std::io::Stdout`])
/// from [`alog::IOConfig`], passes both along with the [`alog::Config`] struct to actually replace
/// any first *word* in `reader` with strings stored in [`alog::Config`].
///
/// ## Errors
///
/// Exits when [`alog::IOConfig::get_output()`] already exists or the new reader / writer retruns
/// an error.
///
/// [`alog::Config`]: ./struct.Config.html
/// [`alog::IOConfig`]: ./struct.IOConfig.html
/// [`alog::IOConfig::get_output()`]: ./struct.IOConfig.html#method.get_output
/// [`std::io::Stdin`]: https://doc.rust-lang.org/std/io/struct.Stdin.html
/// [`std::io::Stdout`]: https://doc.rust-lang.org/std/io/struct.Stdout.html
/// [`std::net::Ipv4Addr`]: https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html
/// [`std::net::Ipv6Addr`]: https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html
pub fn run(config: &Config, ioconfig: &IOConfig) {
    // Set writer
    let mut writer: Box<dyn Write> = match ioconfig.get_output() {
        Some(output) => {
            let f = OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(Path::new(output));
            let f = match f {
                Ok(file) => file,
                Err(e) => {
                    eprintln!("Error writing to file {}: {}.", output, e);
                    std::process::exit(1);
                }
            };
            Box::new(BufWriter::new(f)) as _
        }
        None => Box::new(BufWriter::new(io::stdout())),
    };

    // Set reader
    if let Some(input) = ioconfig.get_input() {
        for arg in input {
            let f = File::open(Path::new(arg));
            let f = match f {
                Ok(file) => file,
                Err(e) => {
                    eprintln!("Error reading file '{}': {}.", arg, e);
                    if let Some(output) = ioconfig.get_output() {
                        std::fs::remove_file(Path::new(output)).unwrap();
                    }
                    process::exit(1);
                }
            };
            let reader: Box<dyn BufRead> = Box::new(BufReader::new(f));
            if let Err(e) = replace_remote_address(config, reader, &mut writer) {
                eprintln!("Error: {}", e);
                if let Some(output) = ioconfig.get_output() {
                    std::fs::remove_file(Path::new(output)).unwrap();
                }
                process::exit(1);
            }
        }
    } else {
        let reader: Box<dyn BufRead> = Box::new(BufReader::new(io::stdin()));
        if let Err(e) = replace_remote_address(config, reader, &mut writer) {
            eprintln!("Error: {}", e);
            if let Some(output) = ioconfig.get_output() {
                std::fs::remove_file(Path::new(output)).unwrap();
            }
            process::exit(1);
        }
    }
}

/// Like [`alog::run`] but will let you pass your own `reader` and `writer`. Replacement strings
/// and config flags will still be read from [`alog::Config`] though.
///
/// ## Example
/// ```
/// use std::io::Cursor;
///
/// let line = Cursor::new(b"8.8.8.8 XxX");
/// let mut buffer = vec![];
///
/// alog::run_raw(&alog::Config::default(), line, &mut buffer);
/// assert_eq!(buffer, b"127.0.0.1 XxX");
/// ```
///
/// To read from Stdin and write to Stdout:
///
/// ```no_run
/// use std::io::{self, BufReader, BufWriter};
///
/// // Consider wrapping io::stdout in BufWriter
/// alog::run_raw(&alog::Config::default(), BufReader::new(io::stdin()), io::stdout());
/// ```
/// ## Errors
///
/// Exits when the new reader or writer retruns an error.
///
/// [`alog::run`]: ./fn.run.html
/// [`alog::Config`]: ./struct.Config.html
pub fn run_raw<R: BufRead, W: Write>(config: &Config, reader: R, mut writer: W) {
    if let Err(e) = replace_remote_address(config, reader, &mut writer) {
        eprintln!("Error: {}", e);
        process::exit(1);
    }
}

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

    #[test]
    fn run_raw_function() {
        use std::io::Cursor;
        let line = Cursor::new(b"8.8.8.8 XxX");
        let mut buffer = vec![];

        run_raw(&Config::default(), line, &mut buffer);
        assert_eq!(buffer, b"127.0.0.1 XxX");
    }

    #[test]
    fn replace_ipv4() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("8.8.8.8 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        replace_remote_address(&Config::default(), log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }

    #[test]
    fn replace_ipv6() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("2a00:1450:4001:81b::2004 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "::1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        replace_remote_address(&Config::default(), log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }

    #[test]
    fn replace_host() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("google.com - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "localhost - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        replace_remote_address(&Config::default(), log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }

    #[test]
    fn replace_custom_ipv4() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("8.8.8.8 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "custom_ipv4 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        let mut conf = Config::default();
        conf.set_ipv4_value("custom_ipv4");

        replace_remote_address(&conf, log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }

    #[test]
    fn replace_custom_ipv6() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("2a00:1450:4001:81b::2004 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "custom_ipv6 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        let mut conf = Config::default();
        conf.set_ipv6_value("custom_ipv6");

        replace_remote_address(&conf, log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }

    #[test]
    fn replace_custom_host() {
        use std::io::Cursor;
        let mut buffer = Cursor::new(vec![]);
        let log = Box::new("google.com - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes());
        let local_log = "custom_host - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"".as_bytes();

        let mut conf = Config::default();
        conf.set_host_value("custom_host");

        replace_remote_address(&conf, log, &mut buffer).unwrap();
        assert_eq!(&buffer.into_inner(), &local_log);
    }
}