Remove FAQ about PKCS12 macros
[openssl-web.git] / docs / faq-3-prog.txt
1 Programming with OpenSSL
2
3 * Is OpenSSL thread-safe?
4
5 Yes but with some limitations; for example, an SSL connection
6 cannot be used concurrently by multiple threads.  This is true for
7 most OpenSSL objects.
8
9 For version 1.1.0 and later, there is nothing further you need do.
10
11 For earlier versions than 1.1.0, it is necessary for your
12 application to set up the thread callback functions.  To do this,
13 your application must call CRYPTO_set_locking_callback(3) and one of
14 the CRYPTO_THREADID_set... API's.  See the OpenSSL threads manpage for
15 details and "note on multi-threading" in the INSTALL file in the source
16 distribution.
17
18 * I've compiled a program under Windows and it crashes: why?
19
20 This is usually because you've missed the comment in INSTALL.W32.
21 Your application must link against the same version of the Win32
22 C-Runtime against which your openssl libraries were linked.  The
23 default version for OpenSSL is /MD - "Multithreaded DLL".
24
25 If you are using Microsoft Visual C++'s IDE (Visual Studio), in
26 many cases, your new project most likely defaulted to "Debug
27 Singlethreaded" - /ML.  This is NOT interchangeable with /MD and your
28 program will crash, typically on the first BIO related read or write
29 operation.
30
31 For each of the six possible link stage configurations within Win32,
32 your application must link  against the same by which OpenSSL was
33 built.  If you are using MS Visual C++ (Studio) this can be changed
34 by:
35
36 <PRE>
37     1. Select Settings... from the Project Menu.
38     2. Select the C/C++ Tab.
39     3. Select "Code Generation from the "Category" drop down list box
40     4. Select the Appropriate library (see table below) from the "Use
41     run-time library" drop down list box.  Perform this step for both
42     your debug and release versions of your application (look at the
43     top left of the settings panel to change between the two)
44
45     Single Threaded           /ML        -  MS VC++ often defaults to
46                                             this for the release
47                                             version of a new project.
48     Debug Single Threaded     /MLd       -  MS VC++ often defaults to
49                                             this for the debug version
50                                             of a new project.
51     Multithreaded             /MT
52     Debug Multithreaded       /MTd
53     Multithreaded DLL         /MD        -  OpenSSL defaults to this.
54     Debug Multithreaded DLL   /MDd
55 </PRE>
56
57 Note that debug and release libraries are NOT interchangeable.  If you
58 built OpenSSL with /MD your application must use /MD and cannot use /MDd.
59
60 As per 0.9.8 the above limitation is eliminated for .DLLs. OpenSSL
61 .DLLs compiled with some specific run-time option [we insist on the
62 default /MD] can be deployed with application compiled with different
63 option or even different compiler. But there is a catch! Instead of
64 re-compiling OpenSSL toolkit, as you would have to with prior versions,
65 you have to compile small C snippet with compiler and/or options of
66 your choice. The snippet gets installed as
67 &lt;install-root&gt;/include/openssl/applink.c and should be either added to
68 your application project or simply #include-d in one [and only one]
69 of your application source files. Failure to link this shim module
70 into your application manifests itself as fatal "no OPENSSL_Applink"
71 run-time error. An explicit reminder is due that in this situation
72 [mixing compiler options] it is as important to add CRYPTO_malloc_init
73 prior first call to OpenSSL.
74
75 * How do I read or write a DER encoded buffer using the ASN1 functions?
76
77 You have two options. You can either use a memory BIO in conjunction
78 with the i2d_*_bio() or d2i_*_bio() functions or you can use the
79 i2d_*(), d2i_*() functions directly. Since these are often the
80 cause of grief here are some code fragments using PKCS7 as an example:
81
82 <PRE>
83     unsigned char *buf, *p;
84     int len = i2d_PKCS7(p7, NULL);
85
86     buf = OPENSSL_malloc(len); /* error checking omitted */
87     p = buf;
88     i2d_PKCS7(p7, &p);
89 </PRE>
90
91 At this point buf contains the len bytes of the DER encoding of p7.
92
93 The opposite assumes we already have len bytes in buf:
94
95 <PRE>
96     unsigned char *p = buf;
97
98     p7 = d2i_PKCS7(NULL, &p, len);
99 </PRE>
100
101 At this point p7 contains a valid PKCS7 structure or NULL if an error
102 occurred. If an error occurred ERR_print_errors(bio) should give more
103 information.
104
105 The reason for the temporary variable 'p' is that the ASN1 functions
106 increment the passed pointer so it is ready to read or write the next
107 structure. This is often a cause of problems: without the temporary
108 variable the buffer pointer is changed to point just after the data
109 that has been read or written. This may well be uninitialized data
110 and attempts to free the buffer will have unpredictable results
111 because it no longer points to the same address.
112
113 Memory allocation and encoding can also be combined in a single
114 operation by the ASN1 routines:
115
116 <PRE>
117     unsigned char *buf = NULL;
118     int len = i2d_PKCS7(p7, &buf);
119
120     if (len < 0) {
121         /* Error */
122     }
123     /* Do some things with 'buf' */
124
125     /* Finished with buf: free it */
126     OPENSSL_free(buf);
127 </PRE>
128
129 In this special case the "buf" parameter is *not* incremented, it points
130 to the start of the encoding.
131
132 * OpenSSL uses DER but I need BER format: does OpenSSL support BER?
133
134 The short answer is yes, because DER is a special case of BER and OpenSSL
135 ASN1 decoders can process BER.
136
137 The longer answer is that ASN1 structures can be encoded in a number of
138 different ways. One set of ways is the Basic Encoding Rules (BER) with various
139 permissible encodings. A restriction of BER is the Distinguished Encoding
140 Rules (DER): these uniquely specify how a given structure is encoded.
141
142 Therefore, because DER is a special case of BER, DER is an acceptable encoding
143 for BER.
144
145 * I've called &lt;some function&gt; and it fails, why?
146
147 Before submitting a report or asking in one of the mailing lists, you
148 should try to determine the cause. In particular, you should call
149 ERR_print_errors(3)
150 or ERR_print_errors_fp(3) after the failed call
151 and see if the message helps. Note that the problem may occur earlier
152 than you think -- you should check for errors after every call where
153 it is possible, otherwise the actual problem may be hidden because
154 some OpenSSL functions clear the error state.
155
156 * I just get a load of numbers for the error output, what do they mean?
157
158 The actual format is described in the ERR_print_errors(3) manual page.
159 You should call the function ERR_load_crypto_strings(3) before hand and
160 the message will be output in text form. If you can't do this (for example
161 it is a pre-compiled binary) you can use the errstr(1) utility on the error
162 code itself (the hex digits after the second colon).
163
164 * Why do I get errors about unknown algorithms?
165
166 The cause is forgetting to load OpenSSL's table of algorithms with
167 OpenSSL_add_all_algorithms(3). See the manual page for more information. This
168 can cause several problems such as being unable to read in an encrypted
169 PEM file, unable to decrypt a PKCS12 file or signature failure when
170 verifying certificates.
171
172 * Why can't the OpenSSH configure script detect OpenSSL?
173
174 Several reasons for problems with the automatic detection exist.
175 OpenSSH requires at least version 0.9.5a of the OpenSSL libraries.
176 Sometimes the distribution has installed an older version in the system
177 locations that is detected instead of a new one installed. The OpenSSL
178 library might have been compiled for another CPU or another mode (32/64 bits).
179 Permissions might be wrong.
180
181 The general answer is to check the config.log file generated when running
182 the OpenSSH configure script. It should contain the detailed information
183 on why the OpenSSL library was not detected or considered incompatible.
184
185 * Can I use OpenSSL's SSL library with non-blocking I/O?
186
187 Yes; make sure to read the SSL_get_error(3) manual page!
188
189 A pitfall to avoid: Don't assume that SSL_read(3) will just read from
190 the underlying transport or that SSL_write(3) will just write to it --
191 it is also possible that SSL_write(3) cannot do any useful work until
192 there is data to read, or that SSL_read(3) cannot do anything until it
193 is possible to send data.  One reason for this is that the peer may
194 request a new TLS/SSL handshake at any time during the protocol,
195 requiring a bi-directional message exchange; both SSL_read(3) and
196 SSL_write(3) will try to continue any pending handshake.
197
198 * Why doesn't my server application receive a client certificate?
199
200 Due to the TLS protocol definition, a client will only send a certificate,
201 if explicitly asked by the server. Use the SSL_VERIFY_PEER flag of the
202 SSL_CTX_set_verify(3) function to enable the use of client certificates.
203
204 * I think I've detected a memory leak, is this a bug?
205
206 In most cases the cause of an apparent memory leak is an OpenSSL internal table
207 that is allocated when an application starts up. Since such tables do not grow
208 in size over time they are harmless.
209
210 These internal tables can be freed up when an application closes using various
211 functions.  Currently these include following:
212
213 Thread-local cleanup functions include ERR_remove_state(3).
214 Application-global cleanup functions that are aware of usage (and therefore
215 thread-safe) include ENGINE_cleanup(3)
216 and CONF_modules_unload(3).
217 "Brutal" (thread-unsafe) Application-global cleanup functions include:
218 ERR_free_strings(3),
219 EVP_cleanup(3)
220 and CRYPTO_cleanup_all_ex_data(3).
221
222 * Why doesn't a memory BIO work when a file does?
223
224 This can occur in several cases for example reading an S/MIME email message.
225 The reason is that a memory BIO can do one of two things when all the data
226 has been read from it.
227
228 The default behaviour is to indicate that no more data is available and that
229 the call should be retried, this is to allow the application to fill up the BIO
230 again if necessary.
231
232 Alternatively it can indicate that no more data is available and that EOF has
233 been reached.
234
235 If a memory BIO is to behave in the same way as a file this second behaviour
236 is needed. This must be done by calling:
237
238 <PRE>
239     BIO_set_mem_eof_return(bio, 0);
240 </PRE>
241
242 See the manual pages for more details.
243
244 * Where are the declarations and implementations of d2i_X509(3) etc?
245
246 These are defined and implemented by macros of the form:
247
248 <PRE>
249     DECLARE_ASN1_FUNCTIONS(X509) and
250     IMPLEMENT_ASN1_FUNCTIONS(X509)
251 </PRE>
252
253 The implementation passes an ASN1 "template" defining the structure into an
254 ASN1 interpreter using generalised functions such as ASN1_item_d2i(3).
255
256 * When debugging I observe SIGILL during OpenSSL initialization: why?
257
258 OpenSSL adapts to processor it executes on and for this reason has to
259 query its capabilities. Unfortunately on some processors the only way
260 to achieve this for non-privileged code is to attempt instructions
261 that can cause Illegal Instruction exceptions. The initialization
262 procedure is coded to handle these exceptions to manipulate corresponding
263 bits in capabilities vector. This normally appears transparent, except
264 when you execute it under debugger, which stops prior delivering signal
265 to handler. Simply resuming execution does the trick, but when debugging
266 a lot it might feel counterproductive. Two options. Either set explicit
267 capability environment variable in order to bypass the capability query
268 (see corresponding crypto/*cap.c for details). Or configure debugger not
269 to stop upon SIGILL exception, e.g. in gdb case add 'handle SIGILL nostop'
270 to your .gdbinit.