blib/lib/Role/Kerberos.pm

filter: Statementstmt 85.7% 12 / 14 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 89.4% 17 / 19 CC 1 SCAR 0.6
CC
1
Cov
86%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Role::Kerberos;
2  
3 1 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 #use namespace::clean;
9  
10 0 ▶use Authen::Krb5 ();
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use Scalar::Util ();
12 use Carp ();
13 #use Try::Tiny ();
14  
15 # Authen::Krb5 contains a global, presumably non-threadsafe pointer to
16 # this execution context. This is the best way I can muster dealing
17 # with it.
18  
19 BEGIN {
20 Authen::Krb5::init_context();
21 }
22  
23 END {
24 Authen::Krb5::free_context();
25 }
26  
27 sub _is_really {
28 my ($x, $class) = @_;
29 defined $x and ref $x and Scalar::Util::blessed($x) and $x->isa($class);
30 }
31  
32 sub _k5err {
33 Carp::croak(@_, ': ', Authen::Krb5::error());
34 }
35  
36 =head1 NAME
37  
38 Role::Kerberos - A role for managing Kerberos 5 credentials
39  
40 =head1 VERSION
41  
42 Version 0.02
43  
44 =cut
45  
46 our $VERSION = '0.02';
47  
48 =head1 SYNOPSIS
49  
50 package My::Kerbject;
51  
52 use Moo;
53 with 'Role::Kerberos';
54  
55 has other_stuff => (
56 # ...
57 );
58  
59 # go nuts...
60  
61 # ...elsewhere:
62  
63 package Somewhere::Else;
64  
65 my $krb = My::Kerbject->new(
66 principal => 'robot@ELITE.REALM',
67 keytab => '/etc/robot/creds.keytab',
68 ccache => '/var/lib/robot/krb5cc',
69 other_stuff => 'derp',
70 );
71  
72 =head1 DESCRIPTION
73  
74 L<Authen::Krb5> is kind of unwieldy. L<Authen::Krb5::Simple> is too
75 simple (no keytabs). L<Authen::Krb5::Effortless> requires too much
76 effort (can't specify keytabs/ccaches outside of environment
77 variables) and L<Authen::Krb5::Easy> hasn't been touched in 13 years.
78  
79 The purpose of this module is to enable you to strap onto an existing
80 L<Moo>(L<se|Moose>) object the functionality necessary to acquire and
81 maintain a Kerberos TGT. My own impetus for writing this module
82 involves making connections authenticated via L<Authen::SASL> and
83 GSSAPI where the keys come from a keytab in a non-default location and
84 the consistency of C<%ENV> is not reliable (that is, in a Web app).
85  
86 =head1 METHODS
87  
88 =head2 new %PARAMS
89  
90 As with all roles, these parameters get integrated into your class's
91 constructor, and also serve as accessor methods. Every one is
92 read-only, and every one is optional except L</principal>.
93  
94 =over 4
95  
96 =item realm
97  
98 The default realm. Taken from the default principal, or otherwise the
99 system default realm if not defined.
100  
101 =cut
102  
103 around BUILDARGS => sub {
104 my $orig = shift;
105 my $class = shift;
106 my %p;
107 if (@_ and ref $_[0] eq 'HASH') {
108 %p = %{$_[0]};
109 }
110 else {
111 %p = @_;
112 }
113  
114 Carp::croak('Must supply at least a principal')
115 unless defined $p{principal} and $p{principal} ne '';
116  
117 if ($p{principal} =~ /@/) {
118 $p{principal} = _coerce_principal($p{principal});
119 $p{realm} ||= $p{principal}->realm;
120 }
121 else {
122 $p{realm} ||= Authen::Krb5::get_default_realm();
123 $p{principal} = sprintf '%s@%s', @p{qw(principal realm)};
124 }
125  
126 if (defined $p{keytab}) {
127 $p{keytab} = _coerce_kt($p{keytab});
128 }
129  
130 if (defined $p{ccache}) {
131 $p{ccache} = _coerce_cc($p{ccache});
132 }
133  
134 $orig->($class, %p);
135 };
136  
137 has realm => (
138 is => 'rw',
139 lazy => 1,
140 default => sub { Authen::Krb5::get_default_realm(); },
141 );
142  
143 =item principal
144  
145 The default principal. Can (should) also contain a realm. If a realm
146 is missing from the principal, it will be added from
147 L</realm>. Coerced from a string into a
148 L<Authen::Krb5/Authen::Krb5::Principal> object. B<Required>.
149  
150 =cut
151  
152 sub _coerce_principal {
153 my $n = shift;
154 return $n if _is_really($n, 'Authen::Krb5::Principal');
155  
156 my $r = shift || Authen::Krb5::get_default_realm();
157  
158 $n = sprintf '%s@%s', $n, $r unless $n =~ /@/;
159  
160 Authen::Krb5::parse_name($n)
161 or _k5err("Could not resolve principal $n");
162 }
163  
164 has principal => (
165 is => 'ro',
166 isa => sub { _is_really(shift, 'Authen::Krb5::Principal') },
167 required => 1,
168 trigger => sub { $_[0]->realm($_[0]->principal->realm) },
169 coerce => \&_coerce_principal,
170 );
171  
172 =item keytab
173  
174 A keytab, if other than C<$ENV{KRB5_KTNAME}>. Will default to that or
175 the system default (e.g. C</etc/krb5.keytab>). Coerced from a file
176 path into an L<Authen::Krb5/Authen::Krb5::Keytab> object.
177  
178 =cut
179  
180 sub _coerce_kt {
181 my $val = shift;
182 #warn 'YO DAWG COERCING KEYTAB';
183 return $val if _is_really($val, 'Authen::Krb5::Keytab');
184  
185 $val = "FILE:$val" unless $val =~ /^[^:]+:/;
186  
187 Authen::Krb5::kt_resolve($val) or _k5err("Could not load keytab $val");
188 }
189  
190 has keytab => (
191 is => 'ro',
192 isa => sub { _is_really(shift, 'Authen::Krb5::Keytab') },
193 lazy => 1,
194 coerce => \&_coerce_kt,
195 default => sub {
196 Authen::Krb5::kt_default() or _k5err("Could not load default keytab");
197 },
198 );
199  
200 =item password
201  
202 The password for the default principal. Don't use this. Use a keytab.
203  
204 =cut
205  
206 has password => (
207 is => 'ro',
208 );
209  
210 =item ccache
211  
212 The locator (e.g. file path) of a credential cache, if different from
213 C<$ENV{KRB5CCNAME}> or the system default. Coerced into an
214 L<Authen::Krb5/Authen::Krb5::Ccache> object.
215  
216 =cut
217  
218 sub _coerce_cc {
219 my $val = shift;
220 return $val if _is_really($val, 'Authen::Krb5::Ccache');
221  
222 $val = "FILE:$val" unless $val =~ /^FILE:/i;
223  
224 Authen::Krb5::cc_resolve($val)
225 or _k5err("Could not load credential cache $val");
226 }
227  
228 has ccache => (
229 is => 'ro',
230 isa => sub { _is_really(shift, 'Authen::Krb5::Ccache') },
231 lazy => 1,
232 coerce => \&_coerce_cc,
233 default => sub {
234 Authen::Krb5::cc_default()
235 or _k5err("Could not resolve default credentials cache");
236 },
237 );
238  
239 =back
240  
241 =head2 kinit %PARAMS
242  
243 Log in to Kerberos. Parameters are optional.
244  
245 =over 4
246  
247 =item principal
248  
249 The principal, if different from that in the constructor.
250  
251 =item realm
252  
253 The realm, if different from that in the constructor. Ignored if the
254 principal contains a realm.
255  
256 =item password
257  
258 The Kerberos password, if logging in with a password. (See
259 L<Term::ReadPassword> for a handy way of ingesting a password from the
260 command line.)
261  
262 =item keytab
263  
264 A keytab, if different from that in the constructor or
265 C<$ENV{KRB5_KTNAME}>. Will be coerced from a file name.
266  
267 =item service
268  
269 A service principal, if different from C<krbtgt/REALM@REALM>.
270  
271 =back
272  
273 =cut
274  
275 sub kinit {
276 my $self = shift;
277 my %p = @_;
278  
279 $p{realm} ||= $self->realm;
280 $p{principal} = $p{principal}
281 ? _coerce_principal(@p{qw(principal realm)}) : $self->principal;
282  
283 my $tgt;
284 if (defined $p{password} or defined $self->password) {
285 warn 'using a password you schlub';
286 my $password = defined $p{password} ? $p{password} : $self->password;
287 my @a = ($p{principal}, $password);
288 push @a, $p{service} if defined $p{service};
289  
290 $tgt = Authen::Krb5::get_init_creds_password(@a)
291 or _k5err('Failed to get TGT');
292 }
293 else {
294 $p{keytab} = $p{keytab} ? _coerce_kt($p{keytab}) : $self->keytab;
295 my @a = @p{qw(principal keytab)};
296 push @a, $p{service} if defined $p{service};
297  
298 $tgt = Authen::Krb5::get_init_creds_keytab(@a)
299 or _k5err('Failed to get TGT');
300 }
301  
302 my $cc = $self->ccache;
303 $cc->initialize($p{principal});
304 $cc->store_cred($tgt);
305 }
306  
307 =head2 klist %PARAMS
308  
309 =cut
310  
311 sub klist {
312 my $self = shift;
313  
314 my $cc = $self->ccache;
315 #my $p = $self->principal;
316 my @out;
317 if (my $cursor = $cc->start_seq_get) {
318 while (my $cred = $cc->next_cred($cursor)) {
319 push @out, {
320 principal => $cred->client,
321 service => $cred->server,
322 auth => $cred->authtime,
323 start => $cred->starttime,
324 end => $cred->endtime,
325 renew => $cred->renew_till,
326 ticket => $cred->ticket,
327 # this segfaults when Authen::Krb5::Keyblock->DESTROY
328 # is called with the key content memory out of bounds,
329 # keyblock => $cred->keyblock,
330 };
331 }
332 $cc->end_seq_get($cursor);
333 }
334  
335 return unless @out;
336 wantarray ? @out : \@out;
337 }
338  
339 =head2 kexpired
340  
341 Returns true if any tickets in the cache are expired.
342  
343 =cut
344  
345 sub kexpired {
346 my $self = shift;
347 my $now = time;
348  
349 my @tickets = $self->klist;
350 return 1 unless @tickets;
351  
352 return scalar grep { $_->{end} < $now } @tickets;
353 }
354  
355  
356 # wishful thinking: Authen::Krb5 does not at the moment expose either
357 # ticket flags or krb5_get_renewed_creds.
358  
359 # =head2 krenew
360  
361 # Checks the TGT and reauthenticates if expired. This is I<not>
362  
363 # =cut
364  
365 =head2 kdestroy
366  
367 Destroy the credentials cache (if there is something to destroy).
368  
369 =cut
370  
371 sub kdestroy {
372 my $self = shift;
373 $self->ccache->destroy if $self->klist;
374 }
375  
376 # XXX do we actually want this to happen?
377 # sub DEMOLISH {
378 # $_[0]->kdestroy;
379 # }
380  
381 # XXX more sensible?
382 sub DEMOLISH {
383 my $self = shift;
384 for my $entry ($self->klist) {
385 delete $entry->{keyblock};
386 }
387 }
388  
389 =head1 AUTHOR
390  
391 Dorian Taylor, C<< <dorian at cpan.org> >>
392  
393 =head1 SEE ALSO
394  
395 =over 4
396  
397 =item L<Authen::Krb5>
398  
399 =item L<Moo::Role>
400  
401 =back
402  
403  
404 =head1 BUGS
405  
406 Please report any bugs or feature requests to C<bug-role-kerberos at
407 rt.cpan.org>, or through the web interface at
408 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Role-Kerberos>. I
409 will be notified, and then you'll automatically be notified of
410 progress on your bug as I make changes.
411  
412 =head1 LICENSE AND COPYRIGHT
413  
414 Copyright 2015 Dorian Taylor.
415  
416 Licensed under the Apache License, Version 2.0 (the "License"); you
417 may not use this file except in compliance with the License. You may
418 obtain a copy of the License at
419 L<http://www.apache.org/licenses/LICENSE-2.0>.
420  
421 Unless required by applicable law or agreed to in writing, software
422 distributed under the License is distributed on an "AS IS" BASIS,
423 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
424 implied. See the License for the specific language governing
425 permissions and limitations under the License.
426  
427 =cut
428  
429 1; # End of Role::Kerberos
↑ Summary