Visualising SSH attacks with R

If you have any machine with an SSH server open to the world and you take a look at your logs, you may be alarmed to see so many login attempts from so many unknown IP addresses. DenyHosts is a pretty neat service for Unix-based systems which works in the background reviewing such logs and appending the offending addresses into the hosts.deny file, thus avoiding brute-force attacks.

The following R snippet may be useful to quickly visualise a hosts.deny file with logs from DenyHosts. Such file may have comments (lines starting with #), and actual records are stored in the form <service>: <IP>. Therefore, read.table is more than enough to load it into R. The rgeolocate package is used to geolocate the IPs, and the counts per country are represented in a world map using rworldmap:

library(dplyr)
library(rgeolocate)
library(rworldmap)
hosts.deny <- "/etc/hosts.deny"
db <- system.file("extdata", "GeoLite2-Country.mmdb", package="rgeolocate")
read.table(hosts.deny, col.names=c("service", "IP")) %>%
  pull(IP) %>%
  maxmind(db, fields="country_code") %>%
  count(country_code) %>%
  as.data.frame() %>%
  joinCountryData2Map(joinCode="ISO2", nameJoinColumn="country_code") %>%
  mapCountryData(nameColumnToPlot="n", catMethod="pretty", mapTitle="Attacks per country")
## 74 codes from your data successfully matched countries in the map
## 2 codes from your data failed to match with a country code in the map
## 168 codes from the map weren't represented in your data

Then, you may consider more specific access restrictions based on IP prefixes…

simmer 3.6.4

The fourth update of the 3.6.x release of simmer, the Discrete-Event Simulator for R, is on CRAN. This release patches several bugs regarding resource priority and preemption management when seized amounts greater than one were involved. Check the examples available in the corresponding issues on GitHub (#114#115#116) to know if you are affected.

It can be noted that we already broke the intended bi-monthly release cycle, but it is for a good reason, since we are preparing a journal publication. Further details to come.

Minor changes and fixes:

  • Fix preemption in non-saturated multi-server resources when seizing amounts > 1 (#114).
  • Fix queue priority in non-saturated finite-queue resources when seizing amounts > 1 (#115).
  • Fix resource seizing: avoid jumping the queue when there is room in the server but other arrivals are waiting (#116).

simmer 3.6.3

The third update of the 3.6.x release of simmer, the Discrete-Event Simulator for R, is on CRAN. First of all and once again, I must thank Duncan Garmonsway (@nacnudus) for writing a new vignette: “The Bank Tutorial: Part II”.

Among various fixes and performance improvements, this release provides a way of knowing the progress of a simulation. This feature is embed into the run() function as a parameter called progress, which accepts a function with a single argument and will be called for each one of the steps (10 by default) with the current progress ratio (a number between 0 and 1). A very naive example using a simple print():

library(simmer)

wait_and_go <- trajectory() %>%
  timeout(1)

simmer() %>%
  add_generator("dummy", wait_and_go, function() 1) %>%
  run(until=10, progress=print, steps=5)
## [1] 0
## [1] 0.2
## [1] 0.4
## [1] 0.6
## [1] 0.8
## [1] 1
## simmer environment: anonymous | now: 10 | next: 10
## { Generator: dummy | monitored: 1 | n_generated: 10 }

Or we can get a nice progress bar with the assistance of the progress package:

simmer() %>%
  add_generator("dummy", wait_and_go, function() 1) %>%
  run(until=1e5, progress=progress::progress_bar$new()$update)
#> [==============---------------------------------------------------------]  20%

But more importantly, this release implements a new way of retrieving attributes (thus deprecating the old approach, which will be still available throughout the 3.6.x series and will be removed in version 3.7). Since v3.1.x, arrival attributes were retrieved by providing a function with one argument. A very simple example:

trajectory() %>%
  set_attribute("delay", 3) %>%
  timeout(function(attr) attr["delay"])
## Warning: Attribute retrieval through function arguments is deprecated.
## Use 'get_attribute' instead.
## trajectory: anonymous, 2 activities
## { Activity: SetAttribute | key: delay, value: 3, global: 0 }
## { Activity: Timeout      | delay: 0x5569098b9228 }

Later on, v3.5.1 added support for global attributes, making it necessary to add a second argument to retrieve this new set of attributes:

trajectory() %>%
  set_attribute("delay", 3, global=TRUE) %>%
  timeout(function(attr, glb) glb["delay"])
## Warning: Attribute retrieval through function arguments is deprecated.
## Use 'get_attribute' instead.
## trajectory: anonymous, 2 activities
## { Activity: SetAttribute | key: delay, value: 3, global: 1 }
## { Activity: Timeout      | delay: 0x556908730320 }

This method is a kind of rarity in simmer. It’s clunky, as it is not easy to document (and therefore to discover and learn), and non-scalable, because new features would require more and more additional arguments. Thus, it is now deprecated, and the get_attribute() function becomes the new method for retrieving attributes. It works in the same way as now() for the simulation time:

env <- simmer()

trajectory() %>%
  set_attribute("delay_1", 3) %>%
  # shortcut equivalent to set_attribute(..., global=TRUE)
  set_global("delay_2", 2) %>% 
  timeout(function() get_attribute(env, "delay_1")) %>%
  # shortcut equivalent to get_attribute(..., global=TRUE)
  timeout(function() get_global(env, "delay_2"))
## trajectory: anonymous, 4 activities
## { Activity: SetAttribute | key: delay_1, value: 3, global: 0 }
## { Activity: SetAttribute | key: delay_2, value: 2, global: 1 }
## { Activity: Timeout      | delay: 0x55690829f550 }
## { Activity: Timeout      | delay: 0x55690830c310 }

This is a little bit more verbose, but I believe it is more consistent and intuitive. Moreover, it allows us to easily implement new features for extracting arrival information. In fact, get_attribute() will come hand in hand with two more verbs: get_name() and get_prioritization(), to retrieve the arrival name and prioritization values respectively.

New features:

  • Show simulation progress via an optional progress callback in run() (#103).
  • New “The Bank Tutorial: Part II” vignette, by Duncan Garmonsway @nacnudus (#106).
  • New getters for running arrivals (#109), meant to be used inside trajectories:
    • get_name() retrieves the arrival name.
    • get_attribute() retrieves an attribute by name. The old method of retrieving them by providing a function with one argument is deprecated in favour of get_attribute(), and will be removed in version 3.7.x.
    • get_prioritization() retrieves the three prioritization values (prioritypreemptiblerestart) of the active arrival.
  • New shortcuts for global attributes (#110): set_global() and get_global(), equivalent to set_attribute(global=TRUE) and get_attribute(global=TRUE) respectively.

Minor changes and fixes:

  • Some code refactoring and performance improvements (2f4b484, ffafe1e, f16912a, fb7941b, 2783cd8).
  • Use Rcpp::DataFrame instead of Rcpp::List (#104).
  • Improve argument parsing and error messages (#107).
  • Improve internal function make_resetable() (c596f73).

Programming with dplyr by using dplyr

The title may seem tautological, but since the arrival of dplyr 0.7.x, there have been some efforts at using dplyr without actually using it that I can’t quite understand. The tidyverse has raised passions, for and against it, for some time already. There are excellent alternatives out there, and I myself use them when I find it suitable. But when I choose to use dplyr, I find it most versatile, and I see no advantage in adding yet another layer that complicates things and makes problems even harder to debug.

Take the example of seplyr. It stands for standard evaluation dplyr, and enables us to program over dplyr without having “to bring in (or study) any deep-theory or heavy-weight tools such as rlang/tidyeval”. Let’s consider the following interactive pipeline:

library(dplyr)

starwars %>%
  group_by(homeworld) %>%
  summarise(mean_height = mean(height, na.rm = TRUE),
            mean_mass = mean(mass, na.rm = TRUE),
            count = n())
## # A tibble: 49 x 4
##         homeworld mean_height mean_mass count
##             <chr>       <dbl>     <dbl> <int>
##  1       Alderaan    176.3333      64.0     3
##  2    Aleen Minor     79.0000      15.0     1
##  3         Bespin    175.0000      79.0     1
##  4     Bestine IV    180.0000     110.0     1
##  5 Cato Neimoidia    191.0000      90.0     1
##  6          Cerea    198.0000      82.0     1
##  7       Champala    196.0000       NaN     1
##  8      Chandrila    150.0000       NaN     1
##  9   Concord Dawn    183.0000      79.0     1
## 10       Corellia    175.0000      78.5     2
## # ... with 39 more rows

Let’s say we want to parametrise the grouping variable and wrap the code above into a re-usable function. Apparently, this is difficult with dplyr. But is it? Not at all: we just need to add one line and a bang-bang (!!):

starwars_mean <- function(var) {
  var <- enquo(var)
  starwars %>%
    group_by(!!var) %>%
    summarise(mean_height = mean(height, na.rm = TRUE),
            mean_mass = mean(mass, na.rm = TRUE),
            count = n())
}

starwars_mean(homeworld)
## # A tibble: 49 x 4
##         homeworld mean_height mean_mass count
##             <chr>       <dbl>     <dbl> <int>
##  1       Alderaan    176.3333      64.0     3
##  2    Aleen Minor     79.0000      15.0     1
##  3         Bespin    175.0000      79.0     1
##  4     Bestine IV    180.0000     110.0     1
##  5 Cato Neimoidia    191.0000      90.0     1
##  6          Cerea    198.0000      82.0     1
##  7       Champala    196.0000       NaN     1
##  8      Chandrila    150.0000       NaN     1
##  9   Concord Dawn    183.0000      79.0     1
## 10       Corellia    175.0000      78.5     2
## # ... with 39 more rows

The enquo() function quotes the name we put in our function (homeworld), and the bang-bang unquotes and uses that name instead of var. That’s it. What about seplyr? With seplyr, we just have to (and I quote)

  • Change dplyr verbs to their matching seplyr “*_se()» adapters.
  • Add quote marks around names and expressions.
  • Convert sequences of expressions (such as in the summarize()) to explicit vectors by adding the “c()” notation.
  • Replace “=” in expressions with “:=”.

This is the result:

library(seplyr)

starwars_mean <- function(my_var) {
  starwars %>%
    group_by_se(my_var) %>%
    summarize_se(c("mean_height" := "mean(height, na.rm = TRUE)",
                   "mean_mass" := "mean(mass, na.rm = TRUE)",
                   "count" := "n()"))
}

starwars_mean("homeworld")
## # A tibble: 49 x 4
##         homeworld mean_height mean_mass count
##             <chr>       <dbl>     <dbl> <int>
##  1       Alderaan    176.3333      64.0     3
##  2    Aleen Minor     79.0000      15.0     1
##  3         Bespin    175.0000      79.0     1
##  4     Bestine IV    180.0000     110.0     1
##  5 Cato Neimoidia    191.0000      90.0     1
##  6          Cerea    198.0000      82.0     1
##  7       Champala    196.0000       NaN     1
##  8      Chandrila    150.0000       NaN     1
##  9   Concord Dawn    183.0000      79.0     1
## 10       Corellia    175.0000      78.5     2
## # ... with 39 more rows

Basically, we had to change the entire pipeline. If re-usability was the goal, I think we lost some of it here. But, wait, we are still using non-standard evaluation in the first example. What if we really need to provide the grouping variable as a string? Easy enough, we just need to change enquo() with as.name() to convert the string to a name:

starwars_mean <- function(var) {
  var <- as.name(var)
  starwars %>%
    group_by(!!var) %>%
    summarise(mean_height = mean(height, na.rm = TRUE),
            mean_mass = mean(mass, na.rm = TRUE),
            count = n())
}

starwars_mean("homeworld")
## # A tibble: 49 x 4
##         homeworld mean_height mean_mass count
##             <chr>       <dbl>     <dbl> <int>
##  1       Alderaan    176.3333      64.0     3
##  2    Aleen Minor     79.0000      15.0     1
##  3         Bespin    175.0000      79.0     1
##  4     Bestine IV    180.0000     110.0     1
##  5 Cato Neimoidia    191.0000      90.0     1
##  6          Cerea    198.0000      82.0     1
##  7       Champala    196.0000       NaN     1
##  8      Chandrila    150.0000       NaN     1
##  9   Concord Dawn    183.0000      79.0     1
## 10       Corellia    175.0000      78.5     2
## # ... with 39 more rows

But we can do even better if we remember that dplyr provides scoped variants (see ?dplyr::scoped) for most of the verbs. In this case, group_by_at() comes in handy:

starwars_mean <- function(var) {
  starwars %>%
    group_by_at(var) %>%
    summarise(mean_height = mean(height, na.rm = TRUE),
            mean_mass = mean(mass, na.rm = TRUE),
            count = n())
}

starwars_mean("homeworld")
## # A tibble: 49 x 4
##         homeworld mean_height mean_mass count
##             <chr>       <dbl>     <dbl> <int>
##  1       Alderaan    176.3333      64.0     3
##  2    Aleen Minor     79.0000      15.0     1
##  3         Bespin    175.0000      79.0     1
##  4     Bestine IV    180.0000     110.0     1
##  5 Cato Neimoidia    191.0000      90.0     1
##  6          Cerea    198.0000      82.0     1
##  7       Champala    196.0000       NaN     1
##  8      Chandrila    150.0000       NaN     1
##  9   Concord Dawn    183.0000      79.0     1
## 10       Corellia    175.0000      78.5     2
## # ... with 39 more rows

That’s it: no bang-bang, just strings and only one change to the original code. Let’s dwell on the potential of the scoped variants with a final example. We can make a completely generic re-usable “grouped mean” function using seplyr and R’s paste0() function to build up expressions:

grouped_mean <- function(data, grouping_variables, value_variables) {
  result_names <- paste0("mean_", value_variables)
  expressions <- paste0("mean(", value_variables, ", na.rm = TRUE)")
  data %>%
    group_by_se(grouping_variables) %>%
    summarize_se(c(result_names := expressions,
                   "count" := "n()"))
}

starwars %>% 
  grouped_mean("eye_color", c("mass", "birth_year"))
## # A tibble: 15 x 4
##        eye_color mean_mass mean_birth_year count
##            <chr>     <dbl>           <dbl> <int>
##  1         black  76.28571        33.00000    10
##  2          blue  86.51667        67.06923    19
##  3     blue-gray  77.00000        57.00000     1
##  4         brown  66.09231       108.96429    21
##  5          dark       NaN             NaN     1
##  6          gold       NaN             NaN     1
##  7 green, yellow 159.00000             NaN     1
##  8         hazel  66.00000        34.50000     3
##  9        orange 282.33333       231.00000     8
## 10          pink       NaN             NaN     1
## 11           red  81.40000        33.66667     5
## 12     red, blue       NaN             NaN     1
## 13       unknown  31.50000             NaN     3
## 14         white  48.00000             NaN     1
## 15        yellow  81.11111        76.38000    11

And the same with dplyr’s scoped verbs (note that I’ve added the last rename_at() on a whim, just to get exactly the same output as before, but it is not really necessary):

grouped_mean <- function(data, grouping_variables, value_variables) {
  data %>%
    group_by_at(grouping_variables) %>%
    mutate(count = n()) %>%
    summarise_at(c(value_variables, "count"), mean, na.rm = TRUE) %>%
    rename_at(value_variables, funs(paste0("mean_", .)))
}

starwars %>% 
  grouped_mean("eye_color", c("mass", "birth_year"))
## # A tibble: 15 x 4
##        eye_color mean_mass mean_birth_year count
##            <chr>     <dbl>           <dbl> <dbl>
##  1         black  76.28571        33.00000    10
##  2          blue  86.51667        67.06923    19
##  3     blue-gray  77.00000        57.00000     1
##  4         brown  66.09231       108.96429    21
##  5          dark       NaN             NaN     1
##  6          gold       NaN             NaN     1
##  7 green, yellow 159.00000             NaN     1
##  8         hazel  66.00000        34.50000     3
##  9        orange 282.33333       231.00000     8
## 10          pink       NaN             NaN     1
## 11           red  81.40000        33.66667     5
## 12     red, blue       NaN             NaN     1
## 13       unknown  31.50000             NaN     3
## 14         white  48.00000             NaN     1
## 15        yellow  81.11111        76.38000    11

Wrapping up, the tidyeval paradigm may seem difficult at a first glance, but don’t miss the wood for the trees: the new version of dplyr is full of tools that will make your life easier, not harder.

constants 0.0.1

The new constants package is available on CRAN. This small package provides the CODATA 2014 internationally recommended values of the fundamental physical constants (universal, electromagnetic, physicochemical, atomic…), provided as symbols for direct use within the R language. Optionally, the values with errors and/or the values with units are also provided if the errors and/or the units packages are installed as well.

But, what is CODATA? The Committee on Data for Science and Technology (CODATA) is an interdisciplinary committee of the International Council for Science. The Task Group on Fundamental Constants periodically provides the internationally accepted set of values of the fundamental physical constants. The version currently in force is the “2014 CODATA”, published on 25 June 2015.

This package wraps the codata dataset, defines unique symbols for each one of the 237 constants, and provides them enclosed in three sets of symbols: symssyms_with_errors and syms_with_units.

library(constants)

# the speed of light
with(syms, c0)
## [1] 299792458
# explore which constants are available
lookup("planck constant", ignore.case=TRUE)
##                  quantity  symbol            value      unit
## 7         Planck constant       h  6.626070040e-34       J s
## 8         Planck constant    h_eV  4.135667662e-15      eV s
## 9         Planck constant    hbar         h/(2*pi)       J s
## 10        Planck constant hbar_eV      h_eV/(2*pi)      eV s
## 11        Planck constant hbar.c0      197.3269788    MeV fm
## 212 molar Planck constant    Na.h 3.9903127110e-10 J s mol-1
## 213 molar Planck constant Na.h.c0   0.119626565582 J m mol-1
##     rel_uncertainty            type
## 7           1.2e-08       universal
## 8           6.1e-09       universal
## 9           1.2e-08       universal
## 10          6.1e-09       universal
## 11          6.1e-09       universal
## 212         4.5e-10 physicochemical
## 213         4.5e-10 physicochemical
# symbols can also be attached to the search path
attach(syms)
# the Planck constant
hbar
## [1] 1.054572e-34

If the errors/units package is installed in your system, constants with errors/units are available:

attach(syms_with_errors)
# the Planck constant with error
hbar
## 1.05457180(1)e-34
attach(syms_with_units)
# the Planck constant with units
hbar
## 1.054572e-34 J*s

The dataset is available for lazy loading:

data(codata)
head(codata)
##                             quantity    symbol        value        unit
## 1           speed of light in vacuum        c0    299792458       m s-1
## 2                  magnetic constant       mu0    4*pi*1e-7       N A-2
## 3                  electric constant  epsilon0 1/(mu0*c0^2)       F m-1
## 4 characteristic impedance of vacuum        Z0       mu0*c0           Ω
## 5  Newtonian constant of gravitation         G  6.67408e-11 m3 kg-1 s-2
## 6  Newtonian constant of gravitation G_hbar.c0  6.70861e-39    GeV-2 c4
##   rel_uncertainty      type
## 1         0.0e+00 universal
## 2         0.0e+00 universal
## 3         0.0e+00 universal
## 4         0.0e+00 universal
## 5         4.7e-05 universal
## 6         4.7e-05 universal
dplyr::count(codata, type, sort=TRUE)
## # A tibble: 15 x 2
##                          type     n
##                         <chr> <int>
##  1    atomic-nuclear-electron    31
##  2      atomic-nuclear-proton    26
##  3     atomic-nuclear-neutron    24
##  4            physicochemical    24
##  5      atomic-nuclear-helion    18
##  6        atomic-nuclear-muon    17
##  7            electromagnetic    17
##  8                  universal    16
##  9    atomic-nuclear-deuteron    15
## 10     atomic-nuclear-general    11
## 11         atomic-nuclear-tau    11
## 12      atomic-nuclear-triton    11
## 13                    adopted     7
## 14       atomic-nuclear-alpha     7
## 15 atomic-nuclear-electroweak     2