File: Spatial.pm

package info (click to toggle)
libdata-password-zxcvbn-perl 1.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,564 kB
  • sloc: perl: 100,730; makefile: 9
file content (280 lines) | stat: -rw-r--r-- 8,369 bytes parent folder | download
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
package Data::Password::zxcvbn::Match::Spatial;
use Moo;
with 'Data::Password::zxcvbn::Match';
use Data::Password::zxcvbn::Combinatorics qw(nCk);
use List::AllUtils qw(min);
our $VERSION = '1.1.3'; # VERSION
# ABSTRACT: match class for sequences of nearby keys


# this should be constrained to the keys of %graphs, but we can't do
# that because users can pass their own graphs to ->make
has graph_name => (is=>'ro',default=>'qwerty');
has graph_meta => (is=>'ro',default=>sub {+{}});
has shifted_count => (is=>'ro',default=>0);
has turns => (is=>'ro',default=>1);


sub estimate_guesses {
    my ($self,$min_guesses) = @_;

    my $starts = $self->graph_meta->{starting_positions};
    my $degree = $self->graph_meta->{average_degree};

    my $guesses = 0;
    my $length = length($self->token);
    my $turns = $self->turns;

    # estimate the number of possible patterns w/ length $length or
    # less with $turns turns or less.
    for my $i (2..$length) {
        my $possible_turns = min($turns, $i-1);
        for my $j (1..$possible_turns) {
            $guesses += nCk($i-1,$j-1) * $starts * $degree**$j;
        }
    }

    # add extra guesses for shifted keys. (% instead of 5, A instead
    # of a.)  math is similar to extra guesses of l33t substitutions
    # in dictionary matches.

    if (my $shifts = $self->shifted_count) {
        my $unshifts = $length - $shifts;
        if ($shifts == 0 || $unshifts == 0) {
            $guesses *= 2;
        }
        else {
            my $shifted_variations = 0;
            for my $i (1..min($shifts,$unshifts)) {
                $shifted_variations += nCk($length,$i);
            }
            $guesses *= $shifted_variations;
        }
    }

    return $guesses;
}


sub make {
    my ($class, $password, $opts) = @_;
    my $graphs = $opts->{graphs}
        || do {
            require Data::Password::zxcvbn::AdjacencyGraph;
            \%Data::Password::zxcvbn::AdjacencyGraph::graphs; ## no critic (ProhibitPackageVars)
        };

    my $length = length($password);
    my @matches = ();
    for my $name (keys %{$graphs}) {
        my $graph = $graphs->{$name}{keys};

        my $i=0;
        while ($i < $length-1) {
            my $j = $i+1;
            # this has to be different from the -1 used later, and
            # different from the direction indices (usually 0..3)
            my $last_direction = -2;
            my $turns = 0;
            my $shifted_count = (
                $name !~ m{keypad} &&
                    substr($password,$i,1) =~
                    m{[~!@#\$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?]}
                )
                ? 1 # first character is shifted
                : 0;

          GROW:
            while (1) {
                my $found = 0;
                # consider growing pattern by one character if j
                # hasn't gone over the edge.
                if ($j < $length) {
                    my $found_direction = -1; my $cur_direction = -1;
                    my $prev_character = substr($password,$j-1,1);
                    my $cur_character = substr($password,$j,1);
                  ADJACENCY:
                    for my $adj (@{ $graph->{$prev_character} || [] }) {
                        ## no critic (ProhibitDeepNests)
                        ++$cur_direction;
                        if (defined($adj) &&
                                (my $idx = index($adj,$cur_character)) >= 0) {
                            $found=1; $found_direction = $cur_direction;
                            # index 1 in the adjacency means the key
                            # is shifted, 0 means unshifted: A vs a, %
                            # vs 5, etc.  for example, 'q' is adjacent
                            # to the entry '2@'.  @ is shifted w/
                            # index 1, 2 is unshifted.
                            ++$shifted_count if $idx==1;
                            if ($last_direction != $cur_direction) {
                                # adding a turn is correct even in the
                                # initial case when last_direction is
                                # -2: every spatial pattern starts
                                # with a turn.
                                ++$turns;
                                $last_direction = $cur_direction;
                            }
                            # found a match, stop looking at this key
                            last ADJACENCY;
                        }
                    }
                }

                if ($found) {
                    # if the current pattern continued, extend j and
                    # try to grow again
                    ++$j;
                }
                else {
                    # otherwise push the pattern discovered so far, if
                    # any...
                    my %meta = %{ $graphs->{$name} };
                    delete $meta{keys};
                    push @matches, $class->new({
                        i => $i, j => $j-1,
                        token => substr($password,$i,$j-$i),
                        graph_name => $name,
                        graph_meta => \%meta,
                        turns => $turns,
                        shifted_count => $shifted_count,
                    }) unless $j-$i<=2; # don't consider short chains

                    # ...and then start a new search for the rest of
                    # the password.
                    $i = $j;
                    last GROW;
                }
            }
        }
    }

    @matches = sort @matches;
    return \@matches;
}


sub feedback_warning {
    my ($self) = @_;

    return $self->turns == 1
        ? 'Straight rows of keys are easy to guess'
        : 'Short keyboard patterns are easy to guess'
        ;
}

sub feedback_suggestions {
    return [ 'Use a longer keyboard pattern with more turns' ];
}


around fields_for_json => sub {
    my ($orig,$self) = @_;
    ( $self->$orig(), qw(graph_name shifted_count turns) )
};

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Data::Password::zxcvbn::Match::Spatial - match class for sequences of nearby keys

=head1 VERSION

version 1.1.3

=head1 DESCRIPTION

This class represents the guess that a certain substring of a password
can be obtained by moving a finger in a continuous line on a keyboard.

=head1 ATTRIBUTES

=head2 C<graph_name>

The name of the keyboard / adjacency graph used for this match

=head2 C<graph_meta>

Hashref, spatial information about the graph:

=over 4

=item *

C<starting_positions>

the number of keys in the keyboard, or starting nodes in the graph

=item *

C<average_degree>

the average number of neighbouring keys, or average out-degree of the graph

=back

=head2 C<shifted_count>

How many of the keys need to be "shifted" to produce the token

=head2 C<turns>

How many times the finger must have changed direction to produce the
token

=head1 METHODS

=head2 C<estimate_guesses>

The number of guesses grows super-linearly with the length of the
pattern, the number of L</turns>, and the amount of L<shifted
keys|/shifted_count>.

=head2 C<make>

  my @matches = @{ Data::Password::zxcvbn::Match::Spatial->make(
    $password,
    { # this is the default
      graphs => \%Data::Password::zxcvbn::AdjacencyGraph::graphs,
    },
  ) };

Scans the C<$password> for substrings that can be produced by typing
on the keyboards described by the C<graphs>.

The data structure needed for C<graphs> is a bit complicated; look at
the L<< C<build-keyboard-adjacency-graphs> script in the
distribution's
repository|https://bitbucket.org/broadbean/p5-data-password-zxcvbn/src/master/maint/build-keyboard-adjacency-graphs
>>.

=head2 C<feedback_warning>

=head2 C<feedback_suggestions>

This class suggests that short keyboard patterns are easy to guess,
and to use longer and less straight ones.

=head2 C<fields_for_json>

The JSON serialisation for matches of this class will contain C<token
i j guesses guesses_log10 graph_name shifted_count turns>.

=head1 AUTHOR

Gianni Ceccarelli <gianni.ceccarelli@broadbean.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2022 by BroadBean UK, a CareerBuilder Company.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut