blib/lib/LineByLine.pm untested

filter: Statementstmt 0.0% 0 / 240 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 410 CC 48 SCAR 54.5
CC
48
Cov
0%
report_tampering
462.0
check_authenticity
306.0
slice_line
30.0
CRAP 233.4
1 #----------------------------------------------------------------
2 # Copyright (c) 2002 Benjamin Crowell
3 # This module is available under the same terms as Perl itself.
4 #----------------------------------------------------------------
5 # POD documentation is at the end of the file.
6 #----------------------------------------------------------------
7  
8  
9 use strict;
10  
11 package Digest::LineByLine;
12  
13 use Digest::SHA1;
14  
15 $VERSION = '1.0'; # $Date: 2002/05/13 10:40:00 $
16  
17 sub new {
18 my $class = shift;
19 my %args = (
20 KEY=>"",
21 DELIMITER=>" #",
22 SALT=>sprintf("%06d",int(rand 1000000)),
23 HASH_FUNCTION=>"SHA1",
24 MIN_LINE_LENGTH=>80,
25 INPUT=>"",
26 @_
27 );
28 my $self = {};
29 bless($self,$class);
30 $self->{KEY} = $args{KEY};
31 $self->{DELIMITER} = $args{DELIMITER};
32 $self->{SALT} = $args{SALT};
33 $self->{HASH_FUNCTION} = $args{HASH_FUNCTION};
34 $self->{MIN_LINE_LENGTH} = $args{MIN_LINE_LENGTH};
35 $self->{INPUT} = $args{INPUT};
36  
37 if ($self->{INPUT} eq "") {
38 $self->{MODE} = "create";
39 }
40 else {
41 $self->{MODE} = "read";
42 }
43  
44 $self->get_named_hash_function();
45 if (!defined $self->{HASH_FUNCTION_REF}) {return undef};
46  
47 $self->initialize();
48  
49 return $self;
50 }
51  
52 # This is what we should do before reading or writing the file.
53 # If, e.g., you read the file twice, you should do this each time.
54 sub initialize {
55 my $self = shift;
56 $self->{RUNNING_HASH} = $self->do_hash("");
57 $self->{LINE_COUNT} = 0;
58 $self->{IS_OPEN} = 0;
59 }
60  
61 sub get_named_hash_function {
62 my $self = shift;
63 $self->{HASH_FUNCTION_REF} = undef;
64 if ($self->{HASH_FUNCTION} eq "SHA1") {
65 $self->{HASH_FUNCTION_REF} =
66 sub {
67 my $data = shift;
68 my $key = shift;
69 return Digest::SHA1::sha1_base64($key,Digest::SHA1::sha1($key,$data));
70 }
71 }
72 }
73  
74 sub head {
75 my $self = shift;
76 return $self->{DELIMITER}.",".identifier_string().",".$self->{SALT}.",".$self->{HASH_FUNCTION}."\n";
77 }
78  
79 sub line {
80 my $self = shift;
81 my $line = shift;
82 chomp $line;
83 ($self->{LINE_COUNT})++;
84 my $stuff = $self->{LINE_COUNT}." ".$line;
85 $self->{RUNNING_HASH} = $self->do_hash($self->{RUNNING_HASH}.$stuff);
86 my $hash = $self->do_hash($stuff);
87 my $mac = $hash.",".length($hash).",".$self->{LINE_COUNT};
88 my $padding = " ";
89 my $len = length($line)+length($self->{DELIMITER})+length($padding)+length($mac);
90 my $min = $self->{MIN_LINE_LENGTH};
91 if ($min>0 && $len<$min) {$padding = $padding . (" "x($min-$len))}
92 return $line.$self->{DELIMITER}.$padding.$mac."\n";
93 }
94  
95 sub tail {
96 my $self = shift;
97 return $self->{DELIMITER}." end,count =".$self->do_hash($self->{LINE_COUNT}).",end\n"
98 .$self->{DELIMITER}." end,running hash=".$self->{RUNNING_HASH}.",end\n";
99 }
100  
101 sub is_authentic {
102 my $self = shift;
103 return $self->authenticity() eq "";
104 }
105  
106 sub authenticity {
107 my $self = shift;
108 if (!defined $self->{AUTHENTICITY}) {
109 $self->{AUTHENTICITY} = $self->check_authenticity();
110 }
111 return $self->{AUTHENTICITY};
112 }
113  
114 # Returns a null string if authentic. If inauthentic, it returns a string,
115 # which is meant for internal use. This routine doesn't try to recover from errors at all ---
116 # it's just meant to be an efficient check on authenticity. In most cases, that's all we
117 # need, since it isn't every day that we detect tampering. Cf. report_on_tampering().
118 sub check_authenticity {
119 my $self = shift;
120 open(FILE,"<".$self->{INPUT}) or return undef;
121 my $head = <FILE>;
122 if ($head eq "") {return "empty file"}
123 chomp $head;
124 if (!($head =~ m/^(.*),([^,]*),([^,]*),([^,]*)/)) {return "bad header"};
125 ($self->{DELIMITER},$self->{SALT},$self->{HASH_FUNCTION}) = ($1,$3,$4);
126 $self->get_named_hash_function();
127 if (!defined $self->{HASH_FUNCTION_REF}) {return "bad hash function ".$self->{HASH_FUNCTION}};
128 $self->initialize();
129 my $part = 2; # what we expect next: 1=header, 2=body, 3=count, 4=running hash
130 while (<FILE>) {
131 my $line = $_;
132 my $recognized_line_type = 0;
133  
134 #------- count line ----------
135 if ($line =~ m/^(.*) end,count *=(.*),end$/) {
136 $recognized_line_type = 1;
137 if ($1 ne $self->{DELIMITER}) {return "bad delimiter on count line, $1"}
138 if ($2 ne $self->do_hash($self->{LINE_COUNT})) {
139 return "bad count, $2,".$self->do_hash($self->{LINE_COUNT})
140 }
141 if ($part!=2) {return "count line out of order"}
142 $part = 4; # expect running hash line next
143 }
144  
145 #------- running hash line ----------
146 if (!$recognized_line_type && $line =~m/^(.*) end,running hash *=(.*),end$/) {
147 $recognized_line_type = 1;
148 if ($1 ne $self->{DELIMITER}) {return "bad delimiter on running hash line"}
149 if ($2 ne $self->{RUNNING_HASH}) {return "bad running hash"}
150 if ($part!=4) {return "running hash line out of order"}
151 }
152  
153 #------- body line ----------
154 if (!$recognized_line_type){
155  
156 if ($part!=2) {return "body line out of order"}
157  
158 my ($err,$stuff) = $self->slice_line($line);
159 if ($err ne "") {return "syntax error at line ".$self->{LINE_COUNT}};
160  
161 ($self->{LINE_COUNT})++;
162 my ($start,$hash,$line_number) = @$stuff;
163 if ($line_number != $self->{LINE_COUNT}) {
164 return "line number mismatch, $line_number,".$self->{LINE_COUNT}
165 };
166  
167 my $what_to_hash = $self->{LINE_COUNT}." ".$start;
168 $self->{RUNNING_HASH} = $self->do_hash($self->{RUNNING_HASH}.$what_to_hash);
169 my $my_hash = $self->do_hash($what_to_hash);
170 if ($hash ne $my_hash) {return "bogus hash at line ".$self->{LINE_COUNT}}
171  
172 }
173 }
174 close(FILE);
175 return "";
176 }
177  
178 # Call this routine for more information if your file has been tampered with. This
179 # is not an efficient way to verify on a routine basis that your file has not been
180 # tampered with -- use is_authentic() for that.
181 sub report_tampering {
182 my $self = shift;
183 open(FILE,"<".$self->{INPUT}) or return undef;
184 my $head = <FILE>;
185 my $report = "file ".$self->{INPUT}."\n\n";
186 if ($head eq "") {return $report . "The file is empty.\n"}
187 chomp $head;
188 if (!($head =~ m/^(.*),([^,]*),([^,]*),([^,]*)/)) {
189 return $report . "The header has been deleted. You may be able to recover the six-digit salt by brute force.\n"
190 };
191 ($self->{DELIMITER},$self->{SALT},$self->{HASH_FUNCTION}) = ($1,$3,$4);
192 $self->get_named_hash_function();
193 if (!defined $self->{HASH_FUNCTION_REF}) {return $report . "The hash function ".$self->{HASH_FUNCTION}." is unknown.\n"};
194 $self->initialize();
195 $report = $report . "The header was read successfully:\n"
196 ." delimiter =".$self->{DELIMITER}."\n"
197 ." salt =".$self->{SALT}."\n"
198 ." hash fn =".$self->{HASH_FUNCTION}."\n\n";
199 my $part = 2; # what we expect next: 1=header, 2=body, 3=count, 4=running hash
200 while (<FILE>) {
201 my $line = $_;
202 my $recognized_line_type = 0;
203  
204 #------- count line ----------
205 if ($line =~ m/^(.*) end,count *=(.*),end$/) {
206 $recognized_line_type = 1;
207 if ($1 ne $self->{DELIMITER}) {
208 $report = $report . "Bad delimiter on count line, $1. It is not possible to check whether lines have been deleted\n"
209 ." from the end of the file.\n"
210 }
211 if ($2 ne $self->do_hash($self->{LINE_COUNT})) {
212 $report = $report . "The number of lines in the file is incorrect. Attempting to reconstruct the\n"
213 . "number by brute force. If no other discrepancies are found, this means that\n"
214 . "the file was tampered with by deleting some lines from the end.\n\n";
215 my $found = "";
216 my ($min,$max) = (0,10*$self->{LINE_COUNT});
217 if ($max<10000) {$max=10000}
218 for (my $n = $min; $n<=$max; $n++) {
219 if ($self->do_hash($n) eq $2) {
220 $found = $n;
221 last;
222 }
223 }
224 if ($found ne "") {
225 $report = $report . "The original file had $found lines in it. The modified file has ".$self->{LINE_COUNT}.".\n";
226 }
227 else {
228 $report = $report . "Brute-force reconstruction failed. The number of lines in the original file\n"
229 . "was not in the range from $min to $max.\n";
230 }
231 }
232 if ($part!=2) {$report = $report . "Count line out of order.\n"}
233 $part = 4; # expect running hash line next
234 }
235  
236 #------- running hash line ----------
237 if (!$recognized_line_type && $line =~m/^(.*) end,running hash *=(.*),end$/) {
238 $recognized_line_type = 1;
239 if ($1 ne $self->{DELIMITER}) {$report = $report . "Bad delimiter on running hash line.\n"}
240 if ($2 ne $self->{RUNNING_HASH}) {
241 $report = $report . "Bad running hash. This is expected to occur for any type of tampering. This\n"
242 . "should never be the only indication of tampering.\n";
243 }
244 if ($part!=4) {$report = $report . "Running hash line out of order.\n"}
245 }
246  
247 #------- body line ----------
248 if (!$recognized_line_type){
249  
250 if ($part!=2) {$report = $report . "Body line out of order at line ".$self->{LINE_COUNT}.":\n$line\n\n"}
251  
252 my ($err,$stuff) = $self->slice_line($line);
253 if ($err ne "") {$report = $report . "Syntax error at line ".$self->{LINE_COUNT}.":\n$line\n\n"};
254  
255 ($self->{LINE_COUNT})++;
256 my ($start,$hash,$line_number) = @$stuff;
257 if ($line_number != $self->{LINE_COUNT}) {
258 $report = $report . "Line number mismatch, original=$line_number, modified=".$self->{LINE_COUNT}.":\n$line\n";
259 if ($line_number>$self->{LINE_COUNT}) {
260 $report = $report .
261 "This may indicate that ".($line_number-$self->{LINE_COUNT})." lines were deleted, or that some lines were permuted.\n";
262 }
263 else {
264 $report = $report .
265 "This may indicate that ".($self->{LINE_COUNT}-$line_number)." lines were inserted, or that some lines were permuted.\n";
266 }
267 $report = $report . "Further mismatches will not be reported unless they indicate further tampering.\n\n";
268 $self->{LINE_COUNT} = $line_number;
269 };
270  
271 my $what_to_hash = $self->{LINE_COUNT}." ".$start;
272 $self->{RUNNING_HASH} = $self->do_hash($self->{RUNNING_HASH}.$what_to_hash);
273 my $my_hash = $self->do_hash($what_to_hash);
274 if ($hash ne $my_hash) {$report = $report . "Line ".$self->{LINE_COUNT}." has been tampered with:\n$line\n\n"}
275  
276 }
277 }
278 close(FILE);
279 return $report;
280 }
281  
282 sub do_hash {
283 my $self = shift;
284 my $data = shift;
285 my $the_function = $self->{HASH_FUNCTION_REF};
286 return &$the_function($self->{SALT}.$data,$self->{KEY});
287 }
288  
289 sub slice_line {
290 my $self = shift;
291 my $line = shift;
292 if (!($line =~ m/^(.*),(\d+),(\d+)\n?$/)) {return ("bad_syntax",[$line])}
293 my ($start,$hash_len,$line_number) = ($1,$2,$3);
294 if (length($start)<$hash_len) {return ("bad_hash_len",[$line])}
295 my $hash = substr($start,-$hash_len);
296 $start = substr($start,0,length($start)-length($hash));
297 $start =~ s/ *$//; # strip off trailing blanks
298 if (length($start)<length($self->{DELIMITER})) {return ("bad_delim_len",[$line])}
299 if (substr($start,-length($self->{DELIMITER})) ne $self->{DELIMITER}) {
300 return ("bad_delim",[$line])
301 }
302 $start = substr($start,0,length($start)-length($self->{DELIMITER}));
303 return ("",[$start,$hash,$line_number]);
304 }
305  
306 sub filter {
307 my $self = shift;
308 my %args = (
309 INFILE=>"-",
310 OUTFILE=>"-",
311 @_
312 );
313 local ($_);
314  
315 open(INFILE,"<".$args{INFILE}) or return $!;
316 open(OUTFILE,">".$args{OUTFILE}) or return $!;
317  
318 print OUTFILE $self->head();
319 while (my $line = <INFILE>) {
320 print OUTFILE $self->line($line);
321 }
322 print OUTFILE $self->tail();
323  
324 }
325  
326 sub strip {
327 my $self = shift;
328 my %args = (
329 INFILE=>"-",
330 OUTFILE=>"-",
331 @_
332 );
333 local ($_);
334  
335 open(INFILE,"<".$args{INFILE}) or return $!;
336 open(OUTFILE,">".$args{OUTFILE}) or return $!;
337  
338 <INFILE>; # Header line goes in the bit bucket.
339 while (my $line = <INFILE>) {
340 $line = $self->strip_line($line);
341 if ($line ne "") {print OUTFILE $line}
342 }
343  
344 close(INFILE);
345 close(OUTFILE);
346  
347 }
348  
349 # Returns a newline-terminated line, with the MAC removed. Returns null if the line isn't a body
350 # line.
351 sub strip_line {
352 my $self = shift;
353 my $line = shift;
354 my $d = $self->{DELIMITER};
355 my $id = identifier_string();
356 if ( $line =~ m/^(.*)end,count(.*),end$/
357 || $line =~ m/^(.*)end,running hash(.*),end$/
358 || $line =~ m/^$d,$id,\d+,[A-Za-z0-9]+/) {
359 return "";
360 }
361 else {
362 my ($err,$stuff) = $self->slice_line($line);
363 return $stuff->[0]."\n";
364 }
365 }
366  
367 sub identifier_string {
368 return "LineByLine.pm";
369 }
370  
371 #=============================================================================
372  
373 =head1 NAME
374  
375 Digest::SHA1::LineByLine - Line-by-line message authentication for a plain text file.
376  
377 =head1 SYNOPSIS
378  
379 # Signing:
380 my $mac = LineByLine->new(KEY=>"secret");
381 print $mac->head();
382 print $mac->line("This is the first line.");
383 print $mac->line("This is the second line.");
384 print $mac->tail();
385  
386 # Authentication:
387 my $mac = LineByLine->new(KEY=>"secret",INPUT=>"myfile");
388 if ($mac->is_authentic()) { # Besides checking authenticity, reads and uses the header line.
389 open(FILE,"<myfile");
390 while (<FILE>) {
391 next LINE unless my $line = $mac->strip_line($_); # gets rid of MAC part
392  
393 ...
394 }
395 ...
396 }
397 else {
398 print "The file has been tampered with.\n";
399 print $mac->report_tampering(); # describes the tampering in human-readable form
400 }
401  
402 # Strip authentication from a preexisting file:
403 $mac->strip(INFILE=>"foo",OUTFILE=>"bar");
404  
405 # Add authentication to a preexisting file, using the key in $mac:
406 $mac->filter(INFILE=>"foo",OUTFILE=>"bar");
407  
408  
409 =head1 DESCRIPTION
410  
411 =head2 What It's For
412  
413 This module allows you to add line-by-line authentication codes
414 to a plain-text file. The file can still be manipulated using all
415 the text-file tools you know and love, including a text editor.
416 However, if someone else tampers with the file, you can detect
417 the tampering.
418  
419 Why not just store a single MAC at the end of the
420 file? Well, LineByLine's authentication method is designed so that you
421 can detect the modification of certain lines, the deletion or
422 addition of lines, and permutations of lines. For example, I use
423 it with the data files for some software I wrote to help teachers
424 keep track of their students' grades --- if my gradebook file has been
425 tampered with, it's interesting to know not just that the tampering
426 occurred but also that the changes consisted of increases in all of
427 John Smith's exam grades. Note that I may also intentionally edit
428 the file myself with a text editor, and forget to redo the MAC. In this
429 situation, a single MAC for the whole file would force me to choose
430 between trashing the whole file and accepting it without knowing what
431 was going on.
432  
433 The issue addressed by this module is not secrecy or encryption: it's
434 authentication. For example, you probably don't care if anyone sees
435 what's in your cron scripts, but you do care if they have modified
436 them.
437  
438 =head2 The Algorithm
439  
440 The authentication scheme is as follows. If the original file
441 consists of lines [L1,...Ln], then the file with authentication
442 has [r,L1,A1,...Ln,An,F(n),Bn], where r is a random
443 salt,
444 Aj=F(j," ",Lj),
445 F(x)=H(r,x),
446 H(x)=SHA1(K,SHA1(K,x)) is a MAC function, K is the key,
447 and Bn is the final member of the sequence defined by
448 sequence B0=F(""), Bj=F(Bj-1,j," ",Lj).
449  
450 In the following example, a two-line text file has had line-by-line
451 authentication added to it, with password "secret":
452  
453 #,LineByLine.pm,207906,SHA1
454 Joe owes me $37.50 from Poker. # aM9YjvDz/MeurH73Fx/L7dJTXMc,27,1
455 He said he'd pay me by Wed. # FpkNiGB1viuHuG2hQ6GjVa5LhiY,27,2
456 # end,count =FD2Y/0me4img5h9u5XoQzyoDS2o,end
457 # end,running hash=t0lWGG+Lq3KS46j9Hv2IScE6xFo,end
458  
459 =head1 METHODS
460  
461  
462 =over 4
463  
464 =item new(KEY=>$key,...)
465  
466 Creates a new LineByLine object.
467 When inputting a file, tack on INPUT=>$filename.
468 The other options are documented below.
469  
470 =item initialize()
471  
472 This is what we should do before reading or writing the file.
473 If, e.g., you read the file twice, you should do this each time.
474  
475 =item head()
476  
477 Returns the header line for the file.
478  
479 =item line($line)
480  
481 Adds a MAC to the line, and returns the result.
482  
483 =item tail()
484  
485 Returns the lines that go at the end of the file.
486  
487 =item is_authentic()
488  
489 Tells whether the file is authentic. If necessary, reads the
490 whole file. When called repeatedly, does not read the file
491 again.
492  
493 =item report_tampering()
494  
495 Similar to is_authentic(), but returns a detailed report
496 on the tampering. Call this routine for more information if your file has been tampered with. This
497 is not an efficient way to verify on a routine basis that your file has not been
498 tampered with -- use is_authentic() for that.
499  
500 =item filter(INPUT=>$infile_name,OUTPUT=>$outfile_name)
501  
502 Adds authentication codes. The files default to stdin
503 and stdout.
504  
505 =item strip(INPUT=>$infile_name,OUTPUT=>$outfile_name)
506  
507 Removes authentication codes. The files default to stdin
508 and stdout.
509  
510 =back
511  
512 =head2 Options When Creating a New LineByLine Object
513  
514 KEY sets the authentication key.
515  
516 DELIMITER is some text to add between the text the MAC on
517 each line. This defaults to " #", which is handy, since # marks
518 comments in many scripting languages and Unix configuration files.
519  
520 SALT defaults to a value supplied randomly by the constructor, and you
521 shouldn't normally override that default. The randomness protects against
522 attacks in which the attacker collects pieces of known plaintext along
523 with their MACs.
524  
525 HASH_FUNCTION defaults to "SHA1", and there are not currently any other
526 legal values. I don't intend to add any other options for the hashing
527 function unless SHA1 is cracked someday.
528 Whatever the hash function is, I'm assuming it returns base64.
529  
530 MIN_LINE_LENGTH defaults to 80. For readability, short lines get
531 blank padding after the delimiter so that the MAC is shoved to the
532 right, out of the way.
533  
534  
535 =head1 SEE ALSO
536  
537 L<Digest::HMAC>, L<Digest::SHA1>
538  
539 =head1 COPYRIGHT
540  
541 This library is free software; you can redistribute it and/or modify it under
542 the same terms as Perl itself.
543  
544 (c) 2002 Ben Crowell
545  
546 =head1 AUTHOR
547  
548 Ben Crowell <b_crowell67@hotmail.com>
549  
550 =cut
551  
552  
553 1;