This R Notebook is the complement to my blog post Network Visualization of Breached Internet Services Using HaveIBeenPwned Data.
This notebook is licensed under the MIT License. If you use the code or data visualization designs contained within this notebook, it would be greatly appreciated if proper attribution is given back to this notebook and/or myself. Thanks! :)
Setup the R packages.
# must install ggnetwork using from source to avoid ggplot2 2.2.0 issue
# install.packages("ggnetwork", type="source")
library(dplyr)
Attaching package: ‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
library(readr)
library(igraph)
Attaching package: ‘igraph’
The following objects are masked from ‘package:dplyr’:
%>%, as_data_frame, groups, union
The following objects are masked from ‘package:stats’:
decompose, spectrum
The following object is masked from ‘package:base’:
union
library(intergraph)
library(sna)
Loading required package: statnet.common
Loading required package: network
network: Classes for Relational Data
Version 1.13.0 created on 2015-08-31.
copyright (c) 2005, Carter T. Butts, University of California-Irvine
Mark S. Handcock, University of California -- Los Angeles
David R. Hunter, Penn State University
Martina Morris, University of Washington
Skye Bender-deMoll, University of Washington
For citation information, type citation("network").
Type help("network-package") to get started.
Attaching package: ‘network’
The following objects are masked from ‘package:igraph’:
%c%, %s%, add.edges, add.vertices, delete.edges, delete.vertices,
get.edge.attribute, get.edges, get.vertex.attribute,
is.bipartite, is.directed, list.edge.attributes,
list.vertex.attributes, set.edge.attribute, set.vertex.attribute
sna: Tools for Social Network Analysis
Version 2.4 created on 2016-07-23.
copyright (c) 2005, Carter T. Butts, University of California-Irvine
For citation information, type citation("sna").
Type help(package="sna") to get started.
Attaching package: ‘sna’
The following objects are masked from ‘package:igraph’:
betweenness, bonpow, closeness, components, degree, dyad.census,
evcent, hierarchy, is.connected, neighborhood, triad.census
library(ggplot2)
library(ggnetwork)
library(plotly)
Attaching package: ‘plotly’
The following object is masked from ‘package:ggplot2’:
last_plot
The following objects are masked from ‘package:igraph’:
%>%, groups
The following object is masked from ‘package:stats’:
filter
The following object is masked from ‘package:graphics’:
layout
library(htmlwidgets)
library(RJSONIO)
sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: macOS Sierra 10.12.2
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] RJSONIO_1.3-0 htmlwidgets_0.8 plotly_4.5.6
[4] ggnetwork_0.5.1 ggplot2_2.2.0 sna_2.4
[7] network_1.13.0 statnet.common_3.3.0 intergraph_2.0-2
[10] igraph_1.0.1 readr_1.0.0 dplyr_0.5.0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.8 knitr_1.15.1 magrittr_1.5 sparklyr_0.5.1
[5] munsell_0.4.3 viridisLite_0.1.3 colorspace_1.3-2 R6_2.2.0
[9] plyr_1.8.4 stringr_1.1.0 httr_1.2.1 tools_3.3.2
[13] grid_3.3.2 gtable_0.2.0 DBI_0.5-1 htmltools_0.3.5
[17] lazyeval_0.2.0 yaml_2.1.14 assertthat_0.1 rprojroot_1.1
[21] digest_0.6.10 tibble_1.2 tidyr_0.6.0 purrr_0.2.2
[25] base64enc_0.1-3 ggrepel_0.6.5 evaluate_0.10 rmarkdown_1.3
[29] stringi_1.1.2 scales_0.4.1 backports_1.0.4 jsonlite_1.1
df <- read_csv('hibp_edges.csv')
Parsed with column specification:
cols(
Source = col_character(),
Target = col_character(),
Weight = col_integer()
)
df %>% arrange(desc(Weight)) %>% head() %>% print()
There are 10816 edges.
df_totals <- read_csv('hibp_services.csv')
Parsed with column specification:
cols(
Service = col_character(),
Total = col_integer()
)
df_totals %>% arrange(desc(Total)) %>% head() %>% print()
There are 1,768,628,867 total records in the dataset. (expected value should ber # of records - # of records from sensitive breaches: about 1,989,141,353 - 221M = 1,768,141,353))
Combine the two dataframes together; this lets us filter the dataframes using vector operations.
df_merged <- df %>% left_join(df_totals, by = c("Source" = "Service")) %>% left_join(df_totals, by = c("Target" = "Service"))
df_merged %>% arrange(desc(Weight)) %>% tail() %>% print()
Keep only edges with 1% of the proportion in both of the services it connects.
df_merged <- df_merged %>% filter(Weight >= Total.x * 0.01,
Weight >= Total.y * 0.01) %>%
select(Source, Target, Weight)
df_merged %>% arrange(desc(Weight)) %>% tail() %>% print()
Get breach data from HaveIBeenPwned for better tooltips.
# http://stackoverflow.com/questions/16947643/getting-imported-json-data-into-a-data-frame-in-r
df_hibp <- fromJSON(content = "https://haveibeenpwned.com/api/v2/breaches")
df_hibp <- do.call("rbind", lapply(df_hibp, as.data.frame))
df_hibp <- df_hibp %>% select(Title, Name, Domain, BreachDate, PwnCount) %>% unique()
df_hibp %>% head() %>% print()
df_hibp <- df_hibp %>% mutate(text = paste(Title, paste(format(PwnCount, big.mark=",", trim=T), "Pwns"), format(as.Date(BreachDate), "%b %d, %Y"), sep="<br>"))
df_hibp %>% select(text) %>% head() %>% print()
Build the graph network.
net <- graph.data.frame(df_merged, directed = FALSE)
V(net)$degree <- centralization.degree(net)$res
V(net)$weighted_degree <- graph.strength(net, weights=V(net)$Weight)
V(net)$text <- df_hibp$text[match(V(net)$name, df_hibp$Name)]
net
IGRAPH UN-- 98 316 --
+ attr: name (v/c), degree (v/n), weighted_degree (v/n), text (v/c),
| Weight (e/n)
+ edges (vertex names):
[1] WarInc --WildStar Dropbox --iMesh
[3] MajorGeeks --Malwarebytes AndroidForums --Plex
[5] GamerzPlanet --NextGenUpdate VBulletin --WHMCS
[7] Aipai --NetEase Nival --WildStar
[9] Avast --BlackHatWorld MoDaCo --Xbox-Scene
[11] CivilOnline --Tianya Nihonomaru --iPmart
[13] Nihonomaru --WIIUISO Nival --XSplit
+ ... omitted several edges
V(net)$group <- membership(cluster_walktrap(net, weights=E(net)$Weight))
V(net)$centrality <- eigen_centrality(net, weights=E(net)$Weight)$vector
Build the ggnetwork.
# ggnetwork sets default nodes randomly; set seed for reproducibility
set.seed(123)
df_net <- ggnetwork(net, layout = "fruchtermanreingold", weights="Weight", niter=50000)
df_net %>% head() %>% print()
plot <- ggplot(df_net, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_edges(aes(alpha = Weight), size=0.25) +
geom_nodes(aes(fill = as.factor(group), size = degree), shape = 21, color = "#1a1a1a", stroke=0.2) +
ggtitle("Network Graph of Breaches from HaveIBeenPwned Database (by @minimaxir)") +
geom_nodelabel_repel(aes(color = as.factor(group), label = vertex.names),
family = "Open Sans Condensed Bold", size=1.5, box.padding = unit(0.05, "lines"),
label.padding= unit(0.1, "lines"), segment.size=0.1, label.size=0.2) +
scale_alpha_continuous(range=c(0.1,1)) +
theme_blank() +
guides(size=FALSE, color=FALSE, alpha=FALSE, fill=FALSE) +
theme(plot.title = element_text(family="Source Sans Pro", size=8, hjust=0.5),
legend.title = element_text(family="Source Sans Pro"),
legend.text = element_text(family="Source Sans Pro"))
Ignoring unknown parameters: segment.color
plot
ggsave("hibp.png", plot, "png", width=6, height=4.5, dpi=300)
Make a second graph for more fine-tuned parameters. (and removing geom_nodelabel_repel
)
In Plotly, alpha
must be a factor variable due to http://stackoverflow.com/a/37498249. This introduces other bugs, so it was converted to a static value.
plot <- ggplot(df_net, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_edges(size=0.2, alpha=0.2) +
geom_nodes(aes(fill = as.factor(group), size = degree, text = text), shape = 21, color = "#1a1a1a", stroke=0.1, text=text) +
ggtitle("Network Graph of Breaches from HaveIBeenPwned Database (by @minimaxir)") +
scale_alpha_discrete(range=c(0,0.5)) +
scale_size_continuous(range=c(2,6)) +
theme_blank() +
theme(plot.title = element_text(family="Source Sans Pro", size=10),
legend.title = element_text(family="Source Sans Pro"),
legend.text = element_text(family="Source Sans Pro"),
legend.position="none")
Ignoring unknown parameters: textIgnoring unknown aesthetics: text
plot %>% ggplotly(tooltip="text") %>% toWebGL()
plot %>% ggplotly(tooltip="text", height=400) %>% toWebGL() %>% saveWidget("hibp-interactive.html", selfcontained=F, libdir="plotly")
The MIT License (MIT)
Copyright (c) 2016 Max Woolf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.