[BACK]Return to Keyring.pm CVS log [TXT][DIR] Up to [local] / palm / Palm-Keyring / lib / Palm

Annotation of palm/Palm-Keyring/lib/Palm/Keyring.pm, Revision 1.37

1.14      andrew      1: package Palm::Keyring;
1.37    ! andrew      2: # $RedRiver: Keyring.pm,v 1.36 2007/02/22 05:16:04 andrew Exp $
1.27      andrew      3: ########################################################################
                      4: # Keyring.pm *** Perl class for Keyring for Palm OS databases.
                      5: #
                      6: #   This started as Memo.pm, I just made it work for Keyring.
1.1       andrew      7: #
1.27      andrew      8: # 2006.01.26 #*#*# andrew fresh <andrew@cpan.org>
                      9: ########################################################################
                     10: # Copyright (C) 2006, 2007 by Andrew Fresh
1.1       andrew     11: #
1.27      andrew     12: # This program is free software; you can redistribute it and/or modify
                     13: # it under the same terms as Perl itself.
                     14: ########################################################################
1.1       andrew     15: use strict;
1.14      andrew     16: use warnings;
1.27      andrew     17:
1.14      andrew     18: use Carp;
                     19:
                     20: use base qw/ Palm::StdAppInfo /;
1.1       andrew     21:
1.24      andrew     22: my $ENCRYPT    = 1;
                     23: my $DECRYPT    = 0;
                     24: my $MD5_CBLOCK = 64;
                     25: my $kSalt_Size = 4;
                     26: my $EMPTY      = q{};
                     27: my $SPACE      = q{ };
                     28: my $NULL       = chr 0;
1.14      andrew     29:
1.28      andrew     30: my @CRYPTS = (
1.34      andrew     31:     {
                     32:         alias     => 'None',
1.28      andrew     33:         name      => 'None',
                     34:         keylen    => 8,
                     35:         blocksize => 1,
1.29      andrew     36:         default_iter => 500,
1.28      andrew     37:     },
1.34      andrew     38:     {
                     39:         alias     => 'DES-EDE3',
1.28      andrew     40:         name      => 'DES_EDE3',
                     41:         keylen    => 24,
                     42:         blocksize =>  8,
                     43:         DES_odd_parity => 1,
1.29      andrew     44:         default_iter => 1000,
1.28      andrew     45:     },
1.34      andrew     46:     {
                     47:         alias     => 'AES128',
1.28      andrew     48:         name      => 'Rijndael',
                     49:         keylen    => 16,
                     50:         blocksize => 16,
1.29      andrew     51:         default_iter => 100,
1.28      andrew     52:     },
1.34      andrew     53:     {
                     54:         alias     => 'AES256',
1.28      andrew     55:         name      => 'Rijndael',
                     56:         keylen    => 32,
                     57:         blocksize => 16,
1.29      andrew     58:         default_iter => 250,
1.28      andrew     59:     },
                     60: );
                     61:
1.1       andrew     62:
1.28      andrew     63: our $VERSION = 0.95;
                     64:
                     65: sub new
                     66: {
1.14      andrew     67:     my $classname = shift;
1.28      andrew     68:     my $options = {};
                     69:
                     70:     # hashref arguments
                     71:     if (ref $_[0] eq 'HASH') {
                     72:       $options = shift;
                     73:     }
                     74:
                     75:     # CGI style arguments
1.29      andrew     76:     elsif ($_[0] =~ /^-[a-zA-Z0-9_]{1,20}$/) {
1.28      andrew     77:       my %tmp = @_;
                     78:       while ( my($key,$value) = each %tmp) {
                     79:         $key =~ s/^-//;
                     80:         $options->{lc $key} = $value;
                     81:       }
                     82:     }
                     83:
                     84:     else {
                     85:         $options->{password} = shift;
                     86:         $options->{version}  = shift;
                     87:     }
1.1       andrew     88:
1.14      andrew     89:     # Create a generic PDB. No need to rebless it, though.
1.28      andrew     90:     my $self = $classname->SUPER::new();
1.1       andrew     91:
1.28      andrew     92:     $self->{name}    = 'Keys-Gtkr';    # Default
                     93:     $self->{creator} = 'Gtkr';
                     94:     $self->{type}    = 'Gkyr';
1.14      andrew     95:
                     96:     # The PDB is not a resource database by
                     97:     # default, but it's worth emphasizing,
                     98:     # since MemoDB is explicitly not a PRC.
1.28      andrew     99:     $self->{attributes}{resource} = 0;
1.1       andrew    100:
1.28      andrew    101:     # Set the version
                    102:     $self->{version} = $options->{version} || 4;
1.1       andrew    103:
1.28      andrew    104:     # Set options
                    105:     $self->{options} = $options;
1.1       andrew    106:
1.29      andrew    107:     # Set defaults
                    108:     if ($self->{version} == 5) {
                    109:         $self->{options}->{cipher} ||= 0; # 'None'
                    110:         $self->{options}->{iterations} ||=
                    111:             $CRYPTS[ $self->{options}->{cipher} ]{default_iter};
                    112:
                    113:        $self->{appinfo}->{cipher} ||= $self->{options}->{cipher};
                    114:        $self->{appinfo}->{iter}   ||= $self->{options}->{iterations};
                    115:     };
                    116:
1.28      andrew    117:     if ( defined $options->{password} ) {
                    118:         $self->Password($options->{password});
1.14      andrew    119:     }
1.1       andrew    120:
1.14      andrew    121:     return $self;
                    122: }
1.1       andrew    123:
1.28      andrew    124: sub import
                    125: {
1.14      andrew    126:     Palm::PDB::RegisterPDBHandlers( __PACKAGE__, [ 'Gtkr', 'Gkyr' ], );
                    127:     return 1;
                    128: }
1.1       andrew    129:
1.34      andrew    130: # Accessors
                    131:
                    132: sub crypts
                    133: {
                    134:     my $crypt = shift;
                    135:     if ($crypt =~ /\D/) {
                    136:         foreach my $c (@CRYPTS) {
                    137:             if ($c->{alias} eq $crypt) {
                    138:                 return $c;
                    139:             }
                    140:         }
                    141:         # didn't find it.
                    142:         return;
                    143:     } else {
                    144:         return $CRYPTS[$crypt];
                    145:     }
                    146: }
                    147:
1.29      andrew    148: # ParseRecord
1.28      andrew    149:
                    150: sub ParseRecord
                    151: {
1.14      andrew    152:     my $self     = shift;
                    153:
1.16      andrew    154:     my $rec = $self->SUPER::ParseRecord(@_);
1.28      andrew    155:     return $rec if ! exists $rec->{data};
                    156:
                    157:     if ($self->{version} == 4) {
                    158:         # skip the first record because it contains the password.
                    159:         return $rec if ! exists $self->{records};
                    160:
                    161:         my ( $name, $encrypted ) = split /$NULL/xm, $rec->{data}, 2;
                    162:
                    163:         return $rec if ! $encrypted;
                    164:         $rec->{name}      = $name;
                    165:         $rec->{encrypted} = $encrypted;
                    166:         delete $rec->{data};
                    167:
                    168:     } elsif ($self->{version} == 5) {
1.29      andrew    169:         my $blocksize = $CRYPTS[ $self->{appinfo}->{cipher} ]{blocksize};
1.28      andrew    170:         my ($field, $extra) = _parse_field($rec->{data});
1.37    ! andrew    171:         delete $rec->{data};
1.16      andrew    172:
1.31      andrew    173:         $rec->{name}      = $field->{data};
1.37    ! andrew    174:         $rec->{ivec}      = substr $extra, 0, $blocksize;
        !           175:         $rec->{encrypted} = substr $extra, $blocksize;
1.28      andrew    176:
                    177:     } else {
1.29      andrew    178:         die 'Unsupported Version';
1.28      andrew    179:         return;
                    180:     }
1.12      andrew    181:
1.16      andrew    182:     return $rec;
1.14      andrew    183: }
1.11      andrew    184:
1.28      andrew    185: # PackRecord
                    186:
                    187: sub PackRecord
                    188: {
1.16      andrew    189:     my $self = shift;
                    190:     my $rec  = shift;
                    191:
1.28      andrew    192:     if ($self->{version} == 4) {
                    193:         if ($rec->{encrypted}) {
                    194:             if (! defined $rec->{name}) {
                    195:                 $rec->{name} = $EMPTY;
                    196:             }
                    197:             $rec->{data} = join $NULL, $rec->{name}, $rec->{encrypted};
                    198:             delete $rec->{name};
                    199:             delete $rec->{encrypted};
                    200:         }
1.29      andrew    201:
1.28      andrew    202:     } elsif ($self->{version} == 5) {
1.37    ! andrew    203:         my $field;
        !           204:         if ($rec->{name}) {
        !           205:             $field = {
        !           206:                 'label_id' => 1,
        !           207:                 'data'     => $rec->{name},
        !           208:                 'font'     => 0,
        !           209:             };
        !           210:         } else {
        !           211:             $field = {
        !           212:                 'label_id' => $EMPTY,
        !           213:                 'data'     => $EMPTY,
        !           214:                 'font'     => 0,
        !           215:             };
        !           216:         }
        !           217:         my $packed = _pack_field($field);
1.29      andrew    218:
1.30      andrew    219:         $rec->{data} = join '', $packed, $rec->{ivec}, $rec->{encrypted};
1.29      andrew    220:
1.28      andrew    221:     } else {
1.29      andrew    222:         die 'Unsupported Version';
1.16      andrew    223:     }
1.1       andrew    224:
1.16      andrew    225:     return $self->SUPER::PackRecord($rec, @_);
1.14      andrew    226: }
1.1       andrew    227:
1.28      andrew    228: # ParseAppInfoBlock
                    229:
                    230: sub ParseAppInfoBlock
                    231: {
                    232:     my $self = shift;
                    233:     my $data = shift;
                    234:     my $appinfo = {};
                    235:
                    236:     &Palm::StdAppInfo::parse_StdAppInfo($appinfo, $data);
                    237:
                    238:     # int8/uint8
                    239:     # - Signed or Unsigned Byte (8 bits). C types: char, unsigned char
                    240:     # int16/uint16
                    241:     # - Signed or Unsigned Word (16 bits). C types: short, unsigned short
                    242:     # int32/uint32
                    243:     # - Signed or Unsigned Doubleword (32 bits). C types: int, unsigned int
                    244:     # sz
                    245:     # - Zero-terminated C-style string
                    246:
                    247:     if ($self->{version} == 4) {
                    248:         # Nothing extra for version 4
                    249:
                    250:     } elsif ($self->{version} == 5) {
                    251:         _parse_appinfo_v5($appinfo) || return;
                    252:
                    253:     } else {
1.29      andrew    254:         die "Unsupported Version";
1.28      andrew    255:         return;
                    256:     }
                    257:
                    258:     return $appinfo;
                    259: }
                    260:
                    261: sub _parse_appinfo_v5
                    262: {
                    263:     my $appinfo = shift;
                    264:
                    265:     if (! exists $appinfo->{other}) {
                    266:         # XXX Corrupt appinfo?
                    267:         return;
                    268:     }
                    269:
                    270:     my $unpackstr
                    271:         = ("C1" x 8)  # 8 uint8s in an array for the salt
1.35      andrew    272:         . ("n1" x 2)  # the iter (uint16) and the cipher (uint16)
1.28      andrew    273:         . ("C1" x 8); # and finally 8 more uint8s for the hash
                    274:
                    275:     my (@salt, $iter, $cipher, @hash);
                    276:     (@salt[0..7], $iter, $cipher, @hash[0..7])
                    277:         = unpack $unpackstr, $appinfo->{other};
                    278:
                    279:     $appinfo->{salt}           = sprintf "%02x" x 8, @salt;
                    280:     $appinfo->{iter}           = $iter;
                    281:     $appinfo->{cipher}         = $cipher;
                    282:     $appinfo->{masterhash}     = sprintf "%02x" x 8, @hash;
                    283:     delete $appinfo->{other};
                    284:
                    285:     return $appinfo
                    286: }
                    287:
                    288: # PackAppInfoBlock
                    289:
                    290: sub PackAppInfoBlock
                    291: {
                    292:     my $self = shift;
                    293:     my $retval;
                    294:
                    295:     if ($self->{version} == 4) {
                    296:         # Nothing to do for v4
                    297:
                    298:     } elsif ($self->{version} == 5) {
1.29      andrew    299:         _pack_appinfo_v5($self->{appinfo});
1.28      andrew    300:     } else {
1.29      andrew    301:         die "Unsupported Version";
1.28      andrew    302:         return;
                    303:     }
                    304:     return &Palm::StdAppInfo::pack_StdAppInfo($self->{appinfo});
                    305: }
                    306:
1.29      andrew    307: sub _pack_appinfo_v5
                    308: {
                    309:     my $appinfo = shift;
                    310:
                    311:     my $packstr
                    312:         = ("C1" x 8)  # 8 uint8s in an array for the salt
1.35      andrew    313:         . ("n1" x 2)  # the iter (uint16) and the cipher (uint16)
1.29      andrew    314:         . ("C1" x 8); # and finally 8 more uint8s for the hash
                    315:
                    316:     my @salt = map { hex $_ } $appinfo->{salt} =~ /../gxm;
                    317:     my @hash = map { hex $_ } $appinfo->{masterhash} =~ /../gxm;
                    318:
                    319:     my $packed = pack($packstr,
                    320:         @salt,
                    321:         $appinfo->{iter},
                    322:         $appinfo->{cipher},
                    323:         @hash
                    324:     );
                    325:
                    326:     $appinfo->{other}  = $packed;
                    327:
                    328:     return $appinfo
                    329: }
                    330:
1.28      andrew    331: # Encrypt
                    332:
                    333: sub Encrypt
                    334: {
1.14      andrew    335:     my $self = shift;
1.16      andrew    336:     my $rec  = shift;
                    337:     my $data = shift;
1.28      andrew    338:     my $pass = shift || $self->{password};
1.34      andrew    339:     my $ivec = shift;
1.16      andrew    340:
1.29      andrew    341:     if ( ! $pass && ! $self->{appinfo}->{key}) {
1.28      andrew    342:         croak("password not set!\n");
1.16      andrew    343:     }
                    344:
                    345:     if ( ! $rec) {
                    346:         croak("Needed parameter 'record' not passed!\n");
                    347:     }
1.14      andrew    348:
1.16      andrew    349:     if ( ! $data) {
                    350:         croak("Needed parameter 'data' not passed!\n");
1.14      andrew    351:     }
                    352:
1.29      andrew    353:     if ( $pass && ! $self->Password($pass)) {
1.16      andrew    354:         croak("Incorrect Password!\n");
                    355:     }
1.14      andrew    356:
1.29      andrew    357:     my $acct;
                    358:     if ($rec->{encrypted}) {
                    359:         $acct = $self->Decrypt($rec, $pass);
                    360:     }
                    361:
                    362:     my $encrypted;
1.28      andrew    363:     if ($self->{version} == 4) {
                    364:         $self->{digest} ||= _calc_keys( $pass );
1.29      andrew    365:         $encrypted = _encrypt_v4($data, $acct, $self->{digest});
                    366:         $rec->{name}    ||= $data->{name};
                    367:
                    368:     } elsif ($self->{version} == 5) {
1.34      andrew    369:         my @accts = ($data, $acct);
1.29      andrew    370:         if ($self->{options}->{v4compatible}) {
                    371:             $rec->{name} ||= $data->{name};
1.34      andrew    372:             foreach my $a (@accts) {
1.29      andrew    373:                 my @fields;
1.34      andrew    374:                 foreach my $k (sort keys %{ $a }) {
1.29      andrew    375:                     my $field = {
                    376:                         label    => $k,
                    377:                         font     => 0,
1.34      andrew    378:                         data     => $a->{$k},
1.29      andrew    379:                     };
                    380:                     push @fields, $field;
                    381:                 }
1.34      andrew    382:                 $a = \@fields;
1.29      andrew    383:             }
                    384:         }
                    385:
                    386:         ($encrypted, $ivec) = _encrypt_v5(
1.34      andrew    387:             @accts,
1.29      andrew    388:             $self->{appinfo}->{key},
                    389:             $self->{appinfo}->{cipher},
1.34      andrew    390:             $ivec,
1.29      andrew    391:         );
1.34      andrew    392:         if (defined $ivec) {
1.29      andrew    393:             $rec->{ivec} = $ivec;
1.28      andrew    394:         }
1.29      andrew    395:
                    396:     } else {
                    397:         die "Unsupported Version";
                    398:     }
                    399:
                    400:     if ($encrypted) {
                    401:         if ($encrypted eq '1') {
1.28      andrew    402:             return 1;
                    403:         }
1.29      andrew    404:
                    405:         $rec->{attributes}{Dirty} = 1;
                    406:         $rec->{attributes}{dirty} = 1;
                    407:         $rec->{encrypted} = $encrypted;
                    408:
                    409:         return 1;
1.28      andrew    410:     } else {
1.29      andrew    411:         return;
1.28      andrew    412:     }
                    413: }
1.14      andrew    414:
1.28      andrew    415: sub _encrypt_v4
                    416: {
1.29      andrew    417:     my $new    = shift;
                    418:     my $old    = shift;
1.28      andrew    419:     my $digest = shift;
                    420:
1.29      andrew    421:     $new->{account}  ||= $EMPTY;
                    422:     $new->{password} ||= $EMPTY;
                    423:     $new->{notes}    ||= $EMPTY;
1.1       andrew    424:
1.22      andrew    425:     my $changed      = 0;
                    426:     my $need_newdate = 0;
1.29      andrew    427:     if ($old && %{ $old }) {
                    428:         foreach my $key (keys %{ $new }) {
1.22      andrew    429:             next if $key eq 'lastchange';
1.29      andrew    430:             if ($new->{$key} ne $old->{$key}) {
1.22      andrew    431:                 $changed = 1;
                    432:                 last;
                    433:             }
                    434:         }
1.29      andrew    435:         if ( exists $new->{lastchange} && exists $old->{lastchange} && (
                    436:             $new->{lastchange}->{day}   != $old->{lastchange}->{day}   ||
                    437:             $new->{lastchange}->{month} != $old->{lastchange}->{month} ||
                    438:             $new->{lastchange}->{year}  != $old->{lastchange}->{year}
1.22      andrew    439:         )) {
                    440:             $changed = 1;
                    441:             $need_newdate = 0;
                    442:         } else {
                    443:             $need_newdate = 1;
                    444:         }
                    445:
                    446:     } else {
                    447:         $changed = 1;
                    448:     }
                    449:
                    450:     # no need to re-encrypt if it has not changed.
                    451:     return 1 if ! $changed;
                    452:
1.21      andrew    453:     my ($day, $month, $year);
                    454:
1.29      andrew    455:     if ($new->{lastchange} && ! $need_newdate ) {
                    456:         $day   = $new->{lastchange}->{day}   || 1;
                    457:         $month = $new->{lastchange}->{month} || 0;
                    458:         $year  = $new->{lastchange}->{year}  || 0;
1.22      andrew    459:
                    460:         # XXX Need to actually validate the above information somehow
                    461:         if ($year >= 1900) {
                    462:             $year -= 1900;
                    463:         }
                    464:     } else {
                    465:         $need_newdate = 1;
                    466:     }
                    467:
                    468:     if ($need_newdate) {
1.21      andrew    469:         ($day, $month, $year) = (localtime)[3,4,5];
                    470:     }
1.22      andrew    471:
1.29      andrew    472:     my $packed_date = _pack_keyring_date( {
1.28      andrew    473:             year  => $year,
                    474:             month => $month,
                    475:             day   => $day,
                    476:     });
1.19      andrew    477:
1.16      andrew    478:     my $plaintext = join $NULL,
1.29      andrew    479:         $new->{account}, $new->{password}, $new->{notes}, $packed_date;
1.1       andrew    480:
1.28      andrew    481:     return _crypt3des( $plaintext, $digest, $ENCRYPT );
                    482: }
1.11      andrew    483:
1.29      andrew    484: sub _encrypt_v5
                    485: {
                    486:     my $new    = shift;
                    487:     my $old    = shift;
                    488:     my $key    = shift;
                    489:     my $cipher = shift;
1.34      andrew    490:     my $ivec   = shift;
                    491:     my $blocksize   = $CRYPTS[ $cipher ]{blocksize};
1.29      andrew    492:     my $keylen      = $CRYPTS[ $cipher ]{keylen};
                    493:     my $cipher_name = $CRYPTS[ $cipher ]{name};
                    494:
1.34      andrew    495:     if (! defined $ivec) {
                    496:         $ivec = pack("C*",map {rand(256)} 1..$blocksize);
                    497:     }
                    498:
1.29      andrew    499:     my $changed = 0;
                    500:     my $need_newdate = 1;
                    501:     my $date_index;
                    502:     for (my $i = 0; $i < @{ $new }; $i++) {
                    503:         if (
1.37    ! andrew    504:             ($new->[$i]->{label_id} && $new->[$i]->{label_id} == 3) ||
        !           505:             ($new->[$i]->{label} && $new->[$i]->{label} eq 'lastchange')
1.29      andrew    506:         ) {
                    507:             $date_index   = $i;
                    508:             if ( $old && $#{ $new } == $#{ $old } && (
1.37    ! andrew    509:                     $new->[$i]{data}{day}   != $old->[$i]{data}{day}   ||
        !           510:                     $new->[$i]{data}{month} != $old->[$i]{data}{month} ||
        !           511:                     $new->[$i]{data}{year}  != $old->[$i]{data}{year}
1.29      andrew    512:                 )) {
                    513:                 $changed      = 1;
                    514:                 $need_newdate = 0;
                    515:             }
                    516:
                    517:         } elsif ($old && $#{ $new } == $#{ $old }) {
                    518:             my $n = join ':', %{ $new->[$i] };
                    519:             my $o = join ':', %{ $old->[$i] };
                    520:             if ($n ne $o) {
                    521:                 $changed = 1;
                    522:             }
                    523:         } elsif ($#{ $new } != $#{ $old }) {
                    524:             $changed = 1;
                    525:         }
                    526:     }
                    527:     if ($old && (! @{ $old }) && $date_index) {
                    528:         $need_newdate = 0;
                    529:     }
                    530:
                    531:     return 1, 0 if $changed == 0;
                    532:
                    533:     if ($need_newdate || ! defined $date_index) {
                    534:         my ($day, $month, $year) = (localtime)[3,4,5];
                    535:         my $date = {
                    536:             year  => $year,
                    537:             month => $month,
                    538:             day   => $day,
                    539:         };
                    540:         if (defined $date_index) {
                    541:             $new->[$date_index]->{data} = $date;
                    542:         } else {
                    543:             push @{ $new }, {
                    544:                 label => 'lastchange',
                    545:                 font  => 0,
                    546:                 data  => $date,
                    547:             };
                    548:         }
                    549:     } else {
                    550:         # XXX Need to actually validate the above information somehow
                    551:         if ($new->[$date_index]->{data}->{year} >= 1900) {
                    552:             $new->[$date_index]->{data}->{year} -= 1900;
                    553:         }
                    554:     }
                    555:
                    556:     my $decrypted;
                    557:     foreach my $field (@{ $new }) {
                    558:         $decrypted .= _pack_field($field);
                    559:     }
                    560:     my $encrypted;
                    561:     if ($cipher_name eq 'None') {
                    562:         # do nothing
                    563:         $encrypted = $decrypted;
                    564:
                    565:     } elsif ($cipher_name eq 'DES_EDE3' or $cipher_name eq 'Rijndael') {
1.35      andrew    566:         require Crypt::CBC;
1.29      andrew    567:         my $c = Crypt::CBC->new(
1.35      andrew    568:             -key         => $key,
1.29      andrew    569:             -literal_key => 1,
                    570:             -iv          => $ivec,
                    571:             -cipher      => $cipher_name,
                    572:             -keysize     => $keylen,
1.34      andrew    573:             -blocksize   => $blocksize,
1.29      andrew    574:             -header      => 'none',
                    575:             -padding     => 'oneandzeroes',
                    576:         );
                    577:
                    578:         if (! $c) {
                    579:             croak("Unable to set up encryption!");
                    580:         }
                    581:
                    582:         $encrypted = $c->encrypt($decrypted);
                    583:
                    584:     } else {
                    585:         die "Unsupported Version";
                    586:     }
                    587:
                    588:     return $encrypted, $ivec;
                    589: }
                    590:
1.28      andrew    591: # Decrypt
1.1       andrew    592:
1.31      andrew    593: sub Decrypt
1.28      andrew    594: {
1.14      andrew    595:     my $self = shift;
1.16      andrew    596:     my $rec  = shift;
1.28      andrew    597:     my $pass = shift || $self->{password};
1.16      andrew    598:
1.29      andrew    599:     if ( ! $pass && ! $self->{appinfo}->{key}) {
1.28      andrew    600:         croak("password not set!\n");
1.16      andrew    601:     }
                    602:
                    603:     if ( ! $rec) {
1.19      andrew    604:         croak("Needed parameter 'record' not passed!\n");
1.16      andrew    605:     }
1.14      andrew    606:
1.30      andrew    607:     if ( $pass && ! $self->Password($pass)) {
1.16      andrew    608:         croak("Invalid Password!\n");
1.14      andrew    609:     }
                    610:
1.28      andrew    611:     if ( ! $rec->{encrypted} ) {
1.16      andrew    612:         croak("No encrypted content!");
                    613:     }
1.14      andrew    614:
1.28      andrew    615:     if ($self->{version} == 4) {
                    616:         $self->{digest} ||= _calc_keys( $pass );
                    617:         my $acct = _decrypt_v4($rec->{encrypted}, $self->{digest});
                    618:         $acct->{name} ||= $rec->{name};
                    619:         return $acct;
1.29      andrew    620:
1.28      andrew    621:     } elsif ($self->{version} == 5) {
                    622:         my $fields = _decrypt_v5(
1.29      andrew    623:             $rec->{encrypted}, $self->{appinfo}->{key},
                    624:             $self->{appinfo}->{cipher}, $rec->{ivec},
1.28      andrew    625:         );
                    626:         if ($self->{options}->{v4compatible}) {
                    627:             my %acct;
                    628:             foreach my $f (@{ $fields }) {
                    629:                 $acct{ $f->{label} } = $f->{data};
                    630:             }
                    631:             $acct{name} ||= $rec->{name};
                    632:             return \%acct;
                    633:         } else {
                    634:             return $fields;
                    635:         }
1.29      andrew    636:
1.28      andrew    637:     } else {
1.29      andrew    638:         die "Unsupported Version";
1.28      andrew    639:     }
                    640:     return;
                    641: }
1.14      andrew    642:
1.28      andrew    643: sub _decrypt_v4
                    644: {
                    645:     my $encrypted = shift;
                    646:     my $digest    = shift;
                    647:
                    648:     my $decrypted = _crypt3des( $encrypted, $digest, $DECRYPT );
1.29      andrew    649:     my ( $account, $password, $notes, $packed_date )
1.28      andrew    650:         = split /$NULL/xm, $decrypted, 4;
1.14      andrew    651:
1.28      andrew    652:     my $modified;
1.29      andrew    653:     if ($packed_date) {
                    654:         $modified = _parse_keyring_date($packed_date);
1.19      andrew    655:     }
                    656:
1.16      andrew    657:     return {
1.20      andrew    658:         account    => $account,
                    659:         password   => $password,
                    660:         notes      => $notes,
1.28      andrew    661:         lastchange => $modified,
1.16      andrew    662:     };
                    663: }
1.14      andrew    664:
1.28      andrew    665: sub _decrypt_v5
                    666: {
1.34      andrew    667:
1.28      andrew    668:     my $encrypted = shift;
                    669:     my $key       = shift;
                    670:     my $cipher    = shift;
1.29      andrew    671:     my $ivec      = shift;
                    672:
                    673:     my $keylen       = $CRYPTS[ $cipher ]{keylen};
                    674:     my $cipher_name  = $CRYPTS[ $cipher ]{name};
1.34      andrew    675:     my $blocksize    = $CRYPTS[ $cipher ]{blocksize};
1.28      andrew    676:
                    677:     my $decrypted;
                    678:
1.29      andrew    679:     if ($cipher_name eq 'None') {
1.28      andrew    680:         # do nothing
                    681:         $decrypted = $encrypted;
                    682:
1.29      andrew    683:     } elsif ($cipher_name eq 'DES_EDE3' or $cipher_name eq 'Rijndael') {
1.35      andrew    684:         require Crypt::CBC;
1.29      andrew    685:         my $c = Crypt::CBC->new(
1.35      andrew    686:             -key         => $key,
1.29      andrew    687:             -literal_key => 1,
                    688:             -iv          => $ivec,
                    689:             -cipher      => $cipher_name,
                    690:             -keysize     => $keylen,
1.34      andrew    691:             -blocksize   => $blocksize,
1.29      andrew    692:             -header      => 'none',
                    693:             -padding     => 'oneandzeroes',
                    694:         );
                    695:
1.28      andrew    696:         if (! $c) {
                    697:             croak("Unable to set up encryption!");
                    698:         }
1.34      andrew    699:         my $len = $blocksize - length($encrypted) % $blocksize;
                    700:         $encrypted .= $NULL x $len;
1.28      andrew    701:         $decrypted  = $c->decrypt($encrypted);
                    702:
                    703:     } else {
1.29      andrew    704:         die "Unsupported Version";
1.28      andrew    705:         return;
                    706:     }
                    707:
                    708:     my @fields;
                    709:     while ($decrypted) {
                    710:         my $field;
                    711:         ($field, $decrypted) = _parse_field($decrypted);
                    712:         if (! $field) {
                    713:             last;
                    714:         }
                    715:         push @fields, $field;
                    716:     }
                    717:
                    718:     return \@fields;
                    719: }
                    720:
                    721: # Password
                    722:
                    723: sub Password
                    724: {
1.16      andrew    725:     my $self = shift;
1.24      andrew    726:     my $pass = shift;
1.16      andrew    727:     my $new_pass = shift;
1.14      andrew    728:
1.24      andrew    729:     if (! $pass) {
                    730:         delete $self->{password};
1.30      andrew    731:         delete $self->{appinfo}->{key};
1.28      andrew    732:         return 1;
1.24      andrew    733:     }
                    734:
1.29      andrew    735:     if (
                    736:         ($self->{version} == 4 && ! exists $self->{records}) ||
                    737:         ($self->{version} == 5 && ! exists $self->{appinfo}->{masterhash})
                    738:     ) {
                    739:         if ($self->{version} == 4) {
                    740:             # Give the PDB the first record that will hold the encrypted password
                    741:             $self->{records} = [ $self->new_Record ];
                    742:         }
1.16      andrew    743:
                    744:         return $self->_password_update($pass);
                    745:     }
                    746:
                    747:     if ($new_pass) {
1.29      andrew    748:         my $v4compat = $self->{options}->{v4compatible};
                    749:         $self->{options}->{v4compatible} = 0;
                    750:
1.16      andrew    751:         my @accts = ();
1.28      andrew    752:         foreach my $i (0..$#{ $self->{records} }) {
1.29      andrew    753:             if ($self->{version} == 4 && $i == 0) {
1.16      andrew    754:                 push @accts, undef;
                    755:                 next;
                    756:             }
1.28      andrew    757:             my $acct = $self->Decrypt($self->{records}->[$i], $pass);
1.16      andrew    758:             if ( ! $acct ) {
1.28      andrew    759:                 croak("Couldn't decrypt $self->{records}->[$i]->{name}");
1.16      andrew    760:             }
                    761:             push @accts, $acct;
                    762:         }
1.14      andrew    763:
1.16      andrew    764:         if ( ! $self->_password_update($new_pass)) {
                    765:             croak("Couldn't set new password!");
                    766:         }
                    767:         $pass = $new_pass;
1.1       andrew    768:
1.16      andrew    769:         foreach my $i (0..$#accts) {
1.29      andrew    770:             if ($self->{version} == 4 && $i == 0) {
                    771:                 next;
                    772:             }
1.28      andrew    773:             delete $self->{records}->[$i]->{encrypted};
                    774:             $self->Encrypt($self->{records}->[$i], $accts[$i], $pass);
1.16      andrew    775:         }
1.29      andrew    776:
                    777:         $self->{options}->{v4compatible} = $v4compat;
1.14      andrew    778:     }
1.1       andrew    779:
1.28      andrew    780:     if (defined $self->{password} && $pass eq $self->{password}) {
                    781:         # already verified this password
                    782:         return 1;
                    783:     }
                    784:
                    785:     if ($self->{version} == 4) {
                    786:         # AFAIK the thing we use to test the password is
                    787:         #     always in the first entry
                    788:         my $valid = _password_verify_v4($pass, $self->{records}->[0]->{data});
                    789:
1.29      andrew    790:         # May as well generate the keys we need now, since we know the password is right
1.28      andrew    791:         if ($valid) {
                    792:             $self->{digest} = _calc_keys($pass);
                    793:             if ($self->{digest} ) {
                    794:                 $self->{password} = $pass;
                    795:                 return 1;
                    796:             }
                    797:         }
                    798:     } elsif ($self->{version} == 5) {
1.35      andrew    799:         return _password_verify_v5($self->{appinfo}, $pass);
1.28      andrew    800:     } else {
                    801:         # XXX unsupported version
                    802:     }
                    803:
                    804:     return;
                    805: }
                    806:
                    807: sub _password_verify_v4
                    808: {
1.32      andrew    809:     require Digest::MD5;
                    810:     import Digest::MD5 qw(md5);
                    811:
1.28      andrew    812:     my $pass = shift;
                    813:     my $data = shift;
                    814:
                    815:     if (! $pass) { croak('No password specified!'); };
                    816:
                    817:     # XXX die "No encrypted password in file!" unless defined $data;
                    818:     if ( ! defined $data) { return; };
                    819:
                    820:     $data =~ s/$NULL$//xm;
                    821:
                    822:     my $salt = substr $data, 0, $kSalt_Size;
                    823:
                    824:     my $msg = $salt . $pass;
                    825:     $msg .= "\0" x ( $MD5_CBLOCK - length $msg );
                    826:
                    827:     my $digest = md5($msg);
                    828:
1.33      andrew    829:     if ($data ne $salt . $digest ) {
1.28      andrew    830:         return;
                    831:     }
                    832:
                    833:     return 1;
                    834: }
                    835:
                    836: sub _password_verify_v5
                    837: {
1.35      andrew    838:     my $appinfo = shift;
1.28      andrew    839:     my $pass    = shift;
                    840:
                    841:     my $salt = pack("H*", $appinfo->{salt});
                    842:
1.29      andrew    843:     my ($key, $hash) = _calc_key_v5(
                    844:         $pass, $salt, $appinfo->{iter},
                    845:         $CRYPTS[ $appinfo->{cipher} ]{keylen},
                    846:         $CRYPTS[ $appinfo->{cipher} ]{DES_odd_parity},
1.28      andrew    847:     );
                    848:
1.35      andrew    849:     #print "Iter: '" . $appinfo->{iter} . "'\n";
1.28      andrew    850:     #print "Key:  '". unpack("H*", $key) . "'\n";
1.35      andrew    851:     #print "Salt: '". unpack("H*", $salt) . "'\n";
1.29      andrew    852:     #print "Hash: '". $hash . "'\n";
1.28      andrew    853:     #print "Hash: '". $appinfo->{masterhash} . "'\n";
                    854:
1.29      andrew    855:     if ($appinfo->{masterhash} eq $hash) {
1.28      andrew    856:         $appinfo->{key} = $key;
                    857:     } else {
                    858:         return;
                    859:     }
1.29      andrew    860:
                    861:     return $key;
                    862: }
                    863:
                    864:
                    865: sub _password_update
                    866: {
                    867:     # It is very important to Encrypt after calling this
                    868:     #     (Although it is generally only called by Encrypt)
                    869:     # because otherwise the data will be out of sync with the
                    870:     # password, and that would suck!
                    871:     my $self   = shift;
                    872:     my $pass   = shift;
                    873:
                    874:     if ($self->{version} == 4) {
                    875:         my $data = _password_update_v4($pass, @_);
                    876:
                    877:         if (! $data) {
                    878:             carp("Failed  to update password!");
                    879:             return;
                    880:         }
                    881:
                    882:         # AFAIK the thing we use to test the password is
                    883:         #     always in the first entry
                    884:         $self->{records}->[0]->{data} = $data;
                    885:         $self->{password} = $pass;
                    886:         $self->{digest}   = _calc_keys( $self->{password} );
                    887:
                    888:         return 1;
                    889:
                    890:     } elsif ($self->{version} == 5) {
                    891:         my $cipher  = shift || $self->{appinfo}->{cipher};
                    892:         my $iter    = shift || $self->{appinfo}->{iter};
                    893:         my $salt    = shift || 0;
                    894:
                    895:         my $hash = _password_update_v5(
                    896:             $self->{appinfo}, $pass, $cipher, $iter, $salt
                    897:         );
                    898:
                    899:         if (! $hash) {
                    900:             carp("Failed  to update password!");
                    901:             return;
                    902:         }
                    903:
                    904:         return 1;
                    905:     } else {
                    906:         croak("Unsupported version ($self->{version})");
                    907:     }
                    908:
                    909:     return;
                    910: }
                    911:
                    912: sub _password_update_v4
                    913: {
1.32      andrew    914:     require Digest::MD5;
                    915:     import Digest::MD5 qw(md5);
                    916:
1.29      andrew    917:     my $pass = shift;
                    918:
                    919:     if (! defined $pass) { croak('No password specified!'); };
                    920:
                    921:     my $salt;
                    922:     for ( 1 .. $kSalt_Size ) {
                    923:         $salt .= chr int rand 255;
                    924:     }
                    925:
                    926:     my $msg = $salt . $pass;
                    927:
                    928:     $msg .= "\0" x ( $MD5_CBLOCK - length $msg );
                    929:
                    930:     my $digest = md5($msg);
                    931:
                    932:     my $data = $salt . $digest;    # . "\0";
                    933:
                    934:     return $data;
                    935: }
                    936:
                    937: sub _password_update_v5
                    938: {
                    939:     my $appinfo = shift;
                    940:     my $pass    = shift;
                    941:     my $cipher  = shift;
                    942:     my $iter    = shift;
                    943:
                    944:     # I thought this needed to be 'blocksize', but apparently not.
                    945:     #my $length  = $CRYPTS[ $cipher ]{blocksize};
                    946:     my $length  = 8;
                    947:     my $salt    = shift || pack("C*",map {rand(256)} 1..$length);
                    948:
                    949:     my ($key, $hash) = _calc_key_v5(
                    950:         $pass, $salt, $iter,
                    951:         $CRYPTS[ $cipher ]->{keylen},
                    952:         $CRYPTS[ $cipher ]->{DES_odd_parity},
                    953:     );
                    954:
                    955:     $appinfo->{salt}           = unpack "H*", $salt;
                    956:     $appinfo->{iter}           = $iter;
                    957:     $appinfo->{cipher}         = $cipher;
                    958:
                    959:     $appinfo->{key}            = $key;
                    960:     $appinfo->{masterhash}     = $hash;
                    961:
1.28      andrew    962:     return $key;
1.1       andrew    963: }
                    964:
1.34      andrew    965: # Helpers
1.28      andrew    966:
                    967: sub _calc_keys
                    968: {
1.14      andrew    969:     my $pass = shift;
                    970:     if (! defined $pass) { croak('No password defined!'); };
                    971:
                    972:     my $digest = md5($pass);
                    973:
                    974:     my ( $key1, $key2 ) = unpack 'a8a8', $digest;
                    975:
                    976:     #--------------------------------------------------
                    977:     # print "key1: $key1: ", length $key1, "\n";
                    978:     # print "key2: $key2: ", length $key2, "\n";
                    979:     #--------------------------------------------------
                    980:
                    981:     $digest = unpack 'H*', $key1 . $key2 . $key1;
                    982:
                    983:     #--------------------------------------------------
                    984:     # print "Digest: ", $digest, "\n";
                    985:     # print length $digest, "\n";
                    986:     #--------------------------------------------------
                    987:
                    988:     return $digest;
1.3       andrew    989: }
                    990:
1.29      andrew    991: sub _calc_key_v5
                    992: {
                    993:     my ($pass, $salt, $iter, $keylen, $dop) = @_;
                    994:
1.32      andrew    995:     require Digest::HMAC_SHA1;
                    996:     import  Digest::HMAC_SHA1 qw(hmac_sha1);
                    997:     require Digest::SHA1;
                    998:     import  Digest::SHA1 qw(sha1);
                    999:
1.29      andrew   1000:     my $key = _pbkdf2( $pass, $salt, $iter, $keylen, \&hmac_sha1 );
                   1001:     if ($dop) { $key = DES_odd_parity($key); }
                   1002:
                   1003:     my $hash = unpack("H*", substr(sha1($key.$salt),0, 8));
                   1004:
                   1005:     return $key, $hash;
                   1006: }
                   1007:
1.28      andrew   1008: sub _crypt3des
                   1009: {
1.32      andrew   1010:     require Crypt::DES;
                   1011:
1.28      andrew   1012:     my ( $plaintext, $passphrase, $flag ) = @_;
                   1013:
                   1014:     $passphrase   .= $SPACE x ( 16 * 3 );
                   1015:     my $cyphertext = $EMPTY;
                   1016:
                   1017:     my $size = length $plaintext;
1.14      andrew   1018:
1.28      andrew   1019:     #print "STRING: '$plaintext' - Length: " . (length $plaintext) . "\n";
1.11      andrew   1020:
1.28      andrew   1021:     my @C;
                   1022:     for ( 0 .. 2 ) {
                   1023:         $C[$_] =
                   1024:           new Crypt::DES( pack 'H*', ( substr $passphrase, 16 * $_, 16 ));
1.16      andrew   1025:     }
                   1026:
1.28      andrew   1027:     for ( 0 .. ( ($size) / 8 ) ) {
                   1028:         my $pt = substr $plaintext, $_ * 8, 8;
                   1029:
                   1030:         #print "PT: '$pt' - Length: " . length($pt) . "\n";
                   1031:         if (! length $pt) { next; };
                   1032:         if ( (length $pt) < 8 ) {
                   1033:             if ($flag == $DECRYPT) { croak('record not 8 byte padded'); };
                   1034:             my $len = 8 - (length $pt);
                   1035:             $pt .= ($NULL x $len);
                   1036:         }
                   1037:         if ( $flag == $ENCRYPT ) {
                   1038:             $pt = $C[0]->encrypt($pt);
                   1039:             $pt = $C[1]->decrypt($pt);
                   1040:             $pt = $C[2]->encrypt($pt);
                   1041:         }
                   1042:         else {
                   1043:             $pt = $C[0]->decrypt($pt);
                   1044:             $pt = $C[1]->encrypt($pt);
                   1045:             $pt = $C[2]->decrypt($pt);
                   1046:         }
                   1047:
                   1048:         #print "PT: '$pt' - Length: " . length($pt) . "\n";
                   1049:         $cyphertext .= $pt;
                   1050:     }
1.11      andrew   1051:
1.28      andrew   1052:     $cyphertext =~ s/$NULL+$//xm;
1.11      andrew   1053:
1.28      andrew   1054:     #print "CT: '$cyphertext' - Length: " . length($cyphertext) . "\n";
1.11      andrew   1055:
1.28      andrew   1056:     return $cyphertext;
                   1057: }
1.11      andrew   1058:
1.28      andrew   1059: sub _parse_field
                   1060: {
                   1061:     my $field = shift;
                   1062:
                   1063:     my @labels;
                   1064:     $labels[0]   = 'name';
                   1065:     $labels[1]   = 'account';
                   1066:     $labels[2]   = 'password';
                   1067:     $labels[3]   = 'lastchange';
                   1068:     $labels[255] = 'notes';
                   1069:
1.35      andrew   1070:     my ($len) = unpack "n1", $field;
1.28      andrew   1071:     if ($len + 4 > length $field) {
                   1072:         return undef, $field;
                   1073:     }
1.34      andrew   1074:     my $unpackstr = "x2 C1 C1 A$len";
                   1075:     my $offset    =   2 +1 +1 +$len;
                   1076:     if ($len % 2) { # && $len + 4 < length $field) {
1.28      andrew   1077:         # trim the 0/1 byte padding for next even address.
1.34      andrew   1078:         $offset++;
1.28      andrew   1079:         $unpackstr .= ' x'
                   1080:     }
1.11      andrew   1081:
1.34      andrew   1082:     my ($label, $font, $data) = unpack $unpackstr, $field;
                   1083:     my $leftover = substr $field, $offset;
1.11      andrew   1084:
1.37    ! andrew   1085:     if ($label && $label == 3) {
1.28      andrew   1086:         $data = _parse_keyring_date($data);
1.14      andrew   1087:     }
1.28      andrew   1088:     return {
                   1089:         #len      => $len,
                   1090:         label    => $labels[ $label ] || $label,
                   1091:         label_id => $label,
                   1092:         font     => $font,
                   1093:         data     => $data,
                   1094:     }, $leftover;
1.6       andrew   1095: }
                   1096:
1.29      andrew   1097: sub _pack_field
                   1098: {
                   1099:     my $field = shift;
1.28      andrew   1100:
1.29      andrew   1101:     my %labels = (
                   1102:         name       =>   0,
                   1103:         account    =>   1,
                   1104:         password   =>   2,
                   1105:         lastchange =>   3,
                   1106:         notes      => 255,
                   1107:     );
1.14      andrew   1108:
1.37    ! andrew   1109:     my $packed;
        !          1110:     if (defined $field) {
        !          1111:         my $label = $field->{label_id} || 0;
        !          1112:         if (defined $field->{label} && ! $label) {
        !          1113:             $label = $labels{ $field->{label} };
        !          1114:         }
        !          1115:         my $font  = $field->{font} || 0;
        !          1116:         my $data  = defined $field->{data} ? $field->{data} : $EMPTY;
        !          1117:
        !          1118:         if ($label && $label == 3) {
        !          1119:             $data = _pack_keyring_date($data);
        !          1120:         }
        !          1121:         my $len = length $data;
        !          1122:         my $packstr = "n1 C1 C1 A*";
        !          1123:
        !          1124:         $packed = pack $packstr, ($len, $label, $font, $data);
        !          1125:
        !          1126:         if ($len % 2) {
        !          1127:             # add byte padding for next even address.
        !          1128:             $packed .= $NULL;
        !          1129:         }
        !          1130:     } else {
        !          1131:         my $packstr = "n1 c1 c1 x1";
        !          1132:         $packed = pack $packstr, 0, 0, 0;
1.14      andrew   1133:     }
                   1134:
1.29      andrew   1135:     return $packed;
                   1136: }
1.11      andrew   1137:
1.29      andrew   1138: sub _parse_keyring_date
                   1139: {
                   1140:     my $data = shift;
1.11      andrew   1141:
1.29      andrew   1142:     my $u = unpack 'n', $data;
                   1143:     my $year  = (($u & 0xFE00) >> 9) + 4; # since 1900
                   1144:     my $month = (($u & 0x01E0) >> 5) - 1; # 0-11
                   1145:     my $day   = (($u & 0x001F) >> 0);     # 1-31
1.11      andrew   1146:
1.29      andrew   1147:     return {
                   1148:         year   => $year,
                   1149:         month  => $month || 0,
                   1150:         day    => $day   || 1,
                   1151:     };
                   1152: }
1.11      andrew   1153:
1.29      andrew   1154: sub _pack_keyring_date
                   1155: {
                   1156:     my $d = shift;
                   1157:     my $year  = $d->{year};
                   1158:     my $month = $d->{month};
                   1159:     my $day   = $d->{day};
1.11      andrew   1160:
1.29      andrew   1161:     $year -= 4;
                   1162:     $month++;
1.11      andrew   1163:
1.29      andrew   1164:     return pack 'n', $day | ($month << 5) | ($year << 9);
1.1       andrew   1165: }
1.29      andrew   1166:
1.1       andrew   1167:
1.28      andrew   1168: sub _hexdump
                   1169: {
                   1170:     my $prefix = shift;   # What to print in front of each line
                   1171:     my $data = shift;     # The data to dump
                   1172:     my $maxlines = shift; # Max # of lines to dump
                   1173:     my $offset;           # Offset of current chunk
                   1174:
                   1175:     for ($offset = 0; $offset < length($data); $offset += 16)
                   1176:     {
                   1177:         my $hex;   # Hex values of the data
                   1178:         my $ascii; # ASCII values of the data
                   1179:         my $chunk; # Current chunk of data
                   1180:
                   1181:         last if defined($maxlines) && ($offset >= ($maxlines * 16));
1.14      andrew   1182:
1.28      andrew   1183:         $chunk = substr($data, $offset, 16);
1.14      andrew   1184:
1.28      andrew   1185:         ($hex = $chunk) =~ s/./sprintf "%02x ", ord($&)/ges;
1.11      andrew   1186:
1.28      andrew   1187:         ($ascii = $chunk) =~ y/\040-\176/./c;
1.14      andrew   1188:
1.28      andrew   1189:         printf "%s %-48s|%-16s|\n", $prefix, $hex, $ascii;
1.14      andrew   1190:     }
1.28      andrew   1191: }
                   1192:
                   1193: sub _bindump
                   1194: {
                   1195:     my $prefix = shift;   # What to print in front of each line
                   1196:     my $data = shift;     # The data to dump
                   1197:     my $maxlines = shift; # Max # of lines to dump
                   1198:     my $offset;           # Offset of current chunk
                   1199:
                   1200:     for ($offset = 0; $offset < length($data); $offset += 8)
                   1201:     {
                   1202:         my $bin;   # binary values of the data
                   1203:         my $ascii; # ASCII values of the data
                   1204:         my $chunk; # Current chunk of data
1.14      andrew   1205:
1.28      andrew   1206:         last if defined($maxlines) && ($offset >= ($maxlines * 8));
1.14      andrew   1207:
1.28      andrew   1208:         $chunk = substr($data, $offset, 8);
1.14      andrew   1209:
1.28      andrew   1210:         ($bin = $chunk) =~ s/./sprintf "%08b ", ord($&)/ges;
1.14      andrew   1211:
1.28      andrew   1212:         ($ascii = $chunk) =~ y/\040-\176/./c;
1.14      andrew   1213:
1.28      andrew   1214:         printf "%s %-72s|%-8s|\n", $prefix, $bin, $ascii;
1.14      andrew   1215:     }
1.28      andrew   1216: }
1.14      andrew   1217:
1.28      andrew   1218: # Thanks to Jochen Hoenicke <hoenicke@gmail.com>
                   1219: # (one of the authors of Palm Keyring)
                   1220: # for these next two subs.
                   1221:
                   1222: # Usage pbkdf2(password, salt, iter, keylen, prf)
                   1223: # iter is number of iterations
                   1224: # keylen is length of generated key in bytes
                   1225: # prf is the pseudo random function (e.g. hmac_sha1)
                   1226: # returns the key.
                   1227: sub _pbkdf2($$$$$)
                   1228: {
                   1229:     my ($password, $salt, $iter, $keylen, $prf) = @_;
                   1230:     my ($k, $t, $u, $ui, $i);
                   1231:     $t = "";
                   1232:     for ($k = 1; length($t) <  $keylen; $k++) {
                   1233:     $u = $ui = &$prf($salt.pack('N', $k), $password);
                   1234:     for ($i = 1; $i < $iter; $i++) {
                   1235:         $ui = &$prf($ui, $password);
                   1236:         $u ^= $ui;
                   1237:     }
                   1238:     $t .= $u;
                   1239:     }
                   1240:     return substr($t, 0, $keylen);
                   1241: }
1.11      andrew   1242:
1.28      andrew   1243: sub DES_odd_parity($) {
                   1244:     my $key = $_[0];
                   1245:     my ($r, $i);
                   1246:     my @odd_parity = (
                   1247:   1,  1,  2,  2,  4,  4,  7,  7,  8,  8, 11, 11, 13, 13, 14, 14,
                   1248:  16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
                   1249:  32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
                   1250:  49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
                   1251:  64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
                   1252:  81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
                   1253:  97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
                   1254: 112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
                   1255: 128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
                   1256: 145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
                   1257: 161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
                   1258: 176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
                   1259: 193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
                   1260: 208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
                   1261: 224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
                   1262: 241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254);
                   1263:     for ($i = 0; $i< length($key); $i++) {
                   1264:     $r .= chr($odd_parity[ord(substr($key, $i, 1))]);
                   1265:     }
                   1266:     return $r;
1.14      andrew   1267: }
1.11      andrew   1268:
1.14      andrew   1269: 1;
                   1270: __END__
                   1271: =head1 NAME
1.11      andrew   1272:
1.14      andrew   1273: Palm::Keyring - Handler for Palm Keyring databases.
1.1       andrew   1274:
1.14      andrew   1275: =head1 DESCRIPTION
1.7       andrew   1276:
1.14      andrew   1277: The Keyring PDB handler is a helper class for the Palm::PDB package. It
                   1278: parses Keyring for Palm OS databases.  See
                   1279: L<http://gnukeyring.sourceforge.net/>.
1.1       andrew   1280:
1.14      andrew   1281: It has the standard Palm::PDB methods with 2 additional public methods.
                   1282: Decrypt and Encrypt.
1.1       andrew   1283:
1.37    ! andrew   1284: It currently supports the v4 Keyring databases as well as
        !          1285: the pre-release v5 databases.  I am not completely happy with the interface
        !          1286: for accessing the v5 database, so any suggestions on improvements on
        !          1287: the interface are appreciated.
1.16      andrew   1288:
                   1289: This module doesn't store the decrypted content.  It only keeps it until it
                   1290: returns it to you or encrypts it.
1.1       andrew   1291:
1.14      andrew   1292: =head1 SYNOPSIS
1.1       andrew   1293:
1.16      andrew   1294:     use Palm::PDB;
                   1295:     use Palm::Keyring;
1.17      andrew   1296:
                   1297:     my $pass = 'password';
1.18      andrew   1298:     my $file = 'Keys-Gtkr.pdb';
                   1299:     my $pdb  = new Palm::PDB;
1.16      andrew   1300:     $pdb->Load($file);
1.17      andrew   1301:
1.28      andrew   1302:     foreach (0..$#{ $pdb->{records} }) {
1.31      andrew   1303:         # skip the password record for version 4 databases
                   1304:         next if $_ == 0 && $pdb->{version} == 4;
1.28      andrew   1305:         my $rec  = $pdb->{records}->[$_];
1.17      andrew   1306:         my $acct = $pdb->Decrypt($rec, $pass);
1.37    ! andrew   1307:         print $rec->{name}, ' - ';
        !          1308:         if ($pdb->{version} == 4 || $pdb->{options}->{v4compatible}) {
        !          1309:             print ' - ', $acct->{account};
        !          1310:         } else {
        !          1311:             foreach my $a (@{ $acct }) {
        !          1312:                 if ($a->{type} eq 'account') {
        !          1313:                     print ' - ',  $a->{data};
        !          1314:                     last;
        !          1315:                 }
        !          1316:             }
        !          1317:         }
        !          1318:         print "\n";
1.16      andrew   1319:     }
1.1       andrew   1320:
1.14      andrew   1321: =head1 SUBROUTINES/METHODS
1.1       andrew   1322:
1.14      andrew   1323: =head2 new
1.11      andrew   1324:
1.31      andrew   1325:     $pdb = new Palm::Keyring([$password[, $version]]);
1.11      andrew   1326:
1.14      andrew   1327: Create a new PDB, initialized with the various Palm::Keyring fields
                   1328: and an empty record list.
1.11      andrew   1329:
1.14      andrew   1330: Use this method if you're creating a Keyring PDB from scratch otherwise you
1.16      andrew   1331: can just use Palm::PDB::new() before calling Load().
1.11      andrew   1332:
1.24      andrew   1333: If you pass in a password, it will initalize the first record with the encrypted
                   1334: password.
                   1335:
1.31      andrew   1336: new() now also takes options in other formats
                   1337:
                   1338:     $pdb = new Palm::Keyring({ key1 => value1,  key2 => value2 });
                   1339:     $pdb = new Palm::Keyring( -key1 => value1, -key2 => value2);
                   1340:
1.37    ! andrew   1341: Supported options
1.31      andrew   1342:
                   1343: =over
                   1344:
                   1345: =item password
                   1346:
                   1347: The password used to initialize the database
                   1348:
                   1349: =item version
                   1350:
                   1351: The version of database to create.  Accepts either 4 or 5.  Currently defaults to 4.
                   1352:
                   1353: =item v4compatible
                   1354:
                   1355: The format of the fields passed to Encrypt and returned from Decrypt have changed.
                   1356: This allows programs to use the newer databases with few changes but with less features.
                   1357:
                   1358: =item cipher
                   1359:
                   1360: The cipher to use.  0, 1, 2 or 3.
                   1361:
                   1362:     0 => None
                   1363:     1 => DES_EDE3
                   1364:     2 => AES128
                   1365:     3 => AES256
                   1366:
                   1367: =item iterations
                   1368:
                   1369: The number of iterations to encrypt with.
                   1370:
1.37    ! andrew   1371: =item options
        !          1372:
        !          1373: A hashref of the options that are set
        !          1374:
1.31      andrew   1375: =back
                   1376:
1.36      andrew   1377: For v5 databases there are some additional appinfo fields set.
                   1378:
1.37    ! andrew   1379:     $pdb->{appinfo} = {
        !          1380:         # normal appinfo stuff described in L<Palm::StdAppInfo>
        !          1381:         cipher     => The index number of the cipher being used
        !          1382:         iter       => Number of iterations for the cipher
        !          1383:     };
1.36      andrew   1384:
1.34      andrew   1385: =head2 crypt
                   1386:
                   1387: Pass in the alias of the crypt to use, or the index.
                   1388:
                   1389: This is a function, not a method.
                   1390:
                   1391:     my $c = Palm::Keyring::crypt($cipher);
                   1392:
                   1393: $c is now:
                   1394:
                   1395:     $c = {
                   1396:         alias     => (None|DES_EDE3|AES128|AES256),
                   1397:         name      => (None|DES_EDE3|Rijndael),
                   1398:         keylen    => <key length of the ciphe>,
                   1399:         blocksize => <block size of the cipher>,
                   1400:         default_iter => <default iterations for the cipher>,
                   1401:     };
                   1402:
1.16      andrew   1403: =head2 Encrypt
1.11      andrew   1404:
1.34      andrew   1405:     $pdb->Encrypt($rec, $acct[, $password[, $ivec]]);
1.11      andrew   1406:
1.16      andrew   1407: Encrypts an account into a record, either with the password previously
                   1408: used, or with a password that is passed.
1.34      andrew   1409:
                   1410: $ivec is the initialization vector to use to encrypt the record.  This is
                   1411: not used by v4 databases.  Normally this is not passed and is generated
                   1412: randomly.
1.1       andrew   1413:
1.28      andrew   1414: $rec is a record from $pdb->{records} or a new_Record().
1.31      andrew   1415: The v4 $acct is a hashref in the format below.
1.1       andrew   1416:
1.31      andrew   1417:     my $v4acct = {
1.28      andrew   1418:         name       => $rec->{name},
1.20      andrew   1419:         account    => $account,
                   1420:         password   => $password,
                   1421:         notes      => $notes,
                   1422:         lastchange => {
                   1423:             year  => 107, # years since 1900
                   1424:             month =>   0, # 0-11, 0 = January, 11 = December
1.21      andrew   1425:             day   =>  30, # 1-31, same as localtime
1.20      andrew   1426:         },
1.16      andrew   1427:     };
1.7       andrew   1428:
1.31      andrew   1429: The v5 $acct is an arrayref full of hashrefs that contain each encrypted field.
                   1430:
                   1431:     my $v5acct = [
                   1432:         {
                   1433:             'label_id' => 2,
                   1434:             'data' => 'abcd1234',
                   1435:             'label' => 'password',
                   1436:             'font' => 0
                   1437:         },
                   1438:         {
                   1439:             'label_id' => 3,
                   1440:             'data' => {
                   1441:                 'month' => 1,
                   1442:                 'day' => 11,
                   1443:                 'year' => 107
                   1444:             },
                   1445:             'label' => 'lastchange',
                   1446:             'font' => 0
                   1447:         },
                   1448:         {
                   1449:             'label_id' => 255,
                   1450:             'data' => 'This is a short note.',
                   1451:             'label' => 'notes',
                   1452:             'font' => 0
                   1453:         }
                   1454:     ];
                   1455:
                   1456:
                   1457: The account name is stored in $rec->{name} for both v4 and v5 databases.
1.37    ! andrew   1458: It is not returned in the decrypted information for v5.
1.31      andrew   1459:
                   1460:     $rec->{name} = 'account name';
                   1461:
1.22      andrew   1462: If you have changed anything other than the lastchange, or don't pass in a
1.24      andrew   1463: lastchange key, Encrypt() will generate a new lastchange date for you.
1.22      andrew   1464:
                   1465: If you pass in a lastchange field that is different than the one in the
                   1466: record, it will honor what you passed in.
                   1467:
1.28      andrew   1468: Encrypt() only uses the $acct->{name} if there is not already a $rec->{name}.
1.22      andrew   1469:
1.16      andrew   1470: =head2 Decrypt
1.1       andrew   1471:
1.16      andrew   1472:     my $acct = $pdb->Decrypt($rec[, $password]);
1.1       andrew   1473:
1.31      andrew   1474: Decrypts the record and returns a reference for the account as described
1.20      andrew   1475: under Encrypt().
1.1       andrew   1476:
1.28      andrew   1477:     foreach (0..$#{ $pdb->{records}) {
1.31      andrew   1478:         next if $_ == 0 && $pdb->{version} == 4;
1.28      andrew   1479:         my $rec = $pdb->{records}->[$_];
1.31      andrew   1480:         my $acct = $pdb->Decrypt($rec);
1.16      andrew   1481:         # do something with $acct
                   1482:     }
1.1       andrew   1483:
1.31      andrew   1484:
1.16      andrew   1485: =head2 Password
1.1       andrew   1486:
1.16      andrew   1487:     $pdb->Password([$password[, $new_password]]);
1.1       andrew   1488:
1.16      andrew   1489: Either sets the password to be used to crypt, or if you pass $new_password,
                   1490: changes the password on the database.
1.1       andrew   1491:
1.16      andrew   1492: If you have created a new $pdb, and you didn't set a password when you
                   1493: called new(), you only need to pass one password and it will set that as
                   1494: the password.
1.1       andrew   1495:
1.24      andrew   1496: If nothing is passed, it forgets the password that it was remembering.
1.36      andrew   1497:
                   1498: After a successful password verification the following fields are set
                   1499:
                   1500: For v4
                   1501:
1.37    ! andrew   1502:     $pdb->{digest}   = the calculated digest used from the key;
        !          1503:     $pdb->{password} = the password that was passed in;
1.36      andrew   1504:
                   1505: For v5
                   1506:
1.37    ! andrew   1507:     $pdb->{appinfo} = {
        !          1508:         # As described under new() with these additional fields
        !          1509:         cipher     => The index number of the cipher being used
        !          1510:         iter       => Number of iterations for the cipher
        !          1511:         key        => The key that is calculated from the password
        !          1512:                       and salt and is used to decrypt the records.
        !          1513:         masterhash => the hash of the key that is stored in the
        !          1514:                       database.  Either set when Loading the database
        !          1515:                       or when setting a new password.
        !          1516:         salt       => the salt that is either read out of the database
        !          1517:                       or calculated when setting a new password.
        !          1518:     };
1.1       andrew   1519:
1.14      andrew   1520: =head1 DEPENDENCIES
1.1       andrew   1521:
1.14      andrew   1522: Palm::StdAppInfo
1.1       andrew   1523:
1.14      andrew   1524: Digest::MD5
1.9       andrew   1525:
1.14      andrew   1526: Crypt::DES
1.4       andrew   1527:
1.14      andrew   1528: Readonly
1.10      andrew   1529:
1.24      andrew   1530: =head1 THANKS
                   1531:
                   1532: I would like to thank the helpful Perlmonk shigetsu who gave me some great advice
                   1533: and helped me get my first module posted.  L<http://perlmonks.org/?node_id=596998>
                   1534:
                   1535: I would also like to thank
                   1536: Johan Vromans
                   1537: E<lt>jvromans@squirrel.nlE<gt> --
                   1538: L<http://www.squirrel.nl/people/jvromans>.
                   1539: He had his own Palm::KeyRing module that he posted a couple of days before
                   1540: mine was ready and he was kind enough to let me have the namespace as well
                   1541: as giving me some very helpful hints about doing a few things that I was
                   1542: unsure of.  He is really great.
                   1543:
1.14      andrew   1544: =head1 BUGS AND LIMITATIONS
1.1       andrew   1545:
1.14      andrew   1546: Please report any bugs or feature requests to
                   1547: C<bug-palm-keyring at rt.cpan.org>, or through the web interface at
                   1548: L<http://rt.cpan.org>.  I will be notified, and then you'll automatically be
                   1549: notified of progress on your bug as I make changes.
1.1       andrew   1550:
                   1551: =head1 AUTHOR
                   1552:
1.27      andrew   1553: Andrew Fresh E<lt>andrew@cpan.orgE<gt>
1.1       andrew   1554:
1.14      andrew   1555: =head1 LICENSE AND COPYRIGHT
                   1556:
                   1557: Copyright 2004, 2005, 2006, 2007 Andrew Fresh, All Rights Reserved.
                   1558:
1.15      andrew   1559: This program is free software; you can redistribute it and/or
                   1560: modify it under the same terms as Perl itself.
1.14      andrew   1561:
1.1       andrew   1562: =head1 SEE ALSO
                   1563:
                   1564: Palm::PDB(3)
                   1565:
                   1566: Palm::StdAppInfo(3)
1.11      andrew   1567:
                   1568: The Keyring for Palm OS website:
                   1569: L<http://gnukeyring.sourceforge.net/>
1.31      andrew   1570:
                   1571: The HACKING guide for palm keyring databases:
                   1572: L<http://gnukeyring.cvs.sourceforge.net/*checkout*/gnukeyring/keyring/HACKING>
1.24      andrew   1573:
                   1574: Johan Vromans also has a wxkeyring app that now uses this module, available
1.27      andrew   1575: from his website at L<http://www.vromans.org/johan/software/sw_palmkeyring.html>

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>