forked from J-PAL/PII-Scan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.R
308 lines (267 loc) · 7.37 KB
/
scan.R
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
# List of required packages
# optparse: command line options/arguments
# rio: load files as data frame
# tools: extract file extension
packages = c("dplyr",
"purrr",
"optparse",
"rio",
"tools")
# Suppress warnings
oldw <- getOption("warn")
options(warn = -1)
# Check for required packages
package.check <- lapply(
packages,
FUN = function(x) {
if ((!require(x, character.only = TRUE, quietly = TRUE,
warn.conflicts = FALSE))) {
stop("Package ", x, " not found and is required.", call. = FALSE)
}
}
)
# Un-suppress warnings
options(warn = oldw)
# Set command line options
option_list = list(
make_option(
c("-p", "--path"),
type = "character",
default = NULL,
help = "Path to search for PII",
metavar = "PATH"
),
make_option(
c("-q", "--quiet"),
type = "logical",
action="store_true",
default = FALSE,
help = "Silent operation; do not display possible PII to the screen"
),
make_option(
"--no-output",
dest = "nooutput",
type = "logical",
action="store_true",
default = FALSE,
help = "Do not output search results to csv file"
),
make_option(
c("-o", "--output-file"),
dest = "outputfile",
type = "character",
default = "PII_output.csv",
metavar = "FILE",
help = "Write csv of possible PII to FILE [default: %default]"
),
make_option(
c("-s", "--strict"),
type = "logical",
action="store_true",
default = FALSE,
help = "Use stric matching when comparing strings. For example, match 'lat' but not 'latin'"
),
make_option(
c("-nl", "--nolabels"),
type = "logical",
dest = "noscanlables",
action="store_true",
default = FALSE,
help = "Do not scan variable labels when checking for PII"
)
)
opt_parser = OptionParser(usage = "usage: %prog --path PATH [options]", option_list = option_list)
opt = parse_args(opt_parser)
# Make sure path is give as option
if (is.null(opt$path)) {
print_help(opt_parser)
stop("A search path must be specified.", call. = FALSE)
}
# Make sure path is for a directory
if (!dir.exists(opt$path)) {
stop("Path must secify a directory.", call. = FALSE)
}
# Set path
path = opt$path
# Set options
strict = opt$strict
quiet = opt$quiet
outputCSV = !opt$nooutput
outputfile = opt$outputfile
no_scan_lables = opt$noscanlables
# Set PII status
PII_Found <- FALSE
# Create prinf function
printf <- function(...)
cat(sprintf(...))
# Strings to look for in variable names
pii_strings_names <-
c("name", "fname", "lname", "first_name", "last_name")
pii_strings_dates <- c("birth", "birthday", "bday", "dob")
pii_strings_locations <-
c(
"district",
"city",
"country",
"subcountry",
"parish",
"loc",
"street",
"village",
"community",
"address",
"gps",
"degree",
"minute",
"second",
"lat",
"lon",
"coord",
"location",
"house",
"compound",
"panchayat",
"territory",
"municipality",
"precinct",
"block",
"zip"
)
pii_strings_other <-
c(
"school",
"social",
"network",
"census",
"gender",
"sex",
"fax",
"email",
"url",
"child",
"beneficiary",
"mother",
"wife",
"father",
"husband",
"phone",
"spouse",
"daughter",
"son"
)
# Create single list of all strings, removing duplicates
pii_strings <-
unique(c(
pii_strings_names,
pii_strings_dates,
pii_strings_locations,
pii_strings_other
))
# Get list of files (.dta or .sas7bdat) to scan for PII
files = list.files(path,
pattern = "\\.dta$|\\.sas7bdat$|\\.sav$|\\.csv$",
recursive = TRUE)
# Initialize output csv
if (outputCSV) {
# Create data frame to hold PII matches
csv_headers <-
data.frame(
"file" = character(0),
"var" = character(0),
"varlabel" = character(0),
"samp1" = character(0),
"samp2" = character(0),
"samp3" = character(0),
"samp4" = character(0),
"samp5" = character(0)
)
write.csv(csv_headers, file = outputfile, quote=FALSE, row.names = FALSE)
}
# Loop over files
for (file in files) {
# Initialize variable count
v <- 0
# Create full path to file
file <- file.path(path,file)
# Get absolute path to file for cleaner output
file <- normalizePath(file)
# Get file type
type <- file_ext(file)
# Read file using rio
data <- import(file)
# Move variable-level attributes to the data frame level
gather_attrs(data)
# Loop over variable names in file
for (varname in names(data)) {
varlabel <- attr(data[[varname]],"label")
FOUND <- FALSE
# Variable count for var.labels index
v <- v + 1
for (string in pii_strings) {
# Match on word boundary if strict
if (strict) {
string <- paste("\b",string,"\b")
}
# Compare string to var, ignoring case
if (grepl(string, varname, ignore.case = TRUE)) {
FOUND <- TRUE
} else if ((!is.null(varlabel)) & !(no_scan_lables)) {
# If no possible PII found in variable name, check label, ignoring case
if (grepl(string, varlabel, ignore.case = TRUE)) {
FOUND <- TRUE
}
}
}
if (FOUND) {
PII_Found <- TRUE
if (!quiet) printf("Possible PII found in %s:\n", file)
# Print warning and first five non-missing, unique values:
if (!quiet) {
if (is.null(varlabel)) {
message <- paste("\"",varname,"\"",sep="")
} else {
message <- paste("\"",varname,"\" with label \"",varlabel,"\"", sep="")
}
printf("\tPossible PII in variable %s:\n", message)
}
#Select the current variable column:
data_col <- data[varname]
#Update the column to be character values:
data_col[varname] <- as.character(data_col[[varname]])
#Select just the current variable:
var_only <- data_col[varname]
#Select unique values of the variable:
var_unique <- unique(var_only)
#Remove NA values from vector (will only paste NA values if there are fewer than 5 unique, non-missing values)
var_unique_nona <- na.omit(var_unique)
# Print first five values
for (i in 1:5) {
if ((!quiet) & (!is.null(var_unique_nona[i,1])) & (!is.na(var_unique_nona[i,1]))) {
printf("\t\tSamp %d value: %s\n", i, var_unique_nona[i,1])
}
} # for ( i in 1:5 )
# Print newline for readability
if (!quiet) printf("\n")
# Write to csv file
if (outputCSV) {
# Create data frame without row names
new_row <- data_frame(
file = paste(file),
var = paste(varname),
varlabel = paste( if (is.null(varlabel)) "" else varlabel),
samp1 = paste(var_unique_nona[1,1]),
samp2 = paste(var_unique_nona[2,1]),
samp3 = paste(var_unique_nona[3,1]),
samp4 = paste(var_unique_nona[4,1]),
samp5 = paste(var_unique_nona[5,1])
)
write.table(new_row, file=outputfile, quote=TRUE, append=TRUE, row.names=FALSE, col.names=FALSE, sep=",")
}
} # if ( var %in% pii_strings )
} # for ( var in names( data ))
} # for ( file in files )
if ( PII_Found ) {
quit(save = "no", status = 10, runLast = FALSE)
} else {
quit(save = "no", status = 0, runLast = FALSE)
}