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
|
//
// Author : Dennis Eriksen <d@ennis.no>
// File : main.rs
// Bin : makepass.rs
// Created : 2023-09-05
// Licence : BSD-3-Clause
//
// Copyright (c) 2018-2023 Dennis Eriksen <d@ennis.no>
//
// Imports
//
use clap::{Arg, ArgAction, Command, crate_authors, value_parser};
use rand::{seq::SliceRandom, Rng};
use std::env;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::process::exit;
use terminal_size::{terminal_size, Width};
//
// Constants
//
const MAX: u8 = 255;
const RANGE_MAX: u8 = 42;
const RANGE_MIN: u8 = 8;
const PASS_WORDS: u8 = 8;
// Character sets
const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGIT: &str = "0123456789";
const OTHER: &str = "!$%&#/()=?+-_,.;:<>[]{}|@*";
const EXTRA: &str = "-_";
// Defaults
const DEFAULT_LENGTH: u8 = 0;
const DEFAULT_NUMBER: u8 = 10;
const DEFAULT_WORDLIST: &str = "/usr/share/dict/words";
// Structure used to pass common data to the print-function
struct CommonPrintData<'a> {
length: u8,
alpha: &'a [char],
alnum: &'a [char],
printbool: bool,
printlen: u8,
col_width: u8,
col_num: u16,
}
//
// Main function. This is where the magic happens
//
fn main() {
// Construct arrays of the character sets
let lower = LOWER.chars().collect::<Vec<_>>();
let upper = UPPER.chars().collect::<Vec<_>>();
let digit = DIGIT.chars().collect::<Vec<_>>();
let other = OTHER.chars().collect::<Vec<_>>();
let extra = EXTRA.chars().collect::<Vec<_>>();
let alpha = [&lower[..], &upper[..]].concat();
let alnum = [&alpha[..], &digit[..]].concat();
let every = [&alnum[..], &other[..]].concat();
// These are the sets we actually use
let mut normal = [&alnum[..], &extra[..]].concat();
let mut special = every;
// Set the defaults
let mut length = DEFAULT_LENGTH;
let mut number = DEFAULT_NUMBER;
let mut wordlist = DEFAULT_WORDLIST.to_string();
//
// env
// Deal with env before cli-args, because cli-args take precedence.
//
let env = (
env::var("MAKEPASS_LENGTH").unwrap_or_default(),
env::var("MAKEPASS_NUMBER").unwrap_or_default(),
env::var("MAKEPASS_WORDLIST").unwrap_or_default(),
env::var("MAKEPASS_NORMAL").unwrap_or_default(),
env::var("MAKEPASS_SPECIAL").unwrap_or_default(),
);
// length
if !env.0.is_empty() {
length = env.0.parse().unwrap_or_else(|_| {
// length is a <u8>, which is 0-255, so no need for further error-checking
eprintln!(
"Error: MAKEPASS_LENGTH is not a valid number. Valid numbers are between 0 and 255"
);
exit(1);
});
}
// number
if !env.1.is_empty() {
// number is a <u8>, but takes a minimum value of 1
match env.1.parse::<u8>() {
Ok(n) if n >= 1 => number = n,
_ => {
eprintln!("Error: MAKEPASS_NUMBER is not a valid number. Valid numbers are between 1 and 255");
exit(1);
}
}
}
if !env.2.is_empty() { // wordlist
wordlist = env.2;
}
if !env.3.is_empty() { // Overwrite normal character array if MAKEPASS_NORMAL is present
normal = env.3.chars().collect::<Vec<_>>();
}
if !env.4.is_empty() { // Overwrite special character array if MAKEPASS_SPECIAL is present
special = env.4.chars().collect::<Vec<_>>();
}
//
// Args
//
let opts = cli().get_matches();
// Set to new value if exists, or just set to old value
length = *opts.get_one::<u8>("length_flag").unwrap_or(&length);
number = *opts.get_one::<u8>("number").unwrap_or(&number);
length = *opts.get_one::<u8>("length_arg").unwrap_or(&length);
let printbool = opts.get_flag("printlen");
//
// Other logic
//
let printlen: u8 = if printbool && length < 100 {
2
} else if printbool {
3
} else {
0
};
// Get the width of the terminal
let size = terminal_size();
let term_width: u16 = match size {
Some((Width(w), _)) => w,
None => 1,
};
// Calculate how wide each column has to be
let col_width: u8 = match length {
0 => RANGE_MAX + 2,
_ => length + 2,
};
// Number of columns to print
// If printbool is true, col_num is term_width / (col_width + printlen + 1)
// Else, col_num is term_width / col_width
// col_num is never 0. Use std::cmp::max to use the largest value of 1 and the above.
let col_num: u16 = std::cmp::max(
1,
match printbool {
true => term_width / (col_width + printlen + 1) as u16,
false => term_width / col_width as u16,
},
);
// Fill in common print data
let data = CommonPrintData {
length: length,
alpha: &alpha,
alnum: &alnum,
printbool: printbool,
printlen: printlen,
col_width: col_width,
col_num: col_num,
};
//
// Do the dirty!
//
// Normal passwords
print_columns("Normal passwords", number, &normal, &data);
println!("");
// Special passwords
print_columns(
"Passwords with special characters",
number / 3 * 2 + 1,
&special,
&data,
);
// Passphrases
if fs::metadata(&wordlist).is_ok() {
// Open the file
let file = fs::File::open(&wordlist).unwrap();
// Create a buffered reader to handle file contents
let reader = io::BufReader::new(file);
// Read words into a Vector
let words = reader.lines().map(|l| l.unwrap()).collect();
// Print
println!("");
println!("Passphrases:");
for _ in 0..number / 2 {
println!("{}", passphrase(&words));
}
}
}
//
// Print passwords in neat columns
//
fn print_columns(title: &str, num: u8, chars: &Vec<char>, data: &CommonPrintData) {
let mut strings: Vec<String> = Vec::new();
for _ in 0..num {
strings.push(randstring(data.length, chars, data.alpha, data.alnum));
}
println!("{}:", title);
let mut i: u16 = 0;
for s in &strings {
i += 1;
if data.printbool {
print!("{1:00$} ", data.printlen as usize, s.len());
}
print!("{1:<0$}", data.col_width as usize, s);
if i % data.col_num == 0 || (i == num as u16 && i % data.col_num > 0) {
println!();
}
}
}
//
// Generate random strings to use as passwords
//
fn randstring(len: u8, chars: &[char], alpha: &[char], alnum: &[char]) -> String {
let mut rng = rand::thread_rng();
let length = if len == 0 {
rng.gen_range(RANGE_MIN..=RANGE_MAX)
} else {
len
};
let mut s = String::with_capacity(length as usize);
for i in 0..length {
let c = if i == 0 {
alpha.choose(&mut rng)
} else if i == length - 1 {
alnum.choose(&mut rng)
} else {
chars.choose(&mut rng)
};
s.push(*c.unwrap());
}
s
}
//
// Generate passphrases
//
fn passphrase(wordlist: &Vec<String>) -> String {
let mut rng = rand::thread_rng();
let mut passphrase = Vec::new();
for _ in 0..PASS_WORDS {
let word = wordlist.choose(&mut rng).unwrap().clone();
passphrase.push(word);
}
passphrase.join("-")
}
//
// Handle command line arguments
//
fn cli() -> Command {
Command::new("makepass")
.about("makepass - create random passwords")
.author(crate_authors!())
.arg(
Arg::new("length_flag")
.short('l')
.value_name("LENGTH")
.help(format!("Length of passwords (0..={0}). 0 = random.", MAX))
.value_parser(value_parser!(u8).range(0..)),
)
.arg(
Arg::new("number")
.short('n')
.value_name("NUM")
.help(format!("Number of passwords (1..={0}). [default: 10]", MAX))
.value_parser(value_parser!(u8).range(1..))
.long_help("this is the long help. What is it?"),
)
.arg(
Arg::new("printlen")
.short('p')
.help("Print length")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("length_arg")
.value_name("LENGTH")
.help(format!(
"Length of passwords (0..={MAX}). 0 = random length."
))
.value_parser(value_parser!(u8).range(0..)),
)
.override_help("NAME
makepass - create several random passwords
SYNOPSIS
makepass [OPTIONS] [NUM]
If a NUM is provided, passwords will be NUM characters long.
By default `makepass` will output passwords from the three following classes:
- Normal passwords - random strings with letters (both lower and upper
case), numbers, and dashes and underscores.
- Passwords with special characters - random strings generated from lower
and upper case letters, numbers, and the following characters:
!#$%&/()=?+-_,.;:<>[]{}|@*
- Passphrases - if we find a dictionary, a series of eight random words
from the dictionary, separated by dashes. The number of words can not be
changed, but you do not have to use all of them. Use as mane as you want.
The first character will always be alphabetic, and the last will always be
alphanumeric.
DESCRIPTION
makepass has the following options:
-h
output this help-text
-l
length of passwords. See MAKEPASS_LENGTH below
-n
number of passwords. See MAKEPASS_NUMBER below
-p
print length of number
ENVIRONMENT
makepass examines the following environmental variables.
MAKEPASS_LENGTH
Specifies the length of passwords. Valid values are 0-255. If 0, a
random value between 8 and 42 will be used for each password. -l
overrides this environmental variable, and the argument NUM overrides
that again. So `MAKEPASS_LENGTH=10 makepass -l 12 14` will give
passwords that are 14 characters long, even though both -l and
MAKEPASS_LENGTH also specifies a length.
MAKEPASS_NUMBER
The number of passwords to generate. This formula is used to determine
how many passwords from each group should be generated:
- (n) normal passwords
- (n / 3 * 2 + 1) special passwords
- (n / 2) passphrases
Where n is 10 by default. Valid values for n are 1-255. Floating-poing
math is not used, so results may vary.
MAKEPASS_PRINTLEN
If 1, print length of all passwords. If 0, don't.
MAKEPASS_NORMAL
String of characters from which to generate \"normal\" passwords.
Defaults to:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_
MAKEPASS_SPECIAL
String of characters from which to generate passwords with special
characters. Defaults to the same characters as in MAKEPASS_NORMAL, plus
these:
!#$%&/()=?+-_,.;:<>[]{}|@*
MAKEPASS_WORDLIST
Specifies the dictionary we find words for passphrases in. If this is
unset or empty, we try \"/usr/share/dict/words\". If that file does not
exist, no passphrases will be provided.
AUTHOR
Dennis Eriksen <https://dnns.no>")
}
|