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