[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.34

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

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