65cf10c41cd293b8e9868746585b7a1dfbe66f70
[platform/upstream/libksba.git] / doc / ksba.texi
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
17 Copyright @copyright{} 2002, 2003, 2004 g10 Code GmbH
18 @end macro
19 @macro mypermissionnotice
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU General Public License as published by the
22 Free Software Foundation; either version 3 of the License, or (at your
23 option) any later version. The text of the license can be found in the
24 section entitled ``Copying''.
25 @end macro
26
27
28
29 @ifinfo
30 This file documents the @acronym{KSBA} library to access X.509 and CMS data
31 structures.
32
33 This 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
72 This 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
92 Appendices
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
98 Indices
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
106 Introduction
107
108 * Getting Started::
109 * Features::
110 * Overview::
111
112 Preparation
113
114 * Header::
115 * Building the source::
116
117 Certificate 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
124 Mastering 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
135 certificates, 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
146 This manual documents the `KSBA' library programming interface.  All
147 functions and data types provided by the library are explained.
148
149 The reader is assumed to possess basic knowledge about the implemented
150 protocols.
151
152 This manual can be used in several ways.  If read from the beginning
153 to the end, it gives a good introduction into the library and how it
154 can be used in an application.  Forward references are included where
155 necessary.  Later on, the manual can be used as a reference manual to
156 get just the information needed about any particular interface of the
157 library.  Experienced programmers might want to start looking at the
158 examples at the end of the manual, and then only read up those parts
159 of 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,
166 and over open coding the protocols in your application directly.
167
168 @table @asis
169 @item It's Free Software
170 Anybody can use, modify, and redistribute it under the terms of the GNU
171 General 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
175 the data in a consistent way.  There is no more need to worry about all
176 the nasty details of the protocols.  The API gives the C programmer a
177 more usual way of interacting with the data.
178
179 @item It copes with the version details
180 X.509 protocols tend to have many different versions and dialects.
181 Applications must usually cope with all of this and it has to be coded
182 over and over again.  `KSBA' hides this by providing just one API which
183 does the Right Thing.  Support for new versions and features of the
184 protocols will be added over time.
185 @end table
186
187
188 @node Overview
189 @section Overview
190
191 @c [Needs more stuff]
192
193 The `KSBA' library is thread-safe as long as objects described by one
194 context are only used by one thread at a time.  No initialization is
195 required.
196
197
198 @node Preparation
199 @chapter Preparation
200
201 To use `KSBA', you have to perform some changes to your sources and the
202 build system.  The necessary changes are small and explained in the
203 following sections.  At the end of this chapter, it is described how the
204 library is initialized, and how the requirements of the library are
205 verified.
206
207 @menu
208 * Header::
209 * Version Check::
210 * Building the source::
211 @end menu
212
213
214 @node Header
215 @section Header
216
217 All interfaces (data types and functions) of the library are defined in
218 the header file @file{ksba.h}.  You must include this in all programs
219 using the library, either directly or through some other header file,
220 like this:
221
222 @smallexample
223 #include <ksba.h>
224 @end smallexample
225
226 The name space of `KSBA' is @code{ksba_*} for function names,
227 @code{ksba*} for data types and @code{KSBA_*} for other symbols.  In
228 addition the same name prefixes with one prepended underscore are
229 reserved for internal use and should never be used by an application.
230
231 @node Version Check
232 @section Version Check
233
234 It is often desirable to check that the version of `KSBA' used is indeed
235 one which fits all requirements.  Even with binary compatibility, new
236 features may have been introduced but through peculiarities of the
237 runtime linker an old version gets actually used.  So you better check
238 that the version is as expected right after program startup.
239
240 @deftypefun {const char *} ksba_check_version (@w{const char *@var{req_version}})
241
242 Check that the the version of the library is at minimum the one given as
243 a string in @var{req_version} and return the actual version string of
244 the 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
246 version string is returned.  It is a pretty good idea to run this
247 function as soon as possible, because it may also initializes some
248 subsystems.  In a multi-threaded environment if should be called before
249 any more threads are created.
250 @end deftypefun
251
252 @node Building the source
253 @section Building the source
254
255 If you want to compile a source file including the @file{ksba.h} header
256 file, you must make sure that the compiler can find it in the directory
257 hierarchy.  This is accomplished by adding the path to the directory in
258 which the header file is located to the compiler's include file search
259 path (via the @option{-I} option).
260
261 However, the path to the include file is determined at the time the
262 source is configured.  To solve this problem, `KSBA' ships with a small
263 helper program @command{ksba-config} that knows about the path to the
264 include file and other configuration options.  The options that need to
265 be added to the compiler invocation at compile time are output by the
266 @option{--cflags} option of @command{ksba-config}.  The following
267 example shows how it can be used at the command line:
268
269 @example
270 gcc -c foo.c `ksba-config --cflags`
271 @end example
272
273 Adding the output of @samp{ksba-config --cflags} to the compiler's
274 command line will ensure that the compiler can find the @file{ksba.h}
275 header file.
276
277 A similar problem occurs when linking the program with the library.
278 Again, the compiler has to find the library files.  For this to work,
279 the 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
282 outputs all other options that are required to link the program with the
283 `KSBA' libraries (in particular, the @samp{-lksba} option).  The
284 example shows how to link @file{foo.o} with the `KSBA' libraries to a
285 program @command{foo}.
286
287 @example
288 gcc -o foo foo.o `ksba-config --libs`
289 @end example
290
291 Of course you can also combine both examples to a single command by
292 specifying both options to @command{ksba-config}:
293
294 @example
295 gcc -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
302 One 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
306 The @code{ksba_cert_t} type is a handle for an X.509 certificate.
307 @end deftp
308
309 @deftp {Data type} ksba_sexp_t
310 The @code{ksba_sexp_t} type describes a canonically encoded S-expression
311 stored in a memory buffer.  It is alias for @code{unsigned char *}.
312 Note that a length argument is not required because the length of such
313 an 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
327 This section explains how to create a certificate object, initialize it,
328 copy it and eventually destroy it.
329
330 @deftypefun ksba_cert_t ksba_cert_new (void)
331 The function @code{ksba_cert_new} creates a new certificate object and
332 returns a handle for it.  The certificate object has initially one
333 reference.
334
335 The only reason why this function may fail is an out-of-memory condition in
336 which case @code{NULL} is returned.  You might then get the actual error
337 code using @samp{gpg_error_from_errno (errno)}.
338 @end deftypefun
339
340 @deftypefun void ksba_cert_ref (@w{ksba_cert_t @var{cert}})
341 The function @code{ksba_cert_ref} bumps the reference counter of the
342 certificate object up by one.  Thus an extra @code{ksba_cert_release} is
343 required 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}})
347 The function @code{ksba_cert_release} reduces the number of references
348 to the certificate object with the handle @var{cert}.  If this was the
349 last reference, it will also destroy the object and releases all
350 associated resources.  It is okay to pass @code{NULL} to the function
351 in 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
356 Read the next certificate from the @var{reader} object and store it in
357 the certificate object @var{cert} for future access.  The certificate is
358 parsed and rejected if it has any syntactical or semantical error
359 (i.e. does not match the @acronym{ASN.1} description).
360
361 The function returns @code{0} if the operation was successfully
362 performed.  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
367 Parse the @var{buffer} which should contain a @acronym{DER} encoded
368 certificate of @var{length} and initialize the certificate object
369 @var{cert} with it.  This function is intended as a convenience
370 function to be used when a certificate is already available in a
371 internal memory buffer.  This avoids the extra code needed to setup the
372 reader object.  Note that @var{cert} must be a valid certificate object.
373
374 The function returns @code{0} if the operation was successfully performed.
375 An 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
381 The functions in this section allow accessing the attributes of a
382 certificate in a well defined manner.  An error will be returned if the
383 certificate 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
388 This function returns a pointer to the @acronym{DER} encoded buffer with
389 the raw certificate.  The length of that buffer gets stored at
390 @var{r_length}.  This function is useful to export or store the raw
391 certificate.
392
393 The function returns @code{NULL} on error or a pointer to a buffer with
394 the raw certificate data.  That pointer is only valid as long as the
395 certificate 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
400 This function feeds the data which is expected to be hashed into the
401 supplied function @var{hasher}, where the first argument passed is
402 @var{hasher_arg}, the second the pointer to the data to be hashed and
403 the third the length of this data.
404
405 The function returns @code{0} on success or an error code when something
406 goes wrong.  The @var{hasher} function is not expected to return an
407 error; instead the caller should setup that function in a way to convey
408 encountered errors by means of the @var{hasher_arg}.  Note that a hash
409 function 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
415 Figure out the the digest algorithm used for the signature and return
416 its @acronym{OID} in dotted decimal format.  This function is most
417 likely used to setup the hash context before calling
418 @code{ksba_cert_hash}.  For some certificate types the returned OID
419 has a special meaning:
420
421 @table @code
422 @item 1.2.840.113549.1.1.10
423 This indicates the RSASSA-PSS algorithm.  The digest algorithm needs
424 to be extracted from the S-expression returned by
425 @code{ksba_cert_get_sig_val}.
426
427 @item 1.3.101.112
428 This is the Ed25519 algorithm which does not use a separate digest
429 algorithm.  See RFC-8410.
430
431 @item 1.3.101.113
432 This is the Ed448 algorithm which does not use a separate digest
433 algorithm.  See RFC-8410.
434
435 @end table
436
437 The function returns @code{NULL} for an error; on success a constant
438 string with the @acronym{OID} is returned.  This string is valid as long
439 the certificate object is valid.
440 @end deftypefun
441
442 @deftypefun ksba_sexp_t ksba_cert_get_serial (@w{ksba_cert_t @var{cert}})
443
444 The function returns the serial number of the certificate @var{cert}.
445 The serial number is an integer returned as an canonical encoded
446 S-expression with just one element.  The caller must free the returned
447 value.  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
452 With @var{idx} given as @code{0}, this function returns the
453 Distinguished Name (@acronym{DN}) of the certificate issuer; this
454 usually is the name of a certification authority (@acronym{CA}).  The
455 format 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
457 severe error and actually should have been caught by the certificate
458 reading function.
459
460 With @var{idx} greater than zero, the function may be used to enumerate
461 alternate issuer names.  The function returns @code{NULL} when there are
462 no more alternate names. Only alternate names recognized by
463 @code{libksba} are returned, others are simply skipped.  The format of
464 the returned name is either a RFC-2253 formated string which can be
465 detected by checking whether the first character is a letter or digit.
466 RFC-822 conformant email addresses are returned enclosed in angle
467 brackets; the opening angle bracket should be used to detect this.
468 Other formats are returned as an S-Expression in canonical format, so a
469 opening parenthesis should be used to detect this encoding. The name may
470 include binary null characters, thus strlen may return a length shorter
471 than actually used.  The real length is implicitly given by the structure
472 of the S-expression, an extra null is appended for safety reasons.
473
474 The caller must free the returned string using @code{ksba_free} or
475 whatever 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
480 With @var{idx} given as @code{0}, this function returns the
481 Distinguished Name (@acronym{DN}) of the certificate's subject.  The
482 format of the returned string is in accordance with RFC-2253.
483 @code{NULL} is returned if the @acronym{DN} is not available.
484
485 With @var{idx} greater than zero, the function may be used to enumerate
486 alternate subject names.  The function returns @code{NULL} when there
487 are no more alternate names. Only alternate names recognized by
488 @code{libksba} are returned, others are simply skipped.  The format of
489 the returned name is either a RFC-2253 formated string which can be
490 detected by checking whether the first character is a letter or digit.
491 RFC-2822 conform email addresses are returned enclosed in angle
492 brackets; the opening angle bracket should be used to detect this.
493 Other formats are returned as an S-Expression in canonical format, so a
494 opening parenthesis should be used to detect this encoding, the name may
495 include binary null characters, thus strlen may return a length shorter
496 than actually used.  The real length is implicitly given by the structure
497 of the S-expression, an extra null is appended for safety reasons.
498
499 The caller must free the returned string using @code{ksba_free} or
500 whatever function has been registered as a replacement.
501 @end deftypefun
502
503
504 @deftp {Data type} ksba_isotime_t
505 Due to problems with the C data type @code{time_t}, which will overflow
506 on most 32 bit machines in the year 2038, it was not advisable to use
507 this type for referencing times stored in certificates.  Instead, you
508 should use the @code{ksba_isotime_t} type, which can represent any time
509 since the year 0.
510
511 It is implemented as a buffer of 16 bytes and may be handled like a
512 standard string.  It should be initialized to zero (i.e. the first
513 byte needs to be 0x00) if it does not hold a valid date.  Date values
514 themselves are stored in ISO format and assumed to be referenced from
515 UTC.  The string with the date value is always guaranteed to be of
516 length 15 and having a format like: @samp{"19610711T172059"}.  Note
517 that the `T' is required by ISO rules.
518
519 A simple assignment of these data types is not a good idea.  You may
520 use @code{strcpy} or better a specialized function like:
521
522 @example
523 void
524 copy_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
533 For reasons of documentation a special function should also be used to
534 compare such times:
535
536 @example
537 int
538 cmp_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
547 Return the validity dates from the certificate.  If no value is
548 available an empty date object (i.e. a @code{strlen} will be
549 stored at @var{timebuf}, otherwise it will receive the date. On failure
550 an error code is returned.
551
552 To 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
579 Return information on the basicConstraint (2.5.19.19) of CERT.  R_CA
580 receives true if this is a CA and only in that case R_PATHLEN is set to
581 the maximum certification path length or -1 if there is no such
582 limitation
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
588 Get the key usage flags. The function returns @code{GPG_ERR_NO_DATA} if no
589 key usage is specified. The usage flags are as shown in RFC3280, section
590 4.2.1.3. The key usage flags are represented by a bitmask, and you can
591 test each bit using symbolic constants, which tells you if that usage
592 is set on the certificate. The constants are
593
594 @table @code
595 @item KSBA_KEYUSAGE_DIGITAL_SIGNATURE
596 Usable for digitalSignature.
597 @item KSBA_KEYUSAGE_NON_REPUDIATION
598 Usable for nonRepudiation.
599 @item KSBA_KEYUSAGE_KEY_ENCIPHERMENT
600 Usable for keyEncipherment.
601 @item KSBA_KEYUSAGE_DATA_ENCIPHERMENT
602 Usable for dataEncipherment.
603 @item KSBA_KEYUSAGE_KEY_AGREEMENT
604 Usable for for keyAgreement.
605 @item KSBA_KEYUSAGE_KEY_CERT_SIGN
606 Usable for keyCertSign.
607 @item KSBA_KEYUSAGE_CRL_SIGN
608 Usable for cRLSign.
609 @item KSBA_KEYUSAGE_ENCIPHER_ONLY
610 Usable for encipherOnly.
611 @item KSBA_KEYUSAGE_DECIPHER_ONLY
612 Usable for decipherOnly.
613 @end table
614
615 These are the basic constraints on usage of a certificate. If you need
616 to 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
621 Return a string containing the extended usages for the certificate,
622 delimited 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
628 Return a string with the certificatePolicies delimited by linefeeds.
629 The return values may be extended to carry more information per line, so
630 the caller should only use the first white-space delimited token per
631 line.  The function returns @code{GPG_ERR_NO_DATA} when this extension
632 is 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
639 Return the CRLDistPoints given in the certificate extension of
640 certificate @var{cert}.  @var{idx} should be iterated starting from 0
641 until the function returns @code{GPG_ERR_EOF}.  @var{r_distpoint} returns a
642 ksba_name_t object with the distribution point name(s); the return value
643 may 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
646 the certificate issuer.  @var{r_reason} returns the reason for the CRL.
647 This is a bit encoded value with no bit set if no reason has been
648 specified in the certificate.
649
650 The caller may pass @code{NULL} to any of the pointer arguments if he is
651 not interested in this value.  The return values for @var{r_distpoint}
652 and @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
659 Return the subjectKeyIdentifier extension as a simple allocated
660 S-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
662 error code.  If @var{r_crit} is not passed as @code{NULL}, the critical flag of
663 this 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
669 Return the authorityKeyIdentifier in @var{r_name} and @var{r_serial} or
670 in @var{r_keyid}.  @code{GPG_ERR_NO_DATA} is returned if no
671 authorityKeyIdentifier has been found.  This error code is also returned
672 if @var{r_keyid} has been given as NULL and only an
673 authorityKeyIdentifier 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
679 Return the authorityInfoAccess attributes. @var{idx} should be
680 iterated starting from 0 until this function returns
681 @code{GPG_ERR_EOF}.  @var{r_method} returns an allocated string with
682 the OID of one item and @var{r_location} returns the GeneralName for
683 that OID.  The returned values for @var{r_method} and @var{r_location}
684 must be released by the caller unless the function returned an error;
685 the function will however make sure that @var{r_method} and
686 @var{r_location} will point to @code{NULL} if the function returns an
687 error.
688
689 See 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
694 Return the subjectInfoAccess attributes. @var{idx} should be
695 iterated starting from 0 until this function returns
696 @code{GPG_ERR_EOF}.  @var{r_method} returns an allocated string with
697 the OID of one item and @var{r_location} returns the GeneralName for
698 that OID.  The returned values for @var{r_method} and @var{r_location}
699 must be released by the caller unless the function returned an error;
700 the function will however make sure that @var{r_method} and
701 @var{r_location} will point to @code{NULL} if the function returns an
702 error.
703
704 See 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
716 Certificate objects play a central role in many applications and often
717 it is desirable to associate other data with the certificate to avoid
718 wrapping the certificate object into an own object.  `KSBA' provides a
719 mechanism 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
724 Stores arbitrary data along with a certificate.  The data is expected in
725 the buffer @var{data} of length @var{datalen}. It will be stored under
726 the string @var{key}.  If data is already stored under this key it will
727 be replaced by the new data. Using @code{NULL} for @var{data} will
728 effectively delete the data.
729
730 On error (i.e. out of memory) an already existing data object
731 stored under @var{key} may get deleted.
732
733 @strong{Caution:} This function is definitely not thread safe because we
734 don'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
740 Return user data for certificate @var{cert} stored under the string
741 @var{key}. The caller needs to provide a suitable large @var{buffer} and
742 the usable length of this buffer in @var{bufferlen}.  If @var{datalen}
743 is not @code{NULL}, the length of the data stored in @var{buffer} will
744 be stored there.
745
746 If @var{buffer} is given as @code{NULL}, @var{bufferlen} will be ignored
747 and the required length of the buffer will be returned at @var{datalen}.
748
749 On 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
751 short and @var{buffer} is not @code{NULL},
752 @code{GPG_ERR_BUFFER_TOO_SHORT} will be returned.
753 @end deftypefun
754
755
756 \f
757 @node CMS
758 @chapter Mastering the Cryptographic Message Syntax
759 The @acronym{CMS} is also known under the name PKCS#7.  Is is
760 a cryptographic framework for securing data transactions and storage, much
761 like OpenPGP.  It is heavily based on X.509 semantics and for example
762 used 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
771 All operations with the CMS framework require the use of a so called CMS
772 object which is internally used to keep track of the current state and to
773 store some meta information.
774
775 @deftp {Data type} ksba_cms_t
776 The @code{ksba_cms_t} type is used for this CMS object.
777 @end deftp
778 @deftp {Data type} ksba_stop_reason_t
779 The @code{ksba_stop_reason_t} type is an enumeration used for communication
780 between the phases of a parsing or building process.
781 @end deftp
782
783
784 @deftypefun ksba_cms_t ksba_cms_new (void)
785
786 This function creates a new CMS object.  The only reason the function
787 may fail is an out-of-memory condition in which case @code{NULL} is
788 returned.  It is safe for the caller to translate this to the standard
789 error code @code{GPG_ERR_ENOMEM}.  Any object created
790 with 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
796 Release all resources associated with the @var{CMS} object.  It is
797 perfectly okay to pass @code{NULL} to this function in which case
798 nothing 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
803 About all usages of the CMS framework require some input and output data
804 (great surprise!).  To accomplish this in the most abstract way, no
805 direct output functions are used - instead special reader and writer
806 objects are used instead.  Depending on the desired operations either a
807 reader, 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
810 those objects have a lifetime at least as long as @var{CMS}.
811
812 If you forget to set these objects, you will get an appropriate error
813 later when data is actually to be read or written.  The function returns
814 zero 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
821 data) and digital signing.  The parser is capable of handling arbitrary
822 amounts of data without requiring much memory.  Well, certain objects
823 are build in memory because it can be assumed that those objects are
824 limited 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
830 This is the core function of the parser and commonly used in a loop.
831 The parsing process is divided into several phases to allow the user
832 to get information at the right time and prepare for further
833 processing.  The caller has to act on certain stop reasons which are
834 returned by @var{r_stopreason} and set up things accordingly;
835 @acronym{KSBA} may introduce new stop reasons to let the caller know
836 other details; there is no need for the caller to act on every stop
837 reason; it should only do so for reasons that the caller understands
838 and which are mandatory.  The function will return with an error if
839 the caller did not setup things correctly for certain stop reasons.
840 @end deftypefun
841
842 The use of this function is best explained by an example, leaving out all
843 error 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
861 This 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
865 As @acronym{CMS} provides a common framework for a variety of data
866 formats, it is probably very useful to check the type of that data very
867 early.  This can be accomplished by hooking into the stop reason
868 @code{KSBA_SR_GOT_CONTENT} and retrieving the content using the following
869 function.
870
871
872 @deftypefun ksba_content_t ksba_cms_get_content_type (@w{ksba_cms_t @var{cms}, int @var{what}})
873
874 By using a value of @code{0} for @var{what} this function returns the
875 content type of the outer container; using @code{1} does return the
876 content type of the enclosed object.
877
878 @deftp {Data type} ksba_content_t
879 The @code{ksba_content_t} type is an enumeration used to describe the
880 content of a CMS message.  Here is a list of possible values:
881
882 @table @code
883 @item KSBA_CT_NONE
884 No content type known (value @code{0})
885
886 @item KSBA_CT_DATA
887 The content is plain data, not further interpreted.
888
889 @item KSBA_CT_SIGNED_DATA
890 The content is an signed CMS object.  This also includes the case of a
891 detached signature where no actual data is included in the message.
892
893 @item  KSBA_CT_ENVELOPED_DATA
894 The content is encrypted using a session key.
895
896 @item KSBA_CT_DIGESTED_DATA
897 Not yet supported
898
899 @item KSBA_CT_ENCRYPTED_DATA
900 Not yet supported
901
902 @item KSBA_CT_AUTH_DATA
903 Not 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
911 Return the object ID of @var{cms}.  This is a constant string valid as
912 long as the context is valid and no new parse is started.  This function
913 is 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}
916 yields the OID of the outer container, a value of @code{1} yields the
917 OID of the inner container if available and the value @code{2} returns
918 the OID of the algorithm used to encrypt the inner container.
919 @end deftypefun
920
921 @node CRLs
922 @chapter Certification Revocation Lists
923 KSBA also comes with an API to process certification revocation lists.
924 The API is similar to the @acronym{CMS} one but returns the contents
925 entry by entry.
926
927
928 @node PKCS10
929 @chapter Certification Requests
930 When using decentral generated keys, it is necessary to send out special
931 formated messages so that a CA can generate the certificate.
932
933
934
935 \f
936 @node Utilities
937 @chapter Utilities
938
939 A few utility function and objects are available.  Some of them must be used
940 to 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
951 This is an object to handle some of the names used in X.509.  We need
952 this object approach because those names may come as a set and there is
953 no other clean way to access them.
954
955 @deftp {Data type} ksba_name_t
956 The @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
962 This function releases the object @var{name}.  Passing @code{NULL} is
963 allowed.
964 @end deftypefun
965
966 @deftypefun {const char *} ksba_name_enum (@w{ksba_name_t @var{name}, int @var{idx}})
967
968 By iterating @var{idx} up starting with 0, this function returns all
969 General Names stored in @var{name}.  The format of the returned name is either
970 a RFC-2253 formated one which can be detected by checking whether the
971 first character is letter or a digit.  RFC 2822 conformant email addresses
972 are returned enclosed in angle brackets, the opening angle bracket
973 should be used to detect this.  Other formats are returned as an
974 S-Expression in canonical format, so an opening parenthesis may be used
975 to detect this encoding, in this case the name may include binary null
976 characters, so strlen might return a length shorter than actually used,
977 the real length is implicitly given by the structure of the S-Exp, an
978 extra null is appended for safety reasons.  One common format return is
979 a Universal Resource Identifier which has the S-expression:
980 @samp{(uri <urivalue>)}.
981
982 The 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
987 Convenience function to return names representing an URI.  Caller
988 must free the returned value.  Note that this function should not be
989 used to enumerate the names.
990
991 Here is an example on how you can use this function to enumerate all
992 @acronym{URI}s:
993
994 @example
995 void
996 print_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
1025 These are helper functions for the so called distinguished names.  They
1026 are 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
1030 Assuming that @var{string} contains an RFC-2253 encoded string, test
1031 whether this string may be passed as a valid DN to libksba.  On success
1032 the functions returns @code{0}.  On error the function returns an error
1033 code and stores the offset of the erroneous part at
1034 @var{rerroff}. @var{rerrlen} will then receive the length of the
1035 erroneous part.
1036
1037 This function is mostly useful to test whether a certain component label
1038 is 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
1040 caller is not interested at this value.
1041
1042 @end deftypefun
1043
1044
1045 gpg_error_t
1046 ksba_dn_str2der (const char *string, void **rder, size_t *rderlen);
1047
1048 gpg_error_t
1049 ksba_dn_der2str (const void *der, size_t derlen, char **r_string);
1050
1051
1052
1053 \f
1054 @node Error Handling
1055 @chapter Error Handling
1056
1057 Most functions in `KSBA' will return an error if they fail.
1058 For this reason, the application should always catch the error
1059 condition and take appropriate measures, for example by releasing the
1060 resources and passing the error up to the caller, or by displaying a
1061 descriptive message to the user and canceling the operation.
1062
1063 Some error values do not indicate a system error or an error in the
1064 operation, but the reasonable result of an operation.  For example, if
1065 you try to access optional attributes of a certificate that are not
1066 present, you get an appropriate error message.  Some error values have
1067 specific meanings if returned by a specific function.  Such cases are
1068 described in the documentation of those functions.
1069
1070 All error codes are defined by the library @code{libgpg-error}.  See
1071 there for ways to check the error values and print descriptive
1072 strings.  Please be aware that you can't check directly against an
1073 error 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
1081 The 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
1100 RFC-2253 defines the following table with string representations of name
1101 components:
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
1118 They are used internally for converting a DN into its string
1119 representation; components not listed in this table will be
1120 represented by their OID.
1121
1122 For the other direction, i.e. creating a DN from the string
1123 representation, 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
1157 KSBA  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.