Drop experimental stuff.
[gnutls.git] / doc / protocol / x509guide.txt
blob4c96aa8f18dc32d79cf348a93bb99bb99d80c2e9
1                              X.509 Style Guide
2                              =================
4                   Peter Gutmann, pgut001@cs.auckland.ac.nz
5                                  October 2000
7 [This file is frequently cited as a reference on PKI issues, when in fact it
8  was really intended as X.509 implementation notes meant mostly for
9  developers, to tell them all the things the standards leave out.  If you're
10  looking for a general overview of PKI that includes most of what's in here
11  but presented in a more accessible manner, you should use "Everything you
12  never wanted to know about PKI but have been forced to find out",
13  http://www.cs.auckland.ac.nz/~pgut001/pubs/pkitutorial.pdf, a less technical
14  overview aimed at people charged with implementing and deploying the
15  technology.  If you need to know what you're in for when you work with PKI,
16  this is definitely the one to read.  Further PKI information and material can
17  be found on my home page, http://www.cs.auckland.ac.nz/~pgut001/].
19 There seems to be a lot of confusion about how to implement and work with X.509
20 certificates, either because of ASN.1 encoding issues, or because vagueness in
21 the relevant standards means people end up taking guesses at what some of the
22 fields are supposed to look like.  For this reason I've put together these
23 guidelines to help in creating software to work with X.509 certificates, PKCS
24 #10 certification requests, CRLs, and other ASN.1-encoded data types.
26                     I knew a guy who set up his own digital ID heirarchy, could
27                     issue his own certificates, sign his own controls, ran SSL
28                     on his servers, etc.  I don't need to pay Verisign a
29                     million bucks a year for keys that expire and expire.  I
30                     just need to turn off the friggen [browser warning]
31                     messages.
32                         -- Mark Bondurant, "Creating My Own Digital ID", in
33                            alt.computer.security.
35 In addition, anyone who has had to work with X.509 has probably experienced
36 what can best be described as ISO water torture, which involves ploughing
37 through all sorts of ISO, ANSI, ITU, and IETF standards, amendments, meeting
38 notes, draft standards, committee drafts, working drafts, and other
39 work-in-progress documents, some of which are best understood when held
40 upside-down in front of a mirror (this has lead to people trading hard-to-find
41 object identifiers and ASN.1 definitions like baseball cards - "I'll swap you
42 the OID for triple DES in exchange for the latest CRL extensions").  This
43 document is an attempt at providing a cookbook for certificates which should
44 give you everything that you can't easily find anywhere else, as well as
45 comments on what you'd typically expect to find in certificates.
47                     Given humanity's track record with languages, you wonder
48                     why we bother with standards committies
49                         -- Marcus Leech
51 Since the original X.509 spec is somewhat vague and open-ended, every
52 non-trivial group which has any reason to work with certificates has to produce
53 an X.509 profile which nails down many features which are left undefined in
54 X.509.
55                     You can't be a real country unless you have a beer and an
56                     airline.  It helps if you have some kind of a football
57                     team, or some nuclear weapons, but at the very least you
58                     need a beer.
59                         -- Frank Zappa
60                     And an X.509 profile.
61                         -- Me
63 The difference between a specification (X.509) and a profile is that a
64 specification doesn't generally set any limitations on combinations what can
65 and can't appear in various certificate types, while a profile sets various
66 limitations, for example by requiring that signing and confidentiality keys be
67 different (the Swedish profile requires this, and the German profile specifies
68 exclusive use of certificates for digital signatures).  The major profiles in
69 use today are:
71     PKIX - Internet PKI profile.
72     FPKI - (US) Federal PKI profile.
73     MISSI - US DoD profile.
74     ISO 15782 - Banking - Certificate Management Part 1: Public Key
75         Certificates.
76     TeleTrust/MailTrusT - German MailTrusT profile for TeleTrusT (it really is
77         capitalised that way).
78     German SigG Profile - Profile to implement the German digital signature law
79                 (the certificate profile SigI is particularly good, providing not just
80                 the usual specification but also examples of each certificate field and
81                 extension including the encoded forms).
82     ISIS Profile - Another German profile.
83     Australian Profile - Profile for the Australian PKAF (this may be the same
84         as DR 98410, which I haven't seen yet).
85     SS 61 43 31 Electronic ID Certificate - Swedish profile.
86     FINEID S3 - Finnish profile.
87     ANX Profile - Automotive Network Exchange profile.
88     Microsoft Profile - This isn't a real profile, but the software is
89         widespread enough and nonstandard enough that it constitutes a
90         significant de facto profile.
92                     No standard or clause in a standard has a divine right of
93                     existence
94                         -- A Microsoft PKI architect explaining Microsoft's
95                            position on standards compliance.
97 Unfortunately the official profiles tend to work like various monotheistic
98 religions where you either do what we say or burn in hell (that is, conforming
99 to one profile generally excludes you from claiming conformance with any others
100 unless they happen to match exactly).  This means that you need to either
101 create a chameleon-like implementation which can change its behaviour at a
102 whim, or restrict yourself to a single profile which may not be accepted in
103 some locales.  There is (currently) no way to mark a certificate to indicate
104 that it should be processed in a manner conformant to a particular profile,
105 which makes it difficult for a relying party to know how their certificate will
106 be processed by a particular implementation.
108                     Interoperability Testing.  Conclusion: It doesn't work
109                         -- Richard Lampart, CESG, talking about UK government
110                            PKI experiences
112 Although I've tried to take into account the various "Use of this feature will
113 result in the immediate demise of all small furry animals in an eight-block
114 radius"-type warnings contained in various standards documents to find a lowest
115 common denominator set of rules which should result in the least pain for all
116 concerned if they're adhered to, the existence of conflicting profiles makes
117 this a bit difficult.  The idea behind the guide is to at least try to present
118 a "If you do this, you should be OK" set of guidelines, rather than a "You're
119 theoretically allowed to do this if you can find an implementation which
120 supports it" feature list.
122 Finally, the guide contains a (rather lengthy) list of implementation errors,
123 bugs, and problems to look out for with various certificates and the related
124 software in order to allow implementors to create workarounds.
126 The conventions used in the text are:
128 - All encodings follow the DER unless otherwise noted.
130 - Most of the formats are ASN.1, or close enough to it to be understandable
131   (the goal was to make it easily understandable, not perfectly grammatically
132   correct).  Occasionally 15 levels of indirection are cut out to make things
133   easier to understand.
135                     The resulting type and value of an instance of use of the
136                     new value notation is determined by the value (and the type
137                     of the value) finally assigned to the distinguished local
138                     reference identified by the keyword VALUE, according to the
139                     processing of the macrodefinition for the new type notation
140                     followed by that for the new value notation.
141                         -- ISO 8824:1988, Annex A
143 Certificate
144 -----------
146 Certificate ::= SEQUENCE {
147     tbsCertificate          TBSCertificate,
148     signatureAlgorithm      AlgorithmIdentifier,
149     signature               BIT STRING
150     }
151                     The goal of a cert is to identify the holder of the
152                     corresponding private key, in a fashion meaningful to
153                     relying parties.
154                         -- Stephen Kent
156                     By the power vested in me, I now declare this text string
157                     and this bit string 'name' and 'key'.  What RSA has joined,
158                     let no man put asunder.
159                         -- Bob Blakley
161 The encoding of the Certificate may follow the BER rather than the DER.  At
162 least one implementation uses the indefinite-length encoding form for the
163 SEQUENCE.
166 TBSCertificate
167 --------------
169 The default tagging for certificates varies depending on which standard you're
170 using.  The original X.509v1 definition used the ASN.1 default of explicit
171 tags, with X.509v3 extensions in a separate module with implicit tags.  The
172 PKIX definition is quite confusing because the ASN.1 definitions in the
173 appendices use TAGS IMPLICIT but mix in X.509v3 definitions which use explicit
174 tags.  Appendix A has such a mixture of implied implicit and implied explicit
175 tags that it's not really possible to tell what tagging you're supposed to use.
176 Appendix B (which first appeared in draft 7, March 1998) is slightly better,
177 but still confusing in that it starts with TAGS IMPLICIT, but tries to
178 partially switch to TAGS EXPLICIT for some sections (for example the
179 TBSCertificate has an 'EXPLICIT' keyword in the definition which is probably
180 intended to signify that everything within it has explicit tagging, except that
181 it's not valid ASN.1).  The definitions given in the body of the document use
182 implicit tags, and the definitions of TBSCertificate and and TBSCertList have
183 both EXPLICIT and IMPLICIT tags present.  To resolve this, you can either rely
184 entirely on Appendix B with the X.509v1 sections moved into a separate section
185 declared without 'IMPLICIT TAGS', or use the X.509v3 definitions.  The SET
186 definitions consistently use implicit tags.
188                     Zaphod felt he was teetering on the edge of madness and
189                     wondered whether he shouldn't just jump over and have done
190                     with it.
191                         -- Douglas Adams, "The Restaurant at the End of the
192                            Universe"
194 TBSCertificate ::= SEQUENCE {
195     version          [ 0 ]  Version DEFAULT v1(0),
196     serialNumber            CertificateSerialNumber,
197     signature               AlgorithmIdentifier,
198     issuer                  Name,
199     validity                Validity,
200     subject                 Name,
201     subjectPublicKeyInfo    SubjectPublicKeyInfo,
202     issuerUniqueID    [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
203     subjectUniqueID   [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
204     extensions        [ 3 ] Extensions OPTIONAL
205     }
208 Version
209 -------
211 Version ::= INTEGER { v1(0), v2(1), v3(2) }
213 This field is used mainly for marketing purposes to claim that software is
214 X.509v3 compliant (even when it isn't).  The default version is v1(0), if the
215 issuerUniqueID or subjectUniqueID are present than the version must be v2(1) or
216 v3(2).  If extensions are present than the version must be v3(2).  An
217 implementation should target v3 certificates, which is what everyone is moving
218 towards.
219                     I was to learn later in life that we tend to meet any new
220                     situation by reorganizing: and a wonderful method it can be
221                     for creating the illusion of progress, while producing
222                     confusion, inefficiency and demoralization
223                         -- Petronius Arbiter, ~60 A.D
225 Note that the version numbers are one less than the actual X.509 version
226 because in the ASN.1 world you start counting from 0, not 1 (although it's not
227 necessary to use sequences of integers for version numbers.  X.420, for
228 example, is under the impression that 2 is followed by 22 rather than the more
229 generally accepted 3).
231 If your software generates v1 certificates, it's a good idea to actually mark
232 them as such and not just mark everything as v3 whether it is or not. Although
233 no standard actually forbids marking a v1 certificate as v3, backwards-
234 compatibility (as well as truth-in-advertising) considerations would indicate
235 that a v1 certificate should be marked as such.
238 SerialNumber
239 ------------
241 CertificateSerialNumber ::= INTEGER
243 This should be unique for each certificate issued by a CA (typically a CA will
244 keep a counter in persistent store somewhere, perhaps a config file under Unix
245 and in the registry under Windows).  A better way is to take the current time
246 in seconds and subtract some base time like the first time you ran the
247 software, to keep the numbers manageable.  This has the further advantage over
248 a simple sequential numbering scheme that it doesn't allow tracking of the
249 number of certificates which have been signed by a CA, which can have nasty
250 consequences both if various braindamaged government regulation attempts ever
251 come to fruition, and because by using sequential numbers a CA ends up
252 revealing just how few certs it's actually signing (at the cost of a cert per
253 week, the competition can find out exactly how many certs are being issued each
254 week).
256 Although this is never mentioned in any standards document, using negative
257 serial numbers is probably a bit silly (note the caveat about encoding INTEGER
258 values in the section on SubjectPublicKeyInfo).
260 Serial numbers aren't necessarily restricted to 32-bit quantitues.  For example
261 the RSADSI Commercial Certification Authority serial number is 0x0241000016,
262 which is larger than 32 bits, and Verisign seem to like using 128 or 160-bit
263 hashes as serial numbers.  If you're writing certificate-handling code, just
264 treat the serial number as a blob which happens to be an encoded integer (this
265 is particularly important for the case of the vendors who have forgotten that
266 the high bit of an integer is the sign bit, and generate negative serial
267 numbers for their certificates).
270 Signature
271 ---------
273 This rather misnamed field contains the algorithm identifier for the signature
274 algorithm used by the CA to sign the certificate.  There doesn't seem to be
275 much use for this field, although you should check that the algorithm
276 identifier matches the one of the signature on the cert (if someone can forge
277 the signature on the cert then they can also change the inner algorithm
278 identifier, it's possible that this was included because of some obscure attack
279 where someone who could convince (broken) signature algorithm A to produce the
280 same signature value as (secure) algorithm B could change the outer,
281 unprotected algorithm identifier from B to A, but couldn't change the inner
282 identifier without invalidating the signature.  What this would achieve is
283 unclear).
285 Be very careful with your use of Object Identifiers.  In many cases there are a
286 great many OIDs available for the same algorithm, but the exact OID you're
287 supposed to use varies somewhat.
289                     You see, the conditional modifers depend on certain
290                     variables like the day of the week, the number of players,
291                     chair positions, things like that. [...] There can't be
292                     more than a dozen or two that are pertinent.
293                         -- Robert Asprin, "Little Myth Marker"
295 Your best bet is to copy the OIDs everyone else uses and/or use the RSADSI or
296 X9 OIDs (rather than the OSI or OIW or any other type of OID).  OTOH if you
297 want to be proprietary while still pretending to follow a standard, use OSI
298 OID's which are often underspecified, so you can do pretty much whatever you
299 want with things like block formatting and padding.
301 Another pitfall to be aware of is that algorithms which have no parameters have
302 this specified as a NULL value rather than omitting the parameters field
303 entirely.  The reason for this is that when the 1988 syntax for
304 AlgorithmIdentifier was translated into the 1997 syntax, the OPTIONAL
305 associated with the AlgorithmIdentifier parameters got lost.  Later it was
306 recovered via a defect report, but by then everyone thought that algorithm
307 parameters were mandatory.  Because of this the algorithm parameters should be
308 specified as NULL, regardless of what you read elsewhere.
310                     The trouble is that things *never* get better, they just
311                     stay the same, only more so
312                         -- Terry Pratchett, "Eric"
315 Name
316 ----
318 Name ::= SEQUENCE OF RelativeDistinguishedName
320 RelativeDistinguishedName ::= SET OF AttributeValueAssertion
322 AttributeValueAssertion ::= SEQUENCE {
323     attributeType           OBJECT IDENTIFIER,
324     attributeValue          ANY
325     }
327 This is used to encode that wonderful ISO creation, the Distinguished Name
328 (DN), a path through an X.500 directory information tree (DIT) which uniquely
329 identifies everything on earth.  Although the RelativeDistinguishedName (RDN)
330 is given as a SET OF AttributeValueAssertion (AVA) each set should only contain
331 one element.  However you may encounter other people's certs which could
332 contain more than one AVA per set, there has been a reported sighting of a
333 certificate which contained more than one element in the SET.
335                     When the X.500 revolution comes, your name will be lined
336                     up against the wall and shot
337                         -- John Gilmore
338                     They can't be read, written, assigned, or routed.  Other
339                     than that, they're perfect
340                         -- Marshall Rose
342 When encoding sets with cardinality > 1, you need to take care to follow the
343 DER rules which say that they should be ordered by their encoded values
344 (although ASN.1 says a SET is unordered, the DER adds ordering rules to ensure
345 it can be encoded in an unambiguous manner).  What you need to do is encode
346 each value in the set, then sort them by the encoded values, and output them
347 wrapped up in the SET OF encoding,
349                     First things first, but not necessarily in that order.
350                         -- Dr.Who
352 however your software really shouldn't be producing these sorts of RDN entries.
354 In theory you don't have to use a Name for the subject name if you don't want
355 to; there is a subjectAltName extension which allows use of email addresses or
356 URL's.  In theory if you want to do this you can make the Name an empty
357 sequence and include a subjectAltName extension and mark it critical, but this
358 will break a lot of implementations.  Because it is possible to do this, you
359 should be prepared to accept a zero-length sequence for the subject name in
360 version 3 certificates.  Since the DN is supposed to encode the location of the
361 certificate in a DIT, having a null issuer name would mean you couldn't
362 actually locate the certificate, so CAs will need to use proper DNs.  The
363 S/MIME certificate spec codifies this by requiring that all issuer DNs be non-
364 null (so only an end-user certificate can have a null DN, and even then it's
365 not really recommended), and this requirement was back-ported to the PKIX
366 profile shortly before it was finalised.  The reason for requiring issuer DNs
367 is that S/MIME v2 and several related standards identify certificates by issuer
368 and serial number, so all CA certificates must contain an issuer DN (S/MIME v3
369 allows subjectKeyIdentifiers, but they're almost never used).
371 SET provides an eminently sensible definition for DNs:
373   Name ::= SEQUENCE SIZE(1..5) OF RelativeDistinguishedName
375   RelativeDistinguishedName ::= SET SIZE(1) OF AttributeTypeAndValue
377   AttributeTypeAndValue ::= { OID, C | O | OU | CN }
379 This means that when you see a SET DN it'll be in a fixed, consistent, and
380 easy-to-process format (note in particular the fixed maximum size, the
381 requirement for a single element per AVA, and the restriction to sensible
382 element types).
384 Note that the (issuer name, serialNumber (with a possible side order of
385 issuerUniqueID, issuerAltName, and keyUsage extension)) tuple uniquely
386 identifies a certificate and can be used as a key to retrieve certificates
387 from an information store.  The subject name alone does not uniquely identify
388 a certificate because a subject can own multiple certificates.
390 You would normally expect to find the following types of AVAs in an X.509
391 certificate, starting from the top:
393 countryName     ::= SEQUENCE { { 2 5 4 6 }, StringType( SIZE( 2 ) ) }
394 organization    ::= SEQUENCE { { 2 5 4 10 }, StringType( SIZE( 1...64 ) ) }
395 organizationalUnitName
396                 ::= SEQUENCE { { 2 5 4 11 }, StringType( SIZE( 1...64 ) ) }
397 commonName      ::= SEQUENCE { { 2 5 4 3 }, StringType( SIZE( 1...64 ) ) }
399 You might also find:
401 localityName    ::= SEQUENCE { { 2 5 4 7 }, StringType( SIZE( 1...64 ) ) }
402 stateOrProvinceName
403                 ::= SEQUENCE { { 2 5 4 8 }, StringType( SIZE( 1...64 ) ) }
405 Some profiles require at least some of these AVAs to be present, for example
406 the German profile requires at least a countryName and commonName, and in some
407 cases also an organization name.  This is a reasonable requirement, as a
408 minimum you should always include the country and common name.
410 Finally, you'll frequently also run into:
412 emailAddress    ::= SEQUENCE { { 1 2 840 113549 1 9 1 }, IA5String }
414 from PKCS #9, although this shouldn't be there.
416                     I can't afford to make exceptions.  Once word leaks out that
417                     a pirate has gone soft, people begin to disobey you and
418                     it's nothing but work, work, work all the time
419                         -- The Dread Pirate Roberts, "The Princess Bride"
421 The reason why oddball components like the emailAddress have no place in a DN
422 created as per the original X.500 vision is because the whole DN is intended to
423 be a strictly heirarchical construction specifying a path through a DIT.
424 Unfortunately the practice adopted by many CAs of tacking on an emailAddress,
425 an element which has no subordinate relationship to the other components of the
426 DN, creates a meaningless mishmash which doesn't follow this hierarchical
427 model.  For this reason the ITU defined the GeneralName, which specifically
428 allows for components such as email addresses, URL's, and other non-DN items.
429 GeneralNames are discussed in "Extensions" below.
431 Since the GeneralName provides a proper means of specifying information like
432 email addresses, your software shouldn't populate DNs with these components,
433 however for compatibility with legacy implementations you need to be able to
434 accept existing certificates which contain odd things in the DN.  Currently all
435 mailers appear to be able to handle an rfc822Name in an altName, so storing it
436 in the correct location shouldn't present any interoperability problems.  One
437 problem with email address handling is that many mailers will accept not only
438 'J.Random Luser <jrandom@aol.com>' as a valid emailAddress/rfc822Name but will
439 be equally happy with 'President William Jefferson Clinton <jrandom@aol.com>'.
440 The former is simply invalid, but the latter can be downright dangerous because
441 it completely bypasses the stated purpose of email certificates, which is to
442 identify the other party in an email exchange.  Both PKIX and S/MIME explicitly
443 require that an rfc822Name only contain an RFC 822 addr-spec which is defined
444 as local-part@domain, so the mailbox form 'Personal Name <local-part@domain>'
445 isn't allowed (many S/MIME implementations don't enforce this though).
446 Unfortunately X.509v3 just requires "an Internet electronic mail address
447 defined in accordance with Internet RFC 822" without tying it down any further,
448 so it could be either an addr-spec or a mailbox.
450                     Okay, I'm going home to drink moderately and then pass out.
451                         -- Steve Rhoades, "Married with Children"
453 The countryName is the ISO 3166 code for the country.  Noone seems to know how
454 to specify non-country-aligned organisations, it's possible that 'EU' will be
455 used at some point but there isn't any way to encode a non-country code
456 although some organisations have tried using 'INT'.  Actually noone really even
457 knows what a countryName is supposed to refer to (let alone something as
458 ambiguous as "locality"), for example it could be your place of birth, country
459 of citizenship, country of current residence, country of incorporation, country
460 where corporate HQ is located, country of choice for tax and/or jurisdictional
461 issues, or a number of other possibilities (moving from countryName to
462 stateOrProvinceName, people in the US military can choose a state as their
463 official "residence" for tax purposes even if they don't own any property in
464 that state, and politicians are allowed to run for office in one state while
465 their wives claim residence and run for office in another state).
467 The details of the StringType are discussed further down.  It's a good idea to
468 actually limit the string lengths to 64 characters as required by X.520
469 because, although many implementations will accept longer encoded strings in
470 certs, some can't manipulate them once they've been decoded by the software,
471 and you'll run into problems with LDAP as well.  This means residents of places
472 like Taumatawhakatangihangakoauotamateaturipukakapikimaungahoronukupokai-
473 whenuakitanataha are out of luck when it comes to getting X.509 certs.
475 Comparing two DNs has its own special problems, and is dealt with in the rather
476 lengthy "Comparing DNs" section below.
478 There appears to be some confusion about what format a Name in a certificate
479 should take.
480                     Insufficient facts always invite danger
481                         -- Spock, "Space Seed"
483 In theory it should be a full, proper DN, which traces a path through the X.500
484 DIT, eg:
486   C=US, L=Area 51, O=Hanger 18, OU=X.500 Standards Designers, CN=John Doe
488 but since the DIT's usually don't exist, exactly what format the DN should take
489 seems open to debate.  A good guideline to follow is to organize the namespace
490 around the C, O, OU, and CN attribute types, but this is directed primarily at
491 corporate structures.  You may also need to use ST(ate) and L(ocality) RDNs.
492 Some implementations seem to let you stuff anything with an OID into a DN,
493 which is not good.
494                     There is nothing in any of these standards that would
495                     prevent me from including a 1 gigabit MPEG movie of me
496                     playing with my cat as one of the RDN components of the DN
497                     in my certificate.
498                         -- Bob Jueneman on IETF-PKIX
499                            (There is a certificate of this form available from
500                            http://www.cs.auckland.ac.nz/~pgut001/pubs/
501                            {dave_ca|dave}.der, although the MPEG is limited to
502                            just over 1MB)
504 With a number of organisations moving towards the use of LDAP-based directory
505 services, it may be that we'll actually see X.500 directories in our lifetime,
507                     Well, it just so happens that your friend here is only
508                     mostly dead.  There's a big difference between mostly dead
509                     and all dead.  Now, mostly dead is slightly alive.
510                         -- Miracle Max, "The Princess Bride"
512 which means you should make an attempt to have a valid DN in the certificate.
513 LDAP uses the RFC 1779 form of DN, which is the opposite endianness to the ISO
514 9594 form used above:
516   CN=John Doe, OU=X.500 Standards Designers, O=Hanger 18, L=Area 51, C=US
518                     There are always alternatives
519                         -- Spock, "The Galileo Seven"
521 In order to work with LDAP implementations, you should ensure you only have a
522 single AVA per RDN (which also avoids the abovementioned DER-encoding hassle).
524 As the above text has probably indicated, DNs don't really work - there's no
525 clear idea of what they should look like, most users don't know about (and
526 don't want to know about) X.500 and its naming conventions, and as a
527 consequence of this the DN can end up containing just about anything.  At the
528 moment they seem to be heading in two main directions:
530  - Public CAs typically set C=CA country, O=CA name, OU=certificate type,
531    CN=user name
532    - A small subset of CAs in Europe which issue certs in accordance with
533      various signature laws and profiles with their own peculiar requirements
534      can have all sorts of oddities in the DN.  You won't run into many of
535      these in the wild.
536    - A small subsets of CAs will modify the DN by adding a unique ID value to
537      the CN to make it a truly Distinguished Name.  See the Bugs and
538      Peculiarities sections for more information on this.
539  - Private CAs (mostly people or organisations signing their own certs)
540    typically set any DN fields supported by their software to whatever makes
541    sense for them (some software requires all fields in the set
542    {C,O,OU,SP,L,CN} to be filled in, leading to strange or meaningless entries
543    as people try and guess what a Locality is supposed to be).
545 Generally you'll only run into certs from public CAs, for which the general
546 rule is that the cert is identified by the CN and/or email address.  Some CAs
547 issue certs with identical CN's and use the email address to disambiguate them,
548 others modify the CN to make it unique.  The accepted user interface seems to
549 be to let users search on the CN and/or email address (and sometimes also the
550 serial number, which doesn't seem terribly useful), display a list of matches,
551 and let the user pick the cert they want.  Probably the best strategy for a
552 user interface which handles certs is:
554   if( email address known )
555     get a cert which matches the email address (any one should do);
556   elseif( name known )
557     search for all certs with CN=name;
558     if( multiple matches )
559       display email addresses for matched certs to user, let them choose;
560   else
561     error;
563 If you need something unique to use as an identifier (for example for a
564 database key) and you know your own software (or more generally software which
565 can do something useful with the identifier) will be used, use an X.500
566 serialNumber in a subjectAltName directoryName or use a subjectAltName
567 otherName (which was explicitly created to allow user-defined identifiers).
568 For internal cert lookups, encode the cert issuer and serial number as a PKCS
569 #7 issuerAndSerialNumber, hash it down to a fixed size with SHA-1 (you can
570 either use the full 20 bytes or some convenient truncated form like 64 bits),
571 and use that to identify the cert.  This works because the internal structure
572 of the DN is irrelevant anyway, and having a fixed-size unique value makes it
573 very easy to perform a lookup in various data structures (for example the
574 random hash value generated leads to probabalistically balanced search trees
575 without requiring any extra effort).
578 Validity
579 --------
581 Validity ::= SEQUENCE {
582     notBefore               UTCTIME,
583     notAfter                UTCTIME
584     }
586 This field denotes the time at which you have to pay your CA a renewal fee to
587 get the certificate reissued.  The IETF originally recommended that all times
588 be expressed in GMT and seconds not be encoded, giving:
590   YYMMDDHHMMZ
592 as the time encoding.  This provided an unambiguous encoding because a value of
593 00 seconds was never encoded, which meant that if you read a UTCTime value
594 generated by an implementation which didn't use seconds and wrote it out again
595 with an implementation which did, it would have the same encoding because the
596 00 wouldn't be encoded.
598 However newer standards (starting with the Defence Messaging System (DMS),
599 SDN.706), require the format to be:
601   YYMMDDHHMMSSZ
603 even if the seconds are 00.  The ASN.1 encoding rules were in late 1996 amended
604 so that seconds are always encoded, with a special note that midnight is
605 encoded as ...000000Z and not ...240000Z.  You should therefore be prepared to
606 encounter UTCTimes with and without the final 00 seconds field, however all
607 newer certificates encode 00 seconds.  If you read and then write out an
608 existing object you may need to remember whether the seconds were encoded or
609 not in the original because adding the 00 will invalidate the signature (this
610 problem is slowly disappearing as pre-00 certificates expire).
612 A good workaround for this problem when generating certificates is to ensure
613 that you never generate a certificate with the seconds set to 00, which means
614 that even if other software re-encodes your certificate, it can't get the
615 encoding wrong.
617 At least one widely-used product generated incorrect non-GMT encodings so you
618 may want to consider handling the "+/-xxxx" time offset format, but you should
619 flag it as a decoding error nonetheless.
621 In coming up with the worlds least efficient machine-readable time encoding
622 format, the ISO nevertheless decided to forgo the encoding of centuries, a
623 problem which has been kludged around by redefining the time as UTCTime if the
624 date is 2049 or ealier, and GeneralizedTime if the date is 2050 or later (the
625 original plan was to cut over in 2015, but it was felt that moving it back to
626 2050 would ensure that the designers were either retired or dead by the time
627 the issue became a serious problem, leaving someone else to take the blame).
628 To decode a date, if it's UTCTime and the year is less than or equal to 49 it's
629 20xx, if it's UTCTime and the year is equal to or greater than 50 it's 19xx,
630 and if it's GeneralizedTime it's encoded properly (but shouldn't really be used
631 for dates before 2050 because you could run into interoperability problems with
632 existing software).  Yuck.
634 To make this even more fun, another spec at one time gave the cutover date as
635 2050/2051 rather than 2049/2050, and allowed GeneralizedTime to be used before
636 2050 if you felt you could get away with it.  It's likely that a lot of
637 conforming systems will briefly become nonconforming systems in about half a
638 centuries time, in a kind of security-standards equivalent of the age-old
639 paradox in which Christians and Moslems will end up in the other side's version
640 of hell.
641                     Confusion now hath made his masterpiece.
642                         -- Macduff, "Macbeth", II.i.
644 Another issue to be aware of is the problem of issuer certificates which have a
645 different validity time than the subject certificates they are used to sign.
646 Although this isn't specified in any standard, some software requires validity
647 period nesting, in which the subject validity period lies inside the issuer
648 validity period.  Most software however performs simple pointwise checking in
649 which it checks whether a cert chain is valid at a certain point in time
650 (typically the current time).  Maintaining the validity nesting requires that a
651 certain amount of care be used in designing overlapping validity periods
652 between successive generations of certificates in a hierarchy.  Further
653 complications arise when an existing CA is re-rooted or re-parented (for
654 example a divisional CA is subordinated to a corporate CA).  Australian and New
655 Zealand readers will appreciate the significance of using the term "re-rooted"
656 to describe this operation.
658 Finally, CAs are handling the problem of expiring certificates by reissuing
659 current ones with the same name and key but different validity periods.  In
660 some cases even CA roots have been reissued with the only different being
661 extended validity periods.  This can result in multiple identical-seeming
662 certificates being valid at one time (in one case three certificates with the
663 same DN and key were valid at once).  The semantics of these certificates/keys
664 are unknown.  Perhaps Validity could simply be renamed to RenewalFeeDueDate to
665 reflect its actual usage.
667 An alternative way to avoid expiry problems is to give the certificate an
668 expiry date several decades in the future.  This is popular for CA certs which
669 don't require an annual renewal fee.
672 SubjectPublicKeyInfo
673 --------------------
675 This contains the public key, either a SEQUENCE of values or a single INTEGER.
676 Keep in mind that ASN.1 integers are signed, so if any integers you want to
677 encode have the high bit set you need to add a single zero octet to the start
678 of the encoded value to ensure that the high bit isn't mistaken for a sign bit.
679 In addition you are allowed at most a single 0 byte at the start of an encoded
680 value (and that only when the high bit is set), if the internal representation
681 you use contains zero bytes at the start you have to remove them on encoding.
682 This is a bit of a nuisance when encoding signatures which have INTEGER values,
683 since you can't tell how big the encoded signature will be without actually
684 generating it.
687 UniqueIdentifier
688 ----------------
690 UniqueIdentifier ::= BITSTRING
692 These were added in X509v2 to handle the possible reuse of subject and/or
693 issuer names over time.  Their use is deprecated by the IETF, so you shouldn't
694 generate these in your certificates.  If you're writing certificate-handling
695 code, just treat them as a blob which happens to be an encoded bitstring.
698 Extensions
699 ----------
701 Extensions ::= SEQUENCE OF Extension
703 Extension ::= SEQUENCE {
704     extnid                  OBJECT IDENTIFIER,
705     critical                BOOLEAN DEFAULT FALSE,
706     extnValue               OCTETSTRING
707     }
709 X.509 certificate extensions are like a LISP property list: an ISO-standardised
710 place to store crufties.  Extensions can consist of key and policy information,
711 certificate subject and issuer attributes, certificate path constraints, CRL
712 distribution points, and private extensions.
714 X.509v3 and the X.509v4 draft contains the ASN.1 formats for the standard V3
715 Certificate, V2 CRL and V2 CRLEntry extensions.  In theory you should be able
716 to handle all of these, but there are large numbers of them and some may not be
717 in active use, or may be meaningless in some contexts.
719                     'It's called a shovel,' said the Senior Wrangler.  'I've
720                     seen the gardeners use them.  You stick the sharp end in
721                     the ground.  Then it gets a bit technical'
722                         -- Terry Pratchett, "Reaper Man"
724 The extensions are encoded with IMPLICIT tags, it's traditional to specify this
725 in some other part of the standard which is at least 20 pages away from the
726 section where the extension is actually defined (but see the comments above
727 about the mixture of explicit and implicit tags in ASN.1 definitions).
729 There are a whole series of superseded and deprecated OIDs for extensions,
730 often going back through several generations.  Older software and certificates
731 (and buggy newer software) will still use obsolete OIDs, any new software
732 should try and emit attributes tagged with the OID du jour rather than using
733 deprecated OIDs.
735 We can break extensions into two types, constraint extensions and informational
736 extensions.  Constraint extensions limit the way in which the key in a
737 certificate, or the certificate itself, can be used.  For example they may
738 limit the key usage to digital signatures only, or limit the DNs for which a CA
739 may issue certificates.  The most common constraint extensions are basic
740 constraints, key usage and extended key usage, certificate policies (modified
741 by policy mappings and policy constraints), and name constraints.  In contrast,
742 informational extensions contain information which may or may not be useful for
743 certificate users, but which doesn't limit the certificate use in any way.  For
744 example an informational extension may contain additional information which
745 identifies the CA which issued it.  The most common informational extensions
746 are key identifiers and alternative names.
748 The processing of these extensions is mostly specified in three different
749 standards, which means that there are three often subtly incompatible ways to
750 handle them.  In theory, constraint extensions should be enforced religiously,
751 however the three standards which cover certificates sometimes differ both in
752 how they specify the interpretation of the critical flag, and how they require
753 constraint extensions to be enforced.
755                     We could not get it out of our minds that some subtle but
756                     profoundly alien element had been added to the aesthetic
757                     feeling behind the technique.
758                         -- H.P.Lovecraft, "At the Mountains of Madness"
760 The general idea behind the critical flag is that it is used to protect the
761 issuing CA against any assumptions made by software which doesn't implement
762 support for a particular extension (none of the X.509-related standards provide
763 much of a definition for what a minimally, average, and fully compliant
764 implementation needs to support, so it's something of a hit and miss
765 proposition for an implementation to rely on the correct handling of a
766 particular extension).  One commentator has compared the various certificate
767 contraints as serving as the equivalent of a Miranda warning ("You have the
768 right to remain silent, you have the right to an attorney, ...") to anyone
769 using the certificate.  Without the critical flag, an issuer who believes that
770 the information contained in an extension is particularly important has no real
771 defence if the end users software chooses to ignore the extension.
773 The original X.509v3 specification requires that a certificate be regarded as
774 invalid if an unrecognised critical extension is encountered.  As for the
775 extension itself, if it's non-critical you can use whatever interpretation you
776 choose (that is, the extension is specified as being of an advisory nature
777 only).  This means that if you encounter constraints which require that a key
778 be used only for digital signatures, you're free to use it for encryption
779 anyway.  If you encounter a key which is marked as being a non-CA key, you can
780 use it as a CA key anyway.  The X.509v3 interpretation of extensions is a bit
781 like the recommended 130 km/h speed limit on autobahns, the theoretical limit
782 is 130, you're sitting there doing 180, and you're getting overtaken by
783 Porsches doing about 250.  The problem with the original X.509v3 definitions is
784 that although they specify the action to take when you don't recognise an
785 extension, they don't really define the action when you do recognise it.  Using
786 this interpretation, it's mostly pointless including non-critical extensions
787 because everyone is free to ignore them (for example the text for the keyUsage
788 extension says that "it is an advisory field and does not imply that usage of
789 the key is restricted to the purpose indicated", which means that the main
790 message it conveys is "I want to bloat up the certificate unnecessarily").
792 The second interpretation of extensions comes from the IETF PKIX profile.  Like
793 X.509v3, this also requires that a certificate be regarded as invalid if an
794 unrecognised critical extension is encountered.  However it seems to imply that
795 a critical extension must be processed, and probably considers non-critical
796 extensions to be advisory only.  Unfortunately the wording is ambiguous enough
797 that a number of interpretations exist.  Section 4.2 says that "CAs are
798 required to support <constraint extensions>", but the degree of support is left
799 open, and what non-CAs are supposed to do isn't specified.  The paragraph
800 which follows this says that implementations "shall recognise extensions",
801 which doesn't imply any requirement to actually act on what you recognise. Even
802 the term "process" is somewhat vague, since processing an extension can consist
803 of popping up a warning dialog with a message which may or may not make sense
804 to the user, with an optional "Don't display this warning again" checkbox.  In
805 this case the application certainly recognised the extension and arguably even
806 processed it, but it didn't force compliance with the intent of the extension,
807 which was probably what was intended by the terms "recognise" and "process".
809 The third interpretation comes from S/MIME, which requires that implementations
810 correctly handle a subset of the constraint and informational extensions.
811 However, as with PKIX, "correctly handle" isn't specified, so it's possible to
812 "correctly handle" an extension as per X.509v3, as per PKIX (choose the
813 interpretation you prefer), or as per S/MIME, which leaves the issue open (it
814 specifies that implementations may include various bits and pieces in their
815 extensions, but not how they should be enforced).  S/MIME seems to place a
816 slightly different interpretation on the critical flag, limiting its use to the
817 small subset of extensions which are mentioned in the S/MIME spec, so it's not
818 possible to add other critical extensions to an S/MIME certificate.
820                     "But it izz written!" bellowed Beelzebub.
821                     "But it might be written differently somewhere else" said
822                         Crowley.  "Where you can't read it".
823                     "In bigger letters" said Aziraphale.
824                     "Underlined" Crowley added.
825                     "Twice" suggested Aziraphale.
826                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
828 Finally, the waters are further muddied by CA policies, which can add their own
829 spin to the above interpretations.  For example the Verisign CPS, section
830 2.4.3, says that "all persons shall process the extension [...] or else ignore
831 the extension", which would seem to cover all the bases.  Other policies are
832 somewhat more specific, for example Netscapes certificate extension
833 specification says that the keyUsage extension can be ignored if it's not
834 marked critical, but Netscape Navigator does appear to enforce the
835 basicConstraints extension in most cases.
837 The whole issue is complicated by the fact that implementations from a large
838 vendor will reject a certificate which contains critical constraint extensions,
839 so that even if you interpret the critical flag to mean "this extension must be
840 enforced" (rather than just "reject this certificate if you don't recognise the
841 extension"), you can't use it because it will render the certificate unusable.
842 These implementations provide yet another interpretation of the critical flag,
843 "reject this certificate if you encounter a critical extension".  The same
844 vendor also has software which ignores the critical flag entirely, making the
845 software essentially useless to relying parties who can't rely on it to perform
846 as required (the exact behaviour depends on the software and version, so one
847 version might reject a certificate with a critical extension while another
848 would ignore a critical extension).
850                     Zaphod stared at him as if expecting a cuckoo to leap out
851                     of his forehead on a small spring.
852                         -- Douglas Adams, "The Restaurant at the End of the
853                            Universe"
855 Because of this confusion, it's probably impossible to include a set of
856 constraint extensions in a certificate which will be handled properly by
857 different implementations.  Because of problems like this, the digital
858 signature laws of some countries are requiring certification of the software
859 being used as part of compliance with the law, so that you can't just claim
860 that your software "supports X.509v3 certificates" (everyone claims this
861 whether they actually do or not), you actually have to prove that it supports
862 what's required by the particular countries' laws.  If you're in a country
863 which has digital signature legislation, make sure the software you're using
864 has been certified to conform to the legal requirements.
866 The best interpretation of constraint extensions is that if a certificate is
867 marked as an X.509v3 certificate, constraints should always be enforced.  This
868 includes enforcing implied settings if the extension is missing, so that a
869 certificate being used in a CA role which has no basicConstraints extension
870 present should be regarded as being invalid (note however the problem with
871 PKIX-compliant certificates described later on).  However even if one of the
872 standards is reworded to precisely define extension handling, there are still
873 plenty of other standards and interpretations which can be used.  The only
874 solution to this would be to include a critical policy extension which requires
875 that all constraint extensions up and down the cert chain be enforced.  Going
876 back to the autobahn analogy, this mirrors the situation at the Austrian
877 border, where everyone slows down to the strictly enforced speed limit as soon
878 as they cross the border.
880 Currently the only way to include a constraint enforcement extension is to make
881 it a critical policy extension.  This is somewhat unfortunate since including
882 some other random policy may make the extension unrecognisable, causing it, and
883 the entire certificate, to be rejected (as usual, what constitutes an
884 unrecognisable extension is open to debate: if you can process all the fields
885 in an extension but don't recognise the contents of one of the fields, it's up
886 to you whether you count this as being unrecognisable or not).
888 A better alternative would be to define a new extension, enforceConstraints:
890 enforceConstraints EXTENSION ::= {
891     SYNTAX EnforceConstraintsSyntax
892     IDENTIFIED BY id-ce-enforceConstraints
893     }
895 EnforceConstraintsSyntax ::= BOOLEAN DEFAULT FALSE
897 This makes the default setting compatible with the current "do whatever you
898 feel like" enforcement of extensions.  Enforcing constraints is defined as
899 enforcing all constraints contained in constraint extensions, incuding implied
900 settings if the extension is missing, as part of the certificate chain
901 validation process (which means that they should be enforced up and down the
902 cert chain).  Recognising/supporting/handling/<whatever other wording is used
903 in standards> an extension is defined as processing and acting on all
904 components of all fields of an extension in a manner which is compliant with
905 the semantic intent of the extension.
907                     'Where was I?' said Zaphod Beeblebrox the Fourth.
908                     'Pontificating' said Zaphod Beeblebrox.
909                     'Oh yes'.
910                         -- Douglas Adams, "The Restaurant at the End of the
911                            Universe"
913 Just to mention a further complication with critical extensions, there are
914 instances in which it's possible to create certificates which are always
915 regarded as being invalid due to conflicts with extensions.  For example a
916 generation n-1 critical extension might be replaced by a generation n critical
917 extension, resulting in a mixture of certs with generation n-1 extensions,
918 generation n-1 and generation n extensions (for compatibility) and (eventually)
919 generation n extensions only.  However until every piece of software is
920 upgraded, generation n-1 software will be forced to reject all certs with
921 generation n extensions, even the (supposedly) backwards-compatibile certs with
922 both generations of extension in them.
924                     'Mr.Beeblebrox, sir', said the insect in awed wonder,
925                     'you're so weird you should be in movies'.
926                         -- Douglas Adams, "The Restaurant at the End of the
927                            Universe"
929 Key Usage, Extended Key Usage, and Netscape cert-type
931 X.509 and PKIX use keyUsage and extKeyUsage to select the key to use from a
932 selection of keys unless the extension is marked critical, in which case it's
933 treated as a usage restriction.  Microsoft claims to support key usage
934 enforcement, although experimentation with implementations has shown that it's
935 mostly ignored (see the entry on Microsoft bugs further on).  In addition if an
936 extKeyUsage extension is present, all certificates in the chain up to the CA
937 root must also support the same extKeyUsage (so that, for example, a general-
938 purpose CA can't sign a server gated crypto certificate - the reasoning behind
939 this is obvious).  As it turns out though, extKeyUsage seems to be mostly
940 ignored just like keyUsage.  
942 Netscape uses keyUsage as a key selection mechanism, and uses the Netscape
943 cert-type extension in a complex manner described in the Netscape certificate
944 extension specification.  Since the cert-type extension includes the equivalent
945 of the basicConstraints CA flag, it's possible to specify some types of CA with
946 the cert-type extension.  If you do this, you should be careful to synchronise
947 the basicConstraints CA flag with the setting of the cert-type extension
948 because some implementations (you can probably guess which one) will allow a
949 Netscape CA-like usage to override a non-CA keyUsage value, treating the
950 certificate as if it were a CA certificate. In addition Netscape also enforces
951 the same extKeyUsage chaining as Microsoft. 
953 Unfortunately the extKeyUsage chaining interpretation is wrong according to
954 PKIX, since the settings apply to the key in the certificate (ie the CA's key)
955 rather than the keys in the certificates it issues.  In other words an
956 extKeyUsage of emailProtection would indicate that the CA's certificate is
957 intended for S/MIME encryption, not that the CA can issue S/MIME certificates.
958 Both of the major implementators of certificate-handling software use the
959 chaining interpretation, but there also exist implementations which use the
960 PKIX interpretation, so the two main camps will fail to verify the other side's
961 cert chains unless they're in the (smaller) third camp which just ignores
962 extKeyUsage.
964 For keyUsage there is much disagreement over the use of the digitalSignature
965 and nonRepuduation bits since there was no clear definition in X.509 of when
966 the nonrepudiation flag should be used alongside or in place of the digital
967 signature flag.  One school of thought holds that digitalSignature should be
968 used for ephemeral authentication (something which occurs automatically and
969 frequently) and nonRepuduation for legally binding long-term signatures
970 (something which is performed consciously and less frequently).  Another school
971 of thought holds that nonRepuduation should act as an additional function for
972 the digitalSignature mechanism, with digitalSignature being a mechanism bit and
973 nonRepuduation being a service bit.  The different profiles are split roughly
974 50:50 on this, with some complicating things by specifying that both bits
975 should be set but the certificate not be used for one or the other purpose.
976 Probably the best usage is to use digitalSignature for "digital signature for
977 authentication purposes" and nonRepudiation for "digital signature for
978 nonrepudiation purposes".
980                     "I think" said the Metatron, "that I shall need to seek
981                         further instructions".
982                     "I alzzo" said Beelzebub.
983                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
985 In terms of profiles, MISSI and FPKI follow the above recommendation, PKIX uses
986 nonRepudiation strictly for nonrepudiation and digitalSignature for everything
987 else, ISO uses digitalSignature for entity authentication and nonRepudiation
988 strictly for nonrepudiation (leaving digital signatures for data authentication
989 without nonrepudiation hanging), and others use something in between.  When
990 this issue was debated on PKI lists in mid-1998, over 100 messages were
991 exchanged without anyone really being able to uncontestably define what
992 digitalSignature and nonRepudiation really signified.  The issue is further
993 confused by the fact that noone can agree on what the term "nonRepudiation"
994 actually means, exemplified by a ~200-message debate in mid-1999 which couldn't
995 reach any useful conclusion.
997                     He had attached the correct colour-coded wires to the
998                     correct pins; he'd checked that it was the right amperage
999                     fuse; he'd screwed it all back together.  So far, no
1000                     problems.  He plugged it into the socket.  Then he switched
1001                     the socket on.  Every light in the house went out.
1002                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
1004 Although everyone has their own interpretation, a good practical definition is
1005 "Nonrepudiation is anything which fails to go away when you stop believing in
1006 it".  Put another way, if you can convince a user that it isn't worth trying to
1007 repudiate a signature then you have nonrepudiation.  This can take the form of
1008 having them sign a legal agreement saying they won't try to repudiate any of
1009 their signatures, giving them a smart card and convincing them that it's so
1010 secure that any attempt to repudiate a signature generated with it would be
1011 futile, threatening to kill their kids, or any other method which has the
1012 desired effect.  One advantage (for vendors) is that you can advertise just
1013 about anything as providing nonrepudiation, since there's sure to be some
1014 definition which matches whatever it is you're doing (there are
1015 "nonrepudiation" schemes in use today which employ a MAC using a secret shared
1016 between the signer and the verifier, which must be relying on a particularly
1017 creative definition of nonrepudiation).
1019                     Bei ihnen auf dem Server muesste irgendwie ein Key
1020                     rumliegen, den ich mit Netscape vermutlich erzeugt hab.
1021                     Wenn da mein Name drin steht, dann wird er das schon sein.
1022                     Koennten sie mir den zertifizieren?
1023                         -- endergone Zwiebeltuete
1025                     One might as well add a "crimeFree" (CF) bit with usage
1026                     specified as 'The crimeFree bit is asserted when subject
1027                     public key is used to verify digital signatures for
1028                     transactions that are not a perpetration of fraud or other
1029                     illegal activities'
1030                         -- Tony Bartoletti on ietf-pkix
1032                     I did have the idea that we mandate that CAs MUST set this
1033                     bit randomly whenever a keyUsage extension is present, just
1034                     to stop people who argue that its absence has a meaning.
1035                         -- Stephen Farrell on ietf-pkix
1038 Basic Constraints
1040 This is used to specify whether a certificate is a CA certificate or not.  You
1041 should always mark this critical, because otherwise some implementations will
1042 ignore it and allow a non-CA certificate to act as a CA.
1044 Alternative Names
1046 The subject and issuer alternative names are used to specify all the things
1047 which aren't suitable for a DN, which for most purposes means practically
1048 everything of any use on the Internet (X.509v3 defines the alternative names
1049 (or, more specifically, the GeneralName type) for use in specifying identifying
1050 information which isn't suited for, or part of, a DN).  This includes email
1051 addresses, URL's for web pages, server addresses, and other odds and ends like
1052 X.400 and EDI addresses.  There's also a facility to include your postal
1053 address, physical address, phone, fax and pager numbers, and of course the
1054 essential MPEG of your cat.
1056 The alternative names can be used for certificate identification in place of
1057 the DNs, however the exact usage is somewhat unclear.  In particular if an
1058 altName is used for certificate chaining purposes, there's a roughly 50/50
1059 split of opinion as to whether all the items in the altName must match or any
1060 one of the items must match.  For example if an altName contains three URL's in
1061 the issuer and one in the client (which matches one of the issuer URL's), noone
1062 really knows whether this counts as a valid altName match or not.  Eventually
1063 someone will make a decision one way or the other, probably the S/MIME
1064 standards group who are rather reliant on altNames for some things (the S/MIME
1065 group have requested that the PKIX group make DNs mandatory in order to allow
1066 proper certificate chaining, and the S/MIME specs themselves require DNs for
1067 CAs).  Until this is sorted out, it's not a good idea to rely on altNames for
1068 chaining.
1070 This confusion is caused by the fact that an altName is serving two conflicting
1071 purposes.  The first of these is to provide extra information on the
1072 certificate owner which can't be specified in the DN, including things like
1073 their phone number, email address, and physical address.  The second is to
1074 provide an alternative to the ITU-managed (or, strictly speaking, non-managed)
1075 DN space.  For example a DNS name or IP address, which falls outside the range
1076 of ITU (non-)management, is controlled by the IETF, which has jurisdiction over
1077 the name space of the Internet-related altName components.  However since an
1078 altName can only specify a collection of names with a single critical attribute
1079 to cover all of them, there's no way to differentiate between something which
1080 really is critical (for example an rfc822Name being used in place of DN) and
1081 something which is merely present to provide extra details on the certificate
1082 owner (an rfc822Name being provided as a contact address).  One IETF draft
1083 overloaded this even further by forcing authorityInfoAccess semantics onto some
1084 of the altName components.
1086 This ambiguity is complicated by the presence of other attributes like path
1087 processing constraints.  For example does an included or excluded subtree
1088 constraint containing a DN cover the subjectName DN, the altName directoryName,
1089 or both?.  More seriously, since a subjectName and altName directoryName have
1090 the same form, it's possible to specify an identical DN in two different ways
1091 across an issuer and subject cert, leading to the same problem described below
1092 in the name constraints section in which it's possible to evade constraint
1093 checks by using alternative encodings for the same item.
1095 The solution to this problem would be to split the altName into two new
1096 extensions, a true altName which provides a single alternative to the
1097 subjectName (for example a single dNSName or rfc822Name) and which is used only
1098 when the subject DN is empty, and a collection of other information about the
1099 subject which follows the current altName syntax but which is used strictly for
1100 informational purposes.  The true altName provides a single alternative for the
1101 subjectName, and the informational altName provides any extra identification
1102 information which the subject may want to include with their certificate.
1104 A different (and much uglier) solution is to try and stuff everything
1105 imaginable into a DN.  The problem with this approach is that it completely
1106 destroys any hope of interoperability with directories, especially X.500
1107 directories which rely on search arguments being predefined as a type of
1108 filter.  Unless you have this predefined filter, you can't easily search the
1109 directory for a match, so it's necessary to have some limits placed on the
1110 types of names (or schemas in X.500-speak) which are acceptable.
1111 Unfortunately the "stuff everything into a DN" approach violates this
1112 principle, making the result un-searchable within a directory, which voids the
1113 reason for having the DN in the first place.
1115 Certificate Policies and Policy Mappings and Constraints
1117 The general idea behind the certificate policies extension is simple enough, it
1118 provides a means for a CA to identify which policy a certificate was issued
1119 under.  This means that when you check a certificate, you can ensure that each
1120 certificate in the chain was issued under a policy you feel comfortable with
1121 (certain security precautions taken, vetting of employees, physical security of
1122 the premises, no loud ties, that sort of thing).  The certificatePolicies
1123 extension (in its minimal form) provides a means of identifying the policy a
1124 certificate was issued under, and the policyMappings extension provides a means
1125 of mapping one policy to another (that is, for a CA to indicate that policy A,
1126 under which it is issuing a certificate, is equivalent to policy B, which is
1127 required by the certificate user).
1129 Unfortunately on top of this there are qualifiers for the certificatePolicies
1130 and the policyConstraints extension to muddy the waters.  As a result, a
1131 certificate policy often consists of a sequence of things identified by unknown
1132 object identifiers, each with another sequence of things identified by
1133 partially known, partially unknown object identifiers, with optional extra
1134 attachments containing references to other things which software is expected to
1135 know about by magic or possibly some form of quantum tunnelling.
1137                     Marx Brothers fans will possibly recall the scene in "A Day
1138                     at the Races" in which Groucho, intending to put his money
1139                     on Sun-up, is induced instead to buy a coded tip from Chico
1140                     and is able to establish the identity of the horse only, at
1141                     some cost in terms of time and money, by successive
1142                     purchases from Chico of the code book, the master code
1143                     book, the breeders' guide and various other works of
1144                     reference, by the end of which the race is over, Sun-up
1145                     having won.
1146                         -- Unknown, forwarded by Ed Gerck to cert-talk
1148 This makes it rather difficult to make validity decisions for a certificate
1149 which have anything more complex than a basic policyIdentifier present.
1151 Because of this, you should only use a single policyIdentifier in a
1152 certificate, and forgo the use of policy qualifiers and other odds and ends.
1153 Currently noone but Verisign appears to use these, the presence of these
1154 qualifiers in the PKIX profile may be related to the presence of Verisign in
1155 the PKIX profiling process.
1157 Name Constraints
1159 The name constraints are used to constrain the certificates' DN to lie inside
1160 or outside a particular subtree, with the excludedSubtrees field taking
1161 precedence over the permittedSubtrees field.  The principal use for this
1162 extension is to allow balkanization of the certificate namespace, so that a CA
1163 can restrict the ability of any CAs it certifies to issue certificates outside
1164 a very restricted domain.
1166 Unfortunately if the X.500 string encoding rules are followed, it's always
1167 possible to avoid the excludedSubtrees by choosing unusual (but perfectly
1168 valid) string encodings which don't appear to match the excludedSubtrees (see
1169 the section on string encodings for more details on this problem).  Although
1170 PKIX constrains the string encodings to allow the nameConstraints to function,
1171 it's a good idea to rely on permittedSubtrees rather than excludedSubtrees for
1172 constraint enforcement (actually since virtually nothing supports this
1173 extension, it's probably not a good idea to rely too much on either type of
1174 constraint, but when it is supported, use permitted rather than excluded
1175 subtrees).
1177 Subject and Authority Key Identifiers
1179 These are used to provide additional identification information for a
1180 certificate.  Unfortunately it's specified in a somewhat complex manner which
1181 requires additional ASN.1 constraints or text to explain it, you should treat
1182 it as if it were specified with the almost-ASN.1 of:
1184 AuthorityKeyIdentifier ::= CHOICE {
1185     keyIdentifier [ 0 ] OCTET STRING,
1186     authorityCert [ 1 ] GeneralNames, authoritySerialNumber [ 2 ] INTEGER
1187     }
1189 X.509v3 allows you to use both types of identifier, but other standards and
1190 profiles either recommend against this or explicitly disallow it, allowing only
1191 the keyIdentifier.  Various profiles have at various times required the use of
1192 the SHA-1 hash of the public key (whatever that constitutes), the SHA-1 hash of
1193 the subjectPublicKeyInfo data (for some reason this has to be done *without*
1194 the tag and length at the start), the SHA-1 hash of the subjectPublicKey (again
1195 without the tag, length, and unused bits portion of the BIT STRING, which
1196 leaves just the raw public key data but omits the algorithm identifier and
1197 parameters so that two keys for different algorithms with different parameters
1198 which happen to share the same public key field end up with the same hash), a
1199 64-bit hash of the subjectPublicKeyInfo (presumably with the tag and length), a
1200 60-bit hash of the subjectPublicKey (again with tag and length) with the first
1201 four bits set to various values to indicate MISSI key types, and some sort of
1202 unique value such as a monotonically increasing sequence.  Several newer
1203 profiles have pretty much given up on this and simply specify "a unique value".
1204 RFC 2459 also allows "a monotomically increasing sequence of integers", which
1205 is a rather bad move since the overall supply of unique small integers is
1206 somewhat limited and this scheme will break as soon as a second CA decides to
1207 issue a cert with a "unique" subjectKeyIdentifier of the same value.
1209 To balance the problems caused by this mess of conflicting and incompatible
1210 standards, it appears that most implementations either ignore the keyIdentifier
1211 entirely or don't bother decoding it, because in 1997 and 1998 a widely-used CA
1212 accidentally issued certificates with an incorrect encoding of the
1213 keyIdentifier (it wasn't even valid ASN.1 data, let alone X.509-conformant
1214 ASN.1) without anyone noticing.  Although a few standards require that a
1215 keyIdentifier be used, its absence doesn't seem to cause any problems for
1216 current implementations.
1218 Recommendation: Don't even try and decode the authorityKeyIdentifier field,
1219     just treat everything inside the OCTET STRING hole as an opaque blob.
1220     Given that most current implementations seem to ignore this extension,
1221     don't create certificate chains which require it to be processed in order
1222     for the chaining to work.
1224 The claimed reason for using the keyIdentifier rather than the
1225 issuerAndSerialNumber is because it allows a certificate chain to be re-rooted
1226 when an intermediate CA changes in some manner (for example when its
1227 responsibilities are handed off from one department in an organisation to
1228 another).  If the certificate is identified through the keyIdentifier, no
1229 nameConstraints are present, the certificate policies are identical or mapped
1230 from one to the other, the altNames chain correctly, and no policyConstraints
1231 are present, then this type of re-rooting is possible (in case anyone missed
1232 the sarcasm in there, the gist is that it's highly unlikely to work).
1234 Other Extensions
1236 There are a wide variety of other extensions defined in various profiles.
1237 These are in effect proprietary extensions because unless you can track down
1238 something which recognises them (typically a single-vendor or small-group-of-
1239 vendors product), you won't be able to do much with them - most software will
1240 either ignore them completely or reject the certificate if the extension is
1241 marked critical and the software behaves as required.  Unless you can mandate
1242 the use of a given piece of certificate-processing software which you've
1243 carefully tested to ensure it processes the extension correctly, and you can
1244 block the use of all other software, you shouldn't rely on these extensions.
1245 Obviously if you're in a closed, carefully controlled environment (for example
1246 a closed shop EDI environment which requires the use of certain extensions such
1247 as reliance limits) the use of specialised extensions isn't a problem, but
1248 otherwise you're on your own.
1250 In addition to the use of other people's extensions, you may feel the need to
1251 define your own.  In short if you're someone other than Microsoft (who can
1252 enforce the acceptance of whatever extensions they feel like), don't do it.
1253 Not only is it going to be practically impossible to find anything to support
1254 them (unless you write it yourself), but it's also very easy to stuff all sorts
1255 of irrelevant, unnecessary, and often downright dangerous information into
1256 certificates without thinking about it.  The canonical example of something
1257 which has no place in a certificate is Microsoft's cAKeyCertIndexPair
1258 extension, which records the state of the CA software running on a Windows 2000
1259 machine at the time the certificate was generated (in other words it offloads
1260 the CA backup task from the machine's administrator to anyone using one of the
1261 certificates).
1262                     Only wimps use tape backup: _real_ men just upload their
1263                     important stuff on ftp, and let the rest of the world
1264                     mirror it.
1265                         -- Linus Torvalds
1267 The canonical example of a dangerous certificate extension is one which
1268 indicates whether the owner is of legal age for some purpose (buying
1269 alcohol/driving/entry into nightclubs/whatever).  Using something like a
1270 drivers license for this creates a booming demand for forged licenses which, by
1271 their very nature, are difficult to create and tied to an individual through a
1272 photo ID.  Doing the same thing with a certificate creates a demand for those
1273 over the age limit to make their keys (trivially copied en masse and not tied
1274 to an individual) available to those under the age limit, or for those under
1275 the age limit to avail themselves of the keys in a surreptitious manner.  The
1276 fact that the borrowed key which is being used to buy beer or rent a porn movie
1277 can also be used to sign a legally binding contract or empty a bank account
1278 probably won't be of concern until it's too late.  This is a good example of
1279 the law of unintended consequences in action.
1281                     If scientists can be counted on for anything, it's for
1282                     creating unintended consequences.
1283                         -- Michael Dougan
1285 A related concern about age indicators in certificates, which was one of the
1286 many nails in X.500's coffin, is the fact that giving a third party the
1287 information needed to query a certificate directory in order to locate, for
1288 example, all teenage girls in your localityName, probably wouldn't be seen as a
1289 feature by most certificate holders.  Similar objections were made to the use
1290 of titles in DNs, for example a search on a title of "Ms" would have allowed
1291 someone to locate all single women in their localityName, and full-blown X.500
1292 would have provided their home addresses and probably phone numbers to boot.
1293 Until early 1999 this type of extension only existed as a hypothetical case,
1294 but it's now present as a mandatory requirement in at least one digital
1295 signature law, which also has as a requirement that all CAs publish their
1296 certificates in some form of openly-accessible directory.
1298                     I saw, and I heard an eagle, flying in mid heaven, saying
1299                     with a loud voice, "Woe! Woe! Woe for those who dwell on
1300                     the earth"
1301                         -- Revelations 8:15
1304 Character Sets
1305 --------------
1307 Character strings are used in various places (most notably in DNs), and are
1308 encumbered by the fact that ASN.1 defines a whole series of odd subsets of
1309 ASCII/ISO 646 as character string types, but only provides a few peculiar and
1310 strange oddball character encodings for anything outside this limited character
1311 range.
1312                     The protruding upper halves of the letters now appear to
1313                     read, in the local language, "Go stick your head in a pig",
1314                     and are no longer illuminated, except at times of special
1315                     celebration.
1316                         -- Douglas Adams, "The Restaurant at the End of the
1317                            Universe"
1319 To use the example of DNs, the allowed string types are:
1321 DirectoryString ::= CHOICE {
1322     teletexString           TeletexString (SIZE (1..maxSize)),
1323     printableString         PrintableString (SIZE (1..maxSize)),
1324     bmpString               BMPString (SIZE (1..maxSize)),
1325     universalString         UniversalString (SIZE (1..maxSize))
1326     }
1328 The easiest one to use, if you can get away with it, is IA5String, which is
1329 basically 7-bit ASCII (including all the control codes), but with the dollar
1330 sign potentially replaced with a "currency symbol".  A more sensible
1331 alternative is VisibleString (aka ISO646String), which is IA5String without the
1332 control codes (this has the advantage that you can't use it to construct macro
1333 viruses using ANSI control sequences).  In the DirectoryString case, you have
1334 to make do with PrintableString, which is one of the odd ASCII/ISO 646 subsets
1335 (for example you can't encode an '@', which makes it rather challenging to
1336 encode email addresses).
1338 Beyond that there is the T.61/TeletexString, which can select different
1339 character sets using escape codes (this is one of the aforementioned "peculiar
1340 and strange oddball encodings").  The character sets are Japanese Kanji (JIS C
1341 6226-1983, set No. 87), Chinese (GB 2312-80, set No. 58), and Greek, using
1342 shifting codes specified in T.61 or the international version, ISO 6937
1343 (strictly speaking T61String isn't defined in T.61 but in X.680, which defines
1344 it by profiling ISO 2022 character set switching).  Some of the characters have
1345 a variable-length encoding (so it takes 2 bytes to encode a character, with the
1346 interpretation being done in a context-specific manner).  The problem isn't
1347 helped by the fact that the T.61 specification has changed over the years as
1348 new character sets were added, and since the T.61 spec has now been withdrawn
1349 by the ITU there's no real way to find out exactly what is supposed to be in
1350 there (but see the previous comment on T.61 vs T61String - a T61String isn't
1351 really a T.61 string).  Even using straight 8859-1 in a T61String doesn't
1352 always work, for example the 8859-1 character code for the Norwegian OE
1353 (slashed O) is defined using a T.61 escape sequence which, if present in a
1354 certificate, may cause a directory to reject the certificate.
1356                     And then there came the crowning horror of all - the
1357                     unbelievable, unthinkable, almost unmentionable thing.
1358                         -- H.P.Lovecraft, "The Statement of Randolph Carter"
1360 For those who haven't reached for a sick bag yet, one definition of T61String
1361 is given in ISO 1990 X.208 which indicates that it contains registered
1362 character sets 87, 102 (a minimalist version of ASCII), 103 (a character set
1363 with the infamous "floating diacritics" which means things like accented
1364 characters are encoded as "<add an accent to the next character> + <character>"
1365 rather than with a single character code), 106 and 107 (two useless sets
1366 containing control characters which noone would put in a name), SPACE + DELETE.
1367 The newer ITU-T 1997 and ISO 1998 X.680 adds the character sets 6, 126, 144,
1368 150, 153, 156, 164, 165, and 168 (the reason for some of these additions is
1369 because once a character set is registered it can never change except by
1370 "clarifying" it, which produces a completely new character set with a new
1371 number (as with sex, once you make a mistake you end up having to support it
1372 for the rest of your life)).  In fact there are even more definitions of
1373 T61String than that: The original CCITT 1984 ASN.1 spec defined T61String by
1374 reference to a real T.61 recommendation (from which finding the actual
1375 permitted characters is challenging, to put it mildly), then the ISO 1986 spec
1376 defined them by reference to the international register, then the CCITT 1988
1377 spec changed them again (the ISO 1990 spec described above may be identical to
1378 the CCITT 1988 one), and finally they were changed again for ISO/ITU-T 1994
1379 (this 1994 spec may again be the same as ITU-T 1997 and ISO 1998).  I'm not
1380 making this up!
1381                     The disciples came to him privately, saying, "Tell us, what
1382                     is the sign of your coming, and of the end of the world?"
1383                     [...] "You will hear of wars and rumors of wars; there will
1384                     be famines, plagues, and earthquakes in various places; the
1385                     sun will be darkened, the moon will not give her light, the
1386                     stars will fall from the sky, the powers of the heavens
1387                     will be shaken; certificates will be issued with floating
1388                     diacritics in their DNs; and then the end will come".
1389                         -- Matthew 24 (mostly)
1391 The encoding for this mess is specified in X.209 which indicates that the
1392 default character sets at the start of a string are 102, 106 and 107, although
1393 in theory you can't really make this assumption without the appropriate escape
1394 sequences to invoke the correct character set.  The general consensus amoung
1395 the X.500/ISODE directory crowd is that you assume that set 103 is used by
1396 default, although Microsoft and Netscape had other ideas for their LDAPv2
1397 products.  In certificates, the common practice seems to be to use straight
1398 latin-1, which is set numbers 6 and 100, the latter not even being an allowed
1399 T61String set.
1400                     There are those who will say Danforth and I were utterly
1401                     mad not to flee for our lives after that; since our
1402                     conclusions were now completely fixed, and of a nature I
1403                     need not even mention to those who have read my account so
1404                     far.
1405                         -- H.P.Lovecraft, "At the Mountains of Madness"
1407 Next are the BMPString and UniversalString, with BMPString having 16-bit
1408 characters (UCS-2) and UniversalString having 32-bit characters (UCS-4), both
1409 encoded in big-endian format.  BMPString is a subset of UniversalString, being
1410 the 16-bit character range in the 0/0 plane (ie the UniversalString characters
1411 in which the 16 high bits are 0), corresponding to straight ISO 10646/Unicode
1412 characters.  The ASN.1 standard says that UniversalString should only be used
1413 if the encoding possibilities are constrained, it's better to avoid it entirely
1414 and only use BMPString/ISO 10646/Unicode.
1416 However, there is a problem with this: at the moment few implementors know how
1417 to handle or encode BMPStrings, and people have made all sorts of guesses as to
1418 how Unicode strings should be encoded: with or without Unicode byte order marks
1419 (BOMs), possibly with a fixed endianness, and with or without the terminating
1420 null character.
1421                     I might as well be frank in stating what we saw; though at
1422                     the time we felt that it was not to be admitted even to
1423                     each other.  The words reaching the reader can never even
1424                     suggest the awfulness of the sight itself.
1425                         -- H.P.Lovecraft, "At the Mountains of Madness"
1427 The correct format for BMPStrings is: big-endian 16-bit characters, no Unicode
1428 byte order marks (BOMs), and no terminating null character (ISO 8825-1 section
1429 8.20).
1431 An exception to this is PFX/PKCS #12, where the passwords are converted to a
1432 Unicode BMPString before being hashed.  However both Netscape and Microsoft's
1433 early implementations treated the terminating null characters as being part of
1434 the string, so the PKCS #12 standard was retroengineered to specify that the
1435 null characters be included in the string.
1437 A final string type which is presently only in the PKIX profile but which
1438 should eventually appear elsewhere is UTF-8, which provides a means of encoding
1439 7, 8, 16, and 32-bit characters into a single character string.  Since ASN.1
1440 already provides character string types which cover everything except some of
1441 the really weird 32-bit characters which noone ever uses,
1443                     It was covered in symbols that only eight other people in
1444                     the world would have been able to comprehend; two of them
1445                     had won Nobel prizes, and one of the other six dribbled a
1446                     lot and wasn't allowed anything sharp because of what he
1447                     might do with it.
1448                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
1450 the least general encoding rule means that UTF-8 strings will practically never
1451 be used.  The original reason they were present in the PKIX profile is because
1452 of an IETF rule which required that all new IETF standards support UTF-8, but a
1453 much more compelling argument which recently emerged is that, since most of the
1454 other ASN.1 character sets are completely unusable, UTF-8 would finally breathe
1455 a bit of sanity into the ASN.1 character set nightmare.  Unfortunately, because
1456 it's quite a task to find ASN.1 compilers (let alone certificate handling
1457 software) which supports UTF-8, you should avoid this string type for now. PKIX
1458 realised the problems which would arise and specified a cutover date of 1
1459 January 2004 for UTF-8 use.  Some drafts have appeared which recommend the use
1460 of RFC 2482 language tags, but these should be avoided since they have little
1461 value (they're only needed for machine processing, if they appear in a text
1462 string intended to be read by a human they'll either understand it or they
1463 won't and a language tag won't help).  In addition UTF-8 language tags are huge
1464 (about 30 bytes) due to the fact that they're located out in plane 14 in the
1465 character set (although I don't have the appropriate reference to hand, plane
1466 14 is probably either Gehenna or Acheron), so the tag would be much larger than
1467 the string being tagged in most cases.
1469 One final problem with UTF-8 is that it shares some of the T.61 string problems
1470 in which it's possible for a malicious encoder to evade checks on strings
1471 either by using different code points which produce identical-looking
1472 characters when displayed or by using suboptimal encodings (in ASN.1 terms,
1473 non-distinguished encodings) of a code point. They are aided in this by the
1474 standard, which says (page 47, section 3.8 of the Unicode 3.0 standard) that
1475 "when converting from UTF-8 to a Unicode scalar value, implementations do not
1476 need to check that the shortest encoding is being used. This simplifies the
1477 conversion algorithm". What this means is that it's possible to encode a
1478 particular character in a dozen different ways in order to evade a check which
1479 uses a straight byte-by-byte comparison as specified in RFC 2459.  Although
1480 some libraries such as glibc 2.2 use "safe" UTF-8 decoders which will reject
1481 non-distinguished encodings, it's not a good idea to assume that everyone does
1482 this.
1484 Because of these problems, the SET designers produced their own alternative,
1485 SETString, for places were DNs weren't required for compatibility purposes.
1486 The design goals for the SETString were to both provide the best coverage of
1487 ASCII and national-language character sets, and also to minimise implementation
1488 pain.  The SETString type is defined as:
1490 SETString ::= CHOICE {
1491     visibleString           VisibleString (SIZE (1..maxSIZE)),
1492     bmpString               BMPString (SIZE (1..maxSIZE))
1493     }
1495 This provides complete ASCII/ISO 646 support using single byte characters, and
1496 national language support through Unicode, which is in common use by industry.
1498 In addition the SET designers decided to create their own version of the
1499 DirectoryString which is a proper subset of the X.500 version.  The initial
1500 version was just an X.500 DirectoryString with a number of constraints applied
1501 to it, but just before publication this was changed to:
1503 DirectoryString ::= CHOICE {
1504     printableString         PrintableString (SIZE(1..maxSIZE)),
1505     bmpString               BMPString (SIZE(1..maxSIZE))
1506     }
1507                     You must unlearn what you have learned.
1508                         -- Yoda
1510 It was felt that this improved readablility and interoperability (and sanity).
1511 T61String was never seriously considered in the design, and UniversalString
1512 with its four-byte characters had no identifiable industry support and required
1513 too much overhead.  If you want to produce certs which work for both generic
1514 X.509 and SET, then using the SET version of the DirectoryString is a good
1515 idea.  It's trivial to convert an ISO 8859-1 T61String to a BMPString and back
1516 (just add/subtract a 0 byte every other byte).
1518 MISSI also subsets the string types, allowing only PrintableString and
1519 T61String in DNs.
1521 When dealing with these character sets you should use the "least inclusive" set
1522 when trying to determine which encoding to use.  This means trying to encode as
1523 PrintableString first, then T61String, and finally BMPString/UniversalString.
1524 SET requires that either PrintableStrings or BMPStrings be used, with
1525 TeletexStrings and UniversalStrings being forbidden.
1527 From this we can build the following set of recommendations:
1529 - Use PrintableString if possible (or VisibleString or IA5String if this is
1530   allowed, because it's rather more useful than PrintableString).
1531 - If you use a T61String (and assuming you don't require SET compliance), avoid
1532   the use of anything involving shifting and escape codes at any cost and just
1533   treat it as a pure ISO 8859-1 string.  If you need anything other than
1534   8859-1, use a BMPString.
1535 - If it won't go into one of the above, try for a BMPString.
1536 - Avoid UniversalStrings.
1538 Version 7 of the PKIX draft dropped the use of T61String altogether (probably
1539 in response to this writeup :-), but this may be a bit extreme since the
1540 extremely limited character range allowed by PrintableString will result in
1541 many simple strings blowing out to BMPStrings, which causes problems on a
1542 number of systems which have little Unicode support.
1544 In 2004, you can switch to UTF-8 strings and forget about this entire section
1545 of the guide.
1546                     I saw coming out of the mouth of the dragon, and out of the
1547                     mouth of the beast, and out of the mouth of the false
1548                     prophet, three unclean spirits, something like frogs; for
1549                     they are spirits of demons, performing signs
1550                         -- Biblical explanation of the origins of character set
1551                            problems, Revelations 16:13-14, recommended
1552                            rendition: Diamanda Galas, The Plague Mass.
1555 Comparing DNs
1556 -------------
1558 This is an issue which is so problematic that it requires a section of its own
1559 to cover it fully.  According to X.500, to compare a DN:
1561 - The number of RDNs must match.
1562 - RDNs must have the same number of AVAs.
1563 - Corresponding AVAs must match for equality:
1564   - Leading and trailing spaces are ignored.
1565   - Multiple internal spaces are treated as a single internal space.
1566   - Characters (not code points, which are a particular encoding of a
1567     character) are matched in a case-insensitive manner.
1569 As it turns out, this matching is virtually impossible to perform (more
1570 specifically, it is virtually impossible to accurately compare two DNs for
1571 equivalence).
1572                     This, many claim, is not merely impossible but clearly
1573                     insane, which is why the advertising executives of the star
1574                     system of Bastablon came up with this quote: 'If you've
1575                     done six impossible things this morning, why not round it
1576                     off with breakfast at Milliways, the Restaurant at the End
1577                     of the Universe?'.
1578                         -- Douglas Adams, "The Restaurant at the End of the
1579                            Universe"
1581 The reason for this is that, with the vast number of character sets, encodings,
1582 and alternative encodings (code points) for the same character, and the often
1583 very limited support for non-ASCII character sets available on many systems, it
1584 isn't possible to accurately and portably compare any RDNs other than those
1585 containing one of the basic ASCII string types.  The best you can probably do
1586 is to use the strategy outlined below.
1588 First, check whether the number of RDNs is equal.  If they match, break up the
1589 DNs into RDNs and check that the RDN types match.  If they also match, you need
1590 to compare the text in each RDN in turn.  This is where it gets tricky.
1592                     He walked across to the window and suddenly stumbled
1593                     because at that moment his Joo-Janta 200 Super-Chromatic
1594                     Peril Sensitive sunglasses had turned utterly black.
1595                         -- Douglas Adams, "The Restaurant at the End of the
1596                            Universe"
1598 First, take both strings and convert them to either ASCII (ISO646String) or
1599 Unicode (BMPString) using the "least inclusive" rule.  This is quite a task in
1600 itself, because several implementations aren't too picky about what they'll put
1601 into a string, and will stuff T61String characters into a PrintableString, or
1602 (more commonly) Unicode characters into a T61String or anything into a
1603 BMPString.  Finding a T61String in a PrintableString or an 8-bit character set
1604 string in a BMPString is relatively easy, but the best guess you can take at
1605 detecting a Unicode string in a T61String is to check whether either the string
1606 length is odd or all the characters are ASCII or ASCII with the high bit set.
1607 If neither are true, it might be a Unicode string disguised as a T61String.
1609 Once this is done, you need to canonicalise the strings into a format in which
1610 a comparison can be done, either to compare strings of different types (eg
1611 8-bit character set or DBCS string to BMPString) or strings with the same type
1612 but different encodings (eg two T61Strings using alternative encodings).  To
1613 convert ASCII-as-Unicode to ASCII, just drop the odd-numbered bytes. Converting
1614 a T61String to Unicode is a bit more tricky.  Under Windows 95 and NT, you can
1615 use MultiByteToWideChar(), although the conversion will depend on the current
1616 code page in use.  On systems with widechar support, you can use mbstowcs()
1617 directly if the widechar size is the same as the BMPString char size (which it
1618 generally isn't), otherwise you need to first convert the string to a widechar
1619 string with mbstowcs() and then back down again to a BMPString, taking the
1620 machine endianness into account.  Again, the behaviour of mbstowcs() will
1621 depend on the current locale in use.  If the system doesn't have widechar
1622 support, the best you can do is a brute-force conversion to Unicode by hoping
1623 it's ISO 8859-1 and adding a zero byte every other byte.
1625 Now that you might have the strings in a format where they can be compared, you
1626 can actually try and compare them.  Again, this often ends up as pure guesswork
1627 if the system doesn't support the necessary character sets, or if the
1628 characters use weird encodings which result in identical characters being
1629 located at different code points.
1631 First, check the converted character sets: If one is Unicode and the other
1632 isn't, then the strings probably differ (depending on how well the
1633 canonicalisation step went).  If the types are the same, strip leading,
1634 trailing, and repeated internal spaces from the string, which isn't as easy as
1635 it sounds since there are several possible code points allocated to a space.
1637 Once you've had a go at stripping spaces, you can try to compare the strings.
1638 If the string is a BMPString then under Windows NT (but not Windows 95) you can
1639 use CompareString(), with the usual caveat that the comparison depends on the
1640 current locale.  On systems which support towlower() you can extract the
1641 characters from the string into widechars (taking machine endianness into
1642 account) and compare the towlower() forms, with the usual caveat about locale
1643 and the added problem that towlower() implementations vary from bare-bones
1644 (8859-1 only under Solaris, HPUX, AIX) to vague (Unicode under Win95, OSF/1).
1645 If there's no support for towlower(), the best you can do is use the normal
1646 tolower() if the characters have a high byte of zero (some systems will support
1647 8859-1 for tolower(), the worst which can happen is that the characters will be
1648 returned unchanged), and compare the code points directly if it isn't an 8-bit
1649 value.
1650                     Zaphods skin was crawling all over his body as if it was
1651                     trying to get off.
1652                         -- Douglas Adams, "The Restaurant at the End of the
1653                            Universe"
1655 Finally, if it's an ASCII string, you can just use a standard case-insensitive
1656 string comparison function.
1658 As you can see, there's almost no way to reliably compare two RDN elements. In
1659 particular, no matter what you do:
1661 - Some malicious users will deliberately pass DN checks with weird encodings.
1662 - Some normal users will accidentally fail DN checks with weird encodings.
1664 This becomes an issue when certain security checks depend on a comparison of
1665 DNs (for example with excluded subtrees in the Name Constraints extension)
1666 because it's possible to create multiple strings which are displayed
1667 identically to the user (especially if you know which platform and/or software
1668 to target) assuming they get displayed at all, but which compare as different
1669 strings.  If you want to be absolutely certain about DN comparisons, you might
1670 need to set a certificate policy of only allowing PrintableStrings in DNs,
1671 because they're the only ones which can be reliably compared.
1674 PKCS #10
1675 --------
1677 According to the PKCS #10 spec, the attributes field is mandatory, so if it's
1678 empty it's encoded as a zero-length field.  The example however assumes that if
1679 there are no attributes, the field shouldn't be present, treating it like an
1680 OPTIONAL field.  A number of vendors conform to the example rather than the
1681 specification, but just to confuse the issue RSADSI, who produced PKCS #10,
1682 regard things the other way around, with the spec being right and the example
1683 being wrong.  The most obvious effect of this is that TIPEM (which was the only
1684 available toolkit for PKCS#10 for a long time) follows the spec and does it
1685 "wrong (sense #2)", whereas more recent independant implementations follow the
1686 example and do it "wrong (sense #1)".
1688 Unfortunately it's difficult to handle certificate requests correctly and be
1689 lenient on decoding.  Because a request could be reencoded into DER before
1690 checking the signature, funny things can happen to your request at the remote
1691 end if the two interpretations of PKCS #10 differ.  Because of this confusion,
1692 you should be prepared to accept either version when decoding, but at the
1693 moment it's not possible to provide any recommendation for encoding.  When
1694 encountering a particularly fascist parser which isn't aware of the PKCS #10
1695 duality, it may be necessary to submit two versions of the request to determine
1696 which one works.
1697                     No, no.  Yes.  No, I tried that.  Yes, both ways.  No, I
1698                     don't know.  No again.  Are there any more questions?
1699                         -- Xena, "Been There, Done That"
1701 PKCS #10 also dates from the days of X.509v1 and includes references to
1702 obsolete and deprecated objects and data formats.  PKCS #6 extended
1703 certificates are a workaround for the abscence of certificate extensions in
1704 X.509v1 and shouldn't be used at all, and it's probably a good idea to avoid
1705 the use of PKCS #9 extended attributes as well (some certification request
1706 protocols bypass the use of PKCS #9 by wrapping extra protocol layers
1707 containing PKCS #9 elements around the outside of PKCS #10).  Instead, you
1708 should use of the CMMF draft, which defines a new attribute identified by the
1709 OID {pkcs-9 14}, with a value of SEQUENCE OF Extension which allows X.509v3
1710 attributes to be encoded into a PKCS #10 certification request.  The complete
1711 encoding used to encode X.509v3 extensions into a PKCS #10 certification
1712 request is therefore:
1714   [0] IMPLICIT SET OF {                 -- attributes from PKCS #10
1715     SEQUENCE {                          -- Attribute from X.501
1716       OBJECT IDENTIFIER,                --   type, {pkcs-9 14}
1717       SET OF {                          --   values
1718         SEQUENCE OF {                   -- ExtensionReq from CMMF draft
1719           <X.509v3 extensions>
1720         }
1721       }
1722     }
1723   }
1725 As of late 1998, virtually all CAs ignore this information and at best add a
1726 few predefined extensions based on the options selected on the web page which
1727 was used to trigger the certification process.  There are one or two
1728 implementations which do support it, and these provide a convenient means of
1729 specifying attributes for a certificate which don't involve kludges via HTML
1730 requests.  Microsoft started supporting something like it in mid-1999, although
1731 they used their own incompatible OID in place of the PKCS #9 one to ensure non-
1732 compatibility with any other implementation (the extensions are encoded in the
1733 standard format, they're just identified in a way which means nothing else can
1734 read them).
1736 Unfortunately since PKCS #10 doesn't mention X.509v3 at all, there's no clear
1737 indication of what is and isn't valid as an attribute for X.509v3, but common
1738 sense should indicate what you can and can't use.  For example a subjectAltName
1739 should be treated as a valid attribute, a basicConstraint may or may not be
1740 treated as valid depending on the CA's certification policy, and an
1741 authorityKeyIdentifier would definitely be an invalid attribute.
1743 SET provides its own version of PKCS #10 which uses a slightly different
1744 encoding to the above and handles the X.509v3 extensions keyUsage,
1745 privateKeyUsagePeriod (whose use is deprecated by PKIX for some reason),
1746 subjectAltName, and the SET extensions certificateType, tunneling, and
1747 additionalPolicy.  Correctly handling the SET extensions while at the same time
1748 avoiding Microsoft's broken extensions which look very similar (see the "Known
1749 Bugs/Peculiarities" section) provides a particularly entertaining exercise for
1750 implementors.
1753 ASN.1 Design Guidelines
1754 -----------------------
1756 This section contains some guidelines on what I consider good ASN.1 style.
1757 This was motivated both by the apparent lack of such guidelines in existing
1758 documents covering ASN.1, and by my seeing the ASN.1 definition of the X.400
1759 ORAddress (Originator/Recipient Address).  Although there are a number of
1760 documents which explain how to use ASN.1, there doesn't seem to be much around
1761 on ASN.1 style, or at least nothing which is easily accessible.  Because of
1762 this I've noted down a few guidelines on good ASN.1 style, tuned towards the
1763 kind of ASN.1 elements which are used in certificate-related work.  In most
1764 cases I'll use the X.400 ORAddress as an example of bad style (I usually use
1765 PFX for this since it's such a target-rich environment, but in this case I'll
1766 make an exception).  The whole ORAddress definition is far too long to include
1767 here (it requires pages and pages of definitions just to allow the encoding of
1768 the equivalent of an email address), but I'll include excerpts where required.
1770                     If you can't be a good example, then you'll just have to be
1771                     a horrible warning.
1772                         -- Catherine Aird
1774 To start off, keep your structure as simple as possible.  Everyone always says
1775 this, but when working with ASN.1 it's particularly important because the
1776 notation gives you the freedom to design incredibly complicated structures
1777 which are almost impossible to work with.
1779                     Bud, if dynamite was dangerous do you think they'd sell it
1780                     to an idiot like me?
1781                         -- Al Bundy, "Married with Children"
1783 Look at the whole ORAddress for an example.
1785                     What we did see was something altogether different, and
1786                     immeasurably more hideous and detestable.  It was the
1787                     utter, objective embodiment of the fantastic novelists
1788                     'thing that should not be'.
1789                         -- H.P.Lovecraft, "At the Mountains of Madness"
1791 This includes provisions for every imaginable type of field and element which
1792 anyone could conceivably want to include in an address.  Now although it's easy
1793 enough to feed the whole thing into an ASN.1 compiler and produce an enormous
1794 chunk of code which encodes and decodes the whole mess, it's still necessary to
1795 manually generate the code to interpret the semantic intent of the content.
1796 This is a complex and error-prone process which isn't helped by the fact that
1797 the structure contains dozens of little-understood and rarely-used fields, all
1798 of which need to be handled correctly by a compliant implementation.  Given the
1799 difficulty of even agreeing on the usage of common fields in certificate
1800 extensions, the problems which will be raised by obscure fields buried fifteen
1801 levels deep in some definition aren't hard to imagine.
1803 ASN.1 *WHAM* is not *WHAM* COBOL *WHAM* *WHAM* *WHAM*.  The whole point of an
1804 abstract syntax notation is that it's not tied to any particular representation
1805 of the underlying data types.  An extreme example of reverse-engineering data
1806 type dependancy back into ASN.1 is X9.42's:
1808   OCTET STRING SIZE(4)  -- (Big-endian) Integer
1810 Artificially restricting an ASN.1 element to fall within the particular
1811 limitations of the hardware you're using creates all sorts of problems for
1812 other users, and for the future when people decide that 640K isn't all the
1813 memory anyone will ever need.  The entire point of ASN.1 is that it not be tied
1814 to a particular implementation, and that users not have to worry about the
1815 underlying data types.  It can also create ambiguous encodings which void the
1816 DER guarantee of identical encodings for identical values: Although the
1817 ANSI/SET provision for handling currencies which may be present in amounts
1818 greater than 10e300 (requiring the amtExp10 field to extend the range of the
1819 ASN.1 INTEGER in the amount field) is laudable, it leads to nondeterministic
1820 encodings in which a single value can be represented in a multitude of ways,
1821 making it impossible to produce a guaranteed, repeatable encoding.
1823 Careful with that tagging Eugene!  In recent ASN.1 work it seems to have become
1824 fashionable to madly tag everything which isn't nailed down, sometimes two or
1825 three times recursively for good measure (see the next point).
1827                     The entire set of PDU's are defined using an incredible
1828                     amount of gratuitous and unnecessary tagging.  Were the
1829                     authors being paid by the tag for this?
1830                         -- Peter Gutmann on ietf-pkix
1832 For example consider the following ORAddress ExtensionAttribute:
1834   ExtensionAttribute ::= SEQUENCE {
1835     extension-attribute-type [0] INTEGER,
1836     extension-attribute-value [1] ANY DEFINED BY extension-attribute-type
1837     }
1839 (this uses the 1988 ASN.1 syntax, more recent versions change this somewhat).
1840 Both of the tags are completely unnecessary, and do nothing apart from
1841 complicating the encoding and decoding process.  Another example of this
1842 problem are extensions like authorityKeyIdentifier, cRLDistributionPoints, and
1843 issuingDistributionPoint which, after several levels of nesting, have every
1844 element in a sequence individually tagged even though, since they're all
1845 distinct, there's no need for any of the tags.
1847 Another type of tagging is used for the ORAddress BuiltInStandardAttributes:
1849   BuiltInStandardAttributes ::= SEQUENCE {
1850     countryName [APPLICATION 1] CHOICE { ... } OPTIONAL,
1851     ...
1852     }
1854 Note the strange nonstandard tagging - even if there's a need to tag this
1855 element (there isn't), the tag should be a context-specific tag and not an
1856 application-specific one (this particular definition mixes context-specific and
1857 application-specific tags apparently at random).  For tagging fields in
1858 sequences or sets, you should always use context-specific tags.
1860 Speaking of sequences and sets, if you want to specify a collection of items in
1861 data which will be signed or otherwise authenticated, use a SEQUENCE rather
1862 than a SET, since the encoding of sets causes serious problems under the DER.
1863 You can see the effect of this in newer PKCS #7 revisions, which substitute
1864 SEQUENCE almost everywhere where the older versions used a SET because it's far
1865 easier to work with the former even though what's actually being represented is
1866 really a SET and not a SEQUENCE.
1868 If you have optional elements in a sequence, it's always possible to eliminate
1869 the tag on the first element (provided it's not itself tagged), since it can be
1870 uniquely decoded without the tag.  For example consider privateKeyUsagePeriod:
1872   PrivateKeyUsagePeriod :: = SEQUENCE {
1873     notBefore [ 0 ] GeneralizedTime OPTIONAL,
1874     notAfter [ 1 ] GeneralizedTime OPTIONAL
1875     }
1877 The first tag is unnecessary since it isn't required for the decoding, so it
1878 could be rewritten:
1880   PrivateKeyUsagePeriod :: = SEQUENCE {
1881     notBefore GeneralizedTime OPTIONAL,
1882     notAfter [ 0 ] GeneralizedTime OPTIONAL
1883     }
1885 saving an unneeded tag.
1887 Because of the ability to specify arbitrarily nested and redefined elements in
1888 ASN.1, some of the redundancy built into a definition may not be immediately
1889 obvious.  For example consider the use of a DN in an IssuingDistributionPoint
1890 extension, which begins:
1892   IssuingDistributionPoint ::= SEQUENCE {
1893     distributionPoint [0] DistributionPointName OPTIONAL,
1894     ...
1895     }
1897   DistributionPointName ::= CHOICE {
1898     fullName [0] GeneralNames,
1899     ...
1900     }
1902   GeneralNames ::= SEQUENCE OF GeneralName
1904   GeneralName ::= CHOICE {
1905     ...
1906     directoryName [4] Name,
1907     ...
1908     }
1910   Name ::= CHOICE {
1911     rdnSequence RDNSequence
1912     }
1914   RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
1916   RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
1918                     [It] was of a baroque monstrosity not often seen outside
1919                     the Maximegalon Museum of Diseased Imaginings.
1920                         -- Douglas Adams, "The Restaurant at the End of the
1921                            Universe"
1923 Once we reach AttributeTypeAndValue we finally get to something which contains
1924 actual data - everything before that point is just wrapping.
1926 Now consider a typical use of this extension, in which you encode the URL at
1927 which CA information is to be found.  This is encoded as:
1929 SEQUENCE { [0] { [0] { SEQUENCE { [6] "http://.." } } } }
1931 All this just to specify a URL!
1933                     It looks like they were trying to stress-test their ASN.1
1934                     compilers.
1935                         -- Roger Schlafly on stds-p1363
1937                     It smelled like slow death in there, malaria, nightmares.
1938                     This was the end of the river alright.
1939                         -- Captain Willard, "Apocalypse Now"
1941 Unfortunately because of the extremely broad definition used (a SEQUENCE OF
1942 GeneralName can encode arbitrary quantities of almost anything imaginable, for
1943 example you could include the contents of an entire X.500 directory in this
1944 extension), producing the code to correctly process every type of field and
1945 item which could occur is virtually impossible, and indeed the semantics for
1946 many types of usage are undefined (consider how you would use a physical
1947 delivery address or a fax number to access a web server).
1949 Because of the potential for creating over-general definitions, once you've
1950 written down the definition in its full form, also write it out in the
1951 compressed form I've used above, and alongside this write down the encoded form
1952 of some typical data.  This will very quickly show up areas in which there's
1953 unnecessary tagging, nesting, and generality, as the above example does.
1955 An extreme example of the misuse of nesting, tagging, and generality is the
1956 ORName, which when fully un-nested is:
1958   ORName ::= [APPLICATION 0] SEQUENCE { [0] { SEQUENCE OF SET OF
1959              AttributeTypeAndValue OPTIONAL } }
1961 (it's not even possible to write all of this on a single line).  This uses
1962 unnecessary tagging, nonstandard tagging, and unnecessary nesting all in a
1963 single definition.
1964                     It will founder upon the rocks of iniquity and sink
1965                     headfirst to vanish without trace into the seas of
1966                     oblivion.
1967                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
1969 The actual effect of the above is pretty close to:
1971   ORName = Anything
1973 Another warning sign that you've constructed something which is too complex to
1974 be practical is the manner in which implementations handle its encoding.  If
1975 you (or others) are treating portions of an object as a blob (without bothering
1976 to encode or decode the individual fields in it) then that's a sign that it's
1977 too complex to work with.  An example of this is the policyQualifiers portion
1978 of the CertificatePolicies extension which, in the two implementations which
1979 have so far come to light which actually produce qualifiers, treat them as a
1980 fixed, opaque blob with none of the fields within it actually being encoded or
1981 decoded.  In this case the entire collection of qualifiers could just as easily
1982 be replaced by a BOOLEAN DEFAULT FALSE to indicate whether they were there or
1983 not.
1985 Another warning sign that something is too complex is when your definition
1986 requires dozens of paragraphs of accompanying text and/or extra constraint
1987 specifications to explain how the whole thing works or to constrain the usage
1988 to a subset of what's specified.  If it requires four pages of explanatory text
1989 to indicate how something is meant to work, it's probably too complex for
1990 practical use.
1991                     No matter how grandiose, how well-planned, how apparently
1992                     foolproof an evil plan, the inherent sinfulness will by
1993                     definition rebound upon its instigators.
1994                         -- Neil Gaiman and Terry Pratchett, "Good Omens"
1996 Finally, stick to standard elements and don't reinvent your own way of doing
1997 things.  Taking the ORAddress again, it provides no less than three different
1998 incompatible ways of encoding a type-and-value combination for use in different
1999 parts of the ORAddress.  The standard way of encoding this (again using the
2000 simpler 1988 syntax) is:
2002   Attribute ::= SEQUENCE {
2003     type OBJECT IDENTIFIER,
2004     value ANY DEFINED BY type
2005     }
2007 The standard syntax for field names is to use biCapitalised words, with the
2008 first letter in lowercase, for example:
2010   md5WithRSAEncryption
2011   certificateHold
2012   permittedSubtrees
2014 Let's take an example.  Say you wanted to design an extension for yet another
2015 online certificate validation protocol which specifies a means of submitting a
2016 certificate validity check request.  This is used so a certificate user can
2017 query the certificate issuer about the status of the certificate they're using.
2018 A first attempt at this might be:
2020   StatusCheck ::= SEQUENCE {
2021     statusCheckLocations  [0] GeneralNames
2022     }
2024 Eliminating the unnecessary nesting and tagging we get:
2026   StatusCheck ::= GeneralNames
2028 However taking a typical encoding (a URL) we see that it comes out as:
2030   StatusCheck ::= SEQUENCE { [6] "http://..." }
2032 In addition the use of a SEQUENCE OF GeneralName makes the whole thing far to
2033 vague to be useful (someone would be perfectly within their rights to specify a
2034 pigeon post address using this definition, and I don't even want to get into
2035 what it would require for an implementation to claim it could "process" this
2036 extension).  Since it's an online check it only really makes sense to do it via
2037 HTTP (or at least something which can be specified through a URL), so we
2038 simplify it down again to:
2040   StatusCheck ::= SEQUENCE OF IA5String     -- Contains a URL
2042 We've now reached an optimal way of specifying the status check which is easily
2043 understandable by anyone reading the definition, and doesn't require enormous
2044 amounts of additional explanatory text (what to do with the URL and how to
2045 handle the presence of multiple URL's is presumably specified as part of the
2046 status-check protocol - all we're interested in is how to specify the
2047 location(s) at which the status check is performed).
2050 base64 Encoding
2051 ---------------
2053 Many programs allow certificate objects to be encoded using the base64 format
2054 popularised in PEM and MIME for transmission of binary data over text-only
2055 channels.  The format for this is:
2057 -----BEGIN <object name>-----
2058 <base64-encoded data>
2059 -----END <object name>-----
2061 Unfortunately there is some disagreement over what <object name> should be for
2062 objects other than certificates (there's no standard for implemetations to be
2063 non-compliant with).  Everyone seems to agree that for certificates it's
2064 'CERTIFICATE' (SSLeay can also accept 'X509 CERTIFICATE').  For certificate
2065 requests, it's generally 'NEW CERTIFICATE REQUEST', although SSLeay can also
2066 generate 'CERTIFICATE REQUEST' and Microsoft creates an undocumented blob which
2067 is nothing like a certificate request while still giving it the certificate
2068 request header.  CRLs are so rare that I haven't been able to collect a large
2069 enough sample to get a consensus, but 'CRL' would seem to be the logical choice
2070 (SSLeay uses 'X509 CRL', matching 'X509 CERTIFICATE'). Finally, if you see 'PGP
2071 ...' then you've got the wrong kind of object.
2073 The number of dashes around the text must be exactly five.
2075                     ... then shalt thou count to three, no more, no less.
2076                     Three shalt be the number thou shalt count, and the number
2077                     of the counting shalt be three.  Four shalt thou not count,
2078                     neither count thou two, excepting that thou then proceed to
2079                     three.  Five is right out.
2080                         -- Monty Python and the Holy Grail
2082 There are three further object types which aren't covered yet, attribute
2083 certificates (which are too new to be used), and Netscape cert sequences and
2084 PKCS #7 cert chains (which are degenerate signed data objects).  The logical
2085 choice for these would be 'ATTRIBUTE CERTIFICATE', 'NETSCAPE CERTIFICATE
2086 SEQUENCE' and 'PKCS7 CERTIFICATE CHAIN'.
2088 Recommendation: When encoding objects, for certificates use 'BEGIN
2089     CERTIFICATE', for attribute certificates use 'BEGIN ATTRIBUTE CERTIFICATE',
2090     for cert requests use 'BEGIN NEW CERTIFICATE REQUEST', for CRLs use 'BEGIN
2091     CRL', for Netscape certificate sequences use 'BEGIN NETSCAPE CERTIFICATE
2092     SEQUENCE', and for PKCS #7 certificate chains use 'BEGIN PKCS7 CERTIFICATE
2093     CHAIN'. When decoding objects, don't make any assumptions about what you
2094     might find for <object name> - it's easiest to just look for 'BEGIN' and
2095     then work out what's in there from the decoded object.
2098 Known Bugs/Peculiarities
2099 ------------------------
2101 The following list of issues cover problems and areas to be aware of in X.509
2102 implementations and related data objects from different vendors.  The coverage
2103 extends to objects related to X.509 such as private keys and encrypted/signed
2104 data.  This section is not intended as a criticism of different vendors, it is
2105 merely an list of issues which people should be aware of when attempting to
2106 write interoperable software.  If vendors or users are aware of fixes for these
2107 problems, could they please notify me of what was fixed, and when or in which
2108 version it occurred.
2110 One general comment about certificates is that, although you are allowed to
2111 deconstruct them and then re-encode them, the fact that there are so many
2112 incorrectly encoded certificates around means that the re-encoded certificates
2113 will fail their signature check.  For this reason it is strongly advised that
2114 you always keep a copy of the original on hand rather than trying to recreate
2115 it from its components as they are stored internally by your software.
2117 An Post
2119   An Post certificates include an enormously long (nearly four times the
2120   maximum allowed size) legal disclaimer in the certificate policy extension
2121   (the certificate contains as much legal disclaimer as all other data
2122   combined).
2124 Bankgate
2126   Bankgate certificates specify the country as "INT", which isn't a valid
2127   country name (presumably it's meant to be either "International" or
2128   "Internet", but as it's used now it means "Limbo").
2130 Belsign
2132   The Belsign CA incorrectly encodes PKCS #7 certificate chains using a zero-
2133   length set of certificates or CRLs if there are none present instead of
2134   omitting the field which should contain them.  Since the field is declared as
2135   OPTIONAL, it should be omitted if it is empty.
2139   BTG certificates contain incorrectly encoded bit strings in key/certificate
2140   usage extensions.
2142 CDSA
2144   CDSA uses a peculiar deprecated DSA OID which appeared in an early,
2145   incomplete version of SDN.702 but vanished in later versions (this OID also
2146   appears in the German PKI profile).  CDSA also doesn't recognise the
2147   recommended X9.57 dsaWithSHA1 OID, causing it to reject DSA certificates
2148   which use it.
2150 CompuSource
2152   This CA has a root cert which has the UTCTime encoded without the seconds
2153   (see the section "Validity" above), newer versions encode the time with the
2154   seconds.  This isn't an error since the accepted encoding was changed in
2155   mid-1996, merely something to be aware of.
2157 COST
2159   The lengths of some of the fields in CRLs are broken.  Specifically, the
2160   lengths of some sequences are calculated incorrectly, so if your code merely
2161   nods at things like SET and SEQUENCE tags and lengths as they whiz past and
2162   then works with the individual fields it'll work, but if it tries to work
2163   with the length values given (for example making sure the lengths of the
2164   components of a sequence add up correctly) then it'll break.  The sequence
2165   lengths are longer than the amount of data in the sequence, the COST code may
2166   be adding the lengths of the elements of the sequence incorrectly (it's a bit
2167   hard to tell what's going wrong.  Basically the CRLs are broken).  This was
2168   supposed to have been fixed, but there still appear to be problems with CRLs
2169   (?).
2171 CRLs
2173   Some CRLs which contain extensions (which are only valid in v2 CRLs) are
2174   marked as v1 CRLs because they don't have a version number field present.
2175   These CRLs are (in theory) invalid, but your software should be prepared to
2176   encounter them.
2180   X.500 directories using DAP return BER-encoded certificates since the DAP
2181   PDU's are BER encoded.  This leads to many certificates failing their
2182   signature check when they are re-encoded using the DER because they use
2183   incorrect or unexpected encodings.  This problem generally requires hacking
2184   the directory software to kludge the encoding, since many certificates can't
2185   survive the re-encoding process.
2187 Deutsches Forschungsnetz (DFN)
2189   The DFN CA used the SecuDE software until late-1998, see the SecuDE entry for
2190   the quirks present in certificates generated with this software.  These
2191   certificates expired at the end of 1998, current certificates are generated
2192   using OpenSSL.
2194 Digicert
2196   (Based on the certificate peculiarities this CA uses the same software as
2197    Sweden Post, but some of the quirks of the Sweden Post certificates aren't
2198    present so it has its own entry)
2200   The subjectKeyIdentifier is encoded in a variety of ways ranging in length
2201   from 1 to 8 bytes.  In CA certs the subjectKeyIdentifier is the same as the
2202   authorityKeyIdentifier (which is valid, but odd) and consists of a text
2203   string identifying the CA key (this isn't explicitly disallowed because of
2204   the confusion over what's really meant to be in there but it isn't really
2205   what's supposed to be in there either).
2207   CA certs include policy mappings which specify the same issuer and subject
2208   domain policy (this is known as a tautology mapping).
2210 Diginotar
2212   End entity certs tend to be issued with a keyUsage specifying every possible
2213   type of key usage, including ones which the algorithm being used is incapable
2214   of.
2216 Digital Signature Trust
2218   The certificate policy contains a longer-than-allowed legal disclaimer,
2219   although not quite as excessive as the An Post one.  Just to make sure you
2220   don't miss it, the certificate includes the whole thing a second time as a
2221   Netscape comment extension.
2223   End entity certs tend to be issued with a keyUsage specifying every possible
2224   type of key usage, including ones which the algorithm being used is incapable
2225   of (since this CA operates under the strict Utah law it's possible that this
2226   takes precedence over the inability of the RSA algorithm to perform Diffie-
2227   Hellman key agreement).
2229 Digitrust Hellas
2231   The Digitrst Hellas CA incorrectly encodes bit strings in key/certificate
2232   usage extensions.
2234 DNs with UniqueIDs
2236   Given that, in practice, Distinguished Names aren't, some organisations which
2237   really require unique names have tried to use unique identifiers as part of
2238   whatever's used as the DN in order to make it Distinguished. Unfortunately
2239   many applications can't handle multi-AVA RDNs, and those which can generally
2240   won't display them to the user, making the use of DN components like
2241   dnQualifiers impossible since all the user sees is a collection of certs
2242   which all appear to have the same DN.  As a result, some organisations modify
2243   the DN by appending a unique identifier value to it.  Examples of these
2244   organisations are the US DoD (a very large and highly distributed
2245   organisation which needs unique ID's) and AlphaTrust (which specialises in
2246   certificates used in transactions which are legally binding regardless of the
2247   state of digital signature legislation).
2249 Entrust
2251   This was formerly a Nortel division, for notes on earlier versions of the
2252   software see the entry for Nortel.  Because of their origins, Entrust-
2253   specific extensions and attributes are still identified with NSN (Nortel
2254   Secure Network) object identifiers.
2256   The Entrust demo web CA encodes liability statements in the issuer DN, making
2257   them unusable with X.500/LDAP directories.  It also issues certificates with
2258   a zero-duration validity (start time == end time), limiting their usefulness
2259   somewhat.
2261   Something identified as 'V3.0c' encodes the outer certificate using the BER
2262   instead of the DER (which is unusual but legal), however it also omits the
2263   final end-of-contents octets (which isn't).  Some of the inner components are
2264   also encoded using the BER (which isn't allowed).  This has been fixed in the
2265   4.0 release.
2267   The same software populates the certificate with multiple generations of
2268   extensions (for example it contains multiple copies of
2269   authorityKeyIdentifier, keyUsage, and cRLDistributionPoints extensions of
2270   different levels of deprecation).  Luckily it doesn't mark any of its
2271   extensions as critical, avoiding the mutual-exclusion problem documented in
2272   the section on extensions.
2274   The extension which identifies V3.0c contains a GeneralString, which is
2275   perfectly legal but may come as a considerable surprise to some decoding
2276   software (GeneralStrings get even weirder than the other ASN.1 types, and
2277   aren't used in anything certificate-related).
2279 Estonian CLO CA
2280 Estonian National PCA
2281 Estonian IOC CA
2282 Estonian Piirivalveamet CA
2283 Estonian Politsei CA
2285   These CAs identify RSA public keys in certificates by a peculiar deprecated
2286   X.500 OID for RSA (2 5 8 1 1).
2288   The Estonian National CA encodes some DN components as PrintableString's
2289   containing illegal characters.  I guess the Estonian ASN.1 Politsei will have
2290   to look at this.
2292   These CAs appear to be using the same software, possibly SecuDE, so they may
2293   exhibit the same DN encoding bug as the Estonian National CA (I only have one
2294   cert from each so it's hard to check this).
2296 First Data
2298   First Data's CA root certificate is (according to the extKeyUsage extension)
2299   used for their SSL server, in SSL clients, and for email encryption.
2301 GeneralName
2303   Some implementations incorrectly encode the iPAddress (yes, it really is
2304   capitalised like that; ASN.1 is bigger than the Internet) as a dotted address
2305   rather than a 4-byte (soon to become 16 byte) OCTET STRING, so you might
2306   encounter "123.124.125.126" instead of the correct 0x7B7C7D7E.
2308 GIP-CPS
2310   The software used in the French healthcare card project incorrectly encodes
2311   cRLDistributionPoints, encoding the fullName as if it were specified with
2312   [0] EXPLICIT GeneralNames, so that the final encoding is [0] + SEQUENCE +
2313   GeneralName rather than [0] + GeneralName.
2317   Older versions of GTE's software encoded UTCTimes without the seconds (see
2318   the section "Validity" above), newer versions encode the time with the
2319   seconds.  This isn't an error since the accepted encoding was changed in
2320   mid-1996, merely something to be aware of.
2322 HBCI
2324   The German Home Banking Computer Interface specification contains some
2325   unusual requirements for certificates.  Signatures are created by signing the
2326   raw, unpadded RIPEMD-160 hash of the data.  Similarly, RSA encryption is
2327   performed by encrypting raw, unpadded content-encryption keys.  This provides
2328   no semantic security (that is, it's trivial to determine whether a given
2329   plaintext corresponds to the ciphertext), and has other problems as well.
2330   The IEEE P1363 standard provides further thoughts on this issue.
2334   IBM's web CA uses the same peculiar deprecated DSA OID as CDSA and JDK.
2335   Since it's based on IBM's Java CryptoFramework it probably ended up in the CA
2336   via its use in the JDK.
2338 ICE-TEL
2340   Early ICE-TEL CRLs are broken, consisting of various portions of full CRLs.
2341   See the entry for SECUDE for the explanation, this has been fixed in the
2342   ICE-TEL successor project ICE-CAR.
2344 IPSEC
2346   IPSEC more or less assumes the use of X.509 certificates, however the
2347   companies implementing it are usually in the VPN business rather than the PKI
2348   business and tend to see certificates as a means to an end rather than an end
2349   in itself.  As a result, the state of certificate handling in IPSEC in
2350   mid-1999 is something of a free-for-all, with certificates containing
2351   whatever seems to work.  For example some IPSEC implementations may place
2352   identification information in the subjectName, some ignore the subjectName
2353   and use the altName, and some use (even require) both.  In general, you
2354   shouldn't make any assumptions about what you'll encounter in certificates
2355   designed for or created by IPSEC implementations.
2357 JDK/Java
2359   JDK 1.1 issues DSA certificates with a signature OID of dsaWithSHA,
2360   1.3.14.3.2.13, but the hash algorithm used is SHA-1.  The OID should be
2361   dsaWithSHA1 1.3.14.3.2.27.  Since noone ever seems to use SHA, a workaround
2362   is to always assume SHA-1 even if the OID says SHA (which is also what the
2363   JDK folks are banking on).  JDK also uses the peculiar deprecated DSA OID 1 3
2364   14 3 2 12 which appeared in an early, incomplete version of SDN.702 but
2365   vanished in later versions (CDSA does this as well, God knows where they're
2366   getting these from).  These strange OIDs are duplicated in other Java
2367   software as well.  Apparently these OIDs arise from RSADSI's BSAFE 3.0, which
2368   is the crypto toolkit which underlies many of these implementations.
2370 Keywitness
2372   Keywitness encodes an email address as a PrintableString as part of a DN
2373   component with an unknown OID registered to Keywitness.  This encoding is
2374   invalid since a PrintableString can't contain an '@' character.
2376   Boolean values are encoded using a non-DER encoding.
2378 LDAP V2/QUIPU
2380   Some implementations will do strange things when storing signed items. Either
2381   the client or the server may modify the objects (for example by uppercasing
2382   parts of DNs, or changing time fields based on their interpretation of UTC,
2383   or dropping seconds in time fields), which changes the resulting DER encoding
2384   and causes the signature check to fail.
2386 Microsoft
2388   [Microsoft splits development along product lines rather than functionality,
2389    so it's not uncommon to find a bug repeated over multiple products from
2390    different teams, or to find a bug which has been fixed in one product
2391    reappear in another.  Because of this the following descriptions don't
2392    usually identify a particular product because it's often a nontrivial
2393    exercise identifying in which locations the problems occur]
2395   Earlier versions of MSIE encoded the emailAddress of a PKCS #10 request
2396   incorrectly.  If the string doesn't fit into the range acceptable for a
2397   PrintableString it produces a UniversalString (with 32-bit wide characters).
2398   Since a PrintableString doesn't include an '@', you always end up with
2399   UniversalStrings.  The correct type should be IA5String.
2401   MS software will often generate components with UniversalStrings in places
2402   where they shouldn't really occur.  According to MS, this was necessary
2403   because BMPStrings weren't allowed in DirectoryStrings until October 1997,
2404   which if true would require another entry in this list, "Some MS software
2405   erroneously produced BMPStrings before it was permitted in October 1997".  It
2406   also seems to randomly use T61Strings where a PrintableString should be used
2407   (there's no discernable pattern to this).  This was fixed in MSIE 4.01 (but
2408   not in other MS software as far as I can tell), where it uses either
2409   PrintableString or BMPString (skipping T61String completely).
2411   The same software will dump multiple AVAs into a single RDN, this is most
2412   probably an encoding bug since the AVAs consist of a random jumble of
2413   components with nothing in common.
2415   Some Microsoft software will generate negative values about 50% of the time
2416   whenever it encodes anything as an INTEGER because it ignores the fact that
2417   the top bit of an integer is the sign bit (this is still occurring in
2418   programs released as recently as early 1998).
2420   When MSIE stores certificates, it recodes some components (specifically the
2421   various time stamps) which don't include seconds so that they now include
2422   seconds, which means that the signatures in the certificates are no longer
2423   valid.  The altered encoding is in fact the correct one, but it's probably
2424   not worth altering the certificate to the correct form if it means breaking
2425   the signature on it.  A workaround for this problem (mentioned in the
2426   "Validity" section of this document) is to ensure you never generate a
2427   certificate with the seconds field set to 0.
2429   MS software enforces validity period nesting for certificates, which can
2430   cause certificates which are valid everywhere else to appear invalid when
2431   loaded into a MS product.
2433   Although various MS programs give the impression of handling certificate
2434   policies, they only have a single hardcoded policy which is the Verisign CPS.
2435   To see an example of this, create a certificate with a policy of (for
2436   example) "This policy isn't worth the paper it's not written on" and view the
2437   cert using Outlook Express.  What's displayed will be the Verisign CPS.
2439   The entire AuthentiCode certification framework collapsed on 1 July 1997 when
2440   the AuthentiCode CA certificates expired (most people never noticed this due
2441   to stealth upgrades of security components when other products were
2442   installed).  Microsoft issued an update (AuthentiCode 2.0) which includes a
2443   partially-documented timestamping mechanism which is supposed to allow
2444   signatures to be updated in some manner.  Creating certificates with a
2445   lifetime of over four decades (see below) is probably also intended to stop
2446   this problem from recurring.
2448   The MakeCert certificate-generation program gives certificates a default
2449   validity of over 40 years (!!!).  This creates three problems: firstly,
2450   implementations which use the ANSI/ISO C time_t type for dates (which most
2451   implementations do) will, for certificates generated after late 1997, be
2452   unable to check the validity period.  Secondly, kids with the next-millenium
2453   equivalent of pocket calculators will be breaking the keys for these
2454   certificates by the time half the validity period is up.  Finally, because of
2455   validity nesting of CA certs which typically expire after a year or two,
2456   these certificates will either be treated as invalid as soon as they're
2457   issued, or will become invalid a long time before their actual expiry date,
2458   depending on how the software enforces validity nesting.
2460   MakeCert generates certificates with peculiar collections of deprecated and
2461   obsolete extensions.  Incredibly, it can be persuaded to generate different
2462   incompatible versions of the same extension depending on what options it's
2463   given.
2465   When asked to add a Netscape-style extension to a code-signing certificate,
2466   MakeCert adds an extension which marks it as an SSL client certificate,
2467   presumably because whoever wrote it got the endianness of the bit strings
2468   reversed.  Given that some implementations will allow Netscape extensions to
2469   override other extensions which are present (both MSIE and Netscape Navigator
2470   seem to treat a Verisign cert with a Netscape extension of "is a CA" and an
2471   X.509v3 extension of "isn't a CA" as being a CA certificate), it'll be
2472   interesting to see what other implementations make of these certificates.
2474   In code signing certificates, the displayName (aka agencyInfo) is encoded as
2475   an extension identified by the X.509 commonName OID, with the data being an
2476   OCTET STRING containing a mostly Unicode representation of an ASCII URL
2477   string, winning it the prize for "Most Mangled Extension".
2479   An ever-changing variety of Microsoft products incorrectly encode bit strings
2480   in certificate extensions.
2482   Outlook Express generates certificates which not only use the GeneralizedTime
2483   encoding more than 50 years before they're allowed to, but give the resulting
2484   certificate an expiry date in the early 17th century.  A Microsoft spokesman
2485   has confirmed that this is deliberate, and not a bug.
2486                     How many Microsoft programmers does it take to change a
2487                       lightbulb?
2488                     None.  They define darkness to be the new industry
2489                       standard.
2490                         -- Unknown
2492   The same certificate type is marked as an X.509 v1 certificate even though it
2493   contains extensions which aren't allowed in X.509 v1.  To be valid, the
2494   certificate should be marked as X.509 v3.
2496   Some MS software will reject a certificate with certain basic extensions
2497   marked critical (this provides one of the nonstandard definitions of the
2498   critical flag mentioned earlier, "reject the certificate if you find a
2499   critical extension").
2501   Other MS software, contradicting the previous bug, will ignore the critical
2502   flag in extensions, making the software useless to relying parties since they
2503   can't rely on it to correctly process critical certificate components.
2505   Microsoft software seems to mostly ignore the keyUsage bits and extKeyUsage
2506   values and use the first certificate it finds for whatever purpose it wants
2507   (for example if a subject has a signature and an encryption cert, it will
2508   take the first one it finds and use it for both purposes, which will result
2509   in the decryption and/or signature check failing).
2511   Microsoft certificates can include arbitrarily mangled interpretations of
2512   what comprises a DN, examples ranging from DNs which consist of a single
2513   CommonName through to DNs with the country missing.
2515   Microsoft's key-handling software assumes that public keys come in a certain
2516   fixed format (for example that keys have a certain, set number of bits, that
2517   (for RSA) p and q are both the same size, and in some cases that e falls
2518   within a certain limited range).  If all these conditions aren't met,
2519   encryption and signatures quietly fail.  To avoid this, you need to make the
2520   keys a standard, common length (eg 512 bits for exportable crypto), make sure
2521   p and q are of the same size, and use a small value for e.
2523   In extentions which contain URL's, Microsoft software will sometimes produce
2524   something which is neither an HTTP URL nor a UNC file URL, but some weird
2525   mixture between the two.
2527   Microsoft certificates contain a peculiar deprecated form of the
2528   authorityKeyIdentifier extension.  In this extension, CA certificates
2529   sometimes identify themselves, rather than the CA which issued the issuing
2530   certificate, which would lead to either endless loops or verification
2531   failures if software took this identification literally.
2533   Extensions in certificate requests are identified using the nonstandard
2534   {microsoft 2 1 14} OID instead of the {pkcs-9 14} one, which means that
2535   although they're standard extensions, no non-MS software can recognise them.
2537   After MSIE 5.0, Microsoft partially switched to using the more standard
2538   {pkcs-9 14} identifier, but also invented their own format for further
2539   extensions alongside the existing one which nothing else can process.  The
2540   extensions contain either ASCII or (lengthy) Unicode strings identifying the
2541   product which created the cert request.
2543   Some DNs produced by MS software are encoded with zero-length strings.
2545   Country codes in DNs created by MS software can contain values other than
2546   the allowed two-character ISO code (for example three-character country name
2547   abbreviations).
2549   Code dating from about the MSIE 5.0 and newer stage will chain certificates
2550   using the authorityKeyIdentifier even if the issuer name doesn't match, in
2551   violation of X.509 and PKIX.  This means that a certificate could claim an
2552   issuer of "Verisign Class 1 Public Primary Certification Authority" even
2553   though it was actually issued by "Honest Joe's Used Cars and Certificates",
2554   and MSIE will accept it as valid.
2556   Date handling for certificates appears to be completely broken, although it's
2557   difficult to determine the real extent and nature of the problems.  For
2558   example a certificate which is valid from December 1951 to December 2050 is
2559   reported by Windows as being valid from December 1950 to December 1950.
2560   Despite this claim, it doesn't recognise the certificate as having expired,
2561   indicating multiple levels of date-processing bugs in both the decoding and
2562   handling of dates.
2564   Certificates don't have to contain valid keys or signatures in order to be
2565   accepted by Windows, for example a test certificate with an exponent of 1
2566   (which means the key has no effect) is accepted as valid.  This is probably
2567   required to support an MSDN knowledge base article which tells users how to
2568   extract keys from CryptoAPI by encrypting them with a public key with an
2569   exponent of 1.
2571   Some Microsoft products have been spotted which generate things which are
2572   claimed to be certificate requests but which actually contain PKCS #7
2573   signedData with a payload which is tagged as raw data but which is really a
2574   certificate request with Microsoft's gratuitously-incompatible CRMF
2575   extensions which aren't CRMF extensions, one of which is a certificate which
2576   is used to sign the PKCS #7 signedData.  Needless to say, nothing in
2577   existence except for a small subset of other Microsoft products know what to
2578   make of this mess.
2580 MISSI
2582   MISSI certificates use shared DSA parameters, with p, q, and g only being
2583   specified in the root CA certificate.  Apart from the risk this introduces
2584   (it allows signatures on certificates to be forged under some circumstances),
2585   it also complicates certificate processing because the parameters needed to
2586   verify a signature are generally held in a certificate held God knows where,
2587   so even if a certificate is valid and trusted, it's not possible to use it
2588   without having the entire cert chain up to the root on hand.
2590 NASA
2592   NASA identifies RSA public keys in certificates by a peculiar deprecated
2593   X.500 OID for RSA (2 5 8 1 1).
2595 Netlock
2597   The Netlock CA incorrectly encodes bit strings in key/certificate usage
2598   extensions.
2600 Netscape
2602   Invalid encoding of some (but only some) occurences of the integer value 0 in
2603   Commerce Server private keys.  The problem occurs when the integer value 0 in
2604   the RSAPrivateKey is encoded as integer, length = 0 rather than integer,
2605   length = 1, value = 0.  This was fixed on 20 March 1996 (between the Commerce
2606   Server 1.13 and Enterprise 2.0 releases).
2608   Some unidentified early Netscape CA software would encode an email address as
2609   a PrintableString CommonName in a DN.  This encoding is invalid since a
2610   PrintableString can't contain an '@' character.  The same CA issued a root
2611   certificate with a validity period of zero by encoding the start and end time
2612   as the same value.
2614   Earlier Netscape software encoded the critical flag in extensions
2615   incorrectly.  The flag is defined as BOOLEAN DEFAULT FALSE, but it was always
2616   encoded even if set to its default value.  This bug was fixed in early 1997.
2618   Handling of non-PrintableString components of DNs is somewhat ad hoc, at one
2619   point the code would take any string which wasn't a PrintableString and
2620   encode it as a T61String, whether it was or not.  This may have been fixed
2621   now, it results in improper encodings but most products don't care because
2622   they don't know what to do with strings that should really be BMPStrings
2623   either.  Also, the Cert Server enforces an upper limit on the DN length of
2624   255 characters when the DN is encoded as per RFC 1779 (so the actual limit is
2625   slightly less than 255 characters).
2627   The Netscape certificate extensions specification states that the keyUsage
2628   extension can be ignored if it's present and non-critical, and lists mappings
2629   from keyUsage to Netscape's own cert-type extension.  Some implementations
2630   follow these mappings and include both types of extension (notably Thawte),
2631   others ignore them and include only the Netscape-specific extension (notably
2632   Verisign).
2634   Navigator can ignore the basicConstraints extension in some instances when it
2635   conflicts with other extensions (see the entry for Verisign for details).
2636   One way to get it to ignore all extensions is to add the cert as type
2637   application/x-x509-ca-cert, in which case it'll accept anything including end
2638   entity certificates and certificates with invalid signatures as CA
2639   certificates.
2641   The Netscape CA software incorrectly encodes bit strings in key/certificate
2642   usage extensions.
2644   Adding a new certificate with the same DN as an existing certificate (for
2645   example a CA and site certificate with the same DN) can corrupt the Netscape
2646   certificate database.
2648   Encountering a T61String in a certificate will cause versions of Netscape
2649   dating from before 1998 to crash with a null pointer dereference.  Current
2650   versions will still crash if they encounter a BMPString or UTF8String.
2652 NIST
2654   NIST has a root CA certificate which the basicConstraints extension
2655   identifies as being a non-CA certificate, making it invalid for its intended
2656   purpose.  One of these broken certificates was used for several versions of
2657   the PKIX X.509 certificate and CRL profile as an example of a CA certificate,
2658   which could result in the same problem as the PKCS #10 example vs
2659   specification contradiction.
2661 Nortel
2663   One of Nortel's CA products encodes UTCTime dates using the incorrect non-GMT
2664   format.  The software is used by (at least) IBM, the Canadian government
2665   (GTIS/PWGCS), and Integrion, and can be identified by the "2.1d" version
2666   string in a Nortel-specific attribute attached to the cert.  Nortels WebCA
2667   1.0 doesn't have this problem, the fact that the 2.1d software uses a number
2668   of old, deprecated OIDs and the WebCA software doesn't would indicate that
2669   this is more recent than whatever produced the "2.1d" certs (the "2.1d"
2670   refers to a particular release of the infrastructure (Entrust/Manager,
2671   Entrust/Officer, and Entrust/Admin) and the corresponding client-side
2672   components (toolkits and Entrust/Client) rather than a single product).  This
2673   problem was fixed in the Entrust 3.0 infrastructure release.
2675   Nortel spun off their crypto/security products group as Entrust Technologies
2676   in January 1997, for further notes see the entry for Entrust.
2678 PKIX
2680   PKIX requires that end entity certificates not have a basicConstraints
2681   extension, which leaves the handling of the CA status of the certificate to
2682   chance.  Several popular applications treat these certificates as CA
2683   certificates for backwards-compatibility with X.509v1 CA certificates which
2684   didn't include basicConstraints, but in practice it's not really possible to
2685   determine how these certificates will be treated.  Because of this, it's not
2686   possible to issue a PKIX-compliant end entity certificate and know how it'll
2687   be treated once it's in circulation.
2689   The theory behind this usage is that applications should know that a v3
2690   certificate without basicConstraints defaults to being a non-CA certificate,
2691   however (even assuming that applications implemented this), if
2692   basicConstraints would have been the only extension in the certificate then
2693   defaulting to leaving it out would make it a v1 certificate as required by
2694   PKIX, so the v1 rules would apply.  To get the required processing, the
2695   certificate would have to be marked as v3 even though it's v1 (and the
2696   application processing it would have to know about the expected behaviour).
2697   In any case it's a somewhat peculiar use of the certificate version number
2698   field to convey certificate constraint information.
2700   One use for this feature is that it may be used as a cryptographically strong
2701   random number generator.  For each crypto key an application would issue 128
2702   basicConstraint-less certificates, hand them out to different
2703   implementations/users, and use their CA/non-CA interpretation as one bit of a
2704   session key.  This should yield close to 128 bits of pure entropy in each
2705   key.
2707   In between the draft versions of the standard (which were around for several
2708   years) and the RFC, the policy qualifiers display text type was quietly
2709   changed to exclude IA5String, which had been present in all the drafts.  As a
2710   result, certificates complying with the drafts didn't comply with the RFC.
2711   Since noone but Verisign seems to use these fields (see comments elsewhere in
2712   this document), it's noticeable by the fact that Verisign certs issued during
2713   the lifetime of the drafts appear to contain a string type which is invalid
2714   according to the RFC.  This isn't a Verisign problem though, since they
2715   complied with the spec at the time the certificates were issued.
2717 Safelayer
2719   Safelayer have solved the T61String problem by unilaterally extending
2720   PrintableString to include latin-1 characters (apparently this was a
2721   conscious decision, not an encoding bug).  Since they're in Spain, this
2722   results in most of their certs having invalid string encodings.
2724 SECUDE
2726   The SecuDE software produces certificates with the public key components
2727   identified by a peculiar deprecated X.500 OID for RSA (2 5 8 1 1).
2729   Certificates are hashed with MD2, despite the fact that this algorithm has
2730   been deprecated for some time.
2732   Older versions of SECUDE produced broken CRLs consisting of various portions
2733   of full CRLs (the software stored the CRLs in a nonstandard format, this was
2734   fixed after 4.x but since this was the last free version it's still in use in
2735   some places).
2737 SecureNet
2739   This CA uses Microsoft software for its certificates, which means they
2740   display all the bugs typical of MS-created certificates (see the extensive
2741   entry under the Microsoft heading for more details).
2743 Security Domain/Zergo/Certificates Australia
2745   The authorityKeyIdentifier contains both a keyIdentifier which isn't the
2746   required SHA-1 hash (the subjectKeyIdentifier is a hash, it's only the
2747   authorityKeyIdentifier which isn't), as well as an authorityCertIssuer
2748   represented as a registeredID object identifier.  Other certificates contain
2749   an authorityCertIssuer consisting of a single zero byte.  Another cert
2750   contains an authorityCertSerialNumber consisting of a single zero byte.
2752   Bit strings in key/certificate usage extensions are encoded incorrectly.
2754   The certificatePolicies extension uses incorrect OIDs for the various
2755   components such as the CPS and unotice, the CPS URL isn't a valid URL, and
2756   the unotice is given as an IA5String rather than a SEQUENCE of assorted
2757   components.  A different certificatePolicies contains what looks like another
2758   invalid OID which could be an attempt at the one in the previously mentioned
2759   certificatePolicies.
2761   In some cases the issuerName is encoded as 127 bytes of zero-padded
2762   registeredID OID.
2764   (Ugh, this stuff just gets worse and worse - the later attempts at things
2765   like PKCS #7 cert chains are so far removed from the real thing that they
2766   don't even remotely approach the actual standard.  I'll stop now).
2768   These issues were resolved in 1999 in a merger with Baltimore by switching to
2769   Baltimore's UniCERT product.
2771 SEIS
2773   The Swedish SEIS project software formerly created UniqueIdentifiers which
2774   contained embedded character strings (this is a peculiarity).  In some
2775   versions of the software, these were flagged as constructed rather than
2776   primitive (this is a bug).  The encoding bug was rectified in later versions.
2777   The character strings encode 16-digit numbers, which are apparently used as
2778   some form of extra identification which doesn't fit easily into a DN.
2780   In the EID v2 certificate draft of February 1998, the use of
2781   UniqueIdentifiers was deprecated in favour of a DN entry under a SEIS OID
2782   which contained the information formerly in the UniqueIdentifiers.
2786   There is a minor problem which arises from the fact that SET uses the ':'
2787   character as a delimiter in commonName components of DNs.  However BMPStrings
2788   have more than one character which looks like a ':'.  The correct one to use
2789   is the ':' which is common to both PrintableString and BMPString, ASCII
2790   character 0x3A.
2792 SHTTP specification
2794   There is at least one invalid PCKS#7 example in earlier versions of the spec.
2795   More recent drafts starting with <draft-ietf-wts-shttp-03.txt>, July 1996,
2796   fix this.  Implementors should ensure they are working with corrected
2797   versions of the draft.
2799 SI-CA
2801   The SI-CA incorrectly encodes some bit strings in key/certificate usage
2802   extensions.  Unlike other implementations and CAs which have this problem, it
2803   doesn't do it consistently, correctly encoding some bitstrings and
2804   incorrectly encoding others.
2806 Signet
2808   [Some of these problems were fixed in late 1998]
2810   Default fields are encoded when they have the default value rather than being
2811   omitted.
2813   Some basicConstraints extensions are marked as being critical, others in the
2814   same chain are marked noncritical (using the incorrect default field
2815   encoding mentioned above).
2817   Bit strings in key/certificate usage extensions are encoded incorrectly.
2819   Leaf certs are identified by giving the issuing cert a path length constraint
2820   of 0 in the basicConstraints extension rather than by marking the cert itself
2821   as being a non-CA cert.  This isn't invalid, but is somewhat peculiar, and
2822   doesn't work if the leaf cert is implicitly trusted (without the signing cert
2823   being present), since there's no indication in the leaf cert itself as to
2824   whether it's a CA cert or not.
2826   BOOLEAN values have non-DER encodings.
2828   The name constraints extension contains a permittedSubtree with what appears
2829   to be an otherName consisting of a single zero byte (no OID or anything
2830   else).
2832 South African CA
2834   This CA has a root cert which has the UTCTime encoded without the seconds
2835   (see the section "Validity" above), newer versions encode the time with the
2836   seconds.  This isn't an error since the accepted encoding was changed in
2837   mid-1996, merely something to be aware of.
2839 SSLeay
2841   SSLeay incorrectly encoded bit strings in key/certificate usage extensions,
2842   this was fixed in late 1998 in version 0.9.1.
2844 Sweden Post/ID2
2846   Sweden Post certificates incorrectly encode the certificate validity time,
2847   omitting the seconds field in the UTCTime field.
2849   The subjectKeyIdentifier is encoded in a variety of ways ranging in length
2850   from 1 to 8 bytes.  In CA certs the subjectKeyIdentifier is the same as the
2851   authorityKeyIdentifier (which is valid, but odd) and consists of a text
2852   string identifying the CA key (this isn't explicitly disallowed because of
2853   the confusion over what's really meant to be in there but it isn't really
2854   what's supposed to be in there either).
2856   Instead of using a common name, the data is encoded as a surname + given name
2857   + unique ID, producing DN fields with multiple AVAs per RDN (this isn't a
2858   bug, but is definitely a peculiarity, and causes problems for software which
2859   expects to use a common name as the identity of the certificate owner).
2861   CA certs include policy mappings which specify the same issuer and subject
2862   domain policy (this is known as a tautology mapping).
2864   End-entity certs include (deprecated) subjectUniqueIdentifier fields (this is
2865   a peculiarity).  The fields contain embedded PrintableString's consisting of
2866   variable-length numbers.
2868 SWIFT
2870   SWIFT certificates have incorrect field lengths for several of the
2871   certificate fields, so that the SWIFT CA doesn't even have a valid root CA
2872   certificate.
2874 Syscall GbR
2876   The Syscall GbR CA incorrectly encodes bit strings in key/certificate usage
2877   extensions.
2879 TC Trustcenter
2881   Some certs contain zero-length strings in the DN, this was fixed in early
2882   1999.
2884 Telesec/Deutsche Telekom Trustcenter
2886                     Interoperability considerations merely create uncertainty
2887                     and don't serve any useful purpose.  The market for digital
2888                     signatures is at hand and it's possible to sell products
2889                     without any interoperability
2890                         -- Telesec project leader discussing the Telesec
2891                            approach to interoperability (translated),
2892                            "Digitale Identitaet" workshop, Berlin, May 1999.
2894   Telesec certificates come in two flavours, general-purpose certificates (for
2895   example for S/MIME and SSL use) and PKS (Public Key Service) certificates
2896   which are intended for use under the German digital signature law.  The two
2897   aren't compatible, and it's not possible to tell which one a given
2898   certificate follows because the certificates don't include any policy
2899   identification extensions.  An example of the kind of problem this causes is
2900   that the Telesec CPS claims certificates will be signed with RSA/MD5, however
2901   published end-entity certs have appeared which are signed with
2902   RSA/RIPEMD-160.  These aren't invalid, they just follow the PKS profile
2903   rather than the PKIX profile or CPS.  Another example of this is the fact
2904   that PKS certificates use GeneralizedTime, which is allowed under the PKS
2905   profile but not the PKIX/SSL/SMIME/etc ones.
2907   Some strings are encoded as T61Strings where PrintableStrings should be used
2908   (there's no pattern to this).  The strings which really are T61Strings use
2909   floating diacritics, which isn't, strictly speaking, illegal, but anyone who
2910   does use them should be hung upside down in a bucket of hungry earthworms.
2912   Common names are encoded in an RDN component with two AVAs, one identified
2913   by an unknown Telekom OID and the second identified with the CN OID, however
2914   the common name in it is modified by appending extra letters and digits which
2915   are intended to distinguish non-unique names in the same manner as the
2916   (deprecated) X.509v2 uniqueIdentifiers.  Since even imaginary (guaranteed
2917   unique) names are modified in this way, it appears that this alteration is
2918   always performed.
2920   The certificates encode INTEGER values incorrectly by setting the high bit,
2921   which makes them negative values.  This is particularly problematic with RSA
2922   keys since they use a hardwired exponent of 3,221,225,473 (!!!) which always
2923   has the high bit set (0xC0000001), so all the RSA certificates have invalid
2924   encodings.  This was corrected in late 1999.
2926   CA certificates are encoded with no basicConstraints present, which under
2927   PKIX rules (which aren't terribly sensible, see an earlier section)
2928   explicitly makes them non-CA certificates and under normal conditions makes
2929   them highly ambiguous at best.
2931   [This stuff just gets worse and worse, but I couldn't be bothered going
2932    through and figuring out all the broken things they do.  Telesec also
2933    hardcode things like certificate parameters into their software (so that,
2934    for example, half the info about a user might be stored on a smart card
2935    (needed for SigG compliance) and the other half is hardcoded into the driver
2936    DLL for the card), guaranteeing that nothing else in existence can work with
2937    it.  Ugh].
2939 Thawte
2941   For a brief while, Thawte encoded email addresses as a PrintableString in a
2942   DN's CommonName.  This encoding is invalid since a PrintableString can't
2943   contain an '@' character.  This problem has been fixed.
2945 TimeStep/Newbridge/Alcatel
2947   TimeStep incorrectly encode the DirectoryName in a GeneralName, using an
2948   implicit rather than an explicit tag.  The ASN.1 encoding rules require that
2949   a tagged CHOICE always have an explicit tag in order to make the underlying
2950   CHOICE tag visible.  Timestep were bought by Newbridge who were in turn
2951   bought by Alcatel, thus the naming confusion.
2953 UNINETT
2955   Some certs from this CA identify RSA public keys in certificates by a
2956   peculiar deprecated X.500 OID for RSA (2 5 8 1 1).  However in one case a
2957   second cert for the same person produced on the same day used rsaEncryption
2958   instead.
2960 uniqueIdentifier
2962   There are at least two incompatible objects called uniqueIdentifier, the
2963   first is an attribute defined in 1991 in RFC 1274 with string syntax and an
2964   illegal OID (rendering it, in theory, invalid), the second is an attribute
2965   defined in 1993 in X.520v2 with BIT STRING syntax.  LDAPv2 used the RFC 1274
2966   interpretation, RFC 2256 changed the name for the X.520 version to
2967   x500uniqueIdentifier for use with LDAPv3.  There is also a uid attribute
2968   defined in RFC 1274, this is different again.
2970 Verisign
2972   Verisign incorrectly encodes the lengths of fields in the (deprecated)
2973   keyUsageRestriction extension, which is used for the Microsoft code signing
2974   certificates they issue.  Some software like MSIE will quite happily accept
2975   the broken extension, but other software which does proper checking will
2976   reject it (actually there are so many weird, unknown critical extensions in
2977   the code signing certs that it's unlikely that anything other than MSIE can
2978   process them anyway).
2980   Verisign were, as of March 1998, still issuing certificates with an MD2 hash,
2981   despite the fact that this algorithm has been deprecated for some time.  This
2982   may be because they have hardware (BBN SafeKeypers) which can only generate
2983   the older type of hash.
2985   Verisign Webpass certificates contain a basicConstraints extension which
2986   designate the certificate as a non-CA certificate, and a Netscape cert-type
2987   extension which designate the certificate as a CA certificate.  Despite this
2988   contradiction, MSIE doesn't seem have any problems with using the
2989   certificate, indicating that it's ignoring the basicConstraints entirely.
2990   Navigator will load the certificate, but gets an internal error when it tries
2991   to use it.  This was fixed in late May 1998.
2993   Some Verisign certificates mix DER and BER inside the signed portion of the
2994   certificate.  Only DER-encoded data is allowed in this part of the
2995   certificate.
2997   For a brief period of time in mid-1998 Verisign issued certificates signed
2998   with an MD2 signature block wrapped inside an MD5 signature block.  This was
2999   fixed fairly quickly.
3001   Verisign doesn't mark extensions as critical, even fundamental ones like
3002   basicConstraints.  This is because of Microsoft software which rejects
3003   certificates with critical extensions.
3005 Y2K/2038 Issues
3007   Many implementations base their internal time encoding on the Unix/ANSI/ISO C
3008   seconds-since-1970 format, and some use 1970 as the rollover date for
3009   interpreting two-digit dates instead of xx50.  This includes, as of late
3010   1997, Netscape and SSLeay.  In addition the January 2038 limit for seconds
3011   expressed as a signed 32-bit quantity means they can't represent dates past
3012   this point (which will cause problems with Microsoft's four-decade validity
3013   periods).  Implementations should therefore be very careful about keys with
3014   very long expiry times, for security as well as date handling reasons,
3017 Annex A
3018 -------
3020 The Standards Designer Joke.  I resisted adding this for a long time, but it
3021 really needs to be present :-).
3023   An engineer, a chemist, and a standards designer are stranded on a desert
3024   island with absolutely nothing on it.  One of them finds a can of spam washed
3025   up by the waves.
3027   The engineer says "Taking the strength of the seams into account, we can
3028   calculate that bashing it against a rock with a given force will open it up
3029   without destroying the contents".
3031   The chemist says "Taking the type of metal the can is made of into account,
3032   we can calculate that further immersion in salt water will corrode it enough
3033   to allow it to be easily opened after a day".
3035   The standards designer gives the other two a condescending look, gazes into
3036   the middle distance, and begins "Assuming we have an electric can opener...".
3039 Acknowledgements
3040 ----------------
3042 Anil Gangolli, Deepak Nadig, Eric Young, Harald Alvestrand, John Pawling, Phil
3043 Griffin, and members of various X.509 and PKI-related mailing lists provided
3044 useful comments on usage recommendations, encoding issues, and bugs.