Convert-ASN1-0.34/0000775000175000017500000000000014464272101011727 5ustar timtimConvert-ASN1-0.34/Makefile.PL0000644000175000017500000000202014464272101013671 0ustar timtim# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.030. use strict; use warnings; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "Convert between perl data structures and ASN.1 encoded packets", "AUTHOR" => "Graham Barr ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Convert-ASN1", "LICENSE" => "perl", "NAME" => "Convert::ASN1", "PREREQ_PM" => {}, "TEST_REQUIRES" => { "Math::BigInt" => "1.997", "Test::More" => "0.90" }, "VERSION" => "0.34", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Math::BigInt" => "1.997", "Test::More" => "0.90" ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Convert-ASN1-0.34/cpanfile0000644000175000017500000000046614464272101013437 0ustar timtim# This file is generated by Dist::Zilla::Plugin::CPANFile v6.030 # Do not edit this file directly. To change prereqs, edit the `dist.ini` file. on 'test' => sub { requires "Math::BigInt" => "1.997"; requires "Test::More" => "0.90"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "0"; }; Convert-ASN1-0.34/examples/0000775000175000017500000000000014464272101013545 5ustar timtimConvert-ASN1-0.34/examples/ldap-search0000644000175000017500000000255514464272101015660 0ustar timtim# This is an example of a search PDU from the LDAP protocol use Convert::ASN1; use Data::Dumper; my %scope = qw(base 0 one 1 single 1 sub 2 subtree 2); my %deref = qw(never 0 search 1 find 2 always 3); my $search_pdu = Convert::ASN1->new; $search_pdu->prepare(q( SEQUENCE { mesgid INTEGER, [APPLICATION 3] SEQUENCE { base STRING, scope ENUM, deref ENUM, sizeLimit INTEGER, timeLimit INTEGER, typesOnly BOOLEAN, filter STRING, -- for test, should be ANY and the var should hold -- a pre-encoded filter attrs SEQUENCE OF STRING } control [0] SEQUENCE OF SEQUENCE { -- this should be optional but we cannot do that inline type STRING, critical BOOLEAN, value STRING OPTIONAL } } )) or die $search_pdu->error; $buf = $search_pdu->encode( mesgid => 3, base => "cn=base", scope => $scope{one}, deref => $deref{find}, sizeLimit => 0, timeLimit => 0, typesOnly => 0, filter => "A filter", attrs => [qw(cn postalAddress)], control => [ { type => "1.2.3.4", critical => 1 }, { type => "9.8.7.6", critical => 0, value => "abc" } ] ); $Data::Dumper::Indent = 1; print Dumper( $search_pdu->decode($buf)); $h = unpack("H*",$buf); $h =~ s/(..)/$1 /g; $h =~ s/(.{47}\s)/$1\n/g; print $h,"\n"; Convert-ASN1-0.34/examples/ldap0000644000175000017500000003215614464272101014415 0ustar timtim$desc = <<'ESQ'; LDAPMessage ::= SEQUENCE { messageID MessageID, protocolOp CHOICE { bindRequest BindRequest, bindResponse BindResponse, unbindRequest UnbindRequest, searchRequest SearchRequest, searchResEntry SearchResultEntry, searchResDone SearchResultDone, searchResRef SearchResultReference, modifyRequest ModifyRequest, modifyResponse ModifyResponse, addRequest AddRequest, addResponse AddResponse, delRequest DelRequest, delResponse DelResponse, modDNRequest ModifyDNRequest, modDNResponse ModifyDNResponse, compareRequest CompareRequest, compareResponse CompareResponse, abandonRequest AbandonRequest, extendedReq ExtendedRequest, extendedResp ExtendedResponse } controls [0] Controls OPTIONAL } MessageID ::= INTEGER -- (0 .. maxInt) -- maxInt INTEGER ::= 2147483647 -- (2^^31 - 1) -- LDAPString ::= OCTET STRING LDAPOID ::= OCTET STRING LDAPDN ::= LDAPString RelativeLDAPDN ::= LDAPString AttributeType ::= LDAPString AttributeDescription ::= LDAPString AttributeDescriptionList ::= SEQUENCE OF AttributeDescription AttributeValue ::= OCTET STRING AttributeValueAssertion ::= SEQUENCE { attributeDesc AttributeDescription, assertionValue AssertionValue } AssertionValue ::= OCTET STRING Attribute ::= SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } MatchingRuleId ::= LDAPString LDAPResult ::= SEQUENCE { resultCode ENUMERATED { success (0), operationsError (1), protocolError (2), timeLimitExceeded (3), sizeLimitExceeded (4), compareFalse (5), compareTrue (6), authMethodNotSupported (7), strongAuthRequired (8), -- 9 reserved -- referral (10), -- new adminLimitExceeded (11), -- new unavailableCriticalExtension (12), -- new confidentialityRequired (13), -- new saslBindInProgress (14), -- new noSuchAttribute (16), undefinedAttributeType (17), inappropriateMatching (18), constraintViolation (19), attributeOrValueExists (20), invalidAttributeSyntax (21), -- 22-31 unused -- noSuchObject (32), aliasProblem (33), invalidDNSyntax (34), -- 35 reserved for undefined isLeaf -- aliasDereferencingProblem (36), -- 37-47 unused -- inappropriateAuthentication (48), invalidCredentials (49), insufficientAccessRights (50), busy (51), unavailable (52), unwillingToPerform (53), loopDetect (54), -- 55-63 unused -- namingViolation (64), objectClassViolation (65), notAllowedOnNonLeaf (66), notAllowedOnRDN (67), entryAlreadyExists (68), objectClassModsProhibited (69), -- 70 reserved for CLDAP -- affectsMultipleDSAs (71), -- new -- 72-79 unused -- other (80)} -- 81-90 reserved for APIs -- matchedDN LDAPDN, errorMessage LDAPString, referral [3] Referral OPTIONAL } Referral ::= SEQUENCE OF LDAPURL LDAPURL ::= LDAPString -- limited to characters permitted in URLs Controls ::= SEQUENCE OF Control Control ::= SEQUENCE { controlType LDAPOID, criticality BOOLEAN , -- DEFAULT FALSE, controlValue OCTET STRING OPTIONAL } BindRequest ::= [APPLICATION 0] SEQUENCE { version INTEGER, -- (1 .. 127), name LDAPDN, authentication AuthenticationChoice } AuthenticationChoice ::= CHOICE { simple [0] OCTET STRING, -- 1 and 2 reserved sasl [3] SaslCredentials } SaslCredentials ::= SEQUENCE { mechanism LDAPString, credentials OCTET STRING OPTIONAL } BindResponse ::= [APPLICATION 1] SEQUENCE { COMPONENTS OF LDAPResult, serverSaslCreds [7] OCTET STRING OPTIONAL } UnbindRequest ::= [APPLICATION 2] NULL SearchRequest ::= [APPLICATION 3] SEQUENCE { baseObject LDAPDN, scope ENUMERATED { baseObject (0), singleLevel (1), wholeSubtree (2) } derefAliases ENUMERATED { neverDerefAliases (0), derefInSearching (1), derefFindingBaseObj (2), derefAlways (3) } sizeLimit INTEGER , -- (0 .. maxInt), timeLimit INTEGER , -- (0 .. maxInt), typesOnly BOOLEAN, filter Filter, attributes AttributeDescriptionList } Filter ::= CHOICE { and [0] SET OF Filter, or [1] SET OF Filter, not [2] Filter, equalityMatch [3] AttributeValueAssertion, substrings [4] SubstringFilter, greaterOrEqual [5] AttributeValueAssertion, lessOrEqual [6] AttributeValueAssertion, present [7] AttributeDescription, approxMatch [8] AttributeValueAssertion, extensibleMatch [9] MatchingRuleAssertion } SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleId OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN } -- DEFAULT FALSE } SearchResultEntry ::= [APPLICATION 4] SEQUENCE { objectName LDAPDN, attributes PartialAttributeList } PartialAttributeList ::= SEQUENCE OF SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } SearchResultReference ::= [APPLICATION 19] SEQUENCE OF LDAPURL SearchResultDone ::= [APPLICATION 5] LDAPResult ModifyRequest ::= [APPLICATION 6] SEQUENCE { object LDAPDN, modification SEQUENCE OF SEQUENCE { operation ENUMERATED { add (0), delete (1), replace (2) } modification AttributeTypeAndValues } } AttributeTypeAndValues ::= SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } ModifyResponse ::= [APPLICATION 7] LDAPResult AddRequest ::= [APPLICATION 8] SEQUENCE { entry LDAPDN, attributes AttributeList } AttributeList ::= SEQUENCE OF SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } AddResponse ::= [APPLICATION 9] LDAPResult DelRequest ::= [APPLICATION 10] LDAPDN DelResponse ::= [APPLICATION 11] LDAPResult ModifyDNRequest ::= [APPLICATION 12] SEQUENCE { entry LDAPDN, newrdn RelativeLDAPDN, deleteoldrdn BOOLEAN, newSuperior [0] LDAPDN OPTIONAL } ModifyDNResponse ::= [APPLICATION 13] LDAPResult CompareRequest ::= [APPLICATION 14] SEQUENCE { entry LDAPDN, ava AttributeValueAssertion } CompareResponse ::= [APPLICATION 15] LDAPResult AbandonRequest ::= [APPLICATION 16] MessageID ExtendedRequest ::= [APPLICATION 23] SEQUENCE { requestName [0] LDAPOID, requestValue [1] OCTET STRING OPTIONAL } ExtendedResponse ::= [APPLICATION 24] SEQUENCE { COMPONENTS OF LDAPResult, responseName [10] LDAPOID OPTIONAL, response [11] OCTET STRING OPTIONAL } VirtualListViewRequest ::= SEQUENCE { beforeCount INTEGER , --(0 .. maxInt), afterCount INTEGER , --(0 .. maxInt), CHOICE { byIndex [0] SEQUENCE { index INTEGER , --(0 .. maxInt), contentCount INTEGER } --(0 .. maxInt) } byValue [1] AssertionValue } -- byValue [1] greaterThanOrEqual assertionValue } contextID OCTET STRING OPTIONAL } VirtualListViewResponse ::= SEQUENCE { targetPosition INTEGER , --(0 .. maxInt), contentCount INTEGER , --(0 .. maxInt), virtualListViewResult ENUMERATED { success (0), operatonsError (1), unwillingToPerform (53), insufficientAccessRights (50), busy (51), timeLimitExceeded (3), adminLimitExceeded (11), sortControlMissing (60), indexRangeError (61), other (80) } } ESQ use lib 'lib'; use Convert::ASN1 qw(:debug); use Convert::ASN1::Debug qw(asn_dump asn_hexdump); $asn = Convert::ASN1->new; $asn->prepare($desc) or die $asn->error; #$asn->dump; $filter = $asn->find('Filter'); # A Filter # (&(!(desc=value))(|(xx=x*y*)(yy=*1*2))) $buf = $filter->encode( { and => [ { not => { equalityMatch => { attributeDesc => 'desc', assertionValue => 'value' } } }, { or => [ { substrings => { type => 'xx', substrings => [ { initial => 'x' }, { any => 'y' } ] } }, { substrings => { type => 'yy', substrings => [ { any => 1 }, { final => 2 } ] } } ] } ] } ) or die $filter->error; asn_dump($buf); $ret = $filter->decode($buf) or die $filter->error; use Data::Dumper; $Data::Dumper::Indent=1; $Data::Dumper::Quotekeys=0; print Dumper($ret); Convert-ASN1-0.34/examples/tsa31610000644000175000017500000004433714464272101014603 0ustar timtim#!/usr/bin/perl # # EdelStamp (C) 2000-2016, ON-X, All rights reserved. # Author: Peter Sylvester # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Function: Create RFC 3161 time stamps # Runs as CGI when REQUEST_METHOD is present. # # Input: The program needs three environment variables: # TSAKeyFile name of a pem encoded RS private key # TSACertificateFile name of a der encoded certficate for the key # TSAPolicy a list of dot separated numbers # # If the program finds REQUEST_METHOD, httpd context is assumed # program reads a time stamp request from STDIN # The REQUEST_METHOD must be POST # # Output: A time stamp response (if http response is 200) to STDOUT. # if under http context headers are prepended. # Not details of errors are provided when status=2=rejected # # Errors: Error details are written to STDERR and can be written to Syslog in # and httpd context: # Environement varibles SyslogOptions and SyslogFacility are used for parameterization # See perl module Sys::Syslog fpr details # Notes: Policy on input is ignored, hash algorithms are not checked and copied as is. # Since the maximim size of a request is limited, it is unlikely that a request # contains the data instead of a hash. # Example: The following example are for the apache httpd server configuration # # ScriptAlias "/tsa/" "/var/www/cgi-bin/" # # AllowOverride None # Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch # Require all granted # SetEnv TSACertificateFile /etc/apache2/pki/TSA.der # SetEnv TSAKeyFile /etc/apache2/pki/TSA.key # SetEnv TSAPolicy 1.2.3.4.1 # SetEnv TSATimeout 15 # SetEnv TSARequestLimit 500 # SetEnv SyslogOptions "nofatal,ndelay,pid" # SetEnv SyslogFacility "user" # use strict; use warnings; use Convert::ASN1; use Time::HiRes; use Digest::SHA qw(sha256 sha1); use Crypt::OpenSSL::RSA; #{status=> {status=>2}} hard coded. my $rejected = "\x30\x05\x30\x03\x02\x01\x02"; binmode(STDOUT); binmode(STDIN); binmode(STDERR,':utf8'); # we like to test out a web server. my $HTTP = defined $ENV{'REQUEST_METHOD'} ; # and we can do syslog my $SYSLOG = ($HTTP && defined $ENV{'SyslogOptions'}); if ($SYSLOG) { use Sys::Syslog ; $ENV{'SyslogFacility'} = 'user' unless $ENV{'SyslogFacility'} ; openlog('EdelStamp', $ENV{'SyslogOptions'}, $ENV{'SyslogFacility'}) or dieif(1,'Cannot open Syslog'); } print "Content-Type: application/timestamp-response\n" ."Content-Transfer-Encoding: binary\n" if $HTTP; # To be or not to be sorry sub dieif { my ($cond,$text) = @_; return unless $cond; print "Content-Length: ".length($rejected)."\n\n" if $HTTP; print $rejected; print STDERR "$text\n"; syslog("info", $ENV{'REMOTE_ADDR'} . " $text") if $SYSLOG; exit ; } # To leave some traces sub log { my ($text) = @_; print STDERR "$text\n"; syslog("info", $ENV{'REMOTE_ADDR'} . " $text") if $SYSLOG; } # Ok, start parse the ASN. It would be nice to have them directly. my $asn = Convert::ASN1->new; $asn->prepare(q< TimeStampReq ::= SEQUENCE { version INTEGER , messageImprint MessageImprint, reqPolicy TSAPolicyId OPTIONAL, nonce INTEGER OPTIONAL, certReq BOOLEAN OPTIONAL, extensions [0] IMPLICIT Extensions OPTIONAL } MessageImprint ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier, hashedMessage OCTET STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters NULL } TSAPolicyId ::= OBJECT IDENTIFIER Extensions ::= SEQUENCE OF Extension Extension ::= SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN OPTIONAL, extnValue OCTET STRING } TimeStampResp ::= SEQUENCE { status PKIStatusInfo, timeStampToken TimeStampToken OPTIONAL } PKIStatusInfo ::= SEQUENCE { status PKIStatus, statusString PKIFreeText OPTIONAL, failInfo PKIFailureInfo OPTIONAL } PKIStatus ::= INTEGER PKIFailureInfo ::= BIT STRING PKIFreeText ::= SEQUENCE OF UTF8String TimeStampToken ::= SEQUENCE { contentType ContentType, content [0] EXPLICIT SignedData } ContentType ::= OBJECT IDENTIFIER TSTInfo ::= SEQUENCE { version INTEGER , policy TSAPolicyId, messageImprint MessageImprint, serialNumber INTEGER, genTime GeneralizedTime, accuracy Accuracy OPTIONAL, ordering BOOLEAN OPTIONAL, nonce INTEGER OPTIONAL, tsa [0] GeneralName OPTIONAL, extensions [1] IMPLICIT Extensions OPTIONAL } Accuracy ::= SEQUENCE { seconds INTEGER OPTIONAL, millis [0] INTEGER OPTIONAL, micros [1] INTEGER OPTIONAL } Attribute ::= SEQUENCE { type AttributeType, values SET OF AttributeValue } AttributeType ::= OBJECT IDENTIFIER AttributeValue ::= ANY AttributeTypeAndValue ::= SEQUENCE { type AttributeType, value AttributeValue } Name ::= CHOICE { -- only one possibility for now rdnSequence RDNSequence } RDNSequence ::= SEQUENCE OF RelativeDistinguishedName DistinguishedName ::= RDNSequence RelativeDistinguishedName ::= SET OF AttributeTypeAndValue --SET SIZE (1 .. MAX) OF DirectoryString ::= CHOICE { teletexString TeletexString, --(SIZE (1..MAX)), printableString PrintableString, --(SIZE (1..MAX)), bmpString BMPString, --(SIZE (1..MAX)), universalString UniversalString, --(SIZE (1..MAX)), utf8String UTF8String, --(SIZE (1..MAX)), ia5String IA5String --added for EmailAddress } Certificate ::= SEQUENCE { tbsCertificate TBSCertificate, signatureAlgorithm AlgorithmIdentifier, signature BIT STRING } TBSCertificate ::= SEQUENCE { version [0] EXPLICIT Version OPTIONAL, --DEFAULT v1 serialNumber CertificateSerialNumber, signature AlgorithmIdentifier, issuer Name, validity Validity, subject Name, subjectPublicKeyInfo SubjectPublicKeyInfo, issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version shall be v2 or v3 subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version shall be v2 or v3 extensions [3] EXPLICIT Extensions OPTIONAL -- If present, version shall be v3 } Version ::= INTEGER --{ v1(0), v2(1), v3(2) } CertificateSerialNumber ::= INTEGER Validity ::= SEQUENCE { notBefore Time, notAfter Time } UniqueIdentifier ::= BIT STRING SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY } GeneralNames ::= SEQUENCE OF GeneralName GeneralName ::= CHOICE { otherName [0] AnotherName, rfc822Name [1] IA5String, dNSName [2] IA5String, x400Address [3] ANY, --ORAddress, directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER } AnotherName ::= SEQUENCE { type OBJECT IDENTIFIER, value [0] EXPLICIT ANY } --DEFINED BY type-id } EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1] DirectoryString } IssuerAltName ::= GeneralNames SubjectDirectoryAttributes ::= SEQUENCE OF Attribute EncapsulatedContentInfo ::= SEQUENCE { eContentType ContentType, eContent [0] EXPLICIT OCTET STRING OPTIONAL } ContentType ::= OBJECT IDENTIFIER CMSVersion ::= INTEGER DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier DigestAlgorithmIdentifier ::= AlgorithmIdentifier SignerInfo ::= SEQUENCE { version CMSVersion, sid SignerIdentifier, digestAlgorithm DigestAlgorithmIdentifier, signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL, signatureAlgorithm SignatureAlgorithmIdentifier, signature SignatureValue, unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL } SignerIdentifier ::= CHOICE { issuerAndSerialNumber IssuerAndSerialNumber, subjectKeyIdentifier [0] OCTET STRING } SignatureAlgorithmIdentifier ::= AlgorithmIdentifier SignedAttributes ::= SET OF ANY UnsignedAttributes ::= SET OF ANY CMSAttribute ::= SEQUENCE { attrType OBJECT IDENTIFIER, attrValues SET OF CMSAttributeValue } CMSAttributeValue ::= ANY SignatureValue ::= OCTET STRING IssuerAndSerialNumber ::= SEQUENCE { issuer Name, serialNumber CertificateSerialNumber } CertificateSerialNumber ::= INTEGER SigningTime ::= Time Time ::= CHOICE { utcTime UTCTime, generalTime GeneralizedTime } MessageDigest ::= OCTET STRING SignedData ::= SEQUENCE { version CMSVersion, digestAlgorithms DigestAlgorithmIdentifiers, encapContentInfo EncapsulatedContentInfo, certificates [0] IMPLICIT CertificateSet OPTIONAL, -- crls [1] IMPLICIT RevocationInfoChoices OPTIONAL, signerInfos SignerInfos } DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier SignerInfos ::= SET OF SignerInfo CertificateSet ::= SET OF CertificateChoices SigningCertificate ::= SEQUENCE { certs SEQUENCE OF ESSCertID, policies SEQUENCE OF PolicyInformation OPTIONAL } PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, policyQualifiers SEQUENCE OF PolicyQualifierInfo } --OPTIONAL } CertPolicyId ::= OBJECT IDENTIFIER PolicyQualifierInfo ::= SEQUENCE { policyQualifierId PolicyQualifierId, qualifier ANY } --DEFINED BY policyQualifierId } PolicyQualifierId ::= OBJECT IDENTIFIER --( id-qt-cps | id-qt-unotice ) -- CPS pointer qualifier CPSuri ::= IA5String -- user notice qualifier UserNotice ::= SEQUENCE { noticeRef NoticeReference OPTIONAL, explicitText DisplayText OPTIONAL} NoticeReference ::= SEQUENCE { organization DisplayText, noticeNumbers SEQUENCE OF INTEGER } DisplayText ::= CHOICE { visibleString VisibleString , bmpString BMPString , utf8String UTF8String } ESSCertID ::= SEQUENCE { certHash OCTET STRING, -- SHA1 hash of entire certificate issuerSerial IssuerSerial OPTIONAL } IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber CertificateSerialNumber } CertificateChoices ::= CHOICE { certificate ANY -- we already have it encoded -- v2AttrCert [2] IMPLICIT AttributeCertificateV2, -- other [3] IMPLICIT OtherCertificateFormat } >) or &dieif(1, "Bad ASN1 definitions: " . $asn->error) ; # a little helper sub asnfind { my ($macro) = @_; my $asn_macro = $asn->find($macro) or &dieif(1,"No ASN1 syntax for '$macro'"); return $asn_macro; } # can we give a response? my $asn_resp = &asnfind('TimeStampResp'); $asn_resp->configure('encoding','DER'); # can we parse? my $asn_tspreq = &asnfind('TimeStampReq'); &dieif(!$HTTP || $ENV{CONTENT_TYPE} ne 'application/timestamp-query',"Invalid content type received"); &dieif(!$HTTP || $ENV{'REQUEST_METHOD'} ne 'POST',"Request Method is not POST"); # requests are small, we don't want large files here and we timeout, # we don't care about contentlength my $cnt=$ENV{'TSATimeout'}+0; $cnt=15 unless $cnt>2 && $cnt<120; my $limit=$ENV{'TSARequestLimit'}+0; $limit=300 unless $limit>5 && $cnt<20000; # normally a request comes in one packet, but we never know. my $pdu=''; while ($cnt-- >0) { my $asn_tspreq = &asnfind('TimeStampReq'); my $next; read STDIN, $next, $limit; if ($next eq '') { sleep(1); } else { $pdu .= $next; &dieif(($cnt <= 0),"Timeout"); &dieif((length($pdu)>$limit),"Request too long"); my $tspreq = $asn_tspreq->decode($pdu); } last unless $asn_tspreq->error() ; } my $tspreq = $asn_tspreq->decode($pdu); &dieif($asn_tspreq->error(),'Invalid request'); &dieif($tspreq->{'version'} != 1,'Invalid version'); # get policy, cert and key { &dieif(!$ENV{'TSAPolicy'}); my $asn_policyid=&asnfind('TSAPolicyId'); $asn_policyid->encode($ENV{'TSAPolicy'}); &dieif($asn_policyid->error(),"Invalid TSAPolicy syntax"); } my $tsa_cert; my $tsa_cert_asn; my $certDigest; { # get certificate my $filename = $ENV{'TSACertificateFile'} or &dieif(1, "Missing environment variable 'TSACertificateFile'"); my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $filename; open TSACERT, "<$filename" or &dieif(1, "cannot open TSACertificateFile '$filename'"); binmode TSACERT; read TSACERT, $tsa_cert_asn, $size; close TSACERT; $certDigest=sha1($tsa_cert_asn); my $asn_cert=&asnfind('Certificate'); $tsa_cert = $asn_cert->decode( $tsa_cert_asn) or &dieif(1, $asn_cert->error()); } my $tsa_key; { # get key my $filename = $ENV{'TSAKeyFile'} or &dieif(1, "Missing environment variable 'TSAKeyFile'");; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $filename; open TSAKEY, "<$filename" or &dieif(1,"cannot open TSAKeyFile '$filename'"); binmode TSAKEY; my $tsa_key_pem; read TSAKEY, $tsa_key_pem, $size; close TSAKEY; $tsa_key = Crypt::OpenSSL::RSA->new_private_key($tsa_key_pem) or &dieif(1,"TSAKeyFile '$filename' cannot be decoded"); } # some magic my $time = Time::HiRes::gettimeofday() ; my $now = int($time); my $serial = ($time-1288070000)*1000000*100000 +$$; my $TSTInfo_asn = &asnfind('TSTInfo'); $TSTInfo_asn->configure('encoding','DER'); $TSTInfo_asn->configure('encode',{time=>'withzone'}); $TSTInfo_asn->configure('encode',{timezone=>0}); # TBD: Add whatever logic you want to fill the TSTInfo, e.g. accurancy, take policy from input. # check the validity of the digest, OIDs + length. my $tstinfo = { version=>1, policy=>$ENV{'TSAPolicy'}, messageImprint=> $tspreq->{'messageImprint'}, genTime=>$now, serialNumber=>$serial, tsa=>{directoryName=>$tsa_cert->{'tbsCertificate'}->{'subject'}} }; $tstinfo->{'nonce'} = $tspreq->{'nonce'} if defined $tspreq->{'nonce'}; # encode the content my $tstinfostr=$TSTInfo_asn->encode($tstinfo) || &dieif(1,"Cannot encode TSTINFO:" .$TSTInfo_asn->error()); # and hash it with sha256 my $DigestAlgorithmIdentifiers=[]; $DigestAlgorithmIdentifiers->[0]={algorithm=>'2 16 840 1 101 3 4 2 1',parameters=>"\x05\x00"}; my $DigestAlgorithmIdentifiers_asn = &asnfind('DigestAlgorithmIdentifiers') ; my $contentDigest=sha256($tstinfostr); # encode message attributes my @CMSAttributeList; my $CMSAttribute_asn = &asnfind('CMSAttribute'); { my $CMSAttributevalue_asn = &asnfind('ContentType'); my $l = []; $l->[0] = $CMSAttributevalue_asn->encode('1.2.840.113549.1.9.16.1.4'); my $CMSAttribute={attrType=>'1.2.840.113549.1.9.3', attrValues=>$l}; push @CMSAttributeList,$CMSAttribute_asn->encode($CMSAttribute); } { my $CMSAttributevalue_asn = &asnfind('SigningTime') ; my $l = []; $l->[0] = $CMSAttributevalue_asn->encode(generalTime=>$now); my $CMSAttribute={attrType=>'1.2.840.113549.1.9.5', attrValues=>$l}; push @CMSAttributeList,$CMSAttribute_asn->encode($CMSAttribute); } { my $CMSAttributevalue_asn = &asnfind('MessageDigest') ; my $l = []; $l->[0] = $CMSAttributevalue_asn->encode($contentDigest); my $CMSAttribute={attrType=>'1.2.840.113549.1.9.4', attrValues=>$l}; push @CMSAttributeList,$CMSAttribute_asn->encode($CMSAttribute); } { my $CMSAttributevalue_asn = &asnfind('SigningCertificate') ; my $SC=[]; $SC->[0] = {certHash=>$certDigest}; my $l = []; $l->[0] = $CMSAttributevalue_asn->encode({certs=>$SC}); my $CMSAttribute={attrType=>'1.2.840.113549.1 9.16.2.12', attrValues=>$l}; push @CMSAttributeList,$CMSAttribute_asn->encode($CMSAttribute); } my @SortedAttributes = sort @CMSAttributeList; # needed for DER, just to be sure. my $CMSAttributes_asn = &asnfind('SignedAttributes') ; my $TBSattrs=$CMSAttributes_asn->encode(\@SortedAttributes) or &dieif(1,$CMSAttributes_asn->error()); # create and sign a signerinfo $tsa_key->use_sha256_hash(); my $SignerInfos=[]; $SignerInfos->[0] = { version =>1, digestAlgorithm=>$DigestAlgorithmIdentifiers->[0], sid=>{issuerAndSerialNumber=>{issuer=>$tsa_cert->{'tbsCertificate'}->{'issuer'}, serialNumber=>$tsa_cert->{'tbsCertificate'}->{'serialNumber'},}}, signedAttrs=>\@SortedAttributes, signatureAlgorithm=>$DigestAlgorithmIdentifiers->[0], signature=>$tsa_key->sign($TBSattrs), }; # finish the token and response my $CertificateSet=[]; $CertificateSet->[0]={certificate=>$tsa_cert_asn}; my $TimeStampToken={ contentType=>'1 2 840 113549 1 7 2', content=>{ version=>3, digestAlgorithms=>$DigestAlgorithmIdentifiers, encapContentInfo=>{ eContentType=>'1.2.840.113549.1.9.16.1.4', eContent=>$tstinfostr }, certificates=>$CertificateSet, signerInfos=>$SignerInfos, }}; my $response = $asn_resp->encode({status=> {status=>0},timeStampToken=>$TimeStampToken}) or &dieif(1,"Cannot create Timestampresponse"); print STDOUT "Content-Disposition: Attachment; filename=$now-$$.tsr\n"; print STDOUT "Content-Length:" .length($response) . "\n\n" if $HTTP; print STDOUT $response; my $messageImprint_asn = &asnfind('MessageImprint'); my $messageImprint= $messageImprint_asn->encode($tspreq->{'messageImprint'}) or &dieif(1,$messageImprint_asn->error()); &log('ReceivedHash ' . unpack('H*', $messageImprint) . ' SignedAtributes ' . unpack("H*",$TBSattrs) ) ; # This is the end (for now) Convert-ASN1-0.34/examples/x509decode0000644000175000017500000003132014464272101015336 0ustar timtim#!/usr/bin/perl # $Id: x509decode,v 1.1 2002/02/10 16:41:28 gbarr Exp $ # (c) 2001-2002 Norbert Klasen, DAASI International GmbH. All rights reserved. # This package is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # decode X.509 certificates # # varable naming # Convert::ASN1 objects are prefixed with asn_ # variables holding binary DER content are prefixed with der_ use strict; use Data::Dumper; $Data::Dumper::Indent=1; $Data::Dumper::Quotekeys=1; $Data::Dumper::Useqq=1; use Convert::ASN1 qw(:io :debug); # parse ASN.1 desciptions my $asn = Convert::ASN1->new; $asn->prepare(<error; -- ASN.1 from RFC2459 and X.509(2001) -- Adapted for use with Convert::ASN1 -- attribute data types -- Attribute ::= SEQUENCE { type AttributeType, values SET OF AttributeValue -- at least one value is required -- } AttributeType ::= OBJECT IDENTIFIER AttributeValue ::= DirectoryString --ANY AttributeTypeAndValue ::= SEQUENCE { type AttributeType, value AttributeValue } -- naming data types -- Name ::= CHOICE { -- only one possibility for now rdnSequence RDNSequence } RDNSequence ::= SEQUENCE OF RelativeDistinguishedName DistinguishedName ::= RDNSequence RelativeDistinguishedName ::= SET OF AttributeTypeAndValue --SET SIZE (1 .. MAX) OF -- Directory string type -- DirectoryString ::= CHOICE { teletexString TeletexString, --(SIZE (1..MAX)), printableString PrintableString, --(SIZE (1..MAX)), bmpString BMPString, --(SIZE (1..MAX)), universalString UniversalString, --(SIZE (1..MAX)), utf8String UTF8String, --(SIZE (1..MAX)), ia5String IA5String --added for EmailAddress } -- certificate and CRL specific structures begin here Certificate ::= SEQUENCE { tbsCertificate TBSCertificate, signatureAlgorithm AlgorithmIdentifier, signature BIT STRING } TBSCertificate ::= SEQUENCE { version [0] EXPLICIT Version OPTIONAL, --DEFAULT v1 serialNumber CertificateSerialNumber, signature AlgorithmIdentifier, issuer Name, validity Validity, subject Name, subjectPublicKeyInfo SubjectPublicKeyInfo, issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version shall be v2 or v3 subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version shall be v2 or v3 extensions [3] EXPLICIT Extensions OPTIONAL -- If present, version shall be v3 } Version ::= INTEGER --{ v1(0), v2(1), v3(2) } CertificateSerialNumber ::= INTEGER Validity ::= SEQUENCE { notBefore Time, notAfter Time } Time ::= CHOICE { utcTime UTCTime, generalTime GeneralizedTime } UniqueIdentifier ::= BIT STRING SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING } Extensions ::= SEQUENCE OF Extension --SIZE (1..MAX) OF Extension Extension ::= SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN OPTIONAL, --DEFAULT FALSE, extnValue OCTET STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY OPTIONAL } --extensions AuthorityKeyIdentifier ::= SEQUENCE { keyIdentifier [0] KeyIdentifier OPTIONAL, authorityCertIssuer [1] GeneralNames OPTIONAL, authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } -- authorityCertIssuer and authorityCertSerialNumber shall both -- be present or both be absent KeyIdentifier ::= OCTET STRING SubjectKeyIdentifier ::= KeyIdentifier -- key usage extension OID and syntax -- id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } KeyUsage ::= BIT STRING --{ -- digitalSignature (0), -- nonRepudiation (1), -- keyEncipherment (2), -- dataEncipherment (3), -- keyAgreement (4), -- keyCertSign (5), -- cRLSign (6), -- encipherOnly (7), -- decipherOnly (8) } -- private key usage period extension OID and syntax -- id-ce-privateKeyUsagePeriod OBJECT IDENTIFIER ::= { id-ce 16 } PrivateKeyUsagePeriod ::= SEQUENCE { notBefore [0] GeneralizedTime OPTIONAL, notAfter [1] GeneralizedTime OPTIONAL } -- either notBefore or notAfter shall be present -- certificate policies extension OID and syntax -- id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } CertificatePolicies ::= SEQUENCE OF PolicyInformation PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, policyQualifiers SEQUENCE OF PolicyQualifierInfo } --OPTIONAL } CertPolicyId ::= OBJECT IDENTIFIER PolicyQualifierInfo ::= SEQUENCE { policyQualifierId PolicyQualifierId, qualifier ANY } --DEFINED BY policyQualifierId } -- Implementations that recognize additional policy qualifiers shall -- augment the following definition for PolicyQualifierId PolicyQualifierId ::= OBJECT IDENTIFIER --( id-qt-cps | id-qt-unotice ) -- CPS pointer qualifier CPSuri ::= IA5String -- user notice qualifier UserNotice ::= SEQUENCE { noticeRef NoticeReference OPTIONAL, explicitText DisplayText OPTIONAL} NoticeReference ::= SEQUENCE { organization DisplayText, noticeNumbers SEQUENCE OF INTEGER } DisplayText ::= CHOICE { visibleString VisibleString , bmpString BMPString , utf8String UTF8String } -- policy mapping extension OID and syntax -- id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } PolicyMappings ::= SEQUENCE OF SEQUENCE { issuerDomainPolicy CertPolicyId, subjectDomainPolicy CertPolicyId } -- subject alternative name extension OID and syntax -- id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } SubjectAltName ::= GeneralNames GeneralNames ::= SEQUENCE OF GeneralName GeneralName ::= CHOICE { otherName [0] AnotherName, rfc822Name [1] IA5String, dNSName [2] IA5String, x400Address [3] ANY, --ORAddress, directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER } -- AnotherName replaces OTHER-NAME ::= TYPE-IDENTIFIER, as -- TYPE-IDENTIFIER is not supported in the '88 ASN.1 syntax AnotherName ::= SEQUENCE { type OBJECT IDENTIFIER, value [0] EXPLICIT ANY } --DEFINED BY type-id } EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1] DirectoryString } -- issuer alternative name extension OID and syntax -- id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } IssuerAltName ::= GeneralNames -- id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } SubjectDirectoryAttributes ::= SEQUENCE OF Attribute -- basic constraints extension OID and syntax -- id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } BasicConstraints ::= SEQUENCE { cA BOOLEAN OPTIONAL, --DEFAULT FALSE, pathLenConstraint INTEGER OPTIONAL } -- name constraints extension OID and syntax -- id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees OPTIONAL, excludedSubtrees [1] GeneralSubtrees OPTIONAL } GeneralSubtrees ::= SEQUENCE OF GeneralSubtree GeneralSubtree ::= SEQUENCE { base GeneralName, minimum [0] BaseDistance OPTIONAL, --DEFAULT 0, maximum [1] BaseDistance OPTIONAL } BaseDistance ::= INTEGER -- policy constraints extension OID and syntax -- id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } PolicyConstraints ::= SEQUENCE { requireExplicitPolicy [0] SkipCerts OPTIONAL, inhibitPolicyMapping [1] SkipCerts OPTIONAL } SkipCerts ::= INTEGER -- CRL distribution points extension OID and syntax -- id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= {id-ce 31} cRLDistributionPoints ::= SEQUENCE OF DistributionPoint DistributionPoint ::= SEQUENCE { distributionPoint [0] DistributionPointName OPTIONAL, reasons [1] ReasonFlags OPTIONAL, cRLIssuer [2] GeneralNames OPTIONAL } DistributionPointName ::= CHOICE { fullName [0] GeneralNames, nameRelativeToCRLIssuer [1] RelativeDistinguishedName } ReasonFlags ::= BIT STRING --{ -- unused (0), -- keyCompromise (1), -- cACompromise (2), -- affiliationChanged (3), -- superseded (4), -- cessationOfOperation (5), -- certificateHold (6), -- privilegeWithdrawn (7), -- aACompromise (8) } -- extended key usage extension OID and syntax -- id-ce-extKeyUsage OBJECT IDENTIFIER ::= {id-ce 37} ExtKeyUsageSyntax ::= SEQUENCE OF KeyPurposeId KeyPurposeId ::= OBJECT IDENTIFIER -- extended key purpose OIDs -- id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } -- id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } -- id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } -- id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } -- id-kp-ipsecEndSystem OBJECT IDENTIFIER ::= { id-kp 5 } -- id-kp-ipsecTunnel OBJECT IDENTIFIER ::= { id-kp 6 } -- id-kp-ipsecUser OBJECT IDENTIFIER ::= { id-kp 7 } -- id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } ASN1 # decoders for basic types my $asn_BitString = Convert::ASN1->new(); $asn_BitString->prepare("bitString BIT STRING"); my $asn_OctetString = Convert::ASN1->new(); $asn_OctetString->prepare("octetString OCTET STRING"); # decoders for extensions my %extnoid2asn = ( '2.5.29.9' => $asn->find('SubjectDirectoryAttributes'), '2.5.29.14' => $asn_OctetString, #'SubjectKeyIdentifier', '2.5.29.15' => $asn_BitString, #'keyUsage', '2.5.29.16' => $asn->find('PrivateKeyUsagePeriod'), '2.5.29.17' => $asn->find('SubjectAltName'), '2.5.29.18' => $asn->find('IssuerAltName'), '2.5.29.19' => $asn->find('BasicConstraints'), # '2.5.29.20' => 'cRLNumber', # '2.5.29.21' => 'cRLReasons', # '2.5.29.23' => 'holdInstructionCode', # '2.5.29.24' => 'invalidityDate', # '2.5.29.27' => 'deltaCRLIndicator', # '2.5.29.28' => 'issuingDistributionPoint', # '2.5.29.29' => 'certificateIssuer', '2.5.29.30' => $asn->find('NameConstraints'), '2.5.29.31' => $asn->find('cRLDistributionPoints'), '2.5.29.32' => $asn->find('CertificatePolicies'), '2.5.29.33' => $asn->find('PolicyMappings'), '2.5.29.35' => $asn->find('AuthorityKeyIdentifier'), '2.5.29.36' => $asn->find('PolicyConstraints'), '2.5.29.37' => $asn->find('ExtKeyUsageSyntax'), # '2.5.29.40' => 'cRLStreamIdentifier', # '2.5.29.44' => 'cRLScope', # '2.5.29.45' => 'statusReferrals', # '2.5.29.46' => 'freshestCRL', # '2.5.29.47' => 'orderedList', # '2.5.29.51' => 'baseUpdateTime', # '2.5.29.53' => 'deltaInfo', # '2.5.29.54' => 'inhibitAnyPolicy', # netscape-cert-extensions '2.16.840.1.113730.1.1' => $asn_BitString, # netscape-cert-type '2.16.840.1.113730.1.2' => $asn->find('DirectoryString'), # netscape-base-url '2.16.840.1.113730.1.3' => $asn->find('DirectoryString'), # netscape-revocation-url '2.16.840.1.113730.1.4' => $asn->find('DirectoryString'), # netscape-ca-revocation-url '2.16.840.1.113730.1.7' => $asn->find('DirectoryString'), # netscape-cert-renewal-url '2.16.840.1.113730.1.8' => $asn->find('DirectoryString'), # netscape-ca-policy-url '2.16.840.1.113730.1.12' => $asn->find('DirectoryString'), # netscape-ssl-server-name '2.16.840.1.113730.1.13' => $asn->find('DirectoryString'), # netscape-comment ); my $asn_cert = $asn->find('Certificate'); while ( my $filename = shift ) { my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $filename; open FILE, "<$filename" or die "no such file"; binmode FILE; my $der_cert; read FILE, $der_cert, $size; close FILE; decodeCert( $der_cert ); } sub decodeCert { my $der_cert = shift; #asn_dump( $der_cert ); my $cert = $asn_cert->decode($der_cert) or die $asn_cert->error; #extensions foreach my $extension ( @{$cert->{'tbsCertificate'}->{'extensions'}} ) { #print "extension: ", $oid2extension{$extension->{'extnID'}}, "\n"; if ( exists $extnoid2asn{$extension->{'extnID'}} ) { $extension->{'extnValue'} = ($extnoid2asn{$extension->{'extnID'}})->decode( $extension->{'extnValue'} ); } else { print STDERR "unknown ", $extension->{'critical'} ? "critical " : "", "extension: ", $extension->{'extnID'}, "\n"; asn_dump( $extension->{'extnValue'} ); } } print Dumper( $cert ); } Convert-ASN1-0.34/LICENSE0000644000175000017500000004642414464272101012744 0ustar timtimThis software is copyright (c) 2023 by Graham Barr. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2023 by Graham Barr. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2023 by Graham Barr. This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Convert-ASN1-0.34/META.yml0000644000175000017500000000154414464272101013202 0ustar timtim--- abstract: 'Convert between perl data structures and ASN.1 encoded packets' author: - 'Graham Barr ' build_requires: Math::BigInt: '1.997' Test::More: '0.90' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.030, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Convert-ASN1 no_index: directory: - examples - lib/Convert/ASN1 - t resources: bugtracker: https://github.com/gbarr/perl-Convert-ASN1/issues repository: git://github.com/gbarr/perl-Convert-ASN1.git version: '0.34' x_generated_by_perl: v5.36.1 x_maintainers: - 'Timothy Legge ' x_serialization_backend: 'YAML::Tiny version 1.74' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' Convert-ASN1-0.34/parser.y0000644000175000017500000003337414464272101013425 0ustar timtim%token WORD 1 %token CLASS 2 %token SEQUENCE 3 %token SET 4 %token CHOICE 5 %token OF 6 %token IMPLICIT 7 %token EXPLICIT 8 %token OPTIONAL 9 %token LBRACE 10 %token RBRACE 11 %token COMMA 12 %token ANY 13 %token ASSIGN 14 %token NUMBER 15 %token ENUM 16 %token COMPONENTS 17 %token POSTRBRACE 18 %token DEFINED 19 %token BY 20 %token EXTENSION_MARKER 21 %{ # Copyright (c) 2000-2005 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Convert::ASN1::parser; use strict; use Convert::ASN1 qw(:all); use vars qw( $asn $yychar $yyerrflag $yynerrs $yyn @yyss $yyssp $yystate @yyvs $yyvsp $yylval $yys $yym $yyval ); BEGIN { Convert::ASN1->_internal_syms } my $yydebug=0; my %yystate; my %base_type = ( BOOLEAN => [ asn_encode_tag(ASN_BOOLEAN), opBOOLEAN ], INTEGER => [ asn_encode_tag(ASN_INTEGER), opINTEGER ], BIT_STRING => [ asn_encode_tag(ASN_BIT_STR), opBITSTR ], OCTET_STRING => [ asn_encode_tag(ASN_OCTET_STR), opSTRING ], STRING => [ asn_encode_tag(ASN_OCTET_STR), opSTRING ], NULL => [ asn_encode_tag(ASN_NULL), opNULL ], OBJECT_IDENTIFIER => [ asn_encode_tag(ASN_OBJECT_ID), opOBJID ], REAL => [ asn_encode_tag(ASN_REAL), opREAL ], ENUMERATED => [ asn_encode_tag(ASN_ENUMERATED), opINTEGER ], ENUM => [ asn_encode_tag(ASN_ENUMERATED), opINTEGER ], 'RELATIVE-OID' => [ asn_encode_tag(ASN_RELATIVE_OID), opROID ], SEQUENCE => [ asn_encode_tag(ASN_SEQUENCE | ASN_CONSTRUCTOR), opSEQUENCE ], EXPLICIT => [ asn_encode_tag(ASN_SEQUENCE | ASN_CONSTRUCTOR), opEXPLICIT ], SET => [ asn_encode_tag(ASN_SET | ASN_CONSTRUCTOR), opSET ], ObjectDescriptor => [ asn_encode_tag(ASN_UNIVERSAL | 7), opSTRING ], UTF8String => [ asn_encode_tag(ASN_UNIVERSAL | 12), opUTF8 ], NumericString => [ asn_encode_tag(ASN_UNIVERSAL | 18), opSTRING ], PrintableString => [ asn_encode_tag(ASN_UNIVERSAL | 19), opSTRING ], TeletexString => [ asn_encode_tag(ASN_UNIVERSAL | 20), opSTRING ], T61String => [ asn_encode_tag(ASN_UNIVERSAL | 20), opSTRING ], VideotexString => [ asn_encode_tag(ASN_UNIVERSAL | 21), opSTRING ], IA5String => [ asn_encode_tag(ASN_UNIVERSAL | 22), opSTRING ], UTCTime => [ asn_encode_tag(ASN_UNIVERSAL | 23), opUTIME ], GeneralizedTime => [ asn_encode_tag(ASN_UNIVERSAL | 24), opGTIME ], GraphicString => [ asn_encode_tag(ASN_UNIVERSAL | 25), opSTRING ], VisibleString => [ asn_encode_tag(ASN_UNIVERSAL | 26), opSTRING ], ISO646String => [ asn_encode_tag(ASN_UNIVERSAL | 26), opSTRING ], GeneralString => [ asn_encode_tag(ASN_UNIVERSAL | 27), opSTRING ], CharacterString => [ asn_encode_tag(ASN_UNIVERSAL | 28), opSTRING ], UniversalString => [ asn_encode_tag(ASN_UNIVERSAL | 28), opSTRING ], BMPString => [ asn_encode_tag(ASN_UNIVERSAL | 30), opSTRING ], BCDString => [ asn_encode_tag(ASN_OCTET_STR), opBCD ], CHOICE => [ '', opCHOICE ], ANY => [ '', opANY ], EXTENSION_MARKER => [ '', opEXTENSIONS ], ); my $tagdefault = 1; # 0:IMPLICIT , 1:EXPLICIT default # args: class,plicit sub need_explicit { (defined($_[0]) && (defined($_[1])?$_[1]:$tagdefault)); } # Given an OP, wrap it in a SEQUENCE sub explicit { my $op = shift; my @seq = @$op; @seq[cTYPE,cCHILD,cVAR,cLOOP] = ('EXPLICIT',[$op],undef,undef); @{$op}[cTAG,cOPT] = (); \@seq; } %} %% top : slist { $$ = { '' => $1 }; } | module ; module : WORD ASSIGN aitem { $$ = { $1, [$3] }; } | module WORD ASSIGN aitem { $$=$1; $$->{$2} = [$4]; } ; aitem : class plicit anyelem postrb { $3->[cTAG] = $1; $$ = need_explicit($1,$2) ? explicit($3) : $3; } | celem ; anyelem : onelem | eelem | oelem | selem ; celem : COMPONENTS OF WORD { @{$$ = []}[cTYPE,cCHILD] = ('COMPONENTS', $3); } ; seqset : SEQUENCE | SET ; selem : seqset OF class plicit sselem optional { $5->[cTAG] = $3; @{$$ = []}[cTYPE,cCHILD,cLOOP,cOPT] = ($1, [$5], 1, $6); $$ = explicit($$) if need_explicit($3,$4); } ; sselem : eelem | oelem | onelem ; onelem : SEQUENCE LBRACE slist RBRACE { @{$$ = []}[cTYPE,cCHILD] = ('SEQUENCE', $3); } | SET LBRACE slist RBRACE { @{$$ = []}[cTYPE,cCHILD] = ('SET', $3); } | CHOICE LBRACE nlist RBRACE { @{$$ = []}[cTYPE,cCHILD] = ('CHOICE', $3); } ; eelem : ENUM LBRACE elist RBRACE { @{$$ = []}[cTYPE] = ('ENUM'); } ; oielem : WORD { @{$$ = []}[cTYPE] = $1; } | SEQUENCE { @{$$ = []}[cTYPE] = $1; } | SET { @{$$ = []}[cTYPE] = $1; } | ANY defined { @{$$ = []}[cTYPE,cCHILD,cDEFINE] = ('ANY',undef,$2); } | ENUM { @{$$ = []}[cTYPE] = $1; } ; defined : { $$=undef; } | DEFINED BY WORD { $$=$3; } ; oelem : oielem ; nlist : nlist1 { $$ = $1; } | nlist1 POSTRBRACE { $$ = $1; } ; nlist1 : nitem { $$ = [ $1 ]; } | nlist1 POSTRBRACE nitem { push @{$$=$1}, $3; } | nlist1 COMMA nitem { push @{$$=$1}, $3; } ; nitem : WORD class plicit anyelem { @{$$=$4}[cVAR,cTAG] = ($1,$2); $$ = explicit($$) if need_explicit($2,$3); } | EXTENSION_MARKER { @{$$=[]}[cTYPE] = 'EXTENSION_MARKER'; } ; slist : { $$ = []; } | slist1 { my $extension = 0; $$ = []; for my $i (@{$1}) { $extension = 1 if $i->[cTYPE] eq 'EXTENSION_MARKER'; $i->[cEXT] = $i->[cOPT]; $i->[cEXT] = 1 if $extension; push @{$$}, $i unless $i->[cTYPE] eq 'EXTENSION_MARKER'; } my $e = []; $e->[cTYPE] = 'EXTENSION_MARKER'; push @{$$}, $e if $extension; } | slist1 POSTRBRACE { my $extension = 0; $$ = []; for my $i (@{$1}) { $extension = 1 if $i->[cTYPE] eq 'EXTENSION_MARKER'; $i->[cEXT] = $i->[cOPT]; $i->[cEXT] = 1 if $extension; push @{$$}, $i unless $i->[cTYPE] eq 'EXTENSION_MARKER'; } my $e = []; $e->[cTYPE] = 'EXTENSION_MARKER'; push @{$$}, $e if $extension; } ; slist1 : sitem { $$ = [ $1 ]; } | slist1 COMMA sitem { push @{$$=$1}, $3; } | slist1 POSTRBRACE sitem { push @{$$=$1}, $3; } ; snitem : oelem optional { @{$$=$1}[cOPT] = ($2); } | eelem | selem | onelem ; sitem : WORD class plicit snitem { @{$$=$4}[cVAR,cTAG] = ($1,$2); $$->[cOPT] = $1 if $$->[cOPT]; $$ = explicit($$) if need_explicit($2,$3); } | celem | class plicit onelem { @{$$=$3}[cTAG] = ($1); $$ = explicit($$) if need_explicit($1,$2); } | EXTENSION_MARKER { @{$$=[]}[cTYPE] = 'EXTENSION_MARKER'; } ; optional : { $$ = undef; } | OPTIONAL { $$ = 1; } ; class : { $$ = undef; } | CLASS ; plicit : { $$ = undef; } | EXPLICIT { $$ = 1; } | IMPLICIT { $$ = 0; } ; elist : eitem {} | elist COMMA eitem {} ; eitem : WORD NUMBER {} ; postrb : {} | POSTRBRACE {} ; %% my %reserved = ( 'OPTIONAL' => $OPTIONAL, 'CHOICE' => $CHOICE, 'OF' => $OF, 'IMPLICIT' => $IMPLICIT, 'EXPLICIT' => $EXPLICIT, 'SEQUENCE' => $SEQUENCE, 'SET' => $SET, 'ANY' => $ANY, 'ENUM' => $ENUM, 'ENUMERATED' => $ENUM, 'COMPONENTS' => $COMPONENTS, '{' => $LBRACE, '}' => $RBRACE, ',' => $COMMA, '::=' => $ASSIGN, 'DEFINED' => $DEFINED, 'BY' => $BY ); my $reserved = join("|", reverse sort grep { /\w/ } keys %reserved); my %tag_class = ( APPLICATION => ASN_APPLICATION, UNIVERSAL => ASN_UNIVERSAL, PRIVATE => ASN_PRIVATE, CONTEXT => ASN_CONTEXT, '' => ASN_CONTEXT # if not specified, its CONTEXT ); ;## ;## This is NOT thread safe !!!!!! ;## my $pos; my $last_pos; my @stacked; sub parse { local(*asn) = \($_[0]); $tagdefault = $_[1] eq 'EXPLICIT' ? 1 : 0; ($pos,$last_pos,@stacked) = (); eval { local $SIG{__DIE__}; compile(verify(yyparse())); } } sub compile_one { my $tree = shift; my $ops = shift; my $name = shift; foreach my $op (@$ops) { next unless ref($op) eq 'ARRAY'; bless $op; my $type = $op->[cTYPE]; if (exists $base_type{$type}) { $op->[cTYPE] = $base_type{$type}->[1]; $op->[cTAG] = defined($op->[cTAG]) ? asn_encode_tag($op->[cTAG]): $base_type{$type}->[0]; } else { die "Unknown type '$type'\n" unless exists $tree->{$type}; my $ref = compile_one( $tree, $tree->{$type}, defined($op->[cVAR]) ? $name . "." . $op->[cVAR] : $name ); if (defined($op->[cTAG]) && $ref->[0][cTYPE] == opCHOICE) { @{$op}[cTYPE,cCHILD] = (opSEQUENCE,$ref); } else { @{$op}[cTYPE,cCHILD,cLOOP] = @{$ref->[0]}[cTYPE,cCHILD,cLOOP]; } $op->[cTAG] = defined($op->[cTAG]) ? asn_encode_tag($op->[cTAG]): $ref->[0][cTAG]; } $op->[cTAG] |= pack("C",ASN_CONSTRUCTOR) if length $op->[cTAG] && ($op->[cTYPE] == opSET || $op->[cTYPE] == opEXPLICIT || $op->[cTYPE] == opSEQUENCE); if ($op->[cCHILD]) { ;# If we have children we are one of ;# opSET opSEQUENCE opCHOICE opEXPLICIT compile_one($tree, $op->[cCHILD], defined($op->[cVAR]) ? $name . "." . $op->[cVAR] : $name); ;# If a CHOICE is given a tag, then it must be EXPLICIT if ($op->[cTYPE] == opCHOICE && defined($op->[cTAG]) && length($op->[cTAG])) { $op = bless explicit($op); $op->[cTYPE] = opSEQUENCE; } if ( @{$op->[cCHILD]} > 1) { ;#if ($op->[cTYPE] != opSEQUENCE) { ;# Here we need to flatten CHOICEs and check that SET and CHOICE ;# do not contain duplicate tags ;#} if ($op->[cTYPE] == opSET) { ;# In case we do CER encoding we order the SET elements by thier tags my @tags = map { length($_->[cTAG]) ? $_->[cTAG] : $_->[cTYPE] == opCHOICE ? (sort map { $_->[cTAG] } $_->[cCHILD])[0] : '' } @{$op->[cCHILD]}; @{$op->[cCHILD]} = @{$op->[cCHILD]}[sort { $tags[$a] cmp $tags[$b] } 0..$#tags]; } } else { ;# A SET of one element can be treated the same as a SEQUENCE $op->[cTYPE] = opSEQUENCE if $op->[cTYPE] == opSET; } } } $ops; } sub compile { my $tree = shift; ;# The tree should be valid enough to be able to ;# - resolve references ;# - encode tags ;# - verify CHOICEs do not contain duplicate tags ;# once references have been resolved, and also due to ;# flattening of COMPONENTS, it is possible for an op ;# to appear in multiple places. So once an op is ;# compiled we bless it. This ensure we dont try to ;# compile it again. while(my($k,$v) = each %$tree) { compile_one($tree,$v,$k); } $tree; } sub verify { my $tree = shift or return; my $err = ""; ;# Well it parsed correctly, now we ;# - check references exist ;# - flatten COMPONENTS OF (checking for loops) ;# - check for duplicate var names while(my($name,$ops) = each %$tree) { my $stash = {}; my @scope = (); my $path = ""; my $idx = 0; while($ops) { if ($idx < @$ops) { my $op = $ops->[$idx++]; my $var; if (defined ($var = $op->[cVAR])) { $err .= "$name: $path.$var used multiple times\n" if $stash->{$var}++; } if (defined $op->[cCHILD]) { if (ref $op->[cCHILD]) { push @scope, [$stash, $path, $ops, $idx]; if (defined $var) { $stash = {}; $path .= "." . $var; } $idx = 0; $ops = $op->[cCHILD]; } elsif ($op->[cTYPE] eq 'COMPONENTS') { splice(@$ops,--$idx,1,expand_ops($tree, $op->[cCHILD])); } else { die "Internal error\n"; } } } else { my $s = pop @scope or last; ($stash,$path,$ops,$idx) = @$s; } } } die $err if length $err; $tree; } sub expand_ops { my $tree = shift; my $want = shift; my $seen = shift || { }; die "COMPONENTS OF loop $want\n" if $seen->{$want}++; die "Undefined macro $want\n" unless exists $tree->{$want}; my $ops = $tree->{$want}; die "Bad macro for COMPUNENTS OF '$want'\n" unless @$ops == 1 && ($ops->[0][cTYPE] eq 'SEQUENCE' || $ops->[0][cTYPE] eq 'SET') && ref $ops->[0][cCHILD]; $ops = $ops->[0][cCHILD]; for(my $idx = 0 ; $idx < @$ops ; ) { my $op = $ops->[$idx++]; if ($op->[cTYPE] eq 'COMPONENTS') { splice(@$ops,--$idx,1,expand_ops($tree, $op->[cCHILD], $seen)); } } @$ops; } sub _yylex { my $ret = &_yylex; warn $ret; $ret; } sub yylex { return shift @stacked if @stacked; while ($asn =~ /\G(?: (\s+|--[^\n]*) | ([,{}]|::=) | ($reserved)\b | ( (?:OCTET|BIT)\s+STRING | OBJECT\s+IDENTIFIER | RELATIVE-OID )\b | (\w+(?:-\w+)*) | \[\s* ( (?:(?:APPLICATION|PRIVATE|UNIVERSAL|CONTEXT)\s+)? \d+ ) \s*\] | \((\d+)\) | (\.\.\.) )/sxgo ) { ($last_pos,$pos) = ($pos,pos($asn)); next if defined $1; # comment or whitespace if (defined $2 or defined $3) { my $ret = $+; # A comma is not required after a '}' so to aid the # parser we insert a fake token after any '}' if ($ret eq '}') { my $p = pos($asn); my @tmp = @stacked; @stacked = (); pos($asn) = $p if yylex() != $COMMA; # swallow it @stacked = (@tmp, $POSTRBRACE); } return $reserved{$yylval = $ret}; } if (defined $4) { ($yylval = $+) =~ s/\s+/_/g; return $WORD; } if (defined $5) { $yylval = $+; return $WORD; } if (defined $6) { my($class,$num) = ($+ =~ /^([A-Z]*)\s*(\d+)$/); $yylval = asn_tag($tag_class{$class}, $num); return $CLASS; } if (defined $7) { $yylval = $+; return $NUMBER; } if (defined $8) { return $EXTENSION_MARKER; } die "Internal error\n"; } die "Parse error before ",substr($asn,$pos,40),"\n" unless $pos == length($asn); 0 } sub yyerror { die @_," ",substr($asn,$last_pos,40),"\n"; } 1; Convert-ASN1-0.34/ChangeLog0000644000175000017500000002661414464272101013510 0ustar timtim0.34 -- Mon Aug 07 19:46:22 ADT 2023 Bug Fixes Thanks to chrisridd and fschlich for these bug fixes * Fixes: #47 2nd - Debug output using print instead of printf * Fixes #47 Debug output using print instead of printf * ASN1.pod: fix minor typo 0.33 -- Wed Sep 22 19:49:53 ADT 2021 * Official CPAN release of 0.33 0.32 -- Tue Sep 21 18:45:20 ADT 2021 * examples/x509decode: parameters are optional for AlgorithmIdentifier when using [ec]dsa algorithms * t/19issue14.t: issue with warnings * Fixes #44 Redundant argument in printf warning * examples/x509decode: fix prototype error * examples/ldap: fix asn1_dump not working 0.31 -- Wed Jun 02 22:28:29 ADT 2021 * Official CPAN release of 0.30 0.30 -- Sat May 29 21:56:29 ADT 2021 * Fixes #43 - Perl 5.35.1 makes scalar assignment to undef a compile time error 0.29 -- Mon May 24 18:27:46 ADT 2021 * Release Version no changes from 0.28 * Increment Version in Makefile.PL 0.28 -- Sun May 23 18:03:47 ADT 2021 * Add github actions for repo testing and add new maintainer [Timothy Legge] * typo fix [Adam Leskis] * Fix test failures under Perl 5.26+ without '.' in @INC [Kent Fredric (KENTNL)] * Correct a typo - SYNOPSIS [Shlomi Fish] * unsafe decoding CVE-2013-7488 [Dana Jacobsen] * Typo fixes from dsteinbrunner [David Steinbrunner] * Add files via upload [Peter Sylvester] 0.27 -- Wed Jun 25 13:47:28 CDT 2014 * Avoid recursion when encountering an invalid tag and length * Avoid negative repetition counts (5.22 compatibility) [Alex Vandiver] * Use pack/unpack instead of chr/org to avoid encoding issues 0.26 -- Sat Jun 09 13:30:16 CDT 2012 * Avoid Modification of a read-only value attempted errors * dump Data::Dumper strings when rtest fails * Add tests from Crypt::X509 that found the last Modification of a read-only value attempted error 0.25 -- Fri Jun 08 19:31:59 CDT 2012 * fix a spelling mistake [gregor herrmann] * Add use strict and fix errors * Fix decoding of indefinite sequences with ANY * POD additions for ANY * EXPLICIT ops must pass their cVAR to their child op * Swallow a , after a } 0.24 -- Mon Jun 04 17:11:08 CDT 2012 * spelling fix [gregor herrmann] * Added tests for extension markers (fails currently) [Niels Laukens] * Bugfix for extension markerss in SETs and CHOICEs [Niels Laukens] * Skip attempting to encode opEXTENSIONS inside of CHOICE * Support for default explicit tagging [Peter Mogensen] * Added tests and doc for explicit tagging [Peter Mogensen] * Add new opEXPLICIT for sequences that are inserted for EXPLICIT tags 0.23 -- Thu May 03 16:32:46 CDT 2012 * Added support for EXTENSION MARKERS (...) (Niels Laukens) * Switch to Dist::Zilla for building Convert::ASN1 0.21 -- Mon Sep 15 14:34:45 CDT 2008 Bug Fixes * Fix decoding of OIDs with large value for 2nd element Enhancements * Support for SEQUENCE with no elements in ASN.1 * Added ability to define what value is put in perl data structory when decoding NULL elements Convert::ASN1 0.21 -- Fri Feb 2 20:24:59 CST 2007 Bug Fixes * Fixed problem with indefinite encoding inside an indefinite encoding Enhancements * Added support for type-local ANY DEFINED BY (patch from Leif Johansson) Convert::ASN1 0.20 -- Tue Feb 21 18:47:43 CST 2006 Bug Fixes * Fixed issues with decoding when calling script contains use encoding 'utf8' * Allow zero-length timestamps to be extracted * Fix incorrect length encoding for bitstrings Enhancements * Support encoding bigint's as BCD Convert::ASN1 0.19 -- Mon Apr 18 19:40:32 CDT 2005 Bug Fixes * Fixed reading of packets with indefinite-length encodings Enhancements * Add support for BCDString 2003-10-08 15:29 Graham Barr * lib/Convert/ASN1.pm: Release 0.18 2003-10-08 15:28 Graham Barr * MANIFEST, Makefile.PL, t/0-signature.t: Use Module::Build to build Makefile and add SIGNATURE 2003-10-08 13:28 Graham Barr * lib/Convert/: ASN1.pm, ASN1/_encode.pm: Fix bug in encoding BIT STRINGS where chr() was causing an upgrade to UTF8 2003-05-12 18:45 Graham Barr * lib/Convert/ASN1.pm: Release 0.17 2003-05-12 18:45 Graham Barr * MANIFEST: Add new tests into MANIFEST 2003-05-12 18:06 Graham Barr * t/funcs.pl: Skip rtest if Data::Dumper is not available 2003-05-07 16:13 Graham Barr * parser.y, lib/Convert/ASN1/parser.pm, t/04opt.t, t/funcs.pl: Support OPTIONAL on SET OF and SEQUENCE OF 2003-05-07 10:26 Graham Barr * lib/Convert/ASN1/_decode.pm, t/00prim.t: Fix OID decoding 2003-05-06 22:47 Graham Barr * t/14any.t: Remove duplicate my 2003-05-06 22:29 Graham Barr * parser.y, lib/Convert/ASN1.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, lib/Convert/ASN1/parser.pm, t/14any.t: Add support for ANY DEFINED BY Patch from Simon Wilkinson 2003-05-06 15:17 Graham Barr * lib/Convert/ASN1/Debug.pm: Fix debug output for OIDs 2003-05-06 13:40 Graham Barr * parser.y, lib/Convert/ASN1.pm, lib/Convert/ASN1.pod, lib/Convert/ASN1/parser.pm, t/08set.t, t/12der.t, t/13utf8.t: CER and DER SET encoding 2003-05-06 12:07 Graham Barr * t/13utf8.t, lib/Convert/ASN1.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm: utf8 support for perl >= 5.8 2002-08-20 01:00 Graham Barr * lib/Convert/ASN1.pm: Release 0.16 2002-08-20 00:59 Graham Barr * README, lib/Convert/ASN1.pod: Update search.cpan.org link and add CPAN RT email address 2002-08-20 00:53 Graham Barr * t/10choice.t: Fix test count 2002-08-20 00:51 Graham Barr * parser.y, lib/Convert/ASN1/_encode.pm, lib/Convert/ASN1/parser.pm, t/10choice.t: Fix for nested CHOICEs and tagged CHOICEs in SEQUENCES 2002-03-25 14:59 Graham Barr * t/: 00prim.t, 01tag.t, 02seq.t, 03seqof.t, 04opt.t, 05time.t, 06bigint.t, 08set.t, 09contr.t, 11indef.t: Add more detail when tests fail 2002-03-25 09:06 Graham Barr * lib/Convert/ASN1/_decode.pm, t/10choice.t, t/11indef.t, MANIFEST: Patch from Wolfgang Laun Fix bug in decode when there are nested CHOICEs Add tests t/10choice.t t/11indef.t 2002-03-25 07:46 Graham Barr * lib/Convert/: ASN1.pm, ASN1.pod, ASN1/_decode.pm: Patch from Wolfgang Laun Addition of prepare_file and the change prepare to accept a filehandle. POD updates. Fix decode of nested indefinate lengths 2002-03-25 07:39 Graham Barr * mkparse, parser.y, lib/Convert/ASN1/parser.pm: Allow '-'s in names and fix an uninit warning in the generated parser 2002-02-15 06:51 Graham Barr * lib/Convert/ASN1/_encode.pm: Use ::isa to determine if stash argument is a HASH 2002-02-10 16:41 Graham Barr * MANIFEST, examples/x509decode: Added x509decode from Norbert Klasen 2002-02-10 16:12 Graham Barr * lib/Convert/ASN1.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, t/00prim.t, t/03seqof.t: Add support for units with one sinlge, unamed entry eg test ::= INTEGER or list ::= SEQUENCE OF OCTET STRING 2002-01-22 11:24 Graham Barr * README, parser.y, lib/Convert/ASN1.pm, lib/Convert/ASN1.pod, lib/Convert/ASN1/Debug.pm, lib/Convert/ASN1/IO.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, lib/Convert/ASN1/parser.pm: Release 0.15 2002-01-21 20:00 Graham Barr * t/06bigint.t: Be safer in creating BigInt objects 2002-01-02 16:56 Graham Barr * lib/Convert/ASN1/_encode.pm: Change the encode errors to include the hierarchical name of the element in the ASN.1 which is causing the problem 2002-01-02 16:31 Graham Barr * lib/Convert/ASN1.pm: Remove unwanted warn statement 2001-09-25 00:05 Graham Barr * lib/Convert/ASN1.pm: Better error reporting for encoding 2001-09-22 01:16 Graham Barr * parser.y, lib/Convert/ASN1.pm, lib/Convert/ASN1/Debug.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, lib/Convert/ASN1/parser.pm, t/00prim.t: Add support for RELATIVE-OID 2001-09-22 01:14 Graham Barr * t/: 00prim.t, 06bigint.t: Move some integer tests that really use bigint from 00prim.t into 06bigint.t 2001-09-21 23:24 Graham Barr * lib/Convert/ASN1.pm, lib/Convert/ASN1/_decode.pm, t/03seqof.t: Support for nested SEQUENCE/SET OF's 2001-09-10 19:03 Graham Barr * README, lib/Convert/ASN1.pm: Release 0.14 2001-09-10 15:35 Graham Barr * MANIFEST, t/08set.t, t/09contr.t: Add tests for contructed elements and SETs 2001-09-10 15:34 Graham Barr * lib/Convert/ASN1/_decode.pm: Add support for decoding contructed elements 2001-09-07 20:04 Graham Barr * lib/Convert/: ASN1.pod, ASN1/_decode.pm: Implement the decode of SETs 2001-09-06 18:54 Graham Barr * lib/Convert/: ASN1.pm, ASN1/Debug.pm: Change asn_dump to putput the correct tag number for long tags and also warn when a length is incorrect 2001-09-06 18:41 Graham Barr * lib/Convert/ASN1/_decode.pm: Fix for indefinite decoding 2001-08-26 08:12 Graham Barr * lib/Convert/ASN1.pm: Release 0.13 2001-08-24 15:13 Graham Barr * parser.y, lib/Convert/ASN1/parser.pm: Remove an unwanted warn statement 2001-08-01 19:02 Graham Barr * lib/Convert/ASN1/_encode.pm, t/00prim.t: Fix boundary condition where we switch over to using Math::BigInt to encode integers 2001-07-31 18:05 Graham Barr * MANIFEST, lib/Convert/ASN1.pm: Release 0.12 2001-07-31 18:04 Graham Barr * lib/Convert/ASN1/_encode.pm: Make sure value passed to enc_integer is treated as a number and not a string 2001-07-31 18:03 Graham Barr * parser.y, lib/Convert/ASN1/parser.pm: Report which type cannot be found on error 2001-06-11 14:13 Graham Barr * lib/Convert/ASN1.pm: Release 0.11 2001-06-11 14:04 Graham Barr * lib/Convert/ASN1/_decode.pm, t/02seq.t: Fix decode of REAL when it is not the last element of a sequence 2001-04-26 07:52 Graham Barr * lib/Convert/ASN1.pm, t/05time.t, t/06bigint.t, t/funcs.pl: Fix syntax to be compatible with perl5.004_04 Skip bigint tests on 5.004 as they trigger lots of warnings in Math::BigInt 2001-04-20 07:26 Graham Barr * lib/Convert/ASN1.pm, lib/Convert/ASN1/_encode.pm, t/06bigint.t: Fix some bigint encoding problems and add some tests 2001-04-20 00:00 Graham Barr * Makefile.PL, lib/Convert/ASN1.pm: Release 0.09 2001-04-19 23:52 Graham Barr * MANIFEST, lib/Convert/ASN1.pm, lib/Convert/ASN1.pod, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, t/funcs.pl: Added support to use Math::BigInt, Thanks to Benjamin Trott 2001-04-19 23:50 Graham Barr * t/05time.t: Tests for UTCTime and GeneralizedTime (The previous was really for bigint tests) 2001-04-19 23:32 Graham Barr * t/06bigint.t: Tests for UTCTime and GeneralizedTime 2001-04-19 20:51 Graham Barr * lib/Convert/ASN1/IO.pm: Fix error message 2001-04-19 20:51 Graham Barr * lib/Convert/ASN1/_decode.pm: Get timezone right when decoding 2001-04-19 20:51 Graham Barr * t/funcs.pl: Useful debug enhancements 2001-02-05 22:36 Graham Barr * MANIFEST: Removed Convert-ASN1.ppd 2001-02-05 22:31 Graham Barr * lib/Convert/ASN1/parser.pm: Added CharacterString UniversalString BMPString 2001-01-29 22:35 Graham Barr * MANIFEST, OldChanges: Move perforce changelog aside and now generate with cvs2cl 2000-05-03 13:24 Graham Barr * MANIFEST, Makefile.PL, README, mkparse, parser.y, examples/ldap, examples/ldap-search, lib/Convert/ASN1.pm, lib/Convert/ASN1.pod, lib/Convert/ASN1/Debug.pm, lib/Convert/ASN1/IO.pm, lib/Convert/ASN1/_decode.pm, lib/Convert/ASN1/_encode.pm, lib/Convert/ASN1/parser.pm, t/00prim.t, t/01tag.t, t/02seq.t, t/03seqof.t, t/04opt.t, t/07io.t, t/funcs.pl: Initial revision Convert-ASN1-0.34/lib/0000775000175000017500000000000014464272101012475 5ustar timtimConvert-ASN1-0.34/lib/Convert/0000775000175000017500000000000014464272101014115 5ustar timtimConvert-ASN1-0.34/lib/Convert/ASN1/0000775000175000017500000000000014464272101014617 5ustar timtimConvert-ASN1-0.34/lib/Convert/ASN1/parser.pm0000644000175000017500000006126214464272101016456 0ustar timtim#$yysccsid = "@(#)yaccpar 1.8 (Berkeley) 01/20/91 (Perl 2.0 12/31/92)"; # 24 "parser.y" ;# Copyright (c) 2000-2005 Graham Barr . All rights reserved. ;# This program is free software; you can redistribute it and/or ;# modify it under the same terms as Perl itself. package Convert::ASN1::parser; $Convert::ASN1::parser::VERSION = '0.34'; use strict; use Convert::ASN1 qw(:all); use vars qw( $asn $yychar $yyerrflag $yynerrs $yyn @yyss $yyssp $yystate @yyvs $yyvsp $yylval $yys $yym $yyval ); BEGIN { Convert::ASN1->_internal_syms } my $yydebug=0; my %yystate; my %base_type = ( BOOLEAN => [ asn_encode_tag(ASN_BOOLEAN), opBOOLEAN ], INTEGER => [ asn_encode_tag(ASN_INTEGER), opINTEGER ], BIT_STRING => [ asn_encode_tag(ASN_BIT_STR), opBITSTR ], OCTET_STRING => [ asn_encode_tag(ASN_OCTET_STR), opSTRING ], STRING => [ asn_encode_tag(ASN_OCTET_STR), opSTRING ], NULL => [ asn_encode_tag(ASN_NULL), opNULL ], OBJECT_IDENTIFIER => [ asn_encode_tag(ASN_OBJECT_ID), opOBJID ], REAL => [ asn_encode_tag(ASN_REAL), opREAL ], ENUMERATED => [ asn_encode_tag(ASN_ENUMERATED), opINTEGER ], ENUM => [ asn_encode_tag(ASN_ENUMERATED), opINTEGER ], 'RELATIVE-OID' => [ asn_encode_tag(ASN_RELATIVE_OID), opROID ], SEQUENCE => [ asn_encode_tag(ASN_SEQUENCE | ASN_CONSTRUCTOR), opSEQUENCE ], EXPLICIT => [ asn_encode_tag(ASN_SEQUENCE | ASN_CONSTRUCTOR), opEXPLICIT ], SET => [ asn_encode_tag(ASN_SET | ASN_CONSTRUCTOR), opSET ], ObjectDescriptor => [ asn_encode_tag(ASN_UNIVERSAL | 7), opSTRING ], UTF8String => [ asn_encode_tag(ASN_UNIVERSAL | 12), opUTF8 ], NumericString => [ asn_encode_tag(ASN_UNIVERSAL | 18), opSTRING ], PrintableString => [ asn_encode_tag(ASN_UNIVERSAL | 19), opSTRING ], TeletexString => [ asn_encode_tag(ASN_UNIVERSAL | 20), opSTRING ], T61String => [ asn_encode_tag(ASN_UNIVERSAL | 20), opSTRING ], VideotexString => [ asn_encode_tag(ASN_UNIVERSAL | 21), opSTRING ], IA5String => [ asn_encode_tag(ASN_UNIVERSAL | 22), opSTRING ], UTCTime => [ asn_encode_tag(ASN_UNIVERSAL | 23), opUTIME ], GeneralizedTime => [ asn_encode_tag(ASN_UNIVERSAL | 24), opGTIME ], GraphicString => [ asn_encode_tag(ASN_UNIVERSAL | 25), opSTRING ], VisibleString => [ asn_encode_tag(ASN_UNIVERSAL | 26), opSTRING ], ISO646String => [ asn_encode_tag(ASN_UNIVERSAL | 26), opSTRING ], GeneralString => [ asn_encode_tag(ASN_UNIVERSAL | 27), opSTRING ], CharacterString => [ asn_encode_tag(ASN_UNIVERSAL | 28), opSTRING ], UniversalString => [ asn_encode_tag(ASN_UNIVERSAL | 28), opSTRING ], BMPString => [ asn_encode_tag(ASN_UNIVERSAL | 30), opSTRING ], BCDString => [ asn_encode_tag(ASN_OCTET_STR), opBCD ], CHOICE => [ '', opCHOICE ], ANY => [ '', opANY ], EXTENSION_MARKER => [ '', opEXTENSIONS ], ); my $tagdefault = 1; # 0:IMPLICIT , 1:EXPLICIT default ;# args: class,plicit sub need_explicit { (defined($_[0]) && (defined($_[1])?$_[1]:$tagdefault)); } ;# Given an OP, wrap it in a SEQUENCE sub explicit { my $op = shift; my @seq = @$op; @seq[cTYPE,cCHILD,cVAR,cLOOP] = ('EXPLICIT',[$op],undef,undef); @{$op}[cTAG,cOPT] = (); \@seq; } sub constWORD () { 1 } sub constCLASS () { 2 } sub constSEQUENCE () { 3 } sub constSET () { 4 } sub constCHOICE () { 5 } sub constOF () { 6 } sub constIMPLICIT () { 7 } sub constEXPLICIT () { 8 } sub constOPTIONAL () { 9 } sub constLBRACE () { 10 } sub constRBRACE () { 11 } sub constCOMMA () { 12 } sub constANY () { 13 } sub constASSIGN () { 14 } sub constNUMBER () { 15 } sub constENUM () { 16 } sub constCOMPONENTS () { 17 } sub constPOSTRBRACE () { 18 } sub constDEFINED () { 19 } sub constBY () { 20 } sub constEXTENSION_MARKER () { 21 } sub constYYERRCODE () { 256 } my @yylhs = ( -1, 0, 0, 2, 2, 3, 3, 6, 6, 6, 6, 8, 13, 13, 12, 14, 14, 14, 9, 9, 9, 10, 18, 18, 18, 18, 18, 19, 19, 11, 16, 16, 20, 20, 20, 21, 21, 1, 1, 1, 22, 22, 22, 24, 24, 24, 24, 23, 23, 23, 23, 15, 15, 4, 4, 5, 5, 5, 17, 17, 25, 7, 7, ); my @yylen = ( 2, 1, 1, 3, 4, 4, 1, 1, 1, 1, 1, 3, 1, 1, 6, 1, 1, 1, 4, 4, 4, 4, 1, 1, 1, 2, 1, 0, 3, 1, 1, 2, 1, 3, 3, 4, 1, 0, 1, 2, 1, 3, 3, 2, 1, 1, 1, 4, 1, 3, 1, 0, 1, 0, 1, 0, 1, 1, 1, 3, 2, 0, 1, ); my @yydefred = ( 0, 0, 54, 0, 50, 0, 1, 0, 0, 48, 0, 40, 0, 0, 0, 0, 57, 56, 0, 0, 0, 3, 0, 6, 0, 11, 0, 0, 0, 0, 49, 0, 41, 42, 0, 22, 0, 0, 0, 0, 46, 44, 0, 45, 0, 29, 47, 4, 0, 0, 0, 0, 7, 8, 9, 10, 0, 25, 0, 52, 43, 0, 0, 0, 0, 36, 0, 0, 32, 62, 5, 0, 0, 0, 58, 0, 18, 19, 0, 20, 0, 0, 28, 60, 21, 0, 0, 0, 34, 33, 59, 0, 0, 17, 15, 16, 0, 35, 14, ); my @yydgoto = ( 5, 6, 7, 21, 8, 18, 51, 70, 9, 52, 53, 54, 55, 44, 96, 60, 66, 73, 45, 57, 67, 68, 10, 11, 46, 74, ); my @yysindex = ( 2, 58, 0, 8, 0, 0, 0, 11, 123, 0, 3, 0, 59, 123, 19, 73, 0, 0, 92, 7, 7, 0, 123, 0, 119, 0, 59, 107, 109, 116, 0, 82, 0, 0, 119, 0, 107, 109, 84, 126, 0, 0, 90, 0, 132, 0, 0, 0, 7, 7, 10, 139, 0, 0, 0, 0, 141, 0, 143, 0, 0, 82, 156, 159, 82, 0, 160, 4, 0, 0, 0, 171, 158, 6, 0, 123, 0, 0, 123, 0, 10, 10, 0, 0, 0, 143, 124, 119, 0, 0, 0, 107, 109, 0, 0, 0, 90, 0, 0, ); my @yyrindex = ( 155, 105, 0, 0, 0, 0, 0, 174, 111, 0, 80, 0, 105, 138, 0, 0, 0, 0, 0, 161, 145, 0, 138, 0, 0, 0, 105, 0, 0, 0, 0, 105, 0, 0, 0, 0, 29, 33, 70, 74, 0, 0, 46, 0, 0, 0, 0, 0, 45, 45, 0, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 105, 0, 0, 164, 0, 0, 0, 0, 0, 0, 0, 138, 0, 0, 138, 0, 0, 165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 93, 0, 0, 0, 25, 0, 0, ); my @yygindex = ( 0, 85, 0, 151, 1, -12, 91, 0, 47, -18, -19, -17, 157, 0, 0, 83, 0, 0, 0, 0, 0, -3, 0, 127, 0, 95, ); sub constYYTABLESIZE () { 181 } my @yytable = ( 30, 24, 13, 1, 2, 41, 40, 42, 31, 2, 34, 64, 15, 22, 14, 19, 80, 84, 85, 3, 25, 20, 81, 4, 3, 51, 51, 22, 4, 23, 23, 65, 13, 24, 24, 12, 51, 51, 23, 13, 23, 23, 24, 51, 24, 24, 51, 23, 53, 53, 53, 24, 53, 53, 61, 61, 37, 51, 51, 23, 2, 2, 75, 86, 51, 78, 87, 94, 93, 95, 27, 27, 12, 23, 26, 26, 3, 88, 89, 27, 38, 27, 27, 26, 2, 26, 26, 26, 27, 23, 23, 38, 26, 24, 24, 27, 28, 29, 23, 59, 23, 23, 24, 56, 24, 24, 53, 23, 53, 53, 53, 24, 53, 53, 55, 55, 55, 48, 53, 49, 35, 53, 36, 37, 29, 35, 50, 91, 92, 29, 16, 17, 38, 62, 63, 39, 58, 38, 61, 55, 39, 55, 55, 55, 72, 39, 32, 33, 53, 53, 53, 55, 53, 53, 55, 37, 39, 69, 53, 53, 53, 71, 53, 53, 53, 53, 53, 76, 53, 53, 77, 79, 82, 83, 2, 30, 31, 47, 97, 98, 90, 43, ); my @yycheck = ( 18, 13, 1, 1, 2, 24, 24, 24, 1, 2, 22, 1, 1, 12, 6, 12, 12, 11, 12, 17, 1, 18, 18, 21, 17, 0, 1, 26, 21, 0, 1, 21, 31, 0, 1, 6, 11, 12, 9, 6, 11, 12, 9, 18, 11, 12, 0, 18, 3, 4, 5, 18, 7, 8, 0, 1, 11, 11, 12, 12, 2, 2, 61, 75, 18, 64, 78, 86, 86, 86, 0, 1, 14, 26, 0, 1, 17, 80, 81, 9, 0, 11, 12, 9, 2, 11, 12, 14, 18, 0, 1, 11, 18, 0, 1, 3, 4, 5, 9, 9, 11, 12, 9, 19, 11, 12, 1, 18, 3, 4, 5, 18, 7, 8, 3, 4, 5, 10, 13, 10, 1, 16, 3, 4, 5, 1, 10, 3, 4, 5, 7, 8, 13, 48, 49, 16, 10, 13, 6, 1, 16, 3, 4, 5, 1, 0, 19, 20, 3, 4, 5, 13, 7, 8, 16, 0, 11, 18, 3, 4, 5, 20, 7, 8, 3, 4, 5, 11, 7, 8, 11, 11, 1, 15, 0, 11, 11, 26, 87, 96, 85, 24, ); sub constYYFINAL () { 5 } sub constYYMAXTOKEN () { 21 } sub yyclearin { $yychar = -1; } sub yyerrok { $yyerrflag = 0; } sub YYERROR { ++$yynerrs; &yy_err_recover; } sub yy_err_recover { if ($yyerrflag < 3) { $yyerrflag = 3; while (1) { if (($yyn = $yysindex[$yyss[$yyssp]]) && ($yyn += constYYERRCODE()) >= 0 && $yyn <= $#yycheck && $yycheck[$yyn] == constYYERRCODE()) { $yyss[++$yyssp] = $yystate = $yytable[$yyn]; $yyvs[++$yyvsp] = $yylval; next yyloop; } else { return(1) if $yyssp <= 0; --$yyssp; --$yyvsp; } } } else { return (1) if $yychar == 0; $yychar = -1; next yyloop; } 0; } # yy_err_recover sub yyparse { if ($yys = $ENV{'YYDEBUG'}) { $yydebug = int($1) if $yys =~ /^(\d)/; } $yynerrs = 0; $yyerrflag = 0; $yychar = (-1); $yyssp = 0; $yyvsp = 0; $yyss[$yyssp] = $yystate = 0; yyloop: while(1) { yyreduce: { last yyreduce if ($yyn = $yydefred[$yystate]); if ($yychar < 0) { if (($yychar = &yylex) < 0) { $yychar = 0; } } if (($yyn = $yysindex[$yystate]) && ($yyn += $yychar) >= 0 && $yyn <= $#yycheck && $yycheck[$yyn] == $yychar) { $yyss[++$yyssp] = $yystate = $yytable[$yyn]; $yyvs[++$yyvsp] = $yylval; $yychar = (-1); --$yyerrflag if $yyerrflag > 0; next yyloop; } if (($yyn = $yyrindex[$yystate]) && ($yyn += $yychar) >= 0 && $yyn <= $#yycheck && $yycheck[$yyn] == $yychar) { $yyn = $yytable[$yyn]; last yyreduce; } if (! $yyerrflag) { &yyerror('syntax error'); ++$yynerrs; } return undef if &yy_err_recover; } # yyreduce $yym = $yylen[$yyn]; $yyval = $yyvs[$yyvsp+1-$yym]; switch: { my $label = "State$yyn"; goto $label if exists $yystate{$label}; last switch; State1: { # 107 "parser.y" { $yyval = { '' => $yyvs[$yyvsp-0] }; last switch; } } State3: { # 112 "parser.y" { $yyval = { $yyvs[$yyvsp-2], [$yyvs[$yyvsp-0]] }; last switch; } } State4: { # 116 "parser.y" { $yyval=$yyvs[$yyvsp-3]; $yyval->{$yyvs[$yyvsp-2]} = [$yyvs[$yyvsp-0]]; last switch; } } State5: { # 123 "parser.y" { $yyvs[$yyvsp-1]->[cTAG] = $yyvs[$yyvsp-3]; $yyval = need_explicit($yyvs[$yyvsp-3],$yyvs[$yyvsp-2]) ? explicit($yyvs[$yyvsp-1]) : $yyvs[$yyvsp-1]; last switch; } } State11: { # 137 "parser.y" { @{$yyval = []}[cTYPE,cCHILD] = ('COMPONENTS', $yyvs[$yyvsp-0]); last switch; } } State14: { # 147 "parser.y" { $yyvs[$yyvsp-1]->[cTAG] = $yyvs[$yyvsp-3]; @{$yyval = []}[cTYPE,cCHILD,cLOOP,cOPT] = ($yyvs[$yyvsp-5], [$yyvs[$yyvsp-1]], 1, $yyvs[$yyvsp-0]); $yyval = explicit($yyval) if need_explicit($yyvs[$yyvsp-3],$yyvs[$yyvsp-2]); last switch; } } State18: { # 160 "parser.y" { @{$yyval = []}[cTYPE,cCHILD] = ('SEQUENCE', $yyvs[$yyvsp-1]); last switch; } } State19: { # 164 "parser.y" { @{$yyval = []}[cTYPE,cCHILD] = ('SET', $yyvs[$yyvsp-1]); last switch; } } State20: { # 168 "parser.y" { @{$yyval = []}[cTYPE,cCHILD] = ('CHOICE', $yyvs[$yyvsp-1]); last switch; } } State21: { # 174 "parser.y" { @{$yyval = []}[cTYPE] = ('ENUM'); last switch; } } State22: { # 179 "parser.y" { @{$yyval = []}[cTYPE] = $yyvs[$yyvsp-0]; last switch; } } State23: { # 180 "parser.y" { @{$yyval = []}[cTYPE] = $yyvs[$yyvsp-0]; last switch; } } State24: { # 181 "parser.y" { @{$yyval = []}[cTYPE] = $yyvs[$yyvsp-0]; last switch; } } State25: { # 183 "parser.y" { @{$yyval = []}[cTYPE,cCHILD,cDEFINE] = ('ANY',undef,$yyvs[$yyvsp-0]); last switch; } } State26: { # 186 "parser.y" { @{$yyval = []}[cTYPE] = $yyvs[$yyvsp-0]; last switch; } } State27: { # 189 "parser.y" { $yyval=undef; last switch; } } State28: { # 190 "parser.y" { $yyval=$yyvs[$yyvsp-0]; last switch; } } State30: { # 196 "parser.y" { $yyval = $yyvs[$yyvsp-0]; last switch; } } State31: { # 197 "parser.y" { $yyval = $yyvs[$yyvsp-1]; last switch; } } State32: { # 201 "parser.y" { $yyval = [ $yyvs[$yyvsp-0] ]; last switch; } } State33: { # 205 "parser.y" { push @{$yyval=$yyvs[$yyvsp-2]}, $yyvs[$yyvsp-0]; last switch; } } State34: { # 209 "parser.y" { push @{$yyval=$yyvs[$yyvsp-2]}, $yyvs[$yyvsp-0]; last switch; } } State35: { # 215 "parser.y" { @{$yyval=$yyvs[$yyvsp-0]}[cVAR,cTAG] = ($yyvs[$yyvsp-3],$yyvs[$yyvsp-2]); $yyval = explicit($yyval) if need_explicit($yyvs[$yyvsp-2],$yyvs[$yyvsp-1]); last switch; } } State36: { # 220 "parser.y" { @{$yyval=[]}[cTYPE] = 'EXTENSION_MARKER'; last switch; } } State37: { # 226 "parser.y" { $yyval = []; last switch; } } State38: { # 228 "parser.y" { my $extension = 0; $yyval = []; for my $i (@{$yyvs[$yyvsp-0]}) { $extension = 1 if $i->[cTYPE] eq 'EXTENSION_MARKER'; $i->[cEXT] = $i->[cOPT]; $i->[cEXT] = 1 if $extension; push @{$yyval}, $i unless $i->[cTYPE] eq 'EXTENSION_MARKER'; } my $e = []; $e->[cTYPE] = 'EXTENSION_MARKER'; push @{$yyval}, $e if $extension; last switch; } } State39: { # 241 "parser.y" { my $extension = 0; $yyval = []; for my $i (@{$yyvs[$yyvsp-1]}) { $extension = 1 if $i->[cTYPE] eq 'EXTENSION_MARKER'; $i->[cEXT] = $i->[cOPT]; $i->[cEXT] = 1 if $extension; push @{$yyval}, $i unless $i->[cTYPE] eq 'EXTENSION_MARKER'; } my $e = []; $e->[cTYPE] = 'EXTENSION_MARKER'; push @{$yyval}, $e if $extension; last switch; } } State40: { # 256 "parser.y" { $yyval = [ $yyvs[$yyvsp-0] ]; last switch; } } State41: { # 260 "parser.y" { push @{$yyval=$yyvs[$yyvsp-2]}, $yyvs[$yyvsp-0]; last switch; } } State42: { # 264 "parser.y" { push @{$yyval=$yyvs[$yyvsp-2]}, $yyvs[$yyvsp-0]; last switch; } } State43: { # 270 "parser.y" { @{$yyval=$yyvs[$yyvsp-1]}[cOPT] = ($yyvs[$yyvsp-0]); last switch; } } State47: { # 279 "parser.y" { @{$yyval=$yyvs[$yyvsp-0]}[cVAR,cTAG] = ($yyvs[$yyvsp-3],$yyvs[$yyvsp-2]); $yyval->[cOPT] = $yyvs[$yyvsp-3] if $yyval->[cOPT]; $yyval = explicit($yyval) if need_explicit($yyvs[$yyvsp-2],$yyvs[$yyvsp-1]); last switch; } } State49: { # 286 "parser.y" { @{$yyval=$yyvs[$yyvsp-0]}[cTAG] = ($yyvs[$yyvsp-2]); $yyval = explicit($yyval) if need_explicit($yyvs[$yyvsp-2],$yyvs[$yyvsp-1]); last switch; } } State50: { # 291 "parser.y" { @{$yyval=[]}[cTYPE] = 'EXTENSION_MARKER'; last switch; } } State51: { # 296 "parser.y" { $yyval = undef; last switch; } } State52: { # 297 "parser.y" { $yyval = 1; last switch; } } State53: { # 301 "parser.y" { $yyval = undef; last switch; } } State55: { # 305 "parser.y" { $yyval = undef; last switch; } } State56: { # 306 "parser.y" { $yyval = 1; last switch; } } State57: { # 307 "parser.y" { $yyval = 0; last switch; } } State58: { # 310 "parser.y" { last switch; } } State59: { # 311 "parser.y" { last switch; } } State60: { # 314 "parser.y" { last switch; } } State61: { # 317 "parser.y" { last switch; } } State62: { # 318 "parser.y" { last switch; } } } # switch $yyssp -= $yym; $yystate = $yyss[$yyssp]; $yyvsp -= $yym; $yym = $yylhs[$yyn]; if ($yystate == 0 && $yym == 0) { $yystate = constYYFINAL(); $yyss[++$yyssp] = constYYFINAL(); $yyvs[++$yyvsp] = $yyval; if ($yychar < 0) { if (($yychar = &yylex) < 0) { $yychar = 0; } } return $yyvs[$yyvsp] if $yychar == 0; next yyloop; } if (($yyn = $yygindex[$yym]) && ($yyn += $yystate) >= 0 && $yyn <= $#yycheck && $yycheck[$yyn] == $yystate) { $yystate = $yytable[$yyn]; } else { $yystate = $yydgoto[$yym]; } $yyss[++$yyssp] = $yystate; $yyvs[++$yyvsp] = $yyval; } # yyloop } # yyparse # 322 "parser.y" my %reserved = ( 'OPTIONAL' => constOPTIONAL(), 'CHOICE' => constCHOICE(), 'OF' => constOF(), 'IMPLICIT' => constIMPLICIT(), 'EXPLICIT' => constEXPLICIT(), 'SEQUENCE' => constSEQUENCE(), 'SET' => constSET(), 'ANY' => constANY(), 'ENUM' => constENUM(), 'ENUMERATED' => constENUM(), 'COMPONENTS' => constCOMPONENTS(), '{' => constLBRACE(), '}' => constRBRACE(), ',' => constCOMMA(), '::=' => constASSIGN(), 'DEFINED' => constDEFINED(), 'BY' => constBY() ); my $reserved = join("|", reverse sort grep { /\w/ } keys %reserved); my %tag_class = ( APPLICATION => ASN_APPLICATION, UNIVERSAL => ASN_UNIVERSAL, PRIVATE => ASN_PRIVATE, CONTEXT => ASN_CONTEXT, '' => ASN_CONTEXT # if not specified, its CONTEXT ); ;## ;## This is NOT thread safe !!!!!! ;## my $pos; my $last_pos; my @stacked; sub parse { local(*asn) = \($_[0]); $tagdefault = $_[1] eq 'EXPLICIT' ? 1 : 0; ($pos,$last_pos,@stacked) = (); eval { local $SIG{__DIE__}; compile(verify(yyparse())); } } sub compile_one { my $tree = shift; my $ops = shift; my $name = shift; foreach my $op (@$ops) { next unless ref($op) eq 'ARRAY'; bless $op; my $type = $op->[cTYPE]; if (exists $base_type{$type}) { $op->[cTYPE] = $base_type{$type}->[1]; $op->[cTAG] = defined($op->[cTAG]) ? asn_encode_tag($op->[cTAG]): $base_type{$type}->[0]; } else { die "Unknown type '$type'\n" unless exists $tree->{$type}; my $ref = compile_one( $tree, $tree->{$type}, defined($op->[cVAR]) ? $name . "." . $op->[cVAR] : $name ); if (defined($op->[cTAG]) && $ref->[0][cTYPE] == opCHOICE) { @{$op}[cTYPE,cCHILD] = (opSEQUENCE,$ref); } else { @{$op}[cTYPE,cCHILD,cLOOP] = @{$ref->[0]}[cTYPE,cCHILD,cLOOP]; } $op->[cTAG] = defined($op->[cTAG]) ? asn_encode_tag($op->[cTAG]): $ref->[0][cTAG]; } $op->[cTAG] |= pack("C",ASN_CONSTRUCTOR) if length $op->[cTAG] && ($op->[cTYPE] == opSET || $op->[cTYPE] == opEXPLICIT || $op->[cTYPE] == opSEQUENCE); if ($op->[cCHILD]) { ;# If we have children we are one of ;# opSET opSEQUENCE opCHOICE opEXPLICIT compile_one($tree, $op->[cCHILD], defined($op->[cVAR]) ? $name . "." . $op->[cVAR] : $name); ;# If a CHOICE is given a tag, then it must be EXPLICIT if ($op->[cTYPE] == opCHOICE && defined($op->[cTAG]) && length($op->[cTAG])) { $op = bless explicit($op); $op->[cTYPE] = opSEQUENCE; } if ( @{$op->[cCHILD]} > 1) { ;#if ($op->[cTYPE] != opSEQUENCE) { ;# Here we need to flatten CHOICEs and check that SET and CHOICE ;# do not contain duplicate tags ;#} if ($op->[cTYPE] == opSET) { ;# In case we do CER encoding we order the SET elements by their tags my @tags = map { length($_->[cTAG]) ? $_->[cTAG] : $_->[cTYPE] == opCHOICE ? (sort map { $_->[cTAG] } $_->[cCHILD])[0] : '' } @{$op->[cCHILD]}; @{$op->[cCHILD]} = @{$op->[cCHILD]}[sort { $tags[$a] cmp $tags[$b] } 0..$#tags]; } } else { ;# A SET of one element can be treated the same as a SEQUENCE $op->[cTYPE] = opSEQUENCE if $op->[cTYPE] == opSET; } } } $ops; } sub compile { my $tree = shift; ;# The tree should be valid enough to be able to ;# - resolve references ;# - encode tags ;# - verify CHOICEs do not contain duplicate tags ;# once references have been resolved, and also due to ;# flattening of COMPONENTS, it is possible for an op ;# to appear in multiple places. So once an op is ;# compiled we bless it. This ensure we don't try to ;# compile it again. while(my($k,$v) = each %$tree) { compile_one($tree,$v,$k); } $tree; } sub verify { my $tree = shift or return; my $err = ""; ;# Well it parsed correctly, now we ;# - check references exist ;# - flatten COMPONENTS OF (checking for loops) ;# - check for duplicate var names while(my($name,$ops) = each %$tree) { my $stash = {}; my @scope = (); my $path = ""; my $idx = 0; while($ops) { if ($idx < @$ops) { my $op = $ops->[$idx++]; my $var; if (defined ($var = $op->[cVAR])) { $err .= "$name: $path.$var used multiple times\n" if $stash->{$var}++; } if (defined $op->[cCHILD]) { if (ref $op->[cCHILD]) { push @scope, [$stash, $path, $ops, $idx]; if (defined $var) { $stash = {}; $path .= "." . $var; } $idx = 0; $ops = $op->[cCHILD]; } elsif ($op->[cTYPE] eq 'COMPONENTS') { splice(@$ops,--$idx,1,expand_ops($tree, $op->[cCHILD])); } else { die "Internal error\n"; } } } else { my $s = pop @scope or last; ($stash,$path,$ops,$idx) = @$s; } } } die $err if length $err; $tree; } sub expand_ops { my $tree = shift; my $want = shift; my $seen = shift || { }; die "COMPONENTS OF loop $want\n" if $seen->{$want}++; die "Undefined macro $want\n" unless exists $tree->{$want}; my $ops = $tree->{$want}; die "Bad macro for COMPUNENTS OF '$want'\n" unless @$ops == 1 && ($ops->[0][cTYPE] eq 'SEQUENCE' || $ops->[0][cTYPE] eq 'SET') && ref $ops->[0][cCHILD]; $ops = $ops->[0][cCHILD]; for(my $idx = 0 ; $idx < @$ops ; ) { my $op = $ops->[$idx++]; if ($op->[cTYPE] eq 'COMPONENTS') { splice(@$ops,--$idx,1,expand_ops($tree, $op->[cCHILD], $seen)); } } @$ops; } sub _yylex { my $ret = &_yylex; warn $ret; $ret; } sub yylex { return shift @stacked if @stacked; while ($asn =~ /\G(?: (\s+|--[^\n]*) | ([,{}]|::=) | ($reserved)\b | ( (?:OCTET|BIT)\s+STRING | OBJECT\s+IDENTIFIER | RELATIVE-OID )\b | (\w+(?:-\w+)*) | \[\s* ( (?:(?:APPLICATION|PRIVATE|UNIVERSAL|CONTEXT)\s+)? \d+ ) \s*\] | \((\d+)\) | (\.\.\.) )/sxgo ) { ($last_pos,$pos) = ($pos,pos($asn)); next if defined $1; # comment or whitespace if (defined $2 or defined $3) { my $ret = $+; # A comma is not required after a '}' so to aid the # parser we insert a fake token after any '}' if ($ret eq '}') { my $p = pos($asn); my @tmp = @stacked; @stacked = (); pos($asn) = $p if yylex() != constCOMMA(); # swallow it @stacked = (@tmp, constPOSTRBRACE()); } return $reserved{$yylval = $ret}; } if (defined $4) { ($yylval = $+) =~ s/\s+/_/g; return constWORD(); } if (defined $5) { $yylval = $+; return constWORD(); } if (defined $6) { my($class,$num) = ($+ =~ /^([A-Z]*)\s*(\d+)$/); $yylval = asn_tag($tag_class{$class}, $num); return constCLASS(); } if (defined $7) { $yylval = $+; return constNUMBER(); } if (defined $8) { return constEXTENSION_MARKER(); } die "Internal error\n"; } die "Parse error before ",substr($asn,$pos,40),"\n" unless $pos == length($asn); 0 } sub yyerror { die @_," ",substr($asn,$last_pos,40),"\n"; } 1; %yystate = ('State51','','State34','','State11','','State33','','State24', '','State47','','State40','','State31','','State37','','State23','', 'State22','','State21','','State57','','State39','','State56','','State20', '','State25','','State38','','State62','','State14','','State19','', 'State5','','State53','','State26','','State27','','State50','','State36', '','State4','','State3','','State32','','State49','','State43','','State30', '','State35','','State52','','State55','','State42','','State28','', 'State58','','State61','','State41','','State18','','State59','','State1', '','State60',''); 1; Convert-ASN1-0.34/lib/Convert/ASN1/_encode.pm0000644000175000017500000002237614464272101016561 0ustar timtim# Copyright (c) 2000-2005 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Convert::ASN1; $Convert::ASN1::VERSION = '0.34'; use strict; use warnings; BEGIN { unless (CHECK_UTF8) { local $SIG{__DIE__}; eval { require bytes } and 'bytes'->import } } # These are the subs which do the encoding, they are called with # 0 1 2 3 4 5 # $opt, $op, $stash, $var, $buf, $loop # The order in the array must match the op definitions above my @encode = ( sub { die "internal error\n" }, \&_enc_boolean, \&_enc_integer, \&_enc_bitstring, \&_enc_string, \&_enc_null, \&_enc_object_id, \&_enc_real, \&_enc_sequence, \&_enc_sequence, # EXPLICIT is the same encoding as sequence \&_enc_sequence, # SET is the same encoding as sequence \&_enc_time, \&_enc_time, \&_enc_utf8, \&_enc_any, \&_enc_choice, \&_enc_object_id, \&_enc_bcd, ); sub _encode { my ($optn, $ops, $stash, $path) = @_; my $var; foreach my $op (@{$ops}) { next if $op->[cTYPE] == opEXTENSIONS; if (defined(my $opt = $op->[cOPT])) { next unless defined $stash->{$opt}; } if (defined($var = $op->[cVAR])) { push @$path, $var; require Carp, Carp::croak(join(".", @$path)," is undefined") unless defined $stash->{$var}; } $_[4] .= $op->[cTAG]; &{$encode[$op->[cTYPE]]}( $optn, $op, (UNIVERSAL::isa($stash, 'HASH') ? ($stash, defined($var) ? $stash->{$var} : undef) : ({}, $stash)), $_[4], $op->[cLOOP], $path, ); pop @$path if defined $var; } $_[4]; } sub _enc_boolean { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path $_[4] .= pack("CC",1, $_[3] ? 0xff : 0); } sub _enc_integer { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path if (abs($_[3]) >= 2**31) { my $os = i2osp($_[3], ref($_[3]) || $_[0]->{encode_bigint} || 'Math::BigInt'); my $len = length $os; my $msb = (vec($os, 0, 8) & 0x80) ? 0 : 255; $len++, $os = pack("C",$msb) . $os if $msb xor $_[3] > 0; $_[4] .= asn_encode_length($len); $_[4] .= $os; } else { my $val = int($_[3]); my $neg = ($val < 0); my $len = num_length($neg ? ~$val : $val); my $msb = $val & (0x80 << (($len - 1) * 8)); $len++ if $neg ? !$msb : $msb; $_[4] .= asn_encode_length($len); $_[4] .= substr(pack("N",$val), -$len); } } sub _enc_bitstring { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my $vref = ref($_[3]) ? \($_[3]->[0]) : \$_[3]; if (CHECK_UTF8 and Encode::is_utf8($$vref)) { utf8::encode(my $tmp = $$vref); $vref = \$tmp; } if (ref($_[3])) { my $less = (8 - ($_[3]->[1] & 7)) & 7; my $len = ($_[3]->[1] + 7) >> 3; $_[4] .= asn_encode_length(1+$len); $_[4] .= pack("C",$less); $_[4] .= substr($$vref, 0, $len); if ($less && $len) { substr($_[4],-1) &= pack("C",(0xff << $less) & 0xff); } } else { $_[4] .= asn_encode_length(1+length $$vref); $_[4] .= pack("C",0); $_[4] .= $$vref; } } sub _enc_string { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path if (CHECK_UTF8 and Encode::is_utf8($_[3])) { utf8::encode(my $tmp = $_[3]); $_[4] .= asn_encode_length(length $tmp); $_[4] .= $tmp; } else { $_[4] .= asn_encode_length(length $_[3]); $_[4] .= $_[3]; } } sub _enc_null { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path $_[4] .= pack("C",0); } sub _enc_object_id { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my @data = ($_[3] =~ /(\d+)/g); if ($_[1]->[cTYPE] == opOBJID) { if(@data < 2) { @data = (0); } else { my $first = $data[1] + ($data[0] * 40); splice(@data,0,2,$first); } } my $l = length $_[4]; $_[4] .= pack("cw*", 0, @data); substr($_[4],$l,1) = asn_encode_length(length($_[4]) - $l - 1); } sub _enc_real { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path # Zero unless ($_[3]) { $_[4] .= pack("C",0); return; } require POSIX; # +oo (well we use HUGE_VAL as Infinity is not available to perl) if ($_[3] >= POSIX::HUGE_VAL()) { $_[4] .= pack("C*",0x01,0x40); return; } # -oo (well we use HUGE_VAL as Infinity is not available to perl) if ($_[3] <= - POSIX::HUGE_VAL()) { $_[4] .= pack("C*",0x01,0x41); return; } if (exists $_[0]->{'encode_real'} && $_[0]->{'encode_real'} ne 'binary') { my $tmp = sprintf("%g",$_[3]); $_[4] .= asn_encode_length(1+length $tmp); $_[4] .= pack("C",1); # NR1? $_[4] .= $tmp; return; } # We have a real number. my $first = 0x80; my($mantissa, $exponent) = POSIX::frexp($_[3]); if ($mantissa < 0.0) { $mantissa = -$mantissa; $first |= 0x40; } my($eMant,$eExp); while($mantissa > 0.0) { ($mantissa, my $int) = POSIX::modf($mantissa * (1<<8)); $eMant .= pack("C",$int); } $exponent -= 8 * length $eMant; _enc_integer(undef, undef, undef, $exponent, $eExp); # $eExp will be prefixed by a length byte if (5 > length $eExp) { $eExp =~ s/\A.//s; $first |= length($eExp)-1; } else { $first |= 0x3; } $_[4] .= asn_encode_length(1 + length($eMant) + length($eExp)); $_[4] .= pack("C",$first); $_[4] .= $eExp; $_[4] .= $eMant; } sub _enc_sequence { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path if (my $ops = $_[1]->[cCHILD]) { my $l = length $_[4]; $_[4] .= "\0\0"; # guess if (defined $_[5]) { my $op = $ops->[0]; # there should only be one my $enc = $encode[$op->[cTYPE]]; my $tag = $op->[cTAG]; my $loop = $op->[cLOOP]; push @{$_[6]}, -1; foreach my $var (@{$_[3]}) { $_[6]->[-1]++; $_[4] .= $tag; &{$enc}( $_[0], # $optn $op, # $op $_[2], # $stash $var, # $var $_[4], # $buf $loop, # $loop $_[6], # $path ); } pop @{$_[6]}; } else { _encode($_[0],$_[1]->[cCHILD], defined($_[3]) ? $_[3] : $_[2], $_[6], $_[4]); } substr($_[4],$l,2) = asn_encode_length(length($_[4]) - $l - 2); } else { $_[4] .= asn_encode_length(length $_[3]); $_[4] .= $_[3]; } } my %_enc_time_opt = ( utctime => 1, withzone => 0, raw => 2); sub _enc_time { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my $mode = $_enc_time_opt{$_[0]->{'encode_time'} || ''} || 0; if ($mode == 2) { $_[4] .= asn_encode_length(length $_[3]); $_[4] .= $_[3]; return; } my $time; my @time; my $offset; my $isgen = $_[1]->[cTYPE] == opGTIME; if (ref($_[3])) { $offset = int($_[3]->[1] / 60); $time = $_[3]->[0] + $_[3]->[1]; } elsif ($mode == 0) { if (exists $_[0]->{'encode_timezone'}) { $offset = int($_[0]->{'encode_timezone'} / 60); $time = $_[3] + $_[0]->{'encode_timezone'}; } else { @time = localtime($_[3]); my @g = gmtime($_[3]); $offset = ($time[1] - $g[1]) + ($time[2] - $g[2]) * 60; $time = $_[3] + $offset*60; } } else { $time = $_[3]; } @time = gmtime($time); $time[4] += 1; $time[5] = $isgen ? ($time[5] + 1900) : ($time[5] % 100); my $tmp = sprintf("%02d"x6, @time[5,4,3,2,1,0]); if ($isgen) { my $sp = sprintf("%.03f",$time); $tmp .= substr($sp,-4) unless $sp =~ /\.000$/; } $tmp .= $offset ? sprintf("%+03d%02d",$offset / 60, abs($offset % 60)) : 'Z'; $_[4] .= asn_encode_length(length $tmp); $_[4] .= $tmp; } sub _enc_utf8 { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path if (CHECK_UTF8) { my $tmp = $_[3]; utf8::upgrade($tmp) unless Encode::is_utf8($tmp); utf8::encode($tmp); $_[4] .= asn_encode_length(length $tmp); $_[4] .= $tmp; } else { $_[4] .= asn_encode_length(length $_[3]); $_[4] .= $_[3]; } } sub _enc_any { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my $handler; if ($_[1]->[cDEFINE] && $_[2]->{$_[1]->[cDEFINE]}) { $handler=$_[0]->{oidtable}{$_[2]->{$_[1]->[cDEFINE]}}; $handler=$_[0]->{handlers}{$_[1]->[cVAR]}{$_[2]->{$_[1]->[cDEFINE]}} unless $handler; } if ($handler) { $_[4] .= $handler->encode($_[3]); } else { $_[4] .= $_[3]; } } sub _enc_choice { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my $stash = defined($_[3]) ? $_[3] : $_[2]; for my $op (@{$_[1]->[cCHILD]}) { next if $op->[cTYPE] == opEXTENSIONS; my $var = defined $op->[cVAR] ? $op->[cVAR] : $op->[cCHILD]->[0]->[cVAR]; if (exists $stash->{$var}) { push @{$_[6]}, $var; _encode($_[0],[$op], $stash, $_[6], $_[4]); pop @{$_[6]}; return; } } require Carp; Carp::croak("No value found for CHOICE " . join(".", @{$_[6]})); } sub _enc_bcd { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $loop, $path my $str = ("$_[3]" =~ /^(\d+)/) ? $1 : ""; $str .= "F" if length($str) & 1; $_[4] .= asn_encode_length(length($str) / 2); $_[4] .= pack("H*", $str); } 1; Convert-ASN1-0.34/lib/Convert/ASN1/Debug.pm0000644000175000017500000001166614464272101016213 0ustar timtim# Copyright (c) 2000-2005 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Convert::ASN1; $Convert::ASN1::VERSION = '0.34'; ## ## just for debug :-) ## sub _hexdump { my($fmt,$pos) = @_[1,2]; # Don't copy buffer $pos ||= 0; my $offset = 0; my $cnt = 1 << 4; my $len = length($_[0]); my $linefmt = ("%02X " x $cnt) . "%s\n"; print "\n"; while ($offset < $len) { my $data = substr($_[0],$offset,$cnt); my @y = unpack("C*",$data); printf $fmt,$pos if $fmt; # On the last time through replace '%02X ' with '__ ' for the # missing values substr($linefmt, 5*@y,5*($cnt-@y)) = "__ " x ($cnt - @y) if @y != $cnt; # Change non-printable chars to '.' $data =~ s/[\x00-\x1f\x7f-\xff]/./sg; printf $linefmt, @y,$data; $offset += $cnt; $pos += $cnt; } } my %type = ( split(/[\t\n]\s*/, q(10 SEQUENCE 01 BOOLEAN 0A ENUM 0D RELATIVE-OID 11 SET 02 INTEGER 03 BIT STRING 04 STRING 05 NULL 06 OBJECT ID ) ) ); my %classes = ( split(/[\t\n]\s*/, q(C0 [PRIVATE %d] 40 [APPLICATION %d] 80 [CONTEXT %d] 00 [UNIVERSAL %d] ) ) ); BEGIN { undef &asn_dump } sub asn_dump { my $fh = @_>1 ? shift : \*STDERR; my $ofh = select($fh); my $pos = 0; my $indent = ""; my @seqend = (); my $length = length($_[0]); my $fmt = $length > 0xffff ? "%08X" : "%04X"; while(1) { while (@seqend && $pos >= $seqend[0]) { $indent = substr($indent,2); warn "Bad sequence length " unless $pos == shift @seqend; printf "$fmt : %s}\n",$pos,$indent; } last unless $pos < $length; my $start = $pos; my($tb,$tag,$tnum) = asn_decode_tag2(substr($_[0],$pos,10)); last unless defined $tb; $pos += $tb; my($lb,$len) = asn_decode_length(substr($_[0],$pos,10)); $pos += $lb; if($tag == 0 && $len == 0) { $seqend[0] = $pos; redo; } printf $fmt. " %4d: %s",$start,$len,$indent; my $label = $type{sprintf("%02X",$tag & ~0x20)} || sprintf($classes{sprintf("%02X",$tag & 0xC0)}, $tag & ~0xE0); print "$label: $tnum"; if ($tag & ASN_CONSTRUCTOR) { print " {\n"; if($len < 0) { unshift(@seqend, length $_[0]); } else { unshift(@seqend, $pos + $len); } $indent .= " "; next; } my $tmp; for ($label) { # switch /^(INTEGER|ENUM)/ && do { Convert::ASN1::_dec_integer({},[],{},$tmp,$_[0],$pos,$len); printf " = %d\n",$tmp; last; }; /^BOOLEAN/ && do { Convert::ASN1::_dec_boolean({},[],{},$tmp,$_[0],$pos,$len); printf " = %s\n",$tmp ? 'TRUE' : 'FALSE'; last; }; /^(?:(OBJECT ID)|(RELATIVE-OID))/ && do { my @op; $op[cTYPE] = $1 ? opOBJID : opROID; Convert::ASN1::_dec_object_id({},\@op,{},$tmp,$_[0],$pos,$len); printf " = %s\n",$tmp; last; }; /^NULL/ && do { print "\n"; last; }; /^STRING/ && do { Convert::ASN1::_dec_string({},[],{},$tmp,$_[0],$pos,$len); if ($tmp =~ /[\x00-\x1f\x7f-\xff]/s) { _hexdump($tmp,$fmt . " : ".$indent, $pos); } else { printf " = '%s'\n",$tmp; } last; }; # /^BIT STRING/ && do { # Convert::BER::BIT_STRING->unpack($ber,\$tmp); # print " = ",$tmp,"\n"; # last; # }; # default -- dump hex data _hexdump(substr($_[0],$pos,$len),$fmt . " : ".$indent, $pos); } $pos += $len; } printf "Buffer contains %d extra bytes\n", $length - $pos if $pos < $length; select($ofh); } BEGIN { undef &asn_hexdump } sub asn_hexdump { my $fh = @_>1 ? shift : \*STDERR; my $ofh = select($fh); _hexdump($_[0]); print "\n"; select($ofh); } BEGIN { undef &dump } sub dump { my $self = shift; for (@{$self->{script}}) { dump_op($_,"",{},1); } } BEGIN { undef &dump_all } sub dump_all { my $self = shift; while(my($k,$v) = each %{$self->{tree}}) { print STDERR "$k:\n"; for (@$v) { dump_op($_,"",{},1); } } } BEGIN { undef &dump_op } sub dump_op { my($op,$indent,$done,$line) = @_; $indent ||= ""; printf STDERR "%3d: ",$line; if ($done->{$op}) { print STDERR " $indent=",$done->{$op},"\n"; return ++$line; } $done->{$op} = $line++; print STDERR $indent,"[ '",unpack("H*",$op->[cTAG]),"', "; print STDERR $op->[cTYPE] =~ /\D/ ? $op->[cTYPE] : $opName[$op->[cTYPE]]; print STDERR ", ",defined($op->[cVAR]) ? $op->[cVAR] : "_"; print STDERR ", ",defined($op->[cLOOP]) ? $op->[cLOOP] : "_"; print STDERR ", ",defined($op->[cOPT]) ? $op->[cOPT] : "_"; print STDERR "]"; if ($op->[cCHILD]) { print STDERR " ",scalar @{$op->[cCHILD]},"\n"; for (@{$op->[cCHILD]}) { $line = dump_op($_,$indent . " ",$done,$line); } } else { print STDERR "\n"; } print STDERR "\n" unless length $indent; $line; } 1; Convert-ASN1-0.34/lib/Convert/ASN1/_decode.pm0000644000175000017500000003760314464272101016546 0ustar timtim# Copyright (c) 2000-2005 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Convert::ASN1; $Convert::ASN1::VERSION = '0.34'; use strict; use warnings; BEGIN { local $SIG{__DIE__}; eval { require bytes and 'bytes'->import }; } # These are the subs that do the decode, they are called with # 0 1 2 3 4 # $optn, $op, $stash, $var, $buf # The order must be the same as the op definitions above my @decode = ( sub { die "internal error\n" }, \&_dec_boolean, \&_dec_integer, \&_dec_bitstring, \&_dec_string, \&_dec_null, \&_dec_object_id, \&_dec_real, \&_dec_sequence, \&_dec_explicit, \&_dec_set, \&_dec_time, \&_dec_time, \&_dec_utf8, undef, # ANY undef, # CHOICE \&_dec_object_id, \&_dec_bcd, ); my @ctr; @ctr[opBITSTR, opSTRING, opUTF8] = (\&_ctr_bitstring,\&_ctr_string,\&_ctr_string); sub _decode { my ($optn, $ops, $stash, $pos, $end, $seqof, $larr) = @_; my $idx = 0; # we try not to copy the input buffer at any time foreach my $buf ($_[-1]) { OP: foreach my $op (@{$ops}) { my $var = $op->[cVAR]; if (length $op->[cTAG]) { TAGLOOP: { my($tag,$len,$npos,$indef) = _decode_tl($buf,$pos,$end,$larr) or do { next OP if $pos==$end and ($seqof || defined $op->[cEXT]); die "decode error"; }; if ($tag eq $op->[cTAG]) { &{$decode[$op->[cTYPE]]}( $optn, $op, $stash, # We send 1 if there is not var as if there is the decode # should be getting undef. So if it does not get undef # it knows it has no variable ($seqof ? $seqof->[$idx++] : defined($var) ? $stash->{$var} : ref($stash) eq 'SCALAR' ? $$stash : 1), $buf,$npos,$len, $larr ); $pos = $npos+$len+$indef; redo TAGLOOP if $seqof && $pos < $end; next OP; } if ($tag eq ($op->[cTAG] | pack("C",ASN_CONSTRUCTOR)) and my $ctr = $ctr[$op->[cTYPE]]) { _decode( $optn, [$op], undef, $npos, $npos+$len, (\my @ctrlist), $larr, $buf, ); ($seqof ? $seqof->[$idx++] # = &{$ctr}(@ctrlist); : defined($var) ? $stash->{$var} # = &{$ctr}(@ctrlist); : ref($stash) eq 'SCALAR' ? $$stash # = &{$ctr}(@ctrlist); : my $any ) # = &{$ctr}(@ctrlist) FIX #43 = &{$ctr}(@ctrlist); $pos = $npos+$len+$indef; redo TAGLOOP if $seqof && $pos < $end; next OP; } if ($seqof || defined $op->[cEXT]) { next OP; } die "decode error " . unpack("H*",$tag) ."<=>" . unpack("H*",$op->[cTAG]), " ",$pos," ",$op->[cTYPE]," ",$op->[cVAR]||''; } } else { # opTag length is zero, so it must be an ANY, CHOICE or EXTENSIONS if ($op->[cTYPE] == opANY) { ANYLOOP: { my($tag,$len,$npos,$indef) = _decode_tl($buf,$pos,$end,$larr) or do { next OP if $pos==$end and ($seqof || defined $op->[cEXT]); die "decode error"; }; $len += $npos - $pos + $indef; my $handler; if ($op->[cDEFINE]) { $handler = $optn->{oidtable} && $optn->{oidtable}{$stash->{$op->[cDEFINE]}}; $handler ||= $optn->{handlers}{$op->[cVAR]}{$stash->{$op->[cDEFINE]}}; } ($seqof ? $seqof->[$idx++] : ref($stash) eq 'SCALAR' ? $$stash : $stash->{$var}) = $handler ? $handler->decode(substr($buf,$pos,$len)) : substr($buf,$pos,$len); $pos += $len; redo ANYLOOP if $seqof && $pos < $end; } } elsif ($op->[cTYPE] == opCHOICE) { CHOICELOOP: { my($tag,$len,$npos,$indef) = _decode_tl($buf,$pos,$end,$larr) or do { next OP if $pos==$end and ($seqof || defined $op->[cEXT]); die "decode error"; }; my $extensions; foreach my $cop (@{$op->[cCHILD]}) { if ($tag eq $cop->[cTAG]) { my $nstash = $seqof ? ($seqof->[$idx++]={}) : defined($var) ? ($stash->{$var}={}) : ref($stash) eq 'SCALAR' ? ($$stash={}) : $stash; &{$decode[$cop->[cTYPE]]}( $optn, $cop, $nstash, ($cop->[cVAR] ? $nstash->{$cop->[cVAR]} : undef), $buf,$npos,$len,$larr, ); $pos = $npos+$len+$indef; redo CHOICELOOP if $seqof && $pos < $end; next OP; } if ($cop->[cTYPE] == opEXTENSIONS) { $extensions = 1; next; } unless (length $cop->[cTAG]) { eval { _decode( $optn, [$cop], (\my %tmp_stash), $pos, $npos+$len+$indef, undef, $larr, $buf, ); my $nstash = $seqof ? ($seqof->[$idx++]={}) : defined($var) ? ($stash->{$var}={}) : ref($stash) eq 'SCALAR' ? ($$stash={}) : $stash; @{$nstash}{keys %tmp_stash} = values %tmp_stash; } or next; $pos = $npos+$len+$indef; redo CHOICELOOP if $seqof && $pos < $end; next OP; } if ($tag eq ($cop->[cTAG] | pack("C",ASN_CONSTRUCTOR)) and my $ctr = $ctr[$cop->[cTYPE]]) { my $nstash = $seqof ? ($seqof->[$idx++]={}) : defined($var) ? ($stash->{$var}={}) : ref($stash) eq 'SCALAR' ? ($$stash={}) : $stash; _decode( $optn, [$cop], undef, $npos, $npos+$len, (\my @ctrlist), $larr, $buf, ); $nstash->{$cop->[cVAR]} = &{$ctr}(@ctrlist); $pos = $npos+$len+$indef; redo CHOICELOOP if $seqof && $pos < $end; next OP; } } if ($pos < $end && $extensions) { $pos = $npos+$len+$indef; redo CHOICELOOP if $seqof && $pos < $end; next OP; } } die "decode error" unless $op->[cEXT]; } elsif ($op->[cTYPE] == opEXTENSIONS) { $pos = $end; # Skip over the rest } else { die "this point should never be reached"; } } } } die "decode error $pos $end" unless $pos == $end; } sub _dec_boolean { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len $_[3] = unpack("C",substr($_[4],$_[5],1)) ? 1 : 0; 1; } sub _dec_integer { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len my $buf = substr($_[4],$_[5],$_[6]); my $tmp = unpack("C",$buf) & 0x80 ? pack("C",255) : pack("C",0); if ($_[6] > 4) { $_[3] = os2ip($buf, $_[0]->{decode_bigint} || 'Math::BigInt'); } else { # N unpacks an unsigned value $_[3] = unpack("l",pack("l",unpack("N", $tmp x (4-$_[6]) . $buf))); } 1; } sub _dec_bitstring { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len $_[3] = [ substr($_[4],$_[5]+1,$_[6]-1), ($_[6]-1)*8-unpack("C",substr($_[4],$_[5],1)) ]; 1; } sub _dec_string { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len $_[3] = substr($_[4],$_[5],$_[6]); 1; } sub _dec_null { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len $_[3] = exists($_[0]->{decode_null}) ? $_[0]->{decode_null} : 1; 1; } sub _dec_object_id { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len my @data = unpack("w*",substr($_[4],$_[5],$_[6])); if ($_[1]->[cTYPE] == opOBJID and @data > 1) { if ($data[0] < 40) { splice(@data, 0, 1, 0, $data[0]); } elsif ($data[0] < 80) { splice(@data, 0, 1, 1, $data[0] - 40); } else { splice(@data, 0, 1, 2, $data[0] - 80); } } $_[3] = join(".", @data); 1; } my @_dec_real_base = (2,8,16); sub _dec_real { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len $_[3] = 0.0, return unless $_[6]; my $first = unpack("C",substr($_[4],$_[5],1)); if ($first & 0x80) { # A real number require POSIX; my $exp; my $expLen = $first & 0x3; my $estart = $_[5]+1; if($expLen == 3) { $estart++; $expLen = unpack("C",substr($_[4],$_[5]+1,1)); } else { $expLen++; } _dec_integer(undef, undef, undef, $exp, $_[4],$estart,$expLen); my $mant = 0.0; for (reverse unpack("C*",substr($_[4],$estart+$expLen,$_[6]-1-$expLen))) { $exp +=8, $mant = (($mant+$_) / 256) ; } $mant *= 1 << (($first >> 2) & 0x3); $mant = - $mant if $first & 0x40; $_[3] = $mant * POSIX::pow($_dec_real_base[($first >> 4) & 0x3], $exp); return; } elsif($first & 0x40) { $_[3] = POSIX::HUGE_VAL(),return if $first == 0x40; $_[3] = - POSIX::HUGE_VAL(),return if $first == 0x41; } elsif(substr($_[4],$_[5],$_[6]) =~ /^.([-+]?)0*(\d+(?:\.\d+(?:[Ee][-+]?\d+)?)?)$/s) { $_[3] = eval "$1$2"; return; } die "REAL decode error\n"; } sub _dec_explicit { # 0 1 2 3 4 5 6 7 # $optn, $op, $stash, $var, $buf, $pos, $len, $larr local $_[1][cCHILD][0][cVAR] = $_[1][cVAR] unless $_[1][cCHILD][0][cVAR]; _decode( $_[0], #optn $_[1]->[cCHILD], #ops $_[2], #stash $_[5], #pos $_[5]+$_[6], #end undef, #loop $_[7], $_[4], #buf ); 1; } sub _dec_sequence { # 0 1 2 3 4 5 6 7 # $optn, $op, $stash, $var, $buf, $pos, $len, $larr if (defined( my $ch = $_[1]->[cCHILD])) { _decode( $_[0], #optn $ch, #ops (defined($_[3]) || $_[1]->[cLOOP]) ? $_[2] : ($_[3]= {}), #stash $_[5], #pos $_[5]+$_[6], #end $_[1]->[cLOOP] && ($_[3]=[]), #loop $_[7], $_[4], #buf ); } else { $_[3] = substr($_[4],$_[5],$_[6]); } 1; } sub _dec_set { # 0 1 2 3 4 5 6 7 # $optn, $op, $stash, $var, $buf, $pos, $len, $larr # decode SET OF the same as SEQUENCE OF my $ch = $_[1]->[cCHILD]; goto &_dec_sequence if $_[1]->[cLOOP] or !defined($ch); my ($optn, $pos, $larr) = @_[0,5,7]; my $stash = defined($_[3]) ? $_[2] : ($_[3]={}); my $end = $pos + $_[6]; my @done; my $extensions; while ($pos < $end) { my($tag,$len,$npos,$indef) = _decode_tl($_[4],$pos,$end,$larr) or die "decode error"; my ($idx, $any, $done) = (-1); SET_OP: foreach my $op (@$ch) { $idx++; if (length($op->[cTAG])) { if ($tag eq $op->[cTAG]) { my $var = $op->[cVAR]; &{$decode[$op->[cTYPE]]}( $optn, $op, $stash, # We send 1 if there is not var as if there is the decode # should be getting undef. So if it does not get undef # it knows it has no variable (defined($var) ? $stash->{$var} : 1), $_[4],$npos,$len,$larr, ); $done = $idx; last SET_OP; } if ($tag eq ($op->[cTAG] | pack("C",ASN_CONSTRUCTOR)) and my $ctr = $ctr[$op->[cTYPE]]) { _decode( $optn, [$op], undef, $npos, $npos+$len, (\my @ctrlist), $larr, $_[4], ); $stash->{$op->[cVAR]} = &{$ctr}(@ctrlist) if defined $op->[cVAR]; $done = $idx; last SET_OP; } next SET_OP; } elsif ($op->[cTYPE] == opANY) { $any = $idx; } elsif ($op->[cTYPE] == opCHOICE) { my $var = $op->[cVAR]; foreach my $cop (@{$op->[cCHILD]}) { if ($tag eq $cop->[cTAG]) { my $nstash = defined($var) ? ($stash->{$var}={}) : $stash; &{$decode[$cop->[cTYPE]]}( $optn, $cop, $nstash, $nstash->{$cop->[cVAR]}, $_[4],$npos,$len,$larr, ); $done = $idx; last SET_OP; } if ($tag eq ($cop->[cTAG] | pack("C",ASN_CONSTRUCTOR)) and my $ctr = $ctr[$cop->[cTYPE]]) { my $nstash = defined($var) ? ($stash->{$var}={}) : $stash; _decode( $optn, [$cop], undef, $npos, $npos+$len, (\my @ctrlist), $larr, $_[4], ); $nstash->{$cop->[cVAR]} = &{$ctr}(@ctrlist); $done = $idx; last SET_OP; } } } elsif ($op->[cTYPE] == opEXTENSIONS) { $extensions = $idx; } else { die "internal error"; } } if (!defined($done) and defined($any)) { my $var = $ch->[$any][cVAR]; $stash->{$var} = substr($_[4],$pos,$len+$npos-$pos) if defined $var; $done = $any; } if( !defined($done) && defined($extensions) ) { $done = $extensions; } die "decode error" if !defined($done) or $done[$done]++; $pos = $npos + $len + $indef; } die "decode error" unless $end == $pos; foreach my $idx (0..$#{$ch}) { die "decode error" unless $done[$idx] or $ch->[$idx][cEXT] or $ch->[$idx][cTYPE] == opEXTENSIONS; } 1; } my %_dec_time_opt = ( unixtime => 0, withzone => 1, raw => 2); sub _dec_time { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len my $mode = $_dec_time_opt{$_[0]->{'decode_time'} || ''} || 0; if ($mode == 2 or $_[6] == 0) { $_[3] = substr($_[4],$_[5],$_[6]); return; } my @bits = (substr($_[4],$_[5],$_[6]) =~ /^((?:\d\d)?\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)((?:\.\d{1,3})?)(([-+])(\d\d)(\d\d)|Z)/) or die "bad time format"; if ($bits[0] < 100) { $bits[0] += 100 if $bits[0] < 50; } else { $bits[0] -= 1900; } $bits[1] -= 1; require Time::Local; my $time = Time::Local::timegm(@bits[5,4,3,2,1,0]); $time += $bits[6] if length $bits[6]; my $offset = 0; if ($bits[7] ne 'Z') { $offset = $bits[9] * 3600 + $bits[10] * 60; $offset = -$offset if $bits[8] eq '-'; $time -= $offset; } $_[3] = $mode ? [$time,$offset] : $time; } sub _dec_utf8 { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len BEGIN { unless (CHECK_UTF8) { local $SIG{__DIE__}; eval { require bytes } and 'bytes'->unimport; eval { require utf8 } and 'utf8'->import; } } if (CHECK_UTF8) { $_[3] = Encode::decode('utf8', substr($_[4],$_[5],$_[6])); } else { $_[3] = (substr($_[4],$_[5],$_[6]) =~ /(.*)/s)[0]; } 1; } sub _decode_tl { my($pos,$end,$larr) = @_[1,2,3]; return if $pos >= $end; my $indef = 0; my $tag = substr($_[0], $pos++, 1); if((unpack("C",$tag) & 0x1f) == 0x1f) { my $b; my $n=1; do { return if $pos >= $end; $tag .= substr($_[0],$pos++,1); $b = ord substr($tag,-1); } while($b & 0x80); } return if $pos >= $end; my $len = ord substr($_[0],$pos++,1); if($len & 0x80) { $len &= 0x7f; if ($len) { return if $pos+$len > $end ; my $padding = $len < 4 ? "\0" x (4 - $len) : ""; ($len,$pos) = (unpack("N", $padding . substr($_[0],$pos,$len)), $pos+$len); } else { unless (exists $larr->{$pos}) { _scan_indef($_[0],$pos,$end,$larr) or return; } $indef = 2; $len = $larr->{$pos}; } } return if $pos+$len+$indef > $end; # return the tag, the length of the data, the position of the data # and the number of extra bytes for indefinite encoding ($tag, $len, $pos, $indef); } sub _scan_indef { my($pos,$end,$larr) = @_[1,2,3]; my @depth = ( $pos ); while(@depth) { return if $pos+2 > $end; if (substr($_[0],$pos,2) eq "\0\0") { my $end = $pos; my $stref = shift @depth; # replace pos with length = end - pos $larr->{$stref} = $end - $stref; $pos += 2; next; } return if $pos >= $end; my $tag = substr($_[0], $pos++, 1); if((unpack("C",$tag) & 0x1f) == 0x1f) { my $b; do { return if $pos >= $end; $tag .= substr($_[0],$pos++,1); $b = ord substr($tag,-1); } while($b & 0x80); } return if $pos >= $end; my $len = ord substr($_[0],$pos++,1); if($len & 0x80) { if ($len &= 0x7f) { return if $pos+$len > $end ; my $padding = $len < 4 ? "\0" x (4 - $len) : ""; $pos += $len + unpack("N", $padding . substr($_[0],$pos,$len)); } else { # reserve another list element unshift @depth, $pos; } } else { $pos += $len; } } 1; } sub _ctr_string { join '', @_ } sub _ctr_bitstring { [ join('', map { $_->[0] } @_), $_[-1]->[1] ] } sub _dec_bcd { # 0 1 2 3 4 5 6 # $optn, $op, $stash, $var, $buf, $pos, $len ($_[3] = unpack("H*", substr($_[4],$_[5],$_[6]))) =~ s/[fF]$//; 1; } 1; Convert-ASN1-0.34/lib/Convert/ASN1/IO.pm0000644000175000017500000001256714464272101015475 0ustar timtim# Copyright (c) 2000-2005 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Convert::ASN1; $Convert::ASN1::VERSION = '0.34'; use strict; use Socket; BEGIN { local $SIG{__DIE__}; eval { require bytes } and 'bytes'->import } sub asn_recv { # $socket, $buffer, $flags my $peer; my $buf; my $n = 128; my $pos = 0; my $depth = 0; my $len = 0; my($tmp,$tb,$lb); MORE: for( $peer = recv($_[0],$buf,$n,MSG_PEEK); defined $peer; $peer = recv($_[0],$buf,$n<<=1,MSG_PEEK) ) { if ($depth) { # Are we searching of "\0\0" unless (2+$pos <= length $buf) { next MORE if $n == length $buf; last MORE; } if(substr($buf,$pos,2) eq "\0\0") { unless (--$depth) { $len = $pos + 2; last MORE; } } } # If we can decode a tag and length we can determine the length ($tb,$tmp) = asn_decode_tag(substr($buf,$pos)); unless ($tb || $pos+$tb < length $buf) { next MORE if $n == length $buf; last MORE; } if (unpack("C",substr($buf,$pos+$tb,1)) == 0x80) { # indefinite length, grrr! $depth++; $pos += $tb + 1; redo MORE; } ($lb,$len) = asn_decode_length(substr($buf,$pos+$tb)); if ($lb) { if ($depth) { $pos += $tb + $lb + $len; redo MORE; } else { $len += $tb + $lb + $pos; last MORE; } } } if (defined $peer) { if ($len > length $buf) { # Check we can read the whole element goto error unless defined($peer = recv($_[0],$buf,$len,MSG_PEEK)); if ($len > length $buf) { # Cannot get whole element $_[1]=''; return $peer; } } elsif ($len == 0) { $_[1] = ''; return $peer; } if ($_[2] & MSG_PEEK) { $_[1] = substr($buf,0,$len); } elsif (!defined($peer = recv($_[0],$_[1],$len,0))) { goto error; } return $peer; } error: $_[1] = undef; } sub asn_read { # $fh, $buffer, $offset # We need to read one packet, and exactly only one packet. # So we have to read the first few bytes one at a time, until # we have enough to decode a tag and a length. We then know # how many more bytes to read if ($_[2]) { if ($_[2] > length $_[1]) { require Carp; Carp::carp("Offset beyond end of buffer"); return; } substr($_[1],$_[2]) = ''; } else { $_[1] = ''; } my $pos = 0; my $need = 0; my $depth = 0; my $ch; my $n; my $e; while(1) { $need = ($pos + ($depth * 2)) || 2; while(($n = $need - length $_[1]) > 0) { $e = sysread($_[0],$_[1],$n,length $_[1]) or goto READ_ERR; } my $tch = unpack("C",substr($_[1],$pos++,1)); # Tag may be multi-byte if(($tch & 0x1f) == 0x1f) { my $ch; do { $need++; while(($n = $need - length $_[1]) > 0) { $e = sysread($_[0],$_[1],$n,length $_[1]) or goto READ_ERR; } $ch = unpack("C",substr($_[1],$pos++,1)); } while($ch & 0x80); } $need = $pos + 1; while(($n = $need - length $_[1]) > 0) { $e = sysread($_[0],$_[1],$n,length $_[1]) or goto READ_ERR; } my $len = unpack("C",substr($_[1],$pos++,1)); if($len & 0x80) { unless ($len &= 0x7f) { $depth++; next; } $need = $pos + $len; while(($n = $need - length $_[1]) > 0) { $e = sysread($_[0],$_[1],$n,length $_[1]) or goto READ_ERR; } $pos += $len + unpack("N", "\0" x (4 - $len) . substr($_[1],$pos,$len)); } elsif (!$len && !$tch) { die "Bad ASN PDU" unless $depth; unless (--$depth) { last; } } else { $pos += $len; } last unless $depth; } while(($n = $pos - length $_[1]) > 0) { $e = sysread($_[0],$_[1],$n,length $_[1]) or goto READ_ERR; } return length $_[1]; READ_ERR: $@ = defined($e) ? "Unexpected EOF" : "I/O Error $!"; # . CORE::unpack("H*",$_[1]); return undef; } sub asn_send { # $sock, $buffer, $flags, $to @_ == 4 ? send($_[0],$_[1],$_[2],$_[3]) : send($_[0],$_[1],$_[2]); } sub asn_write { # $sock, $buffer syswrite($_[0],$_[1], length $_[1]); } sub asn_get { # $fh my $fh = ref($_[0]) ? $_[0] : \($_[0]); my $href = \%{*$fh}; $href->{'asn_buffer'} = '' unless exists $href->{'asn_buffer'}; my $need = delete $href->{'asn_need'} || 0; while(1) { next if $need; my($tb,$tag) = asn_decode_tag($href->{'asn_buffer'}) or next; my($lb,$len) = asn_decode_length(substr($href->{'asn_buffer'},$tb,8)) or next; $need = $tb + $lb + $len; } continue { if ($need && $need <= length $href->{'asn_buffer'}) { my $ret = substr($href->{'asn_buffer'},0,$need); substr($href->{'asn_buffer'},0,$need) = ''; return $ret; } my $get = $need > 1024 ? $need : 1024; sysread($_[0], $href->{'asn_buffer'}, $get, length $href->{'asn_buffer'}) or return undef; } } sub asn_ready { # $fh my $fh = ref($_[0]) ? $_[0] : \($_[0]); my $href = \%{*$fh}; return 0 unless exists $href->{'asn_buffer'}; return $href->{'asn_need'} <= length $href->{'asn_buffer'} if exists $href->{'asn_need'}; my($tb,$tag) = asn_decode_tag($href->{'asn_buffer'}) or return 0; my($lb,$len) = asn_decode_length(substr($href->{'asn_buffer'},$tb,8)) or return 0; $href->{'asn_need'} = $tb + $lb + $len; $href->{'asn_need'} <= length $href->{'asn_buffer'}; } 1; Convert-ASN1-0.34/lib/Convert/ASN1.pod0000644000175000017500000002705614464272101015333 0ustar timtim=head1 NAME Convert::ASN1 - ASN.1 Encode/Decode library =head1 VERSION version 0.34 =head1 SYNOPSIS use Convert::ASN1; $asn = Convert::ASN1->new; $asn->prepare(q< [APPLICATION 7] SEQUENCE { int INTEGER, str OCTET STRING } >); $pdu = $asn->encode( int => 7, str => "string"); $out = $asn->decode($pdu); print $out->{int}," ",$out->{str},"\n"; use Convert::ASN1 qw(:io); $peer = asn_recv($sock,$buffer,0); $nbytes = asn_read($fh, $buffer); $nbytes = asn_send($sock, $buffer, $peer); $nbytes = asn_send($sock, $buffer); $nbytes = asn_write($fh, $buffer); $buffer = asn_get($fh); $yes = asn_ready($fh) =head1 DESCRIPTION Convert::ASN1 encodes and decodes ASN.1 data structures using BER/DER rules. =head1 METHODS =head2 new ( [OPTIONS] ) Constructor, creates a new object. If given, B are the same ones as for L below. =head2 error () Returns the last error. =head2 configure ( OPTIONS ) Configure options to control how Convert::ASN1 will perform various tasks. Options are passed as name-value pairs. =over 4 =item encode Reference to a hash which contains various encode options. =item decode Reference to a hash which contains various decode options. =item encoding One of 'BER' or 'DER'. The default is 'BER' =item tagdefault One of 'EXPLICIT' or 'IMPLICIT'. Default tagging conventions are normally given in the ASN.1 module definition (not supported by the parser). The ASN.1 spec states EXPLICIT tagging is the default, but this option has IMPLICIT tagging default for backward compatibility reasons. =back Encode options =over 4 =item real Which encoding to use for real's. One of 'binary', 'nr1', 'nr2', 'nr3' =item time This controls how UTCTime and GeneralizedTime elements are encoded. The default is C. =over 4 =item utctime The value passed will be encoded without a zone, ie a UTC value. =item withzone The value will be encoded with a zone. By default it will be encoded using the local time offset. The offset may be set using the C configure option. =item raw The value passed should already be in the correct format and will be copied into the PDU as-is. =back =item timezone By default UTCTime and GeneralizedTime will be encoded using the local time offset from UTC. This will over-ride that. It is an offset from UTC in seconds. This option can be overridden by passing a reference to a list of two values as the time value. The list should contain the time value and the offset from UTC in seconds. =item bigint If during encoding an value greater than 32 bits is discovered and is not already a big integer object, then the value will first be converted into a big integer object. This option controls the big integer class into which the objects will be blessed. The default is to use Math::BigInt =back Decode options =over 4 =item time This controls how a UTCTime or a GeneralizedTime element will be decoded. The default is C. =over 4 =item utctime The value returned will be a time value as returned by the C