155714Skris
255714SkrisThis is some preliminary documentation for OpenSSL.
355714Skris
459191SkrisContents:
555714Skris
659191Skris OpenSSL X509V3 extension configuration
759191Skris X509V3 Extension code: programmers guide
859191Skris PKCS#12 Library
955714Skris
1055714Skris
1155714Skris==============================================================================
1255714Skris               OpenSSL X509V3 extension configuration
1355714Skris==============================================================================
1455714Skris
1555714SkrisOpenSSL X509V3 extension configuration: preliminary documentation.
1655714Skris
1755714SkrisINTRODUCTION.
1855714Skris
1955714SkrisFor OpenSSL 0.9.2 the extension code has be considerably enhanced. It is now
2055714Skrispossible to add and print out common X509 V3 certificate and CRL extensions.
2155714Skris
2255714SkrisBEGINNERS NOTE
2355714Skris
2455714SkrisFor most simple applications you don't need to know too much about extensions:
2555714Skristhe default openssl.cnf values will usually do sensible things.
2655714Skris
2755714SkrisIf you want to know more you can initially quickly look through the sections
2855714Skrisdescribing how the standard OpenSSL utilities display and add extensions and
2955714Skristhen the list of supported extensions.
3055714Skris
3155714SkrisFor more technical information about the meaning of extensions see:
3255714Skris
3355714Skrishttp://www.imc.org/ietf-pkix/
3455714Skrishttp://home.netscape.com/eng/security/certs.html
3555714Skris
3655714SkrisPRINTING EXTENSIONS.
3755714Skris
3855714SkrisExtension values are automatically printed out for supported extensions.
3955714Skris
4055714Skrisopenssl x509 -in cert.pem -text
4155714Skrisopenssl crl -in crl.pem -text
4255714Skris
4355714Skriswill give information in the extension printout, for example:
4455714Skris
4555714Skris        X509v3 extensions:
4655714Skris            X509v3 Basic Constraints: 
4755714Skris                CA:TRUE
4855714Skris            X509v3 Subject Key Identifier: 
4955714Skris                73:FE:F7:59:A7:E1:26:84:44:D6:44:36:EE:79:1A:95:7C:B1:4B:15
5055714Skris            X509v3 Authority Key Identifier: 
5155714Skris                keyid:73:FE:F7:59:A7:E1:26:84:44:D6:44:36:EE:79:1A:95:7C:B1:4B:15, DirName:/C=AU/ST=Some-State/O=Internet Widgits Pty Ltd/Email=email@1.address/Email=email@2.address, serial:00
5255714Skris            X509v3 Key Usage: 
5355714Skris                Certificate Sign, CRL Sign
5455714Skris            X509v3 Subject Alternative Name: 
5555714Skris                email:email@1.address, email:email@2.address
5655714Skris
5755714SkrisCONFIGURATION FILES.
5855714Skris
5955714SkrisThe OpenSSL utilities 'ca' and 'req' can now have extension sections listing
6055714Skriswhich certificate extensions to include. In each case a line:
6155714Skris
6255714Skrisx509_extensions = extension_section
6355714Skris
6455714Skrisindicates which section contains the extensions. In the case of 'req' the
6555714Skrisextension section is used when the -x509 option is present to create a
6655714Skrisself signed root certificate.
6755714Skris
6855714SkrisThe 'x509' utility also supports extensions when it signs a certificate.
6955714SkrisThe -extfile option is used to set the configuration file containing the
7055714Skrisextensions. In this case a line with:
7155714Skris
7255714Skrisextensions = extension_section
7355714Skris
7455714Skrisin the nameless (default) section is used. If no such line is included then
7555714Skrisit uses the default section.
7655714Skris
7755714SkrisYou can also add extensions to CRLs: a line
7855714Skris
7955714Skriscrl_extensions = crl_extension_section
8055714Skris
8155714Skriswill include extensions when the -gencrl option is used with the 'ca' utility.
8255714SkrisYou can add any extension to a CRL but of the supported extensions only
8355714SkrisissuerAltName and authorityKeyIdentifier make any real sense. Note: these are
8455714SkrisCRL extensions NOT CRL *entry* extensions which cannot currently be generated.
8555714SkrisCRL entry extensions can be displayed.
8655714Skris
8755714SkrisNB. At this time Netscape Communicator rejects V2 CRLs: to get an old V1 CRL
8855714Skrisyou should not include a crl_extensions line in the configuration file.
8955714Skris
9055714SkrisAs with all configuration files you can use the inbuilt environment expansion
9155714Skristo allow the values to be passed in the environment. Therefore if you have
9255714Skrisseveral extension sections used for different purposes you can have a line:
9355714Skris
9455714Skrisx509_extensions = $ENV::ENV_EXT
9555714Skris
9655714Skrisand set the ENV_EXT environment variable before calling the relevant utility.
9755714Skris
9855714SkrisEXTENSION SYNTAX.
9955714Skris
10055714SkrisExtensions have the basic form:
10155714Skris
10255714Skrisextension_name=[critical,] extension_options
10355714Skris
10455714Skristhe use of the critical option makes the extension critical. Extreme caution
10555714Skrisshould be made when using the critical flag. If an extension is marked
10655714Skrisas critical then any client that does not understand the extension should
10755714Skrisreject it as invalid. Some broken software will reject certificates which
10855714Skrishave *any* critical extensions (these violates PKIX but we have to live
10955714Skriswith it).
11055714Skris
11155714SkrisThere are three main types of extension: string extensions, multi-valued
11255714Skrisextensions, and raw extensions.
11355714Skris
11455714SkrisString extensions simply have a string which contains either the value itself
11555714Skrisor how it is obtained.
11655714Skris
11755714SkrisFor example:
11855714Skris
11955714SkrisnsComment="This is a Comment"
12055714Skris
12155714SkrisMulti-valued extensions have a short form and a long form. The short form
12255714Skrisis a list of names and values:
12355714Skris
12455714SkrisbasicConstraints=critical,CA:true,pathlen:1
12555714Skris
12655714SkrisThe long form allows the values to be placed in a separate section:
12755714Skris
12855714SkrisbasicConstraints=critical,@bs_section
12955714Skris
13055714Skris[bs_section]
13155714Skris
13255714SkrisCA=true
13355714Skrispathlen=1
13455714Skris
13555714SkrisBoth forms are equivalent. However it should be noted that in some cases the
13655714Skrissame name can appear multiple times, for example,
13755714Skris
13855714SkrissubjectAltName=email:steve@here,email:steve@there
13955714Skris
14055714Skrisin this case an equivalent long form is:
14155714Skris
14255714SkrissubjectAltName=@alt_section
14355714Skris
14455714Skris[alt_section]
14555714Skris
14655714Skrisemail.1=steve@here
14755714Skrisemail.2=steve@there
14855714Skris
14955714SkrisThis is because the configuration file code cannot handle the same name
15059191Skrisoccurring twice in the same section.
15155714Skris
15255714SkrisThe syntax of raw extensions is governed by the extension code: it can
15355714Skrisfor example contain data in multiple sections. The correct syntax to
15455714Skrisuse is defined by the extension code itself: check out the certificate
15555714Skrispolicies extension for an example.
15655714Skris
157160814SsimonThere are two ways to encode arbitrary extensions.
15855714Skris
159160814SsimonThe first way is to use the word ASN1 followed by the extension content
160160814Ssimonusing the same syntax as ASN1_generate_nconf(). For example:
161160814Ssimon
162160814Ssimon1.2.3.4=critical,ASN1:UTF8String:Some random data
163160814Ssimon
164160814Ssimon1.2.3.4=ASN1:SEQUENCE:seq_sect
165160814Ssimon
166160814Ssimon[seq_sect]
167160814Ssimon
168160814Ssimonfield1 = UTF8:field1
169160814Ssimonfield2 = UTF8:field2
170160814Ssimon
171160814SsimonIt is also possible to use the word DER to include arbitrary data in any
172160814Ssimonextension.
173160814Ssimon
17455714Skris1.2.3.4=critical,DER:01:02:03:04
17555714Skris1.2.3.4=DER:01020304
17655714Skris
17755714SkrisThe value following DER is a hex dump of the DER encoding of the extension
17855714SkrisAny extension can be placed in this form to override the default behaviour.
17955714SkrisFor example:
18055714Skris
18155714SkrisbasicConstraints=critical,DER:00:01:02:03
18255714Skris
18355714SkrisWARNING: DER should be used with caution. It is possible to create totally
18455714Skrisinvalid extensions unless care is taken.
18555714Skris
18655714SkrisCURRENTLY SUPPORTED EXTENSIONS.
18755714Skris
18855714SkrisIf you aren't sure about extensions then they can be largely ignored: its only
18955714Skriswhen you want to do things like restrict certificate usage when you need to
19055714Skrisworry about them. 
19155714Skris
19255714SkrisThe only extension that a beginner might want to look at is Basic Constraints.
19355714SkrisIf in addition you want to try Netscape object signing the you should also
19455714Skrislook at Netscape Certificate Type.
19555714Skris
19655714SkrisLiteral String extensions.
19755714Skris
19855714SkrisIn each case the 'value' of the extension is placed directly in the
19955714Skrisextension. Currently supported extensions in this category are: nsBaseUrl,
20055714SkrisnsRevocationUrl, nsCaRevocationUrl, nsRenewalUrl, nsCaPolicyUrl,
20155714SkrisnsSslServerName and nsComment.
20255714Skris
20355714SkrisFor example:
20455714Skris
20555714SkrisnsComment="This is a test comment"
20655714Skris
20755714SkrisBit Strings.
20855714Skris
20955714SkrisBit string extensions just consist of a list of supported bits, currently
21055714Skristwo extensions are in this category: PKIX keyUsage and the Netscape specific
21155714SkrisnsCertType.
21255714Skris
21355714SkrisnsCertType (netscape certificate type) takes the flags: client, server, email,
21455714Skrisobjsign, reserved, sslCA, emailCA, objCA.
21555714Skris
21655714SkriskeyUsage (PKIX key usage) takes the flags: digitalSignature, nonRepudiation,
21755714SkriskeyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign,
21855714SkrisencipherOnly, decipherOnly.
21955714Skris
22055714SkrisFor example:
22155714Skris
22255714SkrisnsCertType=server
22355714Skris
22455714SkriskeyUsage=digitalSignature, nonRepudiation
22555714Skris
22655714SkrisHints on Netscape Certificate Type.
22755714Skris
22855714SkrisOther than Basic Constraints this is the only extension a beginner might
22955714Skriswant to use, if you want to try Netscape object signing, otherwise it can
23055714Skrisbe ignored.
23155714Skris
23255714SkrisIf you want a certificate that can be used just for object signing then:
23355714Skris
23455714SkrisnsCertType=objsign
23555714Skris
23655714Skriswill do the job. If you want to use it as a normal end user and server
23755714Skriscertificate as well then
23855714Skris
23955714SkrisnsCertType=objsign,email,server
24055714Skris
24155714Skrisis more appropriate. You cannot use a self signed certificate for object
24255714Skrissigning (well Netscape signtool can but it cheats!) so you need to create
24355714Skrisa CA certificate and sign an end user certificate with it.
24455714Skris
24555714SkrisSide note: If you want to conform to the Netscape specifications then you
24655714Skrisshould really also set:
24755714Skris
24855714SkrisnsCertType=objCA
24955714Skris
25055714Skrisin the *CA* certificate for just an object signing CA and
25155714Skris
25255714SkrisnsCertType=objCA,emailCA,sslCA
25355714Skris
25455714Skrisfor everything. Current Netscape software doesn't enforce this so it can
25555714Skrisbe omitted.
25655714Skris
25755714SkrisBasic Constraints.
25855714Skris
25955714SkrisThis is generally the only extension you need to worry about for simple
26055714Skrisapplications. If you want your certificate to be usable as a CA certificate
26155714Skris(in addition to an end user certificate) then you set this to:
26255714Skris
26355714SkrisbasicConstraints=CA:TRUE
26455714Skris
26555714Skrisif you want to be certain the certificate cannot be used as a CA then do:
26655714Skris
26755714SkrisbasicConstraints=CA:FALSE
26855714Skris
26955714SkrisThe rest of this section describes more advanced usage.
27055714Skris
27155714SkrisBasic constraints is a multi-valued extension that supports a CA and an
27255714Skrisoptional pathlen option. The CA option takes the values true and false and
27355714Skrispathlen takes an integer. Note if the CA option is false the pathlen option
27455714Skrisshould be omitted. 
27555714Skris
27655714SkrisThe pathlen parameter indicates the maximum number of CAs that can appear
27755714Skrisbelow this one in a chain. So if you have a CA with a pathlen of zero it can
27855714Skrisonly be used to sign end user certificates and not further CAs. This all
27955714Skrisassumes that the software correctly interprets this extension of course.
28055714Skris
28155714SkrisExamples:
28255714Skris
28355714SkrisbasicConstraints=CA:TRUE
28455714SkrisbasicConstraints=critical,CA:TRUE, pathlen:0
28555714Skris
28655714SkrisNOTE: for a CA to be considered valid it must have the CA option set to
28755714SkrisTRUE. An end user certificate MUST NOT have the CA value set to true.
28855714SkrisAccording to PKIX recommendations it should exclude the extension entirely,
28955714Skrishowever some software may require CA set to FALSE for end entity certificates.
29055714Skris
29159191SkrisExtended Key Usage.
29259191Skris
29359191SkrisThis extensions consists of a list of usages.
29459191Skris
29559191SkrisThese can either be object short names of the dotted numerical form of OIDs.
29659191SkrisWhile any OID can be used only certain values make sense. In particular the
29759191Skrisfollowing PKIX, NS and MS values are meaningful:
29859191Skris
29959191SkrisValue			Meaning
30059191Skris-----			-------
30159191SkrisserverAuth		SSL/TLS Web Server Authentication.
30259191SkrisclientAuth		SSL/TLS Web Client Authentication.
30359191SkriscodeSigning		Code signing.
30459191SkrisemailProtection		E-mail Protection (S/MIME).
30559191SkristimeStamping		Trusted Timestamping
30659191SkrismsCodeInd		Microsoft Individual Code Signing (authenticode)
30759191SkrismsCodeCom		Microsoft Commercial Code Signing (authenticode)
30859191SkrismsCTLSign		Microsoft Trust List Signing
30959191SkrismsSGC			Microsoft Server Gated Crypto
31059191SkrismsEFS			Microsoft Encrypted File System
31159191SkrisnsSGC			Netscape Server Gated Crypto
31259191Skris
31359191SkrisFor example, under IE5 a CA can be used for any purpose: by including a list
31459191Skrisof the above usages the CA can be restricted to only authorised uses.
31559191Skris
31659191SkrisNote: software packages may place additional interpretations on certificate 
31759191Skrisuse, in particular some usages may only work for selected CAs. Don't for example
31859191Skrisexpect just including msSGC or nsSGC will automatically mean that a certificate
31959191Skriscan be used for SGC ("step up" encryption) otherwise anyone could use it.
32059191Skris
32159191SkrisExamples:
32259191Skris
32359191SkrisextendedKeyUsage=critical,codeSigning,1.2.3.4
32459191SkrisextendedKeyUsage=nsSGC,msSGC
32559191Skris
32655714SkrisSubject Key Identifier.
32755714Skris
32855714SkrisThis is really a string extension and can take two possible values. Either
32955714Skrisa hex string giving details of the extension value to include or the word
33055714Skris'hash' which then automatically follow PKIX guidelines in selecting and
33155714Skrisappropriate key identifier. The use of the hex string is strongly discouraged.
33255714Skris
33355714SkrisExample: subjectKeyIdentifier=hash
33455714Skris
33555714SkrisAuthority Key Identifier.
33655714Skris
33755714SkrisThe authority key identifier extension permits two options. keyid and issuer:
33855714Skrisboth can take the optional value "always".
33955714Skris
34055714SkrisIf the keyid option is present an attempt is made to copy the subject key
34155714Skrisidentifier from the parent certificate. If the value "always" is present
34255714Skristhen an error is returned if the option fails.
34355714Skris
34455714SkrisThe issuer option copies the issuer and serial number from the issuer
34555714Skriscertificate. Normally this will only be done if the keyid option fails or
34655714Skrisis not included: the "always" flag will always include the value.
34755714Skris
34855714SkrisSubject Alternative Name.
34955714Skris
35055714SkrisThe subject alternative name extension allows various literal values to be
35155714Skrisincluded in the configuration file. These include "email" (an email address)
35255714Skris"URI" a uniform resource indicator, "DNS" (a DNS domain name), RID (a
353160814Ssimonregistered ID: OBJECT IDENTIFIER), IP (and IP address) and otherName.
35455714Skris
35555714SkrisAlso the email option include a special 'copy' value. This will automatically
35655714Skrisinclude and email addresses contained in the certificate subject name in
35755714Skristhe extension.
35855714Skris
359160814SsimonotherName can include arbitrary data associated with an OID: the value
360160814Ssimonshould be the OID followed by a semicolon and the content in standard
361160814SsimonASN1_generate_nconf() format.
362160814Ssimon
36355714SkrisExamples:
36455714Skris
365109998SmarkmsubjectAltName=email:copy,email:my@other.address,URI:http://my.url.here/
36655714SkrissubjectAltName=email:my@other.address,RID:1.2.3.4
367160814SsimonsubjectAltName=otherName:1.2.3.4;UTF8:some other identifier
36855714Skris
36955714SkrisIssuer Alternative Name.
37055714Skris
37155714SkrisThe issuer alternative name option supports all the literal options of
37255714Skrissubject alternative name. It does *not* support the email:copy option because
37355714Skristhat would not make sense. It does support an additional issuer:copy option
37455714Skristhat will copy all the subject alternative name values from the issuer 
37555714Skriscertificate (if possible).
37655714Skris
37768651SkrisExample:
37868651Skris
37968651SkrisissuserAltName = issuer:copy
38068651Skris
38168651SkrisAuthority Info Access.
38268651Skris
38368651SkrisThe authority information access extension gives details about how to access
38468651Skriscertain information relating to the CA. Its syntax is accessOID;location
38568651Skriswhere 'location' has the same syntax as subject alternative name (except
38668651Skristhat email:copy is not supported). accessOID can be any valid OID but only
38768651Skriscertain values are meaningful for example OCSP and caIssuers. OCSP gives the
38868651Skrislocation of an OCSP responder: this is used by Netscape PSM and other software.
38968651Skris
39068651SkrisExample:
39168651Skris
39268651SkrisauthorityInfoAccess = OCSP;URI:http://ocsp.my.host/
39368651SkrisauthorityInfoAccess = caIssuers;URI:http://my.ca/ca.html
39468651Skris
39555714SkrisCRL distribution points.
39655714Skris
39755714SkrisThis is a multi-valued extension that supports all the literal options of
39855714Skrissubject alternative name. Of the few software packages that currently interpret
39955714Skristhis extension most only interpret the URI option.
40055714Skris
40155714SkrisCurrently each option will set a new DistributionPoint with the fullName
40255714Skrisfield set to the given value.
40355714Skris
40455714SkrisOther fields like cRLissuer and reasons cannot currently be set or displayed:
40555714Skrisat this time no examples were available that used these fields.
40655714Skris
40755714SkrisIf you see this extension with <UNSUPPORTED> when you attempt to print it out
40855714Skrisor it doesn't appear to display correctly then let me know, including the
40955714Skriscertificate (mail me at steve@openssl.org) .
41055714Skris
41155714SkrisExamples:
41255714Skris
41355714SkriscrlDistributionPoints=URI:http://www.myhost.com/myca.crl
41455714SkriscrlDistributionPoints=URI:http://www.my.com/my.crl,URI:http://www.oth.com/my.crl
41555714Skris
41655714SkrisCertificate Policies.
41755714Skris
41855714SkrisThis is a RAW extension. It attempts to display the contents of this extension:
41955714Skrisunfortunately this extension is often improperly encoded.
42055714Skris
42155714SkrisThe certificate policies extension will rarely be used in practice: few
42255714Skrissoftware packages interpret it correctly or at all. IE5 does partially
42355714Skrissupport this extension: but it needs the 'ia5org' option because it will
42455714Skrisonly correctly support a broken encoding. Of the options below only the
42555714Skrispolicy OID, explicitText and CPS options are displayed with IE5.
42655714Skris
42755714SkrisAll the fields of this extension can be set by using the appropriate syntax.
42855714Skris
42955714SkrisIf you follow the PKIX recommendations of not including any qualifiers and just
43055714Skrisusing only one OID then you just include the value of that OID. Multiple OIDs
43155714Skriscan be set separated by commas, for example:
43255714Skris
43355714SkriscertificatePolicies= 1.2.4.5, 1.1.3.4
43455714Skris
43555714SkrisIf you wish to include qualifiers then the policy OID and qualifiers need to
43655714Skrisbe specified in a separate section: this is done by using the @section syntax
43755714Skrisinstead of a literal OID value.
43855714Skris
43955714SkrisThe section referred to must include the policy OID using the name
44055714SkrispolicyIdentifier, cPSuri qualifiers can be included using the syntax:
44155714Skris
44255714SkrisCPS.nnn=value
44355714Skris
44455714SkrisuserNotice qualifiers can be set using the syntax:
44555714Skris
44655714SkrisuserNotice.nnn=@notice
44755714Skris
44855714SkrisThe value of the userNotice qualifier is specified in the relevant section.
44955714SkrisThis section can include explicitText, organization and noticeNumbers
45055714Skrisoptions. explicitText and organization are text strings, noticeNumbers is a
45155714Skriscomma separated list of numbers. The organization and noticeNumbers options
45255714Skris(if included) must BOTH be present. If you use the userNotice option with IE5
45355714Skristhen you need the 'ia5org' option at the top level to modify the encoding:
45455714Skrisotherwise it will not be interpreted properly.
45555714Skris
45655714SkrisExample:
45755714Skris
45855714SkriscertificatePolicies=ia5org,1.2.3.4,1.5.6.7.8,@polsect
45955714Skris
46055714Skris[polsect]
46155714Skris
46255714SkrispolicyIdentifier = 1.3.5.8
46355714SkrisCPS.1="http://my.host.name/"
46455714SkrisCPS.2="http://my.your.name/"
46555714SkrisuserNotice.1=@notice
46655714Skris
46755714Skris[notice]
46855714Skris
46955714SkrisexplicitText="Explicit Text Here"
47055714Skrisorganization="Organisation Name"
47155714SkrisnoticeNumbers=1,2,3,4
47255714Skris
47355714SkrisTECHNICAL NOTE: the ia5org option changes the type of the 'organization' field,
47455714Skrisaccording to PKIX it should be of type DisplayText but Verisign uses an 
47555714SkrisIA5STRING and IE5 needs this too.
47655714Skris
47755714SkrisDisplay only extensions.
47855714Skris
47955714SkrisSome extensions are only partially supported and currently are only displayed
48055714Skrisbut cannot be set. These include private key usage period, CRL number, and
48155714SkrisCRL reason.
48255714Skris
48355714Skris==============================================================================
48455714Skris		X509V3 Extension code: programmers guide
48555714Skris==============================================================================
48655714Skris
48755714SkrisThe purpose of the extension code is twofold. It allows an extension to be
48855714Skriscreated from a string or structure describing its contents and it prints out an
48955714Skrisextension in a human or machine readable form.
49055714Skris
49155714Skris1. Initialisation and cleanup.
49255714Skris
49359191SkrisNo special initialisation is needed before calling the extension functions.
49459191SkrisYou used to have to call X509V3_add_standard_extensions(); but this is no longer
49559191Skrisrequired and this function no longer does anything.
49655714Skris
49755714Skrisvoid X509V3_EXT_cleanup(void);
49855714Skris
49959191SkrisThis function should be called to cleanup the extension code if any custom
50059191Skrisextensions have been added. If no custom extensions have been added then this
50159191Skriscall does nothing. After this call all custom extension code is freed up but
50259191Skrisyou can still use the standard extensions.
50355714Skris
50455714Skris2. Printing and parsing extensions.
50555714Skris
50655714SkrisThe simplest way to print out extensions is via the standard X509 printing
50755714Skrisroutines: if you use the standard X509_print() function, the supported
50855714Skrisextensions will be printed out automatically.
50955714Skris
51055714SkrisThe following functions allow finer control over extension display:
51155714Skris
51255714Skrisint X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, int flag, int indent);
51355714Skrisint X509V3_EXT_print_fp(FILE *out, X509_EXTENSION *ext, int flag, int indent);
51455714Skris
51555714SkrisThese two functions print out an individual extension to a BIO or FILE pointer.
51655714SkrisCurrently the flag argument is unused and should be set to 0. The 'indent'
51755714Skrisargument is the number of spaces to indent each line.
51855714Skris
51955714Skrisvoid *X509V3_EXT_d2i(X509_EXTENSION *ext);
52055714Skris
52155714SkrisThis function parses an extension and returns its internal structure. The
52255714Skrisprecise structure you get back depends on the extension being parsed. If the
52355714Skrisextension if basicConstraints you will get back a pointer to a
52455714SkrisBASIC_CONSTRAINTS structure. Check out the source in crypto/x509v3 for more
52555714Skrisdetails about the structures returned. The returned structure should be freed
52655714Skrisafter use using the relevant free function, BASIC_CONSTRAINTS_free() for 
52755714Skrisexample.
52855714Skris
52968651Skrisvoid	*	X509_get_ext_d2i(X509 *x, int nid, int *crit, int *idx);
53068651Skrisvoid	*	X509_CRL_get_ext_d2i(X509_CRL *x, int nid, int *crit, int *idx);
53168651Skrisvoid	*	X509_REVOKED_get_ext_d2i(X509_REVOKED *x, int nid, int *crit, int *idx);
53268651Skrisvoid 	*	X509V3_get_d2i(STACK_OF(X509_EXTENSION) *x, int nid, int *crit, int *idx);
53368651Skris
53468651SkrisThese functions combine the operations of searching for extensions and
53568651Skrisparsing them. They search a certificate, a CRL a CRL entry or a stack
53668651Skrisof extensions respectively for extension whose NID is 'nid' and return
53768651Skristhe parsed result of NULL if an error occurred. For example:
53868651Skris
53968651SkrisBASIC_CONSTRAINTS *bs;
54068651Skrisbs = X509_get_ext_d2i(cert, NID_basic_constraints, NULL, NULL);
54168651Skris
54268651SkrisThis will search for the basicConstraints extension and either return
54368651Skrisit value or NULL. NULL can mean either the extension was not found, it
54468651Skrisoccurred more than once or it could not be parsed.
54568651Skris
54668651SkrisIf 'idx' is NULL then an extension is only parsed if it occurs precisely
54768651Skrisonce. This is standard behaviour because extensions normally cannot occur
54868651Skrismore than once. If however more than one extension of the same type can
54968651Skrisoccur it can be used to parse successive extensions for example:
55068651Skris
55168651Skrisint i;
55268651Skrisvoid *ext;
55368651Skris
55468651Skrisi = -1;
55568651Skrisfor(;;) {
55668651Skris	ext = X509_get_ext_d2i(x, nid, crit, &idx);
55768651Skris	if(ext == NULL) break;
55868651Skris	 /* Do something with ext */
55968651Skris}
56068651Skris
56168651SkrisIf 'crit' is not NULL and the extension was found then the int it points to
56268651Skrisis set to 1 for critical extensions and 0 for non critical. Therefore if the
56368651Skrisfunction returns NULL but 'crit' is set to 0 or 1 then the extension was
56468651Skrisfound but it could not be parsed.
56568651Skris
56668651SkrisThe int pointed to by crit will be set to -1 if the extension was not found
56768651Skrisand -2 if the extension occurred more than once (this will only happen if
56868651Skrisidx is NULL). In both cases the function will return NULL.
56968651Skris
57055714Skris3. Generating extensions.
57155714Skris
57255714SkrisAn extension will typically be generated from a configuration file, or some
57355714Skrisother kind of configuration database.
57455714Skris
57555714Skrisint X509V3_EXT_add_conf(LHASH *conf, X509V3_CTX *ctx, char *section,
57655714Skris								 X509 *cert);
57755714Skrisint X509V3_EXT_CRL_add_conf(LHASH *conf, X509V3_CTX *ctx, char *section,
57855714Skris								 X509_CRL *crl);
57955714Skris
58055714SkrisThese functions add all the extensions in the given section to the given
58155714Skriscertificate or CRL. They will normally be called just before the certificate
58255714Skrisor CRL is due to be signed. Both return 0 on error on non zero for success.
58355714Skris
58455714SkrisIn each case 'conf' is the LHASH pointer of the configuration file to use
58555714Skrisand 'section' is the section containing the extension details.
58655714Skris
58759191SkrisSee the 'context functions' section for a description of the ctx parameter.
58855714Skris
58955714Skris
59055714SkrisX509_EXTENSION *X509V3_EXT_conf(LHASH *conf, X509V3_CTX *ctx, char *name,
59155714Skris								 char *value);
59255714Skris
59355714SkrisThis function returns an extension based on a name and value pair, if the
59455714Skrispair will not need to access other sections in a config file (or there is no
59555714Skrisconfig file) then the 'conf' parameter can be set to NULL.
59655714Skris
59755714SkrisX509_EXTENSION *X509V3_EXT_conf_nid(char *conf, X509V3_CTX *ctx, int nid,
59855714Skris								 char *value);
59955714Skris
60055714SkrisThis function creates an extension in the same way as X509V3_EXT_conf() but
60155714Skristakes the NID of the extension rather than its name.
60255714Skris
60355714SkrisFor example to produce basicConstraints with the CA flag and a path length of
60455714Skris10:
60555714Skris
60659191Skrisx = X509V3_EXT_conf_nid(NULL, NULL, NID_basic_constraints,"CA:TRUE,pathlen:10");
60755714Skris
60855714Skris
60955714SkrisX509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc);
61055714Skris
61155714SkrisThis function sets up an extension from its internal structure. The ext_nid
61255714Skrisparameter is the NID of the extension and 'crit' is the critical flag.
61355714Skris
61455714Skris4. Context functions.
61555714Skris
61655714SkrisThe following functions set and manipulate an extension context structure.
61755714SkrisThe purpose of the extension context is to allow the extension code to
61855714Skrisaccess various structures relating to the "environment" of the certificate:
61955714Skrisfor example the issuers certificate or the certificate request.
62055714Skris
62155714Skrisvoid X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject,
62255714Skris                                 X509_REQ *req, X509_CRL *crl, int flags);
62355714Skris
62455714SkrisThis function sets up an X509V3_CTX structure with details of the certificate
62555714Skrisenvironment: specifically the issuers certificate, the subject certificate,
62655714Skristhe certificate request and the CRL: if these are not relevant or not
62755714Skrisavailable then they can be set to NULL. The 'flags' parameter should be set
62855714Skristo zero.
62955714Skris
63055714SkrisX509V3_set_ctx_test(ctx)
63155714Skris
63255714SkrisThis macro is used to set the 'ctx' structure to a 'test' value: this is to
63355714Skrisallow the syntax of an extension (or configuration file) to be tested.
63455714Skris
63555714SkrisX509V3_set_ctx_nodb(ctx)
63655714Skris
63755714SkrisThis macro is used when no configuration database is present.
63855714Skris
63955714Skrisvoid X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH *lhash);
64055714Skris
64155714SkrisThis function is used to set the configuration database when it is an LHASH
64255714Skrisstructure: typically a configuration file.
64355714Skris
64455714SkrisThe following functions are used to access a configuration database: they
64555714Skrisshould only be used in RAW extensions.
64655714Skris
64755714Skrischar * X509V3_get_string(X509V3_CTX *ctx, char *name, char *section);
64855714Skris
64955714SkrisThis function returns the value of the parameter "name" in "section", or NULL
65055714Skrisif there has been an error.
65155714Skris
65255714Skrisvoid X509V3_string_free(X509V3_CTX *ctx, char *str);
65355714Skris
65455714SkrisThis function frees up the string returned by the above function.
65555714Skris
65655714SkrisSTACK_OF(CONF_VALUE) * X509V3_get_section(X509V3_CTX *ctx, char *section);
65755714Skris
65855714SkrisThis function returns a whole section as a STACK_OF(CONF_VALUE) .
65955714Skris
66055714Skrisvoid X509V3_section_free( X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section);
66155714Skris
66255714SkrisThis function frees up the STACK returned by the above function.
66355714Skris
66455714SkrisNote: it is possible to use the extension code with a custom configuration
66555714Skrisdatabase. To do this the "db_meth" element of the X509V3_CTX structure should
66655714Skrisbe set to an X509V3_CTX_METHOD structure. This structure contains the following
66755714Skrisfunction pointers:
66855714Skris
66955714Skrischar * (*get_string)(void *db, char *section, char *value);
67055714SkrisSTACK_OF(CONF_VALUE) * (*get_section)(void *db, char *section);
67155714Skrisvoid (*free_string)(void *db, char * string);
67255714Skrisvoid (*free_section)(void *db, STACK_OF(CONF_VALUE) *section);
67355714Skris
67455714Skristhese will be called and passed the 'db' element in the X509V3_CTX structure
67555714Skristo access the database. If a given function is not implemented or not required
67655714Skrisit can be set to NULL.
67755714Skris
67855714Skris5. String helper functions.
67955714Skris
68055714SkrisThere are several "i2s" and "s2i" functions that convert structures to and
68155714Skrisfrom ASCII strings. In all the "i2s" cases the returned string should be
68255714Skrisfreed using Free() after use. Since some of these are part of other extension
68355714Skriscode they may take a 'method' parameter. Unless otherwise stated it can be
68455714Skrissafely set to NULL.
68555714Skris
68655714Skrischar *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, ASN1_OCTET_STRING *oct);
68755714Skris
68855714SkrisThis returns a hex string from an ASN1_OCTET_STRING.
68955714Skris
69055714Skrischar * i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, ASN1_INTEGER *aint);
69155714Skrischar * i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *meth, ASN1_ENUMERATED *aint);
69255714Skris
69355714SkrisThese return a string decimal representations of an ASN1_INTEGER and an
69455714SkrisASN1_ENUMERATED type, respectively.
69555714Skris
69655714SkrisASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
69755714Skris                                                   X509V3_CTX *ctx, char *str);
69855714Skris
69955714SkrisThis converts an ASCII hex string to an ASN1_OCTET_STRING.
70055714Skris
70155714SkrisASN1_INTEGER * s2i_ASN1_INTEGER(X509V3_EXT_METHOD *meth, char *value);
70255714Skris
70355714SkrisThis converts a decimal ASCII string into an ASN1_INTEGER.
70455714Skris
70555714Skris6. Multi valued extension helper functions.
70655714Skris
70755714SkrisThe following functions can be used to manipulate STACKs of CONF_VALUE
70855714Skrisstructures, as used by multi valued extensions.
70955714Skris
71055714Skrisint X509V3_get_value_bool(CONF_VALUE *value, int *asn1_bool);
71155714Skris
71255714SkrisThis function expects a boolean value in 'value' and sets 'asn1_bool' to
71355714Skrisit. That is it sets it to 0 for FALSE or 0xff for TRUE. The following
71455714Skrisstrings are acceptable: "TRUE", "true", "Y", "y", "YES", "yes", "FALSE"
71555714Skris"false", "N", "n", "NO" or "no".
71655714Skris
71755714Skrisint X509V3_get_value_int(CONF_VALUE *value, ASN1_INTEGER **aint);
71855714Skris
71955714SkrisThis accepts a decimal integer of arbitrary length and sets an ASN1_INTEGER.
72055714Skris
72155714Skrisint X509V3_add_value(const char *name, const char *value,
72255714Skris						STACK_OF(CONF_VALUE) **extlist);
72355714Skris
72455714SkrisThis simply adds a string name and value pair.
72555714Skris
72655714Skrisint X509V3_add_value_uchar(const char *name, const unsigned char *value,
72755714Skris                          			STACK_OF(CONF_VALUE) **extlist);
72855714Skris
72955714SkrisThe same as above but for an unsigned character value.
73055714Skris
73155714Skrisint X509V3_add_value_bool(const char *name, int asn1_bool,
73255714Skris						STACK_OF(CONF_VALUE) **extlist);
73355714Skris
73459191SkrisThis adds either "TRUE" or "FALSE" depending on the value of 'asn1_bool'
73555714Skris
73655714Skrisint X509V3_add_value_bool_nf(char *name, int asn1_bool,
73755714Skris						STACK_OF(CONF_VALUE) **extlist);
73855714Skris
73955714SkrisThis is the same as above except it adds nothing if asn1_bool is FALSE.
74055714Skris
74155714Skrisint X509V3_add_value_int(const char *name, ASN1_INTEGER *aint,
74255714Skris						STACK_OF(CONF_VALUE) **extlist);
74355714Skris
74455714SkrisThis function adds the value of the ASN1_INTEGER in decimal form.
74555714Skris
74655714Skris7. Other helper functions.
74755714Skris
74855714Skris<to be added>
74955714Skris
75055714SkrisADDING CUSTOM EXTENSIONS.
75155714Skris
75255714SkrisCurrently there are three types of supported extensions. 
75355714Skris
75455714SkrisString extensions are simple strings where the value is placed directly in the
75555714Skrisextensions, and the string returned is printed out.
75655714Skris
75755714SkrisMulti value extensions are passed a STACK_OF(CONF_VALUE) name and value pairs
75855714Skrisor return a STACK_OF(CONF_VALUE).
75955714Skris
76055714SkrisRaw extensions are just passed a BIO or a value and it is the extensions
76159191Skrisresponsibility to handle all the necessary printing.
76255714Skris
76355714SkrisThere are two ways to add an extension. One is simply as an alias to an already
76455714Skrisexisting extension. An alias is an extension that is identical in ASN1 structure
76555714Skristo an existing extension but has a different OBJECT IDENTIFIER. This can be
76655714Skrisdone by calling:
76755714Skris
76855714Skrisint X509V3_EXT_add_alias(int nid_to, int nid_from);
76955714Skris
77055714Skris'nid_to' is the new extension NID and 'nid_from' is the already existing
77155714Skrisextension NID.
77255714Skris
77355714SkrisAlternatively an extension can be written from scratch. This involves writing
77455714Skristhe ASN1 code to encode and decode the extension and functions to print out and
77555714Skrisgenerate the extension from strings. The relevant functions are then placed in
77655714Skrisa X509V3_EXT_METHOD structure and int X509V3_EXT_add(X509V3_EXT_METHOD *ext);
77755714Skriscalled.
77855714Skris
77955714SkrisThe X509V3_EXT_METHOD structure is described below.
78055714Skris
781160814Ssimonstruct {
78255714Skrisint ext_nid;
78355714Skrisint ext_flags;
78455714SkrisX509V3_EXT_NEW ext_new;
78555714SkrisX509V3_EXT_FREE ext_free;
78655714SkrisX509V3_EXT_D2I d2i;
78755714SkrisX509V3_EXT_I2D i2d;
78855714SkrisX509V3_EXT_I2S i2s;
78955714SkrisX509V3_EXT_S2I s2i;
79055714SkrisX509V3_EXT_I2V i2v;
79155714SkrisX509V3_EXT_V2I v2i;
79255714SkrisX509V3_EXT_R2I r2i;
79355714SkrisX509V3_EXT_I2R i2r;
79455714Skris
79555714Skrisvoid *usr_data;
79655714Skris};
79755714Skris
79855714SkrisThe elements have the following meanings.
79955714Skris
80055714Skrisext_nid		is the NID of the object identifier of the extension.
80155714Skris
80255714Skrisext_flags	is set of flags. Currently the only external flag is
80355714Skris		X509V3_EXT_MULTILINE which means a multi valued extensions
80455714Skris		should be printed on separate lines.
80555714Skris
80655714Skrisusr_data	is an extension specific pointer to any relevant data. This
80755714Skris		allows extensions to share identical code but have different
80855714Skris		uses. An example of this is the bit string extension which uses
80955714Skris		usr_data to contain a list of the bit names.
81055714Skris
81155714SkrisAll the remaining elements are function pointers.
81255714Skris
81355714Skrisext_new		is a pointer to a function that allocates memory for the
81455714Skris		extension ASN1 structure: for example ASN1_OBJECT_new().
81555714Skris
81655714Skrisext_free	is a pointer to a function that free up memory of the extension
81755714Skris		ASN1 structure: for example ASN1_OBJECT_free().
81855714Skris
81955714Skrisd2i		is the standard ASN1 function that converts a DER buffer into
82055714Skris		the internal ASN1 structure: for example d2i_ASN1_IA5STRING().
82155714Skris
82255714Skrisi2d		is the standard ASN1 function that converts the internal
82355714Skris		structure into the DER representation: for example
82455714Skris		i2d_ASN1_IA5STRING().
82555714Skris
82655714SkrisThe remaining functions are depend on the type of extension. One i2X and
82755714Skrisone X2i should be set and the rest set to NULL. The types set do not need
82855714Skristo match up, for example the extension could be set using the multi valued
82955714Skrisv2i function and printed out using the raw i2r.
83055714Skris
83155714SkrisAll functions have the X509V3_EXT_METHOD passed to them in the 'method'
83255714Skrisparameter and an X509V3_CTX structure. Extension code can then access the
83355714Skrisparent structure via the 'method' parameter to for example make use of the value
83455714Skrisof usr_data. If the code needs to use detail relating to the request it can
83555714Skrisuse the 'ctx' parameter.
83655714Skris
83755714SkrisA note should be given here about the 'flags' member of the 'ctx' parameter.
83855714SkrisIf it has the value CTX_TEST then the configuration syntax is being checked
83955714Skrisand no actual certificate or CRL exists. Therefore any attempt in the config
84055714Skrisfile to access such information should silently succeed. If the syntax is OK
84155714Skristhen it should simply return a (possibly bogus) extension, otherwise it
84255714Skrisshould return NULL.
84355714Skris
84455714Skrischar *i2s(struct v3_ext_method *method, void *ext);
84555714Skris
84655714SkrisThis function takes the internal structure in the ext parameter and returns
84755714Skrisa Malloc'ed string representing its value.
84855714Skris
84955714Skrisvoid * s2i(struct v3_ext_method *method, struct v3_ext_ctx *ctx, char *str);
85055714Skris
85155714SkrisThis function takes the string representation in the ext parameter and returns
85255714Skrisan allocated internal structure: ext_free() will be used on this internal
85355714Skrisstructure after use.
85455714Skris
85555714Skrisi2v and v2i handle a STACK_OF(CONF_VALUE):
85655714Skris
85755714Skristypedef struct
85855714Skris{
85955714Skris        char *section;
86055714Skris        char *name;
86155714Skris        char *value;
86255714Skris} CONF_VALUE;
86355714Skris
86455714SkrisOnly the name and value members are currently used.
86555714Skris
86655714SkrisSTACK_OF(CONF_VALUE) * i2v(struct v3_ext_method *method, void *ext);
86755714Skris
86855714SkrisThis function is passed the internal structure in the ext parameter and
86955714Skrisreturns a STACK of CONF_VALUE structures. The values of name, value,
87055714Skrissection and the structure itself will be freed up with Free after use.
87155714SkrisSeveral helper functions are available to add values to this STACK.
87255714Skris
87355714Skrisvoid * v2i(struct v3_ext_method *method, struct v3_ext_ctx *ctx,
87455714Skris						STACK_OF(CONF_VALUE) *values);
87555714Skris
87655714SkrisThis function takes a STACK_OF(CONF_VALUE) structures and should set the
87755714Skrisvalues of the external structure. This typically uses the name element to
87855714Skrisdetermine which structure element to set and the value element to determine
87955714Skriswhat to set it to. Several helper functions are available for this
88055714Skrispurpose (see above).
88155714Skris
88255714Skrisint i2r(struct v3_ext_method *method, void *ext, BIO *out, int indent);
88355714Skris
88455714SkrisThis function is passed the internal extension structure in the ext parameter
88555714Skrisand sends out a human readable version of the extension to out. The 'indent'
88659191Skrisparameter should be noted to determine the necessary amount of indentation
88755714Skrisneeded on the output.
88855714Skris
88955714Skrisvoid * r2i(struct v3_ext_method *method, struct v3_ext_ctx *ctx, char *str);
89055714Skris
89155714SkrisThis is just passed the string representation of the extension. It is intended
89255714Skristo be used for more elaborate extensions where the standard single and multi
89355714Skrisvalued options are insufficient. They can use the 'ctx' parameter to parse the
89455714Skrisconfiguration database themselves. See the context functions section for details
89555714Skrisof how to do this.
89655714Skris
89755714SkrisNote: although this type takes the same parameters as the "r2s" function there
89855714Skrisis a subtle difference. Whereas an "r2i" function can access a configuration
89955714Skrisdatabase an "s2i" function MUST NOT. This is so the internal code can safely
90055714Skrisassume that an "s2i" function will work without a configuration database.
90155714Skris
90255714Skris==============================================================================
90355714Skris                            PKCS#12 Library
90455714Skris==============================================================================
90555714Skris
90655714SkrisThis section describes the internal PKCS#12 support. There are very few
90755714Skrisdifferences between the old external library and the new internal code at
90855714Skrispresent. This may well change because the external library will not be updated
90955714Skrismuch in future.
91055714Skris
91155714SkrisThis version now includes a couple of high level PKCS#12 functions which
91255714Skrisgenerally "do the right thing" and should make it much easier to handle PKCS#12
91355714Skrisstructures.
91455714Skris
91555714SkrisHIGH LEVEL FUNCTIONS.
91655714Skris
91755714SkrisFor most applications you only need concern yourself with the high level
91855714Skrisfunctions. They can parse and generate simple PKCS#12 files as produced by
91955714SkrisNetscape and MSIE or indeed any compliant PKCS#12 file containing a single
92055714Skrisprivate key and certificate pair.
92155714Skris
92255714Skris1. Initialisation and cleanup.
92355714Skris
92455714SkrisNo special initialisation is needed for the internal PKCS#12 library: the 
92555714Skrisstandard SSLeay_add_all_algorithms() is sufficient. If you do not wish to
92655714Skrisadd all algorithms (you should at least add SHA1 though) then you can manually
92755714Skrisinitialise the PKCS#12 library with:
92855714Skris
92955714SkrisPKCS12_PBE_add();
93055714Skris
93155714SkrisThe memory allocated by the PKCS#12 library is freed up when EVP_cleanup() is
93255714Skriscalled or it can be directly freed with:
93355714Skris
93455714SkrisEVP_PBE_cleanup();
93555714Skris
93655714Skrisafter this call (or EVP_cleanup() ) no more PKCS#12 library functions should
93755714Skrisbe called.
93855714Skris
93955714Skris2. I/O functions.
94055714Skris
94155714Skrisi2d_PKCS12_bio(bp, p12)
94255714Skris
94355714SkrisThis writes out a PKCS12 structure to a BIO.
94455714Skris
94555714Skrisi2d_PKCS12_fp(fp, p12)
94655714Skris
94755714SkrisThis is the same but for a FILE pointer.
94855714Skris
94955714Skrisd2i_PKCS12_bio(bp, p12)
95055714Skris
95155714SkrisThis reads in a PKCS12 structure from a BIO.
95255714Skris
95355714Skrisd2i_PKCS12_fp(fp, p12)
95455714Skris
95555714SkrisThis is the same but for a FILE pointer.
95655714Skris
95759191Skris3. High level functions.
95855714Skris
95955714Skris3.1 Parsing with PKCS12_parse().
96055714Skris
96155714Skrisint PKCS12_parse(PKCS12 *p12, char *pass, EVP_PKEY **pkey, X509 **cert,
96255714Skris								 STACK **ca);
96355714Skris
96455714SkrisThis function takes a PKCS12 structure and a password (ASCII, null terminated)
96555714Skrisand returns the private key, the corresponding certificate and any CA
96655714Skriscertificates. If any of these is not required it can be passed as a NULL.
96755714SkrisThe 'ca' parameter should be either NULL, a pointer to NULL or a valid STACK
96855714Skrisstructure. Typically to read in a PKCS#12 file you might do:
96955714Skris
97055714Skrisp12 = d2i_PKCS12_fp(fp, NULL);
97155714SkrisPKCS12_parse(p12, password, &pkey, &cert, NULL); 	/* CAs not wanted */
97255714SkrisPKCS12_free(p12);
97355714Skris
97455714Skris3.2 PKCS#12 creation with PKCS12_create().
97555714Skris
97655714SkrisPKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert,
97755714Skris			STACK *ca, int nid_key, int nid_cert, int iter,
97855714Skris						 int mac_iter, int keytype);
97955714Skris
98055714SkrisThis function will create a PKCS12 structure from a given password, name,
98155714Skrisprivate key, certificate and optional STACK of CA certificates. The remaining
98255714Skris5 parameters can be set to 0 and sensible defaults will be used.
98355714Skris
98455714SkrisThe parameters nid_key and nid_cert are the key and certificate encryption
98555714Skrisalgorithms, iter is the encryption iteration count, mac_iter is the MAC
98655714Skrisiteration count and keytype is the type of private key. If you really want
98755714Skristo know what these last 5 parameters do then read the low level section.
98855714Skris
98955714SkrisTypically to create a PKCS#12 file the following could be used:
99055714Skris
99155714Skrisp12 = PKCS12_create(pass, "My Certificate", pkey, cert, NULL, 0,0,0,0,0);
99255714Skrisi2d_PKCS12_fp(fp, p12);
99355714SkrisPKCS12_free(p12);
99455714Skris
99559191Skris3.3 Changing a PKCS#12 structure password.
99659191Skris
99759191Skrisint PKCS12_newpass(PKCS12 *p12, char *oldpass, char *newpass);
99859191Skris
99959191SkrisThis changes the password of an already existing PKCS#12 structure. oldpass
100059191Skrisis the old password and newpass is the new one. An error occurs if the old
100159191Skrispassword is incorrect.
100259191Skris
100355714SkrisLOW LEVEL FUNCTIONS.
100455714Skris
100555714SkrisIn some cases the high level functions do not provide the necessary
100655714Skrisfunctionality. For example if you want to generate or parse more complex
100755714SkrisPKCS#12 files. The sample pkcs12 application uses the low level functions
100855714Skristo display details about the internal structure of a PKCS#12 file.
100955714Skris
101055714SkrisIntroduction.
101155714Skris
101255714SkrisThis is a brief description of how a PKCS#12 file is represented internally:
101355714Skrissome knowledge of PKCS#12 is assumed.
101455714Skris
101555714SkrisA PKCS#12 object contains several levels.
101655714Skris
101755714SkrisAt the lowest level is a PKCS12_SAFEBAG. This can contain a certificate, a
101855714SkrisCRL, a private key, encrypted or unencrypted, a set of safebags (so the
101955714Skrisstructure can be nested) or other secrets (not documented at present). 
102055714SkrisA safebag can optionally have attributes, currently these are: a unicode
102155714SkrisfriendlyName (a Unicode string) or a localKeyID (a string of bytes).
102255714Skris
102355714SkrisAt the next level is an authSafe which is a set of safebags collected into
102455714Skrisa PKCS#7 ContentInfo. This can be just plain data, or encrypted itself.
102555714Skris
102655714SkrisAt the top level is the PKCS12 structure itself which contains a set of
102755714SkrisauthSafes in an embedded PKCS#7 Contentinfo of type data. In addition it
102855714Skriscontains a MAC which is a kind of password protected digest to preserve
102955714Skrisintegrity (so any unencrypted stuff below can't be tampered with).
103055714Skris
103155714SkrisThe reason for these levels is so various objects can be encrypted in various
103255714Skrisways. For example you might want to encrypt a set of private keys with
103355714Skristriple-DES and then include the related certificates either unencrypted or
103455714Skriswith lower encryption. Yes it's the dreaded crypto laws at work again which
103555714Skrisallow strong encryption on private keys and only weak encryption on other
103655714Skrisstuff.
103755714Skris
103855714SkrisTo build one of these things you turn all certificates and keys into safebags
103955714Skris(with optional attributes). You collect the safebags into (one or more) STACKS
104055714Skrisand convert these into authsafes (encrypted or unencrypted).  The authsafes
104155714Skrisare collected into a STACK and added to a PKCS12 structure.  Finally a MAC
104255714Skrisinserted.
104355714Skris
104455714SkrisPulling one apart is basically the reverse process. The MAC is verified against
104555714Skristhe given password. The authsafes are extracted and each authsafe split into
104655714Skrisa set of safebags (possibly involving decryption). Finally the safebags are
104755714Skrisdecomposed into the original keys and certificates and the attributes used to
104855714Skrismatch up private key and certificate pairs.
104955714Skris
105055714SkrisAnyway here are the functions that do the dirty work.
105155714Skris
105255714Skris1. Construction functions.
105355714Skris
105455714Skris1.1 Safebag functions.
105555714Skris
105655714SkrisM_PKCS12_x5092certbag(x509)
105755714Skris
105855714SkrisThis macro takes an X509 structure and returns a certificate bag. The
105955714SkrisX509 structure can be freed up after calling this function.
106055714Skris
106155714SkrisM_PKCS12_x509crl2certbag(crl)
106255714Skris
106355714SkrisAs above but for a CRL.
106455714Skris
106555714SkrisPKCS8_PRIV_KEY_INFO *PKEY2PKCS8(EVP_PKEY *pkey)
106655714Skris
106755714SkrisTake a private key and convert it into a PKCS#8 PrivateKeyInfo structure.
106855714SkrisWorks for both RSA and DSA private keys. NB since the PKCS#8 PrivateKeyInfo
106955714Skrisstructure contains a private key data in plain text form it should be free'd
107055714Skrisup as soon as it has been encrypted for security reasons (freeing up the
107155714Skrisstructure zeros out the sensitive data). This can be done with
107255714SkrisPKCS8_PRIV_KEY_INFO_free().
107355714Skris
107455714SkrisPKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage)
107555714Skris
107655714SkrisThis sets the key type when a key is imported into MSIE or Outlook 98. Two
107755714Skrisvalues are currently supported: KEY_EX and KEY_SIG. KEY_EX is an exchange type
107855714Skriskey that can also be used for signing but its size is limited in the export
107955714Skrisversions of MS software to 512 bits, it is also the default. KEY_SIG is a
108055714Skrissigning only key but the keysize is unlimited (well 16K is supposed to work).
108155714SkrisIf you are using the domestic version of MSIE then you can ignore this because
108255714SkrisKEY_EX is not limited and can be used for both.
108355714Skris
108455714SkrisPKCS12_SAFEBAG *PKCS12_MAKE_KEYBAG(PKCS8_PRIV_KEY_INFO *p8)
108555714Skris
108655714SkrisConvert a PKCS8 private key structure into a keybag. This routine embeds the
108755714Skrisp8 structure in the keybag so p8 should not be freed up or used after it is
108855714Skriscalled.  The p8 structure will be freed up when the safebag is freed.
108955714Skris
109055714SkrisPKCS12_SAFEBAG *PKCS12_MAKE_SHKEYBAG(int pbe_nid, unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8)
109155714Skris
109255714SkrisConvert a PKCS#8 structure into a shrouded key bag (encrypted). p8 is not
109355714Skrisembedded and can be freed up after use.
109455714Skris
109555714Skrisint PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name, int namelen)
109655714Skrisint PKCS12_add_friendlyname(PKCS12_SAFEBAG *bag, unsigned char *name, int namelen)
109755714Skris
109855714SkrisAdd a local key id or a friendlyname to a safebag.
109955714Skris
110055714Skris1.2 Authsafe functions.
110155714Skris
110255714SkrisPKCS7 *PKCS12_pack_p7data(STACK *sk)
110355714SkrisTake a stack of safebags and convert them into an unencrypted authsafe. The
110455714Skrisstack of safebags can be freed up after calling this function.
110555714Skris
110655714SkrisPKCS7 *PKCS12_pack_p7encdata(int pbe_nid, unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int iter, STACK *bags);
110755714Skris
110855714SkrisAs above but encrypted.
110955714Skris
111055714Skris1.3 PKCS12 functions.
111155714Skris
111255714SkrisPKCS12 *PKCS12_init(int mode)
111355714Skris
111455714SkrisInitialise a PKCS12 structure (currently mode should be NID_pkcs7_data).
111555714Skris
111655714SkrisM_PKCS12_pack_authsafes(p12, safes)
111755714Skris
111855714SkrisThis macro takes a STACK of authsafes and adds them to a PKCS#12 structure.
111955714Skris
112055714Skrisint PKCS12_set_mac(PKCS12 *p12, unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int iter, EVP_MD *md_type);
112155714Skris
112255714SkrisAdd a MAC to a PKCS12 structure. If EVP_MD is NULL use SHA-1, the spec suggests
112355714Skristhat SHA-1 should be used.
112455714Skris
112555714Skris2. Extraction Functions.
112655714Skris
112755714Skris2.1 Safebags.
112855714Skris
112955714SkrisM_PKCS12_bag_type(bag)
113055714Skris
113155714SkrisReturn the type of "bag". Returns one of the following
113255714Skris
113355714SkrisNID_keyBag
113455714SkrisNID_pkcs8ShroudedKeyBag			7
113555714SkrisNID_certBag				8
113655714SkrisNID_crlBag				9
113755714SkrisNID_secretBag				10
113855714SkrisNID_safeContentsBag			11
113955714Skris
114055714SkrisM_PKCS12_cert_bag_type(bag)
114155714Skris
114255714SkrisReturns type of certificate bag, following are understood.
114355714Skris
114455714SkrisNID_x509Certificate			14
114555714SkrisNID_sdsiCertificate			15
114655714Skris
114755714SkrisM_PKCS12_crl_bag_type(bag)
114855714Skris
114955714SkrisReturns crl bag type, currently only NID_crlBag is recognised.
115055714Skris
115155714SkrisM_PKCS12_certbag2x509(bag)
115255714Skris
115355714SkrisThis macro extracts an X509 certificate from a certificate bag.
115455714Skris
115555714SkrisM_PKCS12_certbag2x509crl(bag)
115655714Skris
115755714SkrisAs above but for a CRL.
115855714Skris
115955714SkrisEVP_PKEY * PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8)
116055714Skris
116155714SkrisExtract a private key from a PKCS8 private key info structure.
116255714Skris
116355714SkrisM_PKCS12_decrypt_skey(bag, pass, passlen) 
116455714Skris
116555714SkrisDecrypt a shrouded key bag and return a PKCS8 private key info structure.
116655714SkrisWorks with both RSA and DSA keys
116755714Skris
116855714Skrischar *PKCS12_get_friendlyname(bag)
116955714Skris
117055714SkrisReturns the friendlyName of a bag if present or NULL if none. The returned
117155714Skrisstring is a null terminated ASCII string allocated with Malloc(). It should 
117255714Skristhus be freed up with Free() after use.
117355714Skris
117455714Skris2.2 AuthSafe functions.
117555714Skris
117655714SkrisM_PKCS12_unpack_p7data(p7)
117755714Skris
117855714SkrisExtract a STACK of safe bags from a PKCS#7 data ContentInfo.
117955714Skris
118055714Skris#define M_PKCS12_unpack_p7encdata(p7, pass, passlen)
118155714Skris
118255714SkrisAs above but for an encrypted content info.
118355714Skris
118455714Skris2.3 PKCS12 functions.
118555714Skris
118655714SkrisM_PKCS12_unpack_authsafes(p12)
118755714Skris
118855714SkrisExtract a STACK of authsafes from a PKCS12 structure.
118955714Skris
119055714SkrisM_PKCS12_mac_present(p12)
119155714Skris
119255714SkrisCheck to see if a MAC is present.
119355714Skris
119455714Skrisint PKCS12_verify_mac(PKCS12 *p12, unsigned char *pass, int passlen)
119555714Skris
119655714SkrisVerify a MAC on a PKCS12 structure. Returns an error if MAC not present.
119755714Skris
119855714Skris
119955714SkrisNotes.
120055714Skris
120155714Skris1. All the function return 0 or NULL on error.
120255714Skris2. Encryption based functions take a common set of parameters. These are
120355714Skrisdescribed below.
120455714Skris
120555714Skrispass, passlen
120655714SkrisASCII password and length. The password on the MAC is called the "integrity
120755714Skrispassword" the encryption password is called the "privacy password" in the
120855714SkrisPKCS#12 documentation. The passwords do not have to be the same. If -1 is
120955714Skrispassed for the length it is worked out by the function itself (currently
121055714Skristhis is sometimes done whatever is passed as the length but that may change).
121155714Skris
121255714Skrissalt, saltlen
121355714SkrisA 'salt' if salt is NULL a random salt is used. If saltlen is also zero a
121455714Skrisdefault length is used.
121555714Skris
121655714Skrisiter
121755714SkrisIteration count. This is a measure of how many times an internal function is
121855714Skriscalled to encrypt the data. The larger this value is the longer it takes, it
121955714Skrismakes dictionary attacks on passwords harder. NOTE: Some implementations do
122055714Skrisnot support an iteration count on the MAC. If the password for the MAC and
122155714Skrisencryption is the same then there is no point in having a high iteration
122255714Skriscount for encryption if the MAC has no count. The MAC could be attacked
122355714Skrisand the password used for the main decryption.
122455714Skris
122555714Skrispbe_nid
122655714SkrisThis is the NID of the password based encryption method used. The following are
122755714Skrissupported.
122855714SkrisNID_pbe_WithSHA1And128BitRC4
122955714SkrisNID_pbe_WithSHA1And40BitRC4
123055714SkrisNID_pbe_WithSHA1And3_Key_TripleDES_CBC
123155714SkrisNID_pbe_WithSHA1And2_Key_TripleDES_CBC
123255714SkrisNID_pbe_WithSHA1And128BitRC2_CBC
123355714SkrisNID_pbe_WithSHA1And40BitRC2_CBC
123455714Skris
123555714SkrisWhich you use depends on the implementation you are exporting to. "Export
123655714Skrisgrade" (i.e. cryptographically challenged) products cannot support all
123755714Skrisalgorithms. Typically you may be able to use any encryption on shrouded key
123855714Skrisbags but they must then be placed in an unencrypted authsafe. Other authsafes
123955714Skrismay only support 40bit encryption. Of course if you are using SSLeay
124055714Skristhroughout you can strongly encrypt everything and have high iteration counts
124155714Skrison everything.
124255714Skris
124355714Skris3. For decryption routines only the password and length are needed.
124455714Skris
124555714Skris4. Unlike the external version the nid's of objects are the values of the
124655714Skrisconstants: that is NID_certBag is the real nid, therefore there is no 
124755714SkrisPKCS12_obj_offset() function.  Note the object constants are not the same as
124855714Skristhose of the external version. If you use these constants then you will need
124955714Skristo recompile your code.
125055714Skris
125155714Skris5. With the exception of PKCS12_MAKE_KEYBAG(), after calling any function or 
125255714Skrismacro of the form PKCS12_MAKE_SOMETHING(other) the "other" structure can be
125355714Skrisreused or freed up safely.
125455714Skris
1255