1\input texinfo
2@setfilename ksba.info
3@settitle The KSBA Reference Manual
4
5@dircategory GNU libraries
6@direntry
7* libksba: (ksba).              An X.509 Library.
8@end direntry
9
10@include version.texi
11
12@c Unify some of the indices.
13@syncodeindex tp fn
14@syncodeindex pg fn
15
16@macro mycopyrightnotice
17Copyright @copyright{} 2002, 2003, 2004 g10 Code GmbH
18@end macro
19@macro mypermissionnotice
20Permission is granted to copy, distribute and/or modify this document
21under the terms of the GNU General Public License as published by the
22Free Software Foundation; either version 3 of the License, or (at your
23option) any later version. The text of the license can be found in the
24section entitled ``Copying''.
25@end macro
26
27
28
29@ifinfo
30This file documents the @acronym{KSBA} library to access X.509 and CMS data
31structures.
32
33This is edition @value{EDITION}, last updated @value{UPDATED}, of
34@cite{The KSBA Reference Manual}, for Version @value{VERSION}.
35@sp 1
36@mycopyrightnotice{}
37@sp 1
38@mypermissionnotice{}
39@end ifinfo
40
41
42@iftex
43@shorttitlepage The `KSBA' Reference Manual
44@titlepage
45@center @titlefont{The `KSBA'}
46@sp 1
47@center @titlefont{Reference Manual}
48@sp 6
49@center Edition @value{EDITION}
50@sp 1
51@center last updated @value{UPDATED}
52@sp 1
53@center for version @value{VERSION}
54@sp 1
55@author by Werner Koch, g10 Code GmbH
56@email{wk@@gnupg.org}
57@page
58@vskip 0pt plus 1filll
59@mycopyrightnotice{}
60@sp 1
61@mypermissionnotice{}
62@end titlepage
63@summarycontents
64@contents
65@page
66@end iftex
67
68
69@ifnottex
70@node Top
71@top Main Menu
72This is edition @value{EDITION}, last updated @value{UPDATED}, of
73@cite{The KSBA Reference Manual}, for Version
74@value{VERSION} of the @acronym{KSBA} library.
75@sp 1
76@mycopyrightnotice{}
77@sp 1
78@mypermissionnotice{}
79@sp 1
80@end ifnottex
81
82@menu
83* Introduction::                How to use this manual.
84* Preparation::                 What you should do before using the library.
85* Certificate Handling::        How to work with X.509 certificates.
86* CMS::                         How to work with CMS (PKCS#7) messages.
87* CRLs::                        How to work with Certificate Revocation Lists.
88* PKCS10::                      How to request certificates.
89* Utilities::                   Various utility functions.
90* Error Handling::              Error numbers and their meanings.
91
92Appendices
93
94* Component Labels::            Labels used in string representations.
95* Copying::                     The GNU General Public License says how you
96                                can copy and share this manual.
97
98Indices
99
100* Concept Index::               Index of concepts and programs.
101* Function and Data Index::     Index of functions, variables and data types.
102
103@detailmenu
104 --- The Detailed Node Listing ---
105
106Introduction
107
108* Getting Started::
109* Features::
110* Overview::
111
112Preparation
113
114* Header::
115* Building the source::
116
117Certificate Handling
118
119* Creating certificates::       How to create a certificate object.
120* Retrieving attributes::       How to get the attributes of a certificate.
121* Setting attributes::          How to set certificates attributes.
122* User data::                   How to associate other data with a certificate.
123
124Mastering the Cryptographic Message Syntax
125
126* CMS Basics::
127* CMS Parser::
128
129@end detailmenu
130@end menu
131
132@node Introduction
133@chapter Introduction
134@acronym{KSBA} is a library to make the task of working with X.509
135certificates, CMS data and related data more easy.
136
137@menu
138* Getting Started::
139* Features::
140* Overview::
141@end menu
142
143@node Getting Started
144@section Getting Started
145
146This manual documents the `KSBA' library programming interface.  All
147functions and data types provided by the library are explained.
148
149The reader is assumed to possess basic knowledge about the implemented
150protocols.
151
152This manual can be used in several ways.  If read from the beginning
153to the end, it gives a good introduction into the library and how it
154can be used in an application.  Forward references are included where
155necessary.  Later on, the manual can be used as a reference manual to
156get just the information needed about any particular interface of the
157library.  Experienced programmers might want to start looking at the
158examples at the end of the manual, and then only read up those parts
159of the interface which are unclear.
160
161
162@node Features
163@section Features
164
165`KSBA' has a couple of advantages over other libraries doing a similar job,
166and over open coding the protocols in your application directly.
167
168@table @asis
169@item It's Free Software
170Anybody can use, modify, and redistribute it under the terms of the GNU
171General Public License (@pxref{Copying}).
172
173@item It hides the low level stuff
174`KSBA' a high level interface to the implemented protocols and presents
175the data in a consistent way.  There is no more need to worry about all
176the nasty details of the protocols.  The API gives the C programmer a
177more usual way of interacting with the data.
178
179@item It copes with the version details
180X.509 protocols tend to have many different versions and dialects.
181Applications must usually cope with all of this and it has to be coded
182over and over again.  `KSBA' hides this by providing just one API which
183does the Right Thing.  Support for new versions and features of the
184protocols will be added over time.
185@end table
186
187
188@node Overview
189@section Overview
190
191@c [Needs more stuff]
192
193The `KSBA' library is thread-safe as long as objects described by one
194context are only used by one thread at a time.  No initialization is
195required.
196
197
198@node Preparation
199@chapter Preparation
200
201To use `KSBA', you have to perform some changes to your sources and the
202build system.  The necessary changes are small and explained in the
203following sections.  At the end of this chapter, it is described how the
204library is initialized, and how the requirements of the library are
205verified.
206
207@menu
208* Header::
209* Version Check::
210* Building the source::
211@end menu
212
213
214@node Header
215@section Header
216
217All interfaces (data types and functions) of the library are defined in
218the header file @file{ksba.h}.  You must include this in all programs
219using the library, either directly or through some other header file,
220like this:
221
222@smallexample
223#include <ksba.h>
224@end smallexample
225
226The name space of `KSBA' is @code{ksba_*} for function names,
227@code{ksba*} for data types and @code{KSBA_*} for other symbols.  In
228addition the same name prefixes with one prepended underscore are
229reserved for internal use and should never be used by an application.
230
231@node Version Check
232@section Version Check
233
234It is often desirable to check that the version of `KSBA' used is indeed
235one which fits all requirements.  Even with binary compatibility, new
236features may have been introduced but through peculiarities of the
237runtime linker an old version gets actually used.  So you better check
238that the version is as expected right after program startup.
239
240@deftypefun {const char *} ksba_check_version (@w{const char *@var{req_version}})
241
242Check that the the version of the library is at minimum the one given as
243a string in @var{req_version} and return the actual version string of
244the library; return @code{NULL} if the condition is not met.  If
245@code{NULL} is passed to this function, no check is done and only the
246version string is returned.  It is a pretty good idea to run this
247function as soon as possible, because it may also initializes some
248subsystems.  In a multi-threaded environment if should be called before
249any more threads are created.
250@end deftypefun
251
252@node Building the source
253@section Building the source
254
255If you want to compile a source file including the @file{ksba.h} header
256file, you must make sure that the compiler can find it in the directory
257hierarchy.  This is accomplished by adding the path to the directory in
258which the header file is located to the compiler's include file search
259path (via the @option{-I} option).
260
261However, the path to the include file is determined at the time the
262source is configured.  To solve this problem, `KSBA' ships with a small
263helper program @command{ksba-config} that knows about the path to the
264include file and other configuration options.  The options that need to
265be added to the compiler invocation at compile time are output by the
266@option{--cflags} option of @command{ksba-config}.  The following
267example shows how it can be used at the command line:
268
269@example
270gcc -c foo.c `ksba-config --cflags`
271@end example
272
273Adding the output of @samp{ksba-config --cflags} to the compiler's
274command line will ensure that the compiler can find the @file{ksba.h}
275header file.
276
277A similar problem occurs when linking the program with the library.
278Again, the compiler has to find the library files.  For this to work,
279the path to the library files has to be added to the library search path
280(via the @option{-L} option).  For this, the option @option{--libs} of
281@command{ksba-config} can be used.  For convenience, this option also
282outputs all other options that are required to link the program with the
283`KSBA' libraries (in particular, the @samp{-lksba} option).  The
284example shows how to link @file{foo.o} with the `KSBA' libraries to a
285program @command{foo}.
286
287@example
288gcc -o foo foo.o `ksba-config --libs`
289@end example
290
291Of course you can also combine both examples to a single command by
292specifying both options to @command{ksba-config}:
293
294@example
295gcc -o foo foo.c `ksba-config --cflags --libs`
296@end example
297
298
299@node Certificate Handling
300@chapter How to work with X.509 certificates.
301
302One of the most complex data formats are the X.509 certificates.
303@acronym{KSBA} provides an easy to use interface to handle them.
304
305@deftp {Data type} ksba_cert_t
306The @code{ksba_cert_t} type is a handle for an X.509 certificate.
307@end deftp
308
309@deftp {Data type} ksba_sexp_t
310The @code{ksba_sexp_t} type describes a canonically encoded S-expression
311stored in a memory buffer.  It is alias for @code{unsigned char *}.
312Note that a length argument is not required because the length of such
313an S-expression is intrinsically available.
314@end deftp
315
316@menu
317* Creating certificates::       How to create a certificate object.
318* Retrieving attributes::       How to get the attributes of a certificate.
319* Setting attributes::          How to set certificates attributes.
320* User data::                   How to associate other data with a certificate.
321@end menu
322
323
324@node Creating certificates
325@section How to create a certificate object
326
327This section explains how to create a certificate object, initialize it,
328copy it and eventually destroy it.
329
330@deftypefun ksba_cert_t ksba_cert_new (void)
331The function @code{ksba_cert_new} creates a new certificate object and
332returns a handle for it.  The certificate object has initially one
333reference.
334
335The only reason why this function may fail is an out-of-memory condition in
336which case @code{NULL} is returned.  You might then get the actual error
337code using @samp{gpg_error_from_errno (errno)}.
338@end deftypefun
339
340@deftypefun void ksba_cert_ref (@w{ksba_cert_t @var{cert}})
341The function @code{ksba_cert_ref} bumps the reference counter of the
342certificate object up by one.  Thus an extra @code{ksba_cert_release} is
343required to actually release the memory used for the object.
344@end deftypefun
345
346@deftypefun void ksba_cert_release (@w{ksba_cert_t @var{cert}})
347The function @code{ksba_cert_release} reduces the number of references
348to the certificate object with the handle @var{cert}.  If this was the
349last reference, it will also destroy the object and releases all
350associated resources.  It is okay to pass @code{NULL} to the function
351in which case nothing happens.
352@end deftypefun
353
354@deftypefun gpg_error_t ksba_cert_read_der (@w{ksba_cert_t @var{cert}}, @w{ksba_reader_t @var{reader}})
355
356Read the next certificate from the @var{reader} object and store it in
357the certificate object @var{cert} for future access.  The certificate is
358parsed and rejected if it has any syntactical or semantical error
359(i.e. does not match the @acronym{ASN.1} description).
360
361The function returns @code{0} if the operation was successfully
362performed.  An error code is returned on failure.
363@end deftypefun
364
365@deftypefun gpg_error_t ksba_cert_init_from_mem (@w{ksba_cert_t @var{cert}}, @w{const void *@var{buffer}}, @w{size_t @var{length}})
366
367Parse the @var{buffer} which should contain a @acronym{DER} encoded
368certificate of @var{length} and initialize the certificate object
369@var{cert} with it.  This function is intended as a convenience
370function to be used when a certificate is already available in a
371internal memory buffer.  This avoids the extra code needed to setup the
372reader object.  Note that @var{cert} must be a valid certificate object.
373
374The function returns @code{0} if the operation was successfully performed.
375An error code is returned on failure.
376@end deftypefun
377
378@node Retrieving attributes
379@section How to get the attributes of a certificate
380
381The functions in this section allow accessing the attributes of a
382certificate in a well defined manner.  An error will be returned if the
383certificate object has not yet been initialized by means of
384@code{ksba_cert_read_der} or @code{ksba_cert_init_from_mem}.
385
386@deftypefun {const unsigned char *} ksba_cert_get_image (@w{ksba_cert_t @var{cert}}, @w{size_t *@var{r_length}})
387
388This function returns a pointer to the @acronym{DER} encoded buffer with
389the raw certificate.  The length of that buffer gets stored at
390@var{r_length}.  This function is useful to export or store the raw
391certificate.
392
393The function returns @code{NULL} on error or a pointer to a buffer with
394the raw certificate data.  That pointer is only valid as long as the
395certificate object @var{cert} is valid and has not been reinitialized.
396@end deftypefun
397
398@deftypefun gpg_error_t ksba_cert_hash (@w{ksba_cert_t @var{cert}}, @w{int @var{what}}, @w{void (*@var{hasher})(void *, const void *, size_t length)}, @w{void *@var{hasher_arg}})
399
400This function feeds the data which is expected to be hashed into the
401supplied function @var{hasher}, where the first argument passed is
402@var{hasher_arg}, the second the pointer to the data to be hashed and
403the third the length of this data.
404
405The function returns @code{0} on success or an error code when something
406goes wrong.  The @var{hasher} function is not expected to return an
407error; instead the caller should setup that function in a way to convey
408encountered errors by means of the @var{hasher_arg}.  Note that a hash
409function is in general not expected to yield errors anyway.
410@end deftypefun
411
412
413@deftypefun {const char *} ksba_cert_get_digest_algo (@w{ksba_cert_t @var{cert}})
414
415Figure out the the digest algorithm used for the signature and return
416its @acronym{OID} in dotted decimal format.  This function is most
417likely used to setup the hash context before calling
418@code{ksba_cert_hash}.  For some certificate types the returned OID
419has a special meaning:
420
421@table @code
422@item 1.2.840.113549.1.1.10
423This indicates the RSASSA-PSS algorithm.  The digest algorithm needs
424to be extracted from the S-expression returned by
425@code{ksba_cert_get_sig_val}.
426
427@item 1.3.101.112
428This is the Ed25519 algorithm which does not use a separate digest
429algorithm.  See RFC-8410.
430
431@item 1.3.101.113
432This is the Ed448 algorithm which does not use a separate digest
433algorithm.  See RFC-8410.
434
435@end table
436
437The function returns @code{NULL} for an error; on success a constant
438string with the @acronym{OID} is returned.  This string is valid as long
439the certificate object is valid.
440@end deftypefun
441
442@deftypefun ksba_sexp_t ksba_cert_get_serial (@w{ksba_cert_t @var{cert}})
443
444The function returns the serial number of the certificate @var{cert}.
445The serial number is an integer returned as an canonical encoded
446S-expression with just one element.  The caller must free the returned
447value.  The value @code{NULL} is returned in case of error.
448@end deftypefun
449
450@deftypefun {char *} ksba_cert_get_issuer (@w{ksba_cert_t @var{cert}, int @var{idx}})
451
452With @var{idx} given as @code{0}, this function returns the
453Distinguished Name (@acronym{DN}) of the certificate issuer; this
454usually is the name of a certification authority (@acronym{CA}).  The
455format of the returned string is in accordance with RFC-2253.
456@code{NULL} is returned if the @acronym{DN} is not available; This is a
457severe error and actually should have been caught by the certificate
458reading function.
459
460With @var{idx} greater than zero, the function may be used to enumerate
461alternate issuer names.  The function returns @code{NULL} when there are
462no more alternate names. Only alternate names recognized by
463@code{libksba} are returned, others are simply skipped.  The format of
464the returned name is either a RFC-2253 formated string which can be
465detected by checking whether the first character is a letter or digit.
466RFC-822 conformant email addresses are returned enclosed in angle
467brackets; the opening angle bracket should be used to detect this.
468Other formats are returned as an S-Expression in canonical format, so a
469opening parenthesis should be used to detect this encoding. The name may
470include binary null characters, thus strlen may return a length shorter
471than actually used.  The real length is implicitly given by the structure
472of the S-expression, an extra null is appended for safety reasons.
473
474The caller must free the returned string using @code{ksba_free} or
475whatever function has been registered as a replacement.
476@end deftypefun
477
478@deftypefun {char *} ksba_cert_get_subject (@w{ksba_cert_t @var{cert}, int @var{idx}})
479
480With @var{idx} given as @code{0}, this function returns the
481Distinguished Name (@acronym{DN}) of the certificate's subject.  The
482format of the returned string is in accordance with RFC-2253.
483@code{NULL} is returned if the @acronym{DN} is not available.
484
485With @var{idx} greater than zero, the function may be used to enumerate
486alternate subject names.  The function returns @code{NULL} when there
487are no more alternate names. Only alternate names recognized by
488@code{libksba} are returned, others are simply skipped.  The format of
489the returned name is either a RFC-2253 formated string which can be
490detected by checking whether the first character is a letter or digit.
491RFC-2822 conform email addresses are returned enclosed in angle
492brackets; the opening angle bracket should be used to detect this.
493Other formats are returned as an S-Expression in canonical format, so a
494opening parenthesis should be used to detect this encoding, the name may
495include binary null characters, thus strlen may return a length shorter
496than actually used.  The real length is implicitly given by the structure
497of the S-expression, an extra null is appended for safety reasons.
498
499The caller must free the returned string using @code{ksba_free} or
500whatever function has been registered as a replacement.
501@end deftypefun
502
503
504@deftp {Data type} ksba_isotime_t
505Due to problems with the C data type @code{time_t}, which will overflow
506on most 32 bit machines in the year 2038, it was not advisable to use
507this type for referencing times stored in certificates.  Instead, you
508should use the @code{ksba_isotime_t} type, which can represent any time
509since the year 0.
510
511It is implemented as a buffer of 16 bytes and may be handled like a
512standard string.  It should be initialized to zero (i.e. the first
513byte needs to be 0x00) if it does not hold a valid date.  Date values
514themselves are stored in ISO format and assumed to be referenced from
515UTC.  The string with the date value is always guaranteed to be of
516length 15 and having a format like: @samp{"19610711T172059"}.  Note
517that the `T' is required by ISO rules.
518
519A simple assignment of these data types is not a good idea.  You may
520use @code{strcpy} or better a specialized function like:
521
522@example
523void
524copy_time (ksba_isotime_t d, const ksba_isotime_t s)
525@{
526  if (!*s)
527    memset (d, 0, 16);
528  else
529    strcpy (d, s);
530@}
531@end example
532
533For reasons of documentation a special function should also be used to
534compare such times:
535
536@example
537int
538cmp_time (const ksba_isotime_t a, const ksba_isotime_t b)
539@{
540  return strcmp (a, b);
541@}
542@end example
543@end deftp
544
545@deftypefun gpg_error_t ksba_cert_get_validity (@w{ksba_cert_t @var{cert}, int @var{what}, ksba_isotime_t @var{timebuf}})
546
547Return the validity dates from the certificate.  If no value is
548available an empty date object (i.e. a @code{strlen} will be
549stored at @var{timebuf}, otherwise it will receive the date. On failure
550an error code is returned.
551
552To return the `notBefore' date, the value @code{0} must be supplied for
553@var{what}; @code{1} yields the `notAfter' value.
554@end deftypefun
555
556@deftypefun ksba_sexp_t ksba_cert_get_public_key (@w{ksba_cert_t @var{cert}})
557
558@c  {{{{ CONTINUE HERE }}}}}}
559
560@c !FIXME!
561[This needs to get written - for now please see libksba/src/cert.c]
562
563@end deftypefun
564
565@deftypefun ksba_sexp_t ksba_cert_get_sig_val (ksba_cert_t @var{cert})
566
567@c !FIXME!
568[This needs to get written - for now please see libksba/src/cert.c]
569@end deftypefun
570
571@deftypefun gpg_error_t ksba_cert_get_extension (@w{ksba_cert_t @var{cert}, int @var{idx}, char const **@var{r_oid}, int *@var{r_crit}, size_t *@var{r_deroff}, size_t *@var{r_derlen}})
572
573@c !FIXME!
574[This needs to get written - for now please see libksba/src/cert.c]
575@end deftypefun
576
577@deftypefun gpg_error_t ksba_cert_is_ca (@w{ksba_cert_t @var{cert}, int *@var{r_ca}, int *@var{r_pathlen}})
578
579Return information on the basicConstraint (2.5.19.19) of CERT.  R_CA
580receives true if this is a CA and only in that case R_PATHLEN is set to
581the maximum certification path length or -1 if there is no such
582limitation
583
584@end deftypefun
585
586@deftypefun gpg_error_t ksba_cert_get_key_usage (@w{ksba_cert_t @var{cert}, unsigned int *@var{r_flags}})
587
588Get the key usage flags. The function returns @code{GPG_ERR_NO_DATA} if no
589key usage is specified. The usage flags are as shown in RFC3280, section
5904.2.1.3. The key usage flags are represented by a bitmask, and you can
591test each bit using symbolic constants, which tells you if that usage
592is set on the certificate. The constants are
593
594@table @code
595@item KSBA_KEYUSAGE_DIGITAL_SIGNATURE
596Usable for digitalSignature.
597@item KSBA_KEYUSAGE_NON_REPUDIATION
598Usable for nonRepudiation.
599@item KSBA_KEYUSAGE_KEY_ENCIPHERMENT
600Usable for keyEncipherment.
601@item KSBA_KEYUSAGE_DATA_ENCIPHERMENT
602Usable for dataEncipherment.
603@item KSBA_KEYUSAGE_KEY_AGREEMENT
604Usable for for keyAgreement.
605@item KSBA_KEYUSAGE_KEY_CERT_SIGN
606Usable for keyCertSign.
607@item KSBA_KEYUSAGE_CRL_SIGN
608Usable for cRLSign.
609@item KSBA_KEYUSAGE_ENCIPHER_ONLY
610Usable for encipherOnly.
611@item KSBA_KEYUSAGE_DECIPHER_ONLY
612Usable for decipherOnly.
613@end table
614
615These are the basic constraints on usage of a certificate. If you need
616to get additional constraints, see @code{ksba_cert_get_ext_key_usages}.
617@end deftypefun
618
619@deftypefun gpg_error_t ksba_cert_get_ext_key_usages (@w{ksba_cert_t @var{cert}, char **@var{result}})
620
621Return a string containing the extended usages for the certificate,
622delimited by linefeeds.
623@end deftypefun
624
625
626@deftypefun gpg_error_t ksba_cert_get_cert_policies (@w{ksba_cert_t @var{cert}, char **@var{r_policies}})
627
628Return a string with the certificatePolicies delimited by linefeeds.
629The return values may be extended to carry more information per line, so
630the caller should only use the first white-space delimited token per
631line.  The function returns @code{GPG_ERR_NO_DATA} when this extension
632is not used.  Caller must free the returned value.
633
634@end deftypefun
635
636
637@deftypefun gpg_error_t ksba_cert_get_crl_dist_point (@w{ksba_cert_t @var{cert}, int @var{idx}, ksba_name_t *@var{r_distpoint}, ksba_name_t *@var{r_issuer}, unsigned int *@var{r_reason}})
638
639Return the CRLDistPoints given in the certificate extension of
640certificate @var{cert}.  @var{idx} should be iterated starting from 0
641until the function returns @code{GPG_ERR_EOF}.  @var{r_distpoint} returns a
642ksba_name_t object with the distribution point name(s); the return value
643may be @code{NULL} to indicate that this name is not available.
644@var{r_issuer} returns the CRL issuer; if the returned value is
645@code{NULL} the caller should assume that the CRL issuer is the same as
646the certificate issuer.  @var{r_reason} returns the reason for the CRL.
647This is a bit encoded value with no bit set if no reason has been
648specified in the certificate.
649
650The caller may pass @code{NULL} to any of the pointer arguments if he is
651not interested in this value.  The return values for @var{r_distpoint}
652and @var{r_issuer} must be released by the caller using
653@code{ksba_name_release}.
654@end deftypefun
655
656
657@deftypefun gpg_error_t ksba_cert_get_subj_key_id (@w{ksba_cert_t @var{cert}, int *@var{r_crit}, ksba_sexp_t *@var{r_keyid}})
658
659Return the subjectKeyIdentifier extension as a simple allocated
660S-expression at the address of @var{r_keyid}. 0 is returned on success,
661@code{GPG_ERR_NO_DATA} if no such extension is available or any other
662error code.  If @var{r_crit} is not passed as @code{NULL}, the critical flag of
663this is extension is stored at this address.
664@end deftypefun
665
666
667@deftypefun gpg_error_t ksba_cert_get_auth_key_id (@w{ksba_cert_t @var{cert}, ksba_sexp_t *@var{r_keyid}, ksba_name_t *@var{r_name}, ksba_sexp_t *@var{r_serial}})
668
669Return the authorityKeyIdentifier in @var{r_name} and @var{r_serial} or
670in @var{r_keyid}.  @code{GPG_ERR_NO_DATA} is returned if no
671authorityKeyIdentifier has been found.  This error code is also returned
672if @var{r_keyid} has been given as NULL and only an
673authorityKeyIdentifier with the keyIdentifier method is available.
674@end deftypefun
675
676
677@deftypefun gpg_error_t ksba_cert_get_authority_info_access (@w{ksba_cert_t @var{cert}, int @var{idx}, char **@var{r_method}, ksba_name_t *@var{r_location}})
678
679Return the authorityInfoAccess attributes. @var{idx} should be
680iterated starting from 0 until this function returns
681@code{GPG_ERR_EOF}.  @var{r_method} returns an allocated string with
682the OID of one item and @var{r_location} returns the GeneralName for
683that OID.  The returned values for @var{r_method} and @var{r_location}
684must be released by the caller unless the function returned an error;
685the function will however make sure that @var{r_method} and
686@var{r_location} will point to @code{NULL} if the function returns an
687error.
688
689See RFC-2459, section 4.2.2.1 for the definition of this attribute.
690@end deftypefun
691
692@deftypefun gpg_error_t ksba_cert_get_subject_info_access (@w{ksba_cert_t @var{cert}, int @var{idx}, char **@var{r_method}, ksba_name_t *@var{r_location}})
693
694Return the subjectInfoAccess attributes. @var{idx} should be
695iterated starting from 0 until this function returns
696@code{GPG_ERR_EOF}.  @var{r_method} returns an allocated string with
697the OID of one item and @var{r_location} returns the GeneralName for
698that OID.  The returned values for @var{r_method} and @var{r_location}
699must be released by the caller unless the function returned an error;
700the function will however make sure that @var{r_method} and
701@var{r_location} will point to @code{NULL} if the function returns an
702error.
703
704See RFC-2459, section 4.2.2.2 for the definition of this attribute.
705@end deftypefun
706
707
708@node Setting attributes
709@section How to set certificate attributes
710
711[This needs to be written.  For example code see newpg/sm/sign.c]
712
713@node User data
714@section How to associate other data with a certificate.
715
716Certificate objects play a central role in many applications and often
717it is desirable to associate other data with the certificate to avoid
718wrapping the certificate object into an own object.  `KSBA' provides a
719mechanism for this by means of two functions:
720
721@deftypefun gpg_error_t ksba_cert_set_user_data (@w{ksba_cert_t @var{cert}, const char *@var{key}, const void *@var{data}, size_t @var{datalen}})
722
723
724Stores arbitrary data along with a certificate.  The data is expected in
725the buffer @var{data} of length @var{datalen}. It will be stored under
726the string @var{key}.  If data is already stored under this key it will
727be replaced by the new data. Using @code{NULL} for @var{data} will
728effectively delete the data.
729
730On error (i.e. out of memory) an already existing data object
731stored under @var{key} may get deleted.
732
733@strong{Caution:} This function is definitely not thread safe because we
734don't employ any locking mechanisms.
735@end deftypefun
736
737
738@deftypefun gpg_error_t ksba_cert_get_user_data (@w{ksba_cert_t @var{cert},} @w{const char *@var{key},} @w{void *@var{buffer},} @w{size_t @var{bufferlen},} @w{size_t *@var{datalen}})
739
740Return user data for certificate @var{cert} stored under the string
741@var{key}. The caller needs to provide a suitable large @var{buffer} and
742the usable length of this buffer in @var{bufferlen}.  If @var{datalen}
743is not @code{NULL}, the length of the data stored in @var{buffer} will
744be stored there.
745
746If @var{buffer} is given as @code{NULL}, @var{bufferlen} will be ignored
747and the required length of the buffer will be returned at @var{datalen}.
748
749On success 0 is returned.  If no data is stored under the given key,
750@code{GPG_ERR_NOT_FOUND} is returned.  If the provided buffer is too
751short and @var{buffer} is not @code{NULL},
752@code{GPG_ERR_BUFFER_TOO_SHORT} will be returned.
753@end deftypefun
754
755
756
757@node CMS
758@chapter Mastering the Cryptographic Message Syntax
759The @acronym{CMS} is also known under the name PKCS#7.  Is is
760a cryptographic framework for securing data transactions and storage, much
761like OpenPGP.  It is heavily based on X.509 semantics and for example
762used with the email encryption protocol S/MIME.
763
764@menu
765* CMS Basics::
766* CMS Parser::
767@end menu
768
769@node CMS Basics
770@section CMS Basics
771All operations with the CMS framework require the use of a so called CMS
772object which is internally used to keep track of the current state and to
773store some meta information.
774
775@deftp {Data type} ksba_cms_t
776The @code{ksba_cms_t} type is used for this CMS object.
777@end deftp
778@deftp {Data type} ksba_stop_reason_t
779The @code{ksba_stop_reason_t} type is an enumeration used for communication
780between the phases of a parsing or building process.
781@end deftp
782
783
784@deftypefun ksba_cms_t ksba_cms_new (void)
785
786This function creates a new CMS object.  The only reason the function
787may fail is an out-of-memory condition in which case @code{NULL} is
788returned.  It is safe for the caller to translate this to the standard
789error code @code{GPG_ERR_ENOMEM}.  Any object created
790with this function should be released after use by using
791@code{ksba_cms_release}.
792@end deftypefun
793
794@deftypefun void ksba_cms_release (@w{ksba_cms_t @var{cms}})
795
796Release all resources associated with the @var{CMS} object.  It is
797perfectly okay to pass @code{NULL} to this function in which case
798nothing happens.
799@end deftypefun
800
801@deftypefun gpg_error_t ksba_cms_set_reader_writer (@w{ksba_cms_t @var{cms}, ksba_reader_t @var{r}, ksba_writer_t @var{w}})
802
803About all usages of the CMS framework require some input and output data
804(great surprise!).  To accomplish this in the most abstract way, no
805direct output functions are used - instead special reader and writer
806objects are used instead.  Depending on the desired operations either a
807reader, a writer or both must be given.  Associate a reader object with
808@var{cms} by passing it as @var{r} and a writer object by passing it as
809@var{w}.  Note that no reference counting is done,so make sure that
810those objects have a lifetime at least as long as @var{CMS}.
811
812If you forget to set these objects, you will get an appropriate error
813later when data is actually to be read or written.  The function returns
814zero on success or an error code when invalid objects are passed.
815@end deftypefun
816
817
818@node CMS Parser
819@section CMS Parser
820@acronym{KSBA} includes a versatile CMS parser for encryption (enveloped
821data) and digital signing.  The parser is capable of handling arbitrary
822amounts of data without requiring much memory.  Well, certain objects
823are build in memory because it can be assumed that those objects are
824limited in size; e.g. it does not make sense to use a video clip as the
825@acronym{DN} despite the fact that the standard does not forbid it.
826
827
828@deftypefun gpg_error_t ksba_cms_parse (@w{ksba_cms_t @var{cms}, ksba_stop_reason_t *@var{r_stopreason}})
829
830This is the core function of the parser and commonly used in a loop.
831The parsing process is divided into several phases to allow the user
832to get information at the right time and prepare for further
833processing.  The caller has to act on certain stop reasons which are
834returned by @var{r_stopreason} and set up things accordingly;
835@acronym{KSBA} may introduce new stop reasons to let the caller know
836other details; there is no need for the caller to act on every stop
837reason; it should only do so for reasons that the caller understands
838and which are mandatory.  The function will return with an error if
839the caller did not setup things correctly for certain stop reasons.
840@end deftypefun
841
842The use of this function is best explained by an example, leaving out all
843error checking.
844@example
845  do
846    @{
847      ksba_cms_parse (cms, &stopreason);
848      if (stopreason == KSBA_SR_BEGIN_DATA)
849        @{
850          get_recipients ();
851          decrypt_session_key ();
852          setup_bulk_decryption ();
853        @}
854      else if (stopreason == KSBA_SR_END_DATA)
855        @{
856          remove_padding ();
857        @}
858    @}
859  while (stopreason != KSBA_SR_READY);
860@end example
861This function assumes that the parsed data is so called `enveloped data'.
862
863@c FIXME: Reference to a list of stop reasons used here.
864
865As @acronym{CMS} provides a common framework for a variety of data
866formats, it is probably very useful to check the type of that data very
867early.  This can be accomplished by hooking into the stop reason
868@code{KSBA_SR_GOT_CONTENT} and retrieving the content using the following
869function.
870
871
872@deftypefun ksba_content_t ksba_cms_get_content_type (@w{ksba_cms_t @var{cms}, int @var{what}})
873
874By using a value of @code{0} for @var{what} this function returns the
875content type of the outer container; using @code{1} does return the
876content type of the enclosed object.
877
878@deftp {Data type} ksba_content_t
879The @code{ksba_content_t} type is an enumeration used to describe the
880content of a CMS message.  Here is a list of possible values:
881
882@table @code
883@item KSBA_CT_NONE
884No content type known (value @code{0})
885
886@item KSBA_CT_DATA
887The content is plain data, not further interpreted.
888
889@item KSBA_CT_SIGNED_DATA
890The content is an signed CMS object.  This also includes the case of a
891detached signature where no actual data is included in the message.
892
893@item  KSBA_CT_ENVELOPED_DATA
894The content is encrypted using a session key.
895
896@item KSBA_CT_DIGESTED_DATA
897Not yet supported
898
899@item KSBA_CT_ENCRYPTED_DATA
900Not yet supported
901
902@item KSBA_CT_AUTH_DATA
903Not yet supported
904@end table
905@end deftp
906@end deftypefun
907
908
909@deftypefun {const char *} ksba_cms_get_content_oid (@w{ksba_cms_t @var{cms}, int @var{what}})
910
911Return the object ID of @var{cms}.  This is a constant string valid as
912long as the context is valid and no new parse is started.  This function
913is similar to @code{ksba_cms_get_content_type} but returns the
914@acronym{OID} actually used in the data.  Depending on the value of
915@var{what} different values are returned: Using a value of @code{0}
916yields the OID of the outer container, a value of @code{1} yields the
917OID of the inner container if available and the value @code{2} returns
918the OID of the algorithm used to encrypt the inner container.
919@end deftypefun
920
921@node CRLs
922@chapter Certification Revocation Lists
923KSBA also comes with an API to process certification revocation lists.
924The API is similar to the @acronym{CMS} one but returns the contents
925entry by entry.
926
927
928@node PKCS10
929@chapter Certification Requests
930When using decentral generated keys, it is necessary to send out special
931formated messages so that a CA can generate the certificate.
932
933
934
935
936@node Utilities
937@chapter Utilities
938
939A few utility function and objects are available.  Some of them must be used
940to support some of the main functions.
941
942@menu
943* Names::                      General Names object
944* OIDs::                       Object Identifier helpers
945* DNs::                        Distinguished Name helpers
946@end menu
947
948@node Names
949@section General Names object
950
951This is an object to handle some of the names used in X.509.  We need
952this object approach because those names may come as a set and there is
953no other clean way to access them.
954
955@deftp {Data type} ksba_name_t
956The @code{ksba_name_t} type is an object to represent names sets.
957@end deftp
958
959
960@deftypefun void ksba_name_release (@w{ksba_name_t @var{name}})
961
962This function releases the object @var{name}.  Passing @code{NULL} is
963allowed.
964@end deftypefun
965
966@deftypefun {const char *} ksba_name_enum (@w{ksba_name_t @var{name}, int @var{idx}})
967
968By iterating @var{idx} up starting with 0, this function returns all
969General Names stored in @var{name}.  The format of the returned name is either
970a RFC-2253 formated one which can be detected by checking whether the
971first character is letter or a digit.  RFC 2822 conformant email addresses
972are returned enclosed in angle brackets, the opening angle bracket
973should be used to detect this.  Other formats are returned as an
974S-Expression in canonical format, so an opening parenthesis may be used
975to detect this encoding, in this case the name may include binary null
976characters, so strlen might return a length shorter than actually used,
977the real length is implicitly given by the structure of the S-Exp, an
978extra null is appended for safety reasons.  One common format return is
979a Universal Resource Identifier which has the S-expression:
980@samp{(uri <urivalue>)}.
981
982The returned string has the same lifetime as @var{name}.
983@end deftypefun
984
985@deftypefun {char *} ksba_name_get_uri (@w{ksba_name_t @var{name}, int @var{idx}})
986
987Convenience function to return names representing an URI.  Caller
988must free the returned value.  Note that this function should not be
989used to enumerate the names.
990
991Here is an example on how you can use this function to enumerate all
992@acronym{URI}s:
993
994@example
995void
996print_names (ksba_name_t name)
997@{
998  int idx;
999  const char *s;
1000
1001  for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
1002    @{
1003      char *p = ksba_name_get_uri (name, idx);
1004      if (p)
1005        @{
1006           puts (p);
1007           ksba_free (p);
1008        @}
1009    @}
1010@}
1011@end example
1012@end deftypefun
1013
1014
1015@node OIDs
1016@section Object Identifier helpers
1017
1018@c !FIXME!
1019[This needs to get written - for now please see libksba/src/oids.c]
1020
1021
1022@node DNs
1023@section Distinguished Name helpers
1024
1025These are helper functions for the so called distinguished names.  They
1026are used for example as the issuer and subject name.
1027
1028@deftypefun gpg_error_t ksba_dn_teststr (@w{const char *@var{string}}, @w{int @var{seq}}, @w{size_t *@var{rerroff}}, @w{size_t *@var{rerrlen}})
1029
1030Assuming that @var{string} contains an RFC-2253 encoded string, test
1031whether this string may be passed as a valid DN to libksba.  On success
1032the functions returns @code{0}.  On error the function returns an error
1033code and stores the offset of the erroneous part at
1034@var{rerroff}. @var{rerrlen} will then receive the length of the
1035erroneous part.
1036
1037This function is mostly useful to test whether a certain component label
1038is supported. @var{seq} should be passed as @code{0} for now.  Any of
1039@var{rerroff} and @var{rerrlen} may be passed as @var{NULL} if the
1040caller is not interested at this value.
1041
1042@end deftypefun
1043
1044
1045gpg_error_t
1046ksba_dn_str2der (const char *string, void **rder, size_t *rderlen);
1047
1048gpg_error_t
1049ksba_dn_der2str (const void *der, size_t derlen, char **r_string);
1050
1051
1052
1053
1054@node Error Handling
1055@chapter Error Handling
1056
1057Most functions in `KSBA' will return an error if they fail.
1058For this reason, the application should always catch the error
1059condition and take appropriate measures, for example by releasing the
1060resources and passing the error up to the caller, or by displaying a
1061descriptive message to the user and canceling the operation.
1062
1063Some error values do not indicate a system error or an error in the
1064operation, but the reasonable result of an operation.  For example, if
1065you try to access optional attributes of a certificate that are not
1066present, you get an appropriate error message.  Some error values have
1067specific meanings if returned by a specific function.  Such cases are
1068described in the documentation of those functions.
1069
1070All error codes are defined by the library @code{libgpg-error}.  See
1071there for ways to check the error values and print descriptive
1072strings.  Please be aware that you can't check directly against an
1073error code but have to do it like this:
1074
1075@example
1076  err = ksba_foo ();
1077  if (gpg_err_code (err) == GPG_ERR_EOF)
1078    okay = 1;
1079@end example
1080
1081The only exception is that success (i.e. no error) is defined to be
1082@code{0}; thus you may directly test for success like:
1083
1084@example
1085  if (!ksba_foo ())
1086    okay = 1;
1087@end example
1088
1089
1090@c The following table lists the error codes as used by this library.
1091@c
1092@c @table @code
1093@c
1094@c @end table
1095@c
1096
1097@node Component Labels
1098@appendix Component Labels
1099
1100RFC-2253 defines the following table with string representations of name
1101components:
1102
1103@multitable {SERIALNUMBER} {organizationalUnit}  {xxx}
1104@item Label   @tab  Component           @tab OID
1105@item
1106@item C       @tab  countryName         @tab 2.5.4.6
1107@item CN      @tab  commonName          @tab 2.5.4.3
1108@item DC      @tab  domainComponent     @tab 0.9.2342.19200300.100.1.25
1109@item L       @tab  localityName        @tab 2.5.4.7
1110@item O       @tab  organizationName    @tab 2.5.4.10
1111@item OU      @tab  organizationalUnit  @tab 2.5.4.11
1112@item ST      @tab  stateOrProvince     @tab 2.5.4.8
1113@item STREET  @tab  streetAddress       @tab 2.5.4.9
1114@item UID     @tab  userid              @tab 0.9.2342.19200300.100.1.1
1115
1116@end multitable
1117
1118They are used internally for converting a DN into its string
1119representation; components not listed in this table will be
1120represented by their OID.
1121
1122For the other direction, i.e. creating a DN from the string
1123representation, KSBA recognizes the following extra labels:
1124
1125@multitable {SERIALNUMBER} {organizationalUnit}  {xxx}
1126@item Label        @tab  Component        @tab OID
1127@item
1128@item ADDR         @tab  postalAddress    @tab 2.5.4.16
1129@item BC           @tab  businessCategory @tab 2.5.4.15
1130@item D            @tab  description      @tab 2.5.4.13
1131@item EMAIL        @tab  emailAddress     @tab 1.2.840.113549.1.9.1
1132@item GN           @tab  givenName        @tab 2.5.4.42
1133@item POSTALCODE   @tab  postalCode       @tab 2.5.4.17
1134@item PSEUDO       @tab  pseudonym        @tab 2.5.4.65
1135@item SERIALNUMBER @tab  serialNumber     @tab 2.5.4.5
1136@item SN           @tab  surname          @tab 2.5.4.4
1137@item T            @tab  title            @tab 2.5.4.12
1138
1139@end multitable
1140
1141
1142@include gpl.texi
1143
1144@node Concept Index
1145@unnumbered Concept Index
1146@printindex cp
1147@node Function and Data Index
1148@unnumbered Function and Data Index
1149@printindex fn
1150@bye
1151
1152
1153
1154         Old Information which might not be correct anymore:
1155         ---------------------------------------------------
1156
1157KSBA  provides these subsystems:
1158
1159
1160* ASN.1 Parser  (ksba_asn_*)
1161
1162  KSBA provides a simple ASN.1 parser which can be used to read
1163  definitions directly from an ASN.1 module without the need of
1164  generating extra tables.  For ease of maintenance it also comes with
1165  a tool to create static data structures to avoid that overhead and
1166  the need to include ASN.1 modules.
1167
1168  The primary goal of this parser is to provide the ASN.1 syntax tree
1169  to be used by other library modules.
1170
1171* BER Decoder (ksba_ber_decoder_*)
1172
1173  This is a decoder for the ASN.1 Basic Encoding Rules with a facility
1174  to detect valid DER encoding (DER is a subset of BER).  By using
1175  thresholds and pre-registered callout function it is possible to
1176  work on indefinite length data stream and limiting the memory usage
1177  to a fixed upper bound.
1178
1179* BER Encoder (ksba_ber_encoder_*)
1180
1181  This is the counterpart to the DER Decoder with the ability to
1182  restrict the encoding to DER.
1183
1184* Certificate Handling (ksba_cert_*)
1185
1186  The main bulk of the provided functions are used to give a clean
1187  interface to X.509 certificates by translating X.509 data types to
1188  more standard data types.
1189
1190* CMS Handling (ksba_cms_*)
1191
1192  The Cryptographic Message Syntax is the core data type for S/MIME
1193  and therefore KSBA provides an interface to parse and create these
1194  objects without the need to cope with ASN.1.
1195
1196* Reader and Writer (ksba_reader_*, ksba_writer_*)
1197
1198  Abstraction objects to access memory areas, files or file
1199  descriptor.
1200