File Coverage

blib/lib/AnyEvent/TLS.pm
Criterion Covered Total %
statement 95 174 54.6
branch 40 140 28.5
condition 13 72 18.0
subroutine 11 23 47.8
pod 6 8 75.0
total 165 417 39.5


line stmt bran cond sub pod time code
1             package AnyEvent::TLS;
2              
3 1     1   593 use Carp qw(croak);
  1         2  
  1         88  
4 1     1   8 use Scalar::Util ();
  1         2  
  1         18  
5              
6 1     1   4 use AnyEvent (); BEGIN { AnyEvent::common_sense }
  1     1   2  
  1         17  
  1         4  
7 1     1   5 use AnyEvent::Util ();
  1         1  
  1         29  
8              
9 1     1   6 use Net::SSLeay;
  1         1  
  1         470  
10              
11             =head1 NAME
12              
13             AnyEvent::TLS - SSLv2/SSLv3/TLSv1 contexts for use in AnyEvent::Handle
14              
15             =cut
16              
17             our $VERSION = $AnyEvent::VERSION;
18              
19             =head1 SYNOPSIS
20              
21             # via AnyEvent::Handle
22              
23             use AnyEvent;
24             use AnyEvent::Handle;
25             use AnyEvent::Socket;
26              
27             # simple https-client
28             my $handle = new AnyEvent::Handle
29             connect => [$host, $port],
30             tls => "connect",
31             tls_ctx => { verify => 1, verify_peername => "https" },
32             ...
33              
34             # simple ssl-server
35             tcp_server undef, $port, sub {
36             my ($fh) = @_;
37              
38             my $handle = new AnyEvent::Handle
39             fh => $fh,
40             tls => "accept",
41             tls_ctx => { cert_file => "my-server-keycert.pem" },
42             ...
43              
44             # directly
45              
46             my $tls = new AnyEvent::TLS
47             verify => 1,
48             verify_peername => "ldaps",
49             ca_file => "/etc/cacertificates.pem";
50              
51             =head1 DESCRIPTION
52              
53             This module is a helper module that implements TLS/SSL (Transport Layer
54             Security/Secure Sockets Layer) contexts. A TLS context is a common set of
55             configuration values for use in establishing TLS connections.
56              
57             For some quick facts about SSL/TLS, see the section of the same name near
58             the end of the document.
59              
60             A single TLS context can be used for any number of TLS connections that
61             wish to use the same certificates, policies etc.
62              
63             Note that this module is inherently tied to L, as this
64             library is used to implement it. Since that perl module is rather ugly,
65             and OpenSSL has a rather ugly license, AnyEvent might switch TLS providers
66             at some future point, at which this API will change dramatically, at least
67             in the Net::SSLeay-specific parts (most constructor arguments should still
68             work, though).
69              
70             Although this module does not require a specific version of Net::SSLeay,
71             many features will gradually stop working, or bugs will be introduced with
72             old versions (verification might succeed when it shouldn't - this is a
73             real security issue). Version 1.35 is recommended, 1.33 should work, 1.32
74             might, and older versions are yours to keep.
75              
76             =head1 USAGE EXAMPLES
77              
78             See the L manpage, NONFREQUENTLY ASKED QUESTIONS, for
79             some actual usage examples.
80              
81             =head1 PUBLIC METHODS AND FUNCTIONS
82              
83             =over 4
84              
85             =cut
86              
87             our $REF_IDX; # our session ex_data id
88              
89             # create temp file, populate it, and return a guard and filename
90             sub _tmpfile($) {
91 0 0   0   0 require File::Temp unless $File::Temp::VERSION;
92              
93             # File::Temp opens the file with mode 0600
94 0         0 my ($fh, $path) = File::Temp::tempfile ("aetlsXXXXXXXXX", TMPDIR => 1, EXLOCK => 0);
95 0     0   0 my $guard = AnyEvent::Util::guard { unlink $path };
  0         0  
96              
97 0         0 syswrite $fh, $_[0];
98 0         0 close $fh;
99              
100 0         0 ($path, $guard)
101             }
102              
103             our %DH_PARAMS = (
104             # These are the DH parameters from "Assigned Number for SKIP Protocols"
105             # (http://www.skip-vpn.org/spec/numbers.html).
106             # (or http://web.archive.org/web/20011212141438/http://www.skip-vpn.org/spec/numbers.html#params)
107             # See there for how they were generated.
108             # Note that g might not be a generator,
109             # but this is not a problem since p is a safe prime.
110             skip512 => "MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak|XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC",
111             skip1024 => "MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY|jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6|ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC",
112             skip2048 => "MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV|89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50|T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb|zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX|Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT|CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==",
113             skip4096 => "MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ|l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt|Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS|Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98|VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc|alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM|sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9|ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte|OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH|AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL|KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=",
114              
115             # generated on a linux desktop with openssl using /dev/urandom - entropy_avail was >= 3600 each time
116             # the 8192 bit key took 25 hours to generate :/
117             schmorp1024 => "MIGHAoGBAN+GjqAhNxLesSuGfDzYe6HdexXtHuxe85umshfPHfnmLSkGWl/FE27+|v+50mwY5XaNnCmo1VvGju4iTKxWoZTGgslUSc8KX197XWAXIpab8ESyg442if9Kr|vSOuu0fopwvvTOgHK8mkEWI4joU5G4/MQy+pnC5NIEVBP4HtGiTrAgEC",
118             schmorp1539 => "MIHHAoHBByJzpVGUsXysX8w/+uuXRUCL9exhAixoHkaJU5lf4noJUtp9F0yr/5rb|hF8M9mSZJ+RlPyB+Zt37GPp1WQDO1+/2yZJX9kHE3+h5JCRoR8PKc2G+ts9jhM7r|CnTQ0z0b6s12Pusf+UhQPwLust4JAYE/LPuTK8yFiVx5L2a+aZhGMVlYN/12SEtY|jRl3lGXdZj9g8E2PzTQbA9CGy5dGIvz/ENTzTVleKuQ+80bzpVEPjZL9tv43Zc+l|MFLzxuE5uwIBAg==",
119             schmorp2048 => "MIIBCAKCAQEAhR5Fn9h3Tgnc+q4o3CMkZtre3lLUyDT+1bf3aiVOt22JdDQndZLc|FeKz8AqliB3UIgNExc6oDtuG4znKPgklfOnHv/a9tl1AYQbV+QFM/E0jYl6oG8tF|Epgxezt1GCivvtu64ql0s213wr64QffNMt3hva8lNqK1PXfqp13PzzLzAVsfghrv|fMAX7/bYm1T5fAJdcah6FeZkKof+mqbs8HtRjfvrUF2npEM2WdupFu190vcwABnN|TTJheXCWv2BF2f9EEr61q3OUhSNWIThtZP+NKe2bACm1PebT0drAcaxKoMz9LjKr|y5onGs0TOuQ7JmhtZL45Zr4LwBcyTucLUwIBAg==",
120             schmorp4096 => "MIICCAKCAgEA5WwA5lQg09YRYqc/JILCd2AfBmYBkF19wmCEJB8G3JhTxv8EGvYk|xyP2ecKVUvHTG8Xw/qpW8nRqzPIyV8QRf6YFYSf33Qnx2xYhcnqOumU3nfC0SNOL|/w2q1BA9BbHtW4574P+6hOQx9ftRtbtZ2HPKBMRcAKGjpYZiKopv0+UAM4NpEC2p|bfajp7pyVLeb/Aqm/oWP3L63wPlY1SDp+XRzrOAKB+/uLGqEwV0bBaxxGL29BpOp|O2z1ALGXiDCcLs9WTn9WqUhWDzUN6fahm53rd7zxwpFCb6K2YhaK0peG95jzSUJ8|aoL0KgWuC6v5+gPJHRu0HrQIdfAdN4VchqYOKE46uNNkQl8VJGu4RjYB7lFBpRwO|g2HCsGMo2X7BRmA1st66fh+JOd1smXMZG/2ozTOooL+ixcx4spNneg4aQerWl5cb|nWXKtPCp8yPzt/zoNzL3Fon2Ses3sNgMos0M/ZbnigScDxz84Ms6V/X8Z0L4m/qX|mL42dP40tgvmgqi6BdsBzcIWeHlEcIhmGcsEBxxKEg7gjb0OjjvatpUCJhmRrGjJ|LtMkBR68qr42OBMN/PBB4KPOWNUqTauXZajfCwYdbpvV24ZhtkcRdw1zisyARBSh|aTKW/GV8iLsUzlYN27LgVEwMwnWQaoecW6eOTNKGUURC3In6XZSvVzsCAQI=",
121             schmorp8192 => "MIIECAKCBAEA/SAEbRSSLenVxoInHiltm/ztSwehGOhOiUKfzDcKlRBZHlCC9jBl|S/aeklM6Ucg8E6J2bnfoh6CAdnE/glQOn6CifhZr8X/rnlL9/eP+r9m+aiAw4l0D|MBd8BondbEqwTZthMmLtx0SslnevsFAZ1Cj8WgmUNaSPOukvJ1N7aQ98U+E99Pw3|VG8ANBydXqLqW2sogS8FtZoMbVywcQuaGmC7M6i3Akxe3CCSIpR/JkEZIytREBSC|CH+x3oW/w+wHzq3w8DGB9hqz1iMXqDMiPIMSdXC0DaIPokLnd7X8u6N14yCAco2h|P0gspD3J8pS2FpUY8ZTVjzbVCjhNNmTryBZAxHSWBuX4xYcCHUtfGlUe/IGLSVE1|xIdFpZUfvlvAJjVq0/TtDMg3r2JSXrhQVlr8MPJwSApDVr5kOBHT/uABio4z+5yR|PAvundznfyo9GGAWhIA36GQqsxSQfoRTjWssFoR/cu+9aomRwwOLkvObu8nCVVLH|nLdKDk5cIR0TvNs9HZ6ZmkzL7ah7cPzEKl7U6eE6yZLVYMNecnPLS6PSAIG4gxcq|CVQrrZjQLfTDrJn0OGgpShX85RaDsuiRtp2bpDZ23YDqdwr4wRjvIargjqc2zcF+|jIb7dUS6ci7bVG/CGOQUuiMWAiXZ3a1f343SMf9A05/sf1xwnMeco6STBLZ3X+PA|4urU+grtpWaFtS/fPD2ILn8nrJ3WuSKKUeSnVM46mmJQsOkyn7z8l3jNLB17GYKo|qc+0UuU/2PM9qtZdZElSM/ACLV2vdCuaibop4B9UIP9z3F8kfZ72+zKxpGiE+Bo1|x8SfG8FQw90mYIx+qZzJ8MCvc2wh+l4wDX5KxrhwvcouE2tHQlwfDgv/DiIXp173|hAmUCV0+bPRW8IIJvBODdAWtJe9hNwxj1FFYmPA7l4wa3gXV4I6tb+iO1MbwVjZ/|116tD5MdCo3JuSisgPYCHfkQccwEO0FHEuBbmfN+fQimQ8H0dePP8XctwbkplsB+|aLT5hYKmva/j9smEswgyHglPwc3WvZ+2DgKk7A7DHi7a2gDwCRQlHaXtNWx3992R|dfNgkSeB1CvGSQoo95WpC9ZoqGmcSlVqdetDU8iglPmfYTKO8aIPA6TuTQ/lQ0IW|90LQmqP23FwnNFiyqX8+rztLq4KVkTyeHIQwig6vFxgD8N+SbZCW2PPiB72TVF2U|WePU8MRTv1OIGBUBajF49k28HnZPSGlILHtFEkYkbPvomcE5ENnoejwzjktOTS5d|/R3SIOvCauOzadtzwTYOXT78ORaR1KI1cm8DzkkwJTd/Rrk07Q5vnvnSJQMwFUeH|PwJIgWBQf/GZ/OsDHmkbYR2ZWDClbKw2mwIBAg==",
122             );
123              
124             =item $tls = new AnyEvent::TLS key => value...
125              
126             The constructor supports these arguments (all as key => value pairs).
127              
128             =over 4
129              
130             =item method => "SSLv2" | "SSLv3" | "TLSv1" | "TLSv1_1" | "TLSv1_2" | "any"
131              
132             The protocol parser to use. C, C, C, C
133             and C will use a parser for those protocols only (so will
134             I accept or create connections with/to other protocol versions),
135             while C (the default) uses a parser capable of all three
136             protocols.
137              
138             The default is to use C<"any"> but disable SSLv2. This has the effect of
139             sending a SSLv2 hello, indicating the support for SSLv3 and TLSv1, but not
140             actually negotiating an (insecure) SSLv2 connection.
141              
142             Specifying a specific version is almost always wrong to use for a server
143             speaking to a wide variety of clients (e.g. web browsers), and often wrong
144             for a client. If you only want to allow a specific protocol version, use
145             the C, C, C, C or C arguments instead.
146              
147             For new services it is usually a good idea to enforce a C method
148             from the beginning.
149              
150             C and C require L >= 1.55 and OpenSSL
151             >= 1.0.1. Check the L and OpenSSL documentations for more
152             details.
153              
154             =item sslv2 => $enabled
155              
156             Enable or disable SSLv2 (normally I).
157              
158             =item sslv3 => $enabled
159              
160             Enable or disable SSLv3 (normally I).
161              
162             =item tlsv1 => $enabled
163              
164             Enable or disable TLSv1 (normally I).
165              
166             =item tlsv1_1 => $enabled
167              
168             Enable or disable TLSv1_1 (normally I).
169              
170             This requires L >= 1.55 and OpenSSL >= 1.0.1. Check the
171             L and OpenSSL documentations for more details.
172              
173             =item tlsv1_2 => $enabled
174              
175             Enable or disable TLSv1_2 (normally I).
176              
177             This requires L >= 1.55 and OpenSSL >= 1.0.1. Check the
178             L and OpenSSL documentations for more details.
179              
180             =item verify => $enable
181              
182             Enable or disable peer certificate checking (default is I, which
183             is I).
184              
185             This is the "master switch" for all verify-related parameters and
186             functions.
187              
188             If it is disabled, then no peer certificate verification will be done
189             - the connection will be encrypted, but the peer certificate won't be
190             verified against any known CAs, or whether it is still valid or not. No
191             peername verification or custom verification will be done either.
192              
193             If enabled, then the peer certificate (required in client mode, optional
194             in server mode, see C) will be checked against
195             its CA certificate chain - that means there must be a signing chain from
196             the peer certificate to any of the CA certificates you trust locally, as
197             specified by the C and/or C and/or C parameters
198             (or the system default CA repository, if all of those parameters are
199             missing - see also the L manpage for the description of
200             PERL_ANYEVENT_CA_FILE).
201              
202             Other basic checks, such as checking the validity period, will also be
203             done, as well as optional peername/hostname/common name verification
204             C.
205              
206             An optional C callback can also be set, which will be invoked
207             with the verification results, and which can override the decision.
208              
209             =item verify_require_client_cert => $enable
210              
211             Enable or disable mandatory client certificates (default is
212             I). When this mode is enabled, then a client certificate will be
213             required in server mode (a server certificate is mandatory, so in client
214             mode, this switch has no effect).
215              
216             =item verify_peername => $scheme | $callback->($tls, $cert, $peername)
217              
218             TLS only protects the data that is sent - it cannot automatically verify
219             that you are really talking to the right peer. The reason is that
220             certificates contain a "common name" (and a set of possible alternative
221             "names") that need to be checked against the peername (usually, but not
222             always, the DNS name of the server) in a protocol-dependent way.
223              
224             This can be implemented by specifying a callback that has to verify that
225             the actual C<$peername> matches the given certificate in C<$cert>.
226              
227             Since this can be rather hard to implement, AnyEvent::TLS offers a variety
228             of predefined "schemes" (lifted from L) that are named
229             like the protocols that use them:
230              
231             =over 4
232              
233             =item ldap (rfc4513), pop3,imap,acap (rfc2995), nntp (rfc4642)
234              
235             Simple wildcards in subjectAltNames are possible, e.g. *.example.org
236             matches www.example.org but not lala.www.example.org. If nothing from
237             subjectAltNames matches, it checks against the common name, but there are
238             no wildcards allowed.
239              
240             =item http (rfc2818)
241              
242             Extended wildcards in subjectAltNames are possible, e.g. *.example.org or
243             even www*.example.org. Wildcards in the common name are not allowed. The
244             common name will be only checked if no host names are given in
245             subjectAltNames.
246              
247             =item smtp (rfc3207)
248              
249             This RFC isn't very useful in determining how to do verification so it
250             just assumes that subjectAltNames are possible, but no wildcards are
251             possible anywhere.
252              
253             =item [$wildcards_in_alt, $wildcards_in_cn, $check_cn]
254              
255             You can also specify a scheme yourself by using an array reference with
256             three integers.
257              
258             C<$wildcards_in_alt> and C<$wildcards_in_cn> specify whether and where
259             wildcards (C<*>) are allowed in subjectAltNames and the common name,
260             respectively. C<0> means no wildcards are allowed, C<1> means they
261             are allowed only as the first component (C<*.example.org>), and C<2>
262             means they can be used anywhere (C), except that very
263             dangerous matches will not be allowed (C<*.org> or C<*>).
264              
265             C<$check_cn> specifies if and how the common name field is checked: C<0>
266             means it will be completely ignored, C<1> means it will only be used if
267             no host names have been found in the subjectAltNames, and C<2> means the
268             common name will always be checked against the peername.
269              
270             =back
271              
272             You can specify either the name of the parent protocol (recommended,
273             e.g. C, C), the protocol name as usually used in URIs
274             (e.g. C, C) or the RFC (not recommended, e.g. C,
275             C).
276              
277             This verification will only be done when verification is enabled (C<<
278             verify => 1 >>).
279              
280             =item verify_cb => $callback->($tls, $ref, $cn, $depth, $preverify_ok, $x509_store_ctx, $cert)
281              
282             Provide a custom peer verification callback used by TLS sessions,
283             which is called with the result of any other verification (C,
284             C).
285              
286             This callback will only be called when verification is enabled (C<< verify
287             => 1 >>).
288              
289             C<$tls> is the C object associated with the session,
290             while C<$ref> is whatever the user associated with the session (usually
291             an L object when used by AnyEvent::Handle).
292              
293             C<$depth> is the current verification depth - C<$depth = 0> means the
294             certificate to verify is the peer certificate, higher levels are its CA
295             certificate and so on. In most cases, you can just return C<$preverify_ok>
296             if the C<$depth> is non-zero:
297              
298             verify_cb => sub {
299             my ($tls, $ref, $cn, $depth, $preverify_ok, $x509_store_ctx, $cert) = @_;
300              
301             return $preverify_ok
302             if $depth;
303              
304             # more verification
305             },
306              
307             C<$preverify_ok> is true iff the basic verification of the certificates
308             was successful (a valid CA chain must exist, the certificate has passed
309             basic validity checks, peername verification succeeded).
310              
311             C<$x509_store_ctx> is the Net::SSLeay::X509_CTX> object.
312              
313             C<$cert> is the C object representing the
314             peer certificate, or zero if there was an error. You can call
315             C to get a nice user-readable string to
316             identify the certificate.
317              
318             The callback must return either C<0> to indicate failure, or C<1> to
319             indicate success.
320              
321             =item verify_client_once => $enable
322              
323             Enable or disable skipping the client certificate verification on
324             renegotiations (default is I, the certificate will always be
325             checked). Only makes sense in server mode.
326              
327             =item ca_file => $path
328              
329             If this parameter is specified and non-empty, it will be the path to a
330             file with (server) CA certificates in PEM format that will be loaded. Each
331             certificate will look like:
332              
333             -----BEGIN CERTIFICATE-----
334             ... (CA certificate in base64 encoding) ...
335             -----END CERTIFICATE-----
336              
337             You have to enable verify mode (C<< verify => 1 >>) for this parameter to
338             have any effect.
339              
340             =item ca_path => $path
341              
342             If this parameter is specified and non-empty, it will be
343             the path to a directory with hashed CA certificate files in
344             PEM format. When the ca certificate is being verified, the
345             certificate will be hashed and looked up in that directory (see
346             L for
347             details)
348              
349             The certificates specified via C take precedence over the ones
350             found in C.
351              
352             You have to enable verify mode (C<< verify => 1 >>) for this parameter to
353             have any effect.
354              
355             =item ca_cert => $string
356              
357             In addition or instead of using C and/or C, you can
358             also use C to directly specify the CA certificates (there can be
359             multiple) in PEM format, in a string.
360              
361             =item check_crl => $enable
362              
363             Enable or disable certificate revocation list checking. If enabled, then
364             peer certificates will be checked against a list of revoked certificates
365             issued by the CA. The revocation lists will be expected in the C
366             directory.
367              
368             certificate verification will fail if this is enabled but no revocation
369             list was found.
370              
371             This requires OpenSSL >= 0.9.7b. Check the OpenSSL documentation for more
372             details.
373              
374             =item key_file => $path
375              
376             Path to the local private key file in PEM format (might be a combined
377             certificate/private key file).
378              
379             The local certificate is used to authenticate against the peer - servers
380             mandatorily need a certificate and key, clients can use a certificate and
381             key optionally to authenticate, e.g. for log-in purposes.
382              
383             The key in the file should look similar this:
384              
385             -----BEGIN RSA PRIVATE KEY-----
386             ...header data
387             ... (key data in base64 encoding) ...
388             -----END RSA PRIVATE KEY-----
389              
390             =item key => $string
391              
392             The private key string in PEM format (see C, only one of
393             C or C can be specified).
394              
395             The idea behind being able to specify a string is to avoid blocking in
396             I/O. Unfortunately, Net::SSLeay fails to implement any interface to the
397             needed OpenSSL functionality, this is currently implemented by writing to
398             a temporary file.
399              
400             =item cert_file => $path
401              
402             The path to the local certificate file in PEM format (might be a combined
403             certificate/private key file, including chained certificates).
404              
405             The local certificate (and key) are used to authenticate against the
406             peer - servers mandatorily need a certificate and key, clients can use
407             certificate and key optionally to authenticate, e.g. for log-in purposes.
408              
409             The certificate in the file should look like this:
410              
411             -----BEGIN CERTIFICATE-----
412             ... (certificate in base64 encoding) ...
413             -----END CERTIFICATE-----
414              
415             If the certificate file or string contain both the certificate and
416             private key, then there is no need to specify a separate C or
417             C.
418              
419             Additional signing certifiates to send to the peer (in SSLv3 and newer)
420             can be specified by appending them to the certificate proper: the order
421             must be from issuer certificate over any intermediate CA certificates to
422             the root CA.
423              
424             So the recommended ordering for a combined key/cert/chain file, specified
425             via C or C looks like this:
426              
427             certificate private key
428             client/server certificate
429             ca 1, signing client/server certficate
430             ca 2, signing ca 1
431             ...
432              
433             =item cert => $string
434              
435             The local certificate in PEM format (might be a combined
436             certificate/private key file). See C.
437              
438             The idea behind being able to specify a string is to avoid blocking in
439             I/O. Unfortunately, Net::SSLeay fails to implement any interface to the
440             needed OpenSSL functionality, this is currently implemented by writing to
441             a temporary file.
442              
443             =item cert_password => $string | $callback->($tls)
444              
445             The certificate password - if the certificate is password-protected, then
446             you can specify its password here.
447              
448             Instead of providing a password directly (which is not so recommended),
449             you can also provide a password-query callback. The callback will be
450             called whenever a password is required to decode a local certificate, and
451             is supposed to return the password.
452              
453             =item dh_file => $path
454              
455             Path to a file containing Diffie-Hellman parameters in PEM format, for
456             use in servers. See also C on how to specify them directly, or use a
457             pre-generated set.
458              
459             Diffie-Hellman key exchange generates temporary encryption keys that
460             are not transferred over the connection, which means that even if the
461             certificate key(s) are made public at a later time and a full dump of the
462             connection exists, the key still cannot be deduced.
463              
464             These ciphers are only available with SSLv3 and later (which is the
465             default with AnyEvent::TLS), and are only used in server/accept
466             mode. Anonymous DH protocols are usually disabled by default, and usually
467             not even compiled into the underlying library, as they provide no direct
468             protection against man-in-the-middle attacks. The same is true for the
469             common practise of self-signed certificates that you have to accept first,
470             of course.
471              
472             =item dh => $string
473              
474             Specify the Diffie-Hellman parameters in PEM format directly as a string
475             (see C), the default is C unless C was
476             specified.
477              
478             AnyEvent::TLS supports supports a number of precomputed DH parameters,
479             since computing them is expensive. They are:
480              
481             # from "Assigned Number for SKIP Protocols"
482             skip512, skip1024, skip2048, skip4096
483              
484             # from schmorp
485             schmorp1024, schmorp1539, schmorp2048, schmorp4096, schmorp8192
486              
487             The default was chosen as a trade-off between security and speed, and
488             should be secure for a few years. It is said that 2048 bit DH parameters
489             are safe till 2030, and DH parameters shorter than 900 bits are totally
490             insecure.
491              
492             To disable DH protocols completely, specify C as C parameter.
493              
494             =item dh_single_use => $enable
495              
496             Enables or disables "use only once" mode when using Diffie-Hellman key
497             exchange. When enabled (default), each time a new key is exchanged a new
498             Diffie-Hellman key is generated, which improves security as each key is
499             only used once. When disabled, the key will be created as soon as the
500             AnyEvent::TLS object is created and will be reused.
501              
502             All the DH parameters supplied with AnyEvent::TLS should be safe with
503             C switched off, but YMMV.
504              
505             =item cipher_list => $string
506              
507             The list of ciphers to use, as a string (example:
508             C). The format
509             of this string and its default value is documented at
510             L.
511              
512             =item session_ticket => $enable
513              
514             Enables or disables RC5077 support (Session Resumption without Server-Side
515             State). The default is disabled for clients, as many (buggy) TLS/SSL
516             servers choke on it, but enabled for servers.
517              
518             When enabled and supported by the server, a session ticket will be
519             provided to the client, which allows fast resuming of connections.
520              
521             =item prepare => $coderef->($tls)
522              
523             If this argument is present, then it will be called with the new
524             AnyEvent::TLS object after any other initialisation has bee done, in case
525             you wish to fine-tune something...
526              
527             =cut
528              
529             #=item trust => $trust
530             #
531             #Sets the expected (root) certificate use on this context, i.e. what
532             #certificates to trust. The default is C, and the following strings
533             #are supported:
534             #
535             # compat any certifictae will do
536             # ssl_client only trust client certificates
537             # ssl_server only trust server certificates
538             # email only trust e-mail certificates
539             # object_sign only trust signing (CA) certificates
540             # ocsp_sign only trust ocsp signing certs
541             # ocsp_request only trust ocsp request certs
542              
543             # purpose?
544              
545             #TODO
546             # verify_depth?
547             # reuse_ctx
548             # session_cache_size
549             # session_cache
550              
551             #=item debug => $level
552             #
553             #Enable or disable sending debugging output to STDERR. This is, as
554             #the name says, mostly for debugging. The default is taken from the
555             #C environment variable.
556             #
557             #=cut
558              
559             =back
560              
561             =cut
562              
563             sub init ();
564              
565             #our %X509_TRUST = (
566             # compat => 1,
567             # ssl_client => 2,
568             # ssl_server => 3,
569             # email => 4,
570             # object_sign => 5,
571             # ocsp_sign => 6,
572             # ocsp_request => 7,
573             #);
574              
575             BEGIN {
576 1   33 1   15 eval 'sub _check_tls_gt_1 (){'
577             . (($Net::SSLeay::VERSION >= 1.55 && Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x1000100f) * 1)
578             . '}';
579              
580             # as of this writing, Net::SSLeay (1.85-2) has not been ported to OpenSSL 1.1,
581             # but many distributions and users compile it against openssl 1.1, leading to
582             # many symbols not being defined because they are now enums instead of macros
583             # and have different prefixes.
584             # The only one we use is SSL_ST_OK, or TLS_ST_OK, which should be available
585             # as Net::SSLeay::ST_OK. If it is not callable, we define it to be 1, which
586             # hopefully will not change.
587             eval 'Net::SSLeay::ST_OK (); 1'
588 1 50       198 or *Net::SSLeay::ST_OK = sub () { 1 };
589             }
590              
591             our %SSL_METHODS = (
592             any => \&Net::SSLeay::CTX_new,
593             sslv23 => \&Net::SSLeay::CTX_new, # deliberately undocumented
594             sslv2 => \&Net::SSLeay::CTX_v2_new,
595             sslv3 => \&Net::SSLeay::CTX_v3_new,
596             tlsv1 => \&Net::SSLeay::CTX_tlsv1_new,
597             );
598              
599             # Add TLSv1_1 and TLSv1_2 if Net::SSLeay and openssl allow them
600             if (_check_tls_gt_1) {
601             $SSL_METHODS{tlsv1_1} = \&Net::SSLeay::CTX_tlsv1_1_new;
602             $SSL_METHODS{tlsv1_2} = \&Net::SSLeay::CTX_tlsv1_2_new;
603             } else {
604             for my $method (qw(tlsv1_1 tlsv1_2)) {
605             $SSL_METHODS{$method} = sub { croak "AnyEvent::TLS method '$method' requires openssl v1.0.1 and Net::SSLeay 1.55 or higher" };
606             }
607             }
608              
609             sub new {
610 1     1 1 94 my ($class, %arg) = @_;
611              
612 1 50       8 init unless $REF_IDX;
613              
614 1   50     17 my $method = lc $arg{method} || "any";
615              
616 1   33     169 my $ctx = ($SSL_METHODS{$method}
617             || croak "'$method' is not a valid AnyEvent::TLS method (must be one of @{[ sort keys %SSL_METHODS ]})")->();
618              
619 1         10 my $self = bless { ctx => $ctx }, $class; # to make sure it's destroyed if we croak
620              
621 1         8 my $op = Net::SSLeay::OP_ALL ();
622              
623 1 50       103 $op |= Net::SSLeay::OP_NO_SSLv2 () unless $arg{sslv2};
624 1 50 33     95 $op |= Net::SSLeay::OP_NO_SSLv3 () if exists $arg{sslv3} && !$arg{sslv3};
625 1 50 33     5 $op |= Net::SSLeay::OP_NO_TLSv1 () if exists $arg{tlsv1} && !$arg{tlsv1};
626 1 0 33     5 $op |= Net::SSLeay::OP_NO_TLSv1_1 () if exists $arg{tlsv1_1} && !$arg{tlsv1_1} && _check_tls_gt_1;
      50        
627 1 0 33     5 $op |= Net::SSLeay::OP_NO_TLSv1_2 () if exists $arg{tlsv1_2} && !$arg{tlsv1_2} && _check_tls_gt_1;
      50        
628 1 50 33     8 $op |= Net::SSLeay::OP_SINGLE_DH_USE () if !exists $arg{dh_single_use} || $arg{dh_single_use};
629              
630 1         92 Net::SSLeay::CTX_set_options ($ctx, $op);
631              
632             Net::SSLeay::CTX_set_cipher_list ($ctx, $arg{cipher_list})
633             or croak "'$arg{cipher_list}' was not accepted as a valid cipher list by AnyEvent::TLS"
634 1 50 0     4 if exists $arg{cipher_list};
635              
636 1         3 my ($dh_bio, $dh_file);
637              
638 1 50       4 if (exists $arg{dh_file}) {
639 0         0 $dh_file = $arg{dh_file};
640              
641 0 0       0 $dh_bio = Net::SSLeay::BIO_new_file ($dh_file, "r")
642             or croak "$dh_file: failed to open DH parameter file: $!";
643             } else {
644 1 50       5 $arg{dh} = "schmorp1539" unless exists $arg{dh};
645              
646 1 50       4 if (defined $arg{dh}) {
647 1         2 $dh_file = "dh string";
648              
649 1 50       6 if ($arg{dh} =~ /^\w+$/) {
650 1         4 $dh_file = "dh params $arg{dh}";
651             $arg{dh} = "-----BEGIN DH PARAMETERS-----\n"
652 1         6 . $DH_PARAMS{$arg{dh}} . "\n"
653             . "-----END DH PARAMETERS-----";
654 1         14 $arg{dh} =~ s/\|/\n/g;
655             }
656              
657 1         11 $dh_bio = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
658 1         6 Net::SSLeay::BIO_write ($dh_bio, $arg{dh});
659             }
660             }
661              
662 1 50       4 if ($dh_bio) {
663 1         36 my $dh = Net::SSLeay::PEM_read_bio_DHparams ($dh_bio);
664 1         6 Net::SSLeay::BIO_free ($dh_bio);
665 1 50       3 $dh or croak "$dh_file: failed to parse DH parameters - not PEM format?";
666 1         7 my $rv = Net::SSLeay::CTX_set_tmp_dh ($ctx, $dh);
667 1         5 Net::SSLeay::DH_free ($dh);
668 1 50       4 $rv or croak "$dh_file: failed to set DH parameters";
669             }
670              
671 1 50       5 if ($arg{verify}) {
672 0         0 $self->{verify_mode} = Net::SSLeay::VERIFY_PEER ();
673              
674             $self->{verify_mode} |= Net::SSLeay::VERIFY_FAIL_IF_NO_PEER_CERT ()
675 0 0       0 if $arg{verify_require_client_cert};
676              
677             $self->{verify_mode} |= Net::SSLeay::VERIFY_CLIENT_ONCE ()
678 0 0       0 if $arg{verify_client_once};
679              
680             } else {
681 1         7 $self->{verify_mode} = Net::SSLeay::VERIFY_NONE ();
682             }
683              
684             $self->{verify_peername} = $arg{verify_peername}
685 1 50       91 if exists $arg{verify_peername};
686              
687             $self->{verify_cb} = $arg{verify_cb}
688 1 50       4 if exists $arg{verify_cb};
689              
690             $self->{session_ticket} = $arg{session_ticket}
691 1 50       3 if exists $arg{session_ticket};
692              
693             $self->{debug} = $ENV{PERL_ANYEVENT_TLS_DEBUG}
694 1 50       4 if length $ENV{PERL_ANYEVENT_TLS_DEBUG};
695              
696             $self->{debug} = $arg{debug}
697 1 50       9 if exists $arg{debug};
698              
699 1         3 my $pw = $arg{cert_password};
700 1 50   0   12 Net::SSLeay::CTX_set_default_passwd_cb ($ctx, ref $pw ? $pw : sub { $pw });
  0         0  
701              
702 1 50       4 if ($self->{verify_mode}) {
703 0 0 0     0 if (exists $arg{ca_file} or exists $arg{ca_path} or exists $arg{ca_cert}) {
    0 0        
      0        
704             # either specified: use them
705 0 0       0 if (exists $arg{ca_cert}) {
706 0         0 my ($ca_file, $g1) = _tmpfile delete $arg{ca_cert};
707 0         0 Net::SSLeay::CTX_load_verify_locations ($ctx, $ca_file, undef);
708             }
709 0 0 0     0 if (exists $arg{ca_file} or exists $arg{ca_path}) {
710 0         0 Net::SSLeay::CTX_load_verify_locations ($ctx, $arg{ca_file}, $arg{ca_path});
711             }
712             } elsif (length $ENV{PERL_ANYEVENT_CA_FILE} or length $ENV{PERL_ANYEVENT_CA_PATH}) {
713             Net::SSLeay::CTX_load_verify_locations (
714             $ctx,
715             $ENV{PERL_ANYEVENT_CA_FILE},
716             $ENV{PERL_ANYEVENT_CA_PATH},
717 0         0 );
718             } else {
719             # else fall back to defaults
720 0         0 Net::SSLeay::CTX_set_default_verify_paths ($ctx);
721             }
722             }
723              
724 1 50 33     7 if (exists $arg{cert} or exists $arg{cert_file}) {
725 1         2 my ($g1, $g2);
726              
727 1 50       3 if (exists $arg{cert}) {
728             croak "specifying both cert_file and cert is not allowed"
729 0 0       0 if exists $arg{cert_file};
730              
731 0         0 ($arg{cert_file}, $g1) = _tmpfile delete $arg{cert};
732             }
733              
734 1 50 33     6 if (exists $arg{key} or exists $arg{key_file}) {
735 0 0       0 if (exists $arg{key}) {
736             croak "specifying both key_file and key is not allowed"
737 0 0       0 if exists $arg{key_file};
738 0         0 ($arg{key_file}, $g2) = _tmpfile delete $arg{key};
739             }
740             } else {
741 1         2 $arg{key_file} = $arg{cert_file};
742             }
743              
744             Net::SSLeay::CTX_use_PrivateKey_file
745 1 50       6 ($ctx, $arg{key_file}, Net::SSLeay::FILETYPE_PEM ())
746             or croak "$arg{key_file}: failed to load local private key (key_file or key)";
747              
748             Net::SSLeay::CTX_use_certificate_chain_file ($ctx, $arg{cert_file})
749 1 50       345 or croak "$arg{cert_file}: failed to use local certificate chain (cert_file or cert)";
750             }
751              
752 1 50       6 if ($arg{check_crl}) {
753 0 0       0 Net::SSLeay::OPENSSL_VERSION_NUMBER () >= 0x00090702f
754             or croak "check_crl requires openssl v0.9.7b or higher";
755              
756 0         0 Net::SSLeay::X509_STORE_set_flags (
757             Net::SSLeay::CTX_get_cert_store ($ctx),
758             Net::SSLeay::X509_V_FLAG_CRL_CHECK ());
759             }
760              
761 1         6 Net::SSLeay::CTX_set_read_ahead ($ctx, 1);
762              
763             $arg{prepare}->($self)
764 1 50       3 if $arg{prepare};
765              
766 1         6 $self
767             }
768              
769             =item $tls = new_from_ssleay AnyEvent::TLS $ctx
770              
771             This constructor takes an existing L SSL_CTX object
772             (which is just an integer) and converts it into an C
773             object. This only works because AnyEvent::TLS is currently implemented
774             using Net::SSLeay. As this is such a horrible perl module and OpenSSL has
775             such an annoying license, this might change in the future, in which case
776             this method might vanish.
777              
778             =cut
779              
780             sub new_from_ssleay {
781 0     0 1 0 my ($class, $ctx) = @_;
782              
783 0         0 bless { ctx => $ctx }, $class
784             }
785              
786             =item $ctx = $tls->ctx
787              
788             Returns the actual L object (just an integer).
789              
790             =cut
791              
792             sub ctx {
793             $_[0]{ctx}
794 0     0 1 0 }
795              
796             sub verify_hostname($$$);
797              
798             sub _verify_hostname {
799 0     0   0 my ($self, $cn, $cert) = @_;
800            
801 0 0       0 return 1
802             unless defined $cn;
803              
804             return 1
805 0 0 0     0 unless exists $self->{verify_peername} && "none" ne lc $self->{verify_peername};
806              
807             return $self->{verify_peername}->($self, $cn, $cert)
808 0 0 0     0 if ref $self->{verify_peername} && "ARRAY" ne ref $self->{verify_peername};
809              
810             verify_hostname $cn, $cert, $self->{verify_peername}
811 0         0 }
812              
813             sub verify {
814 0     0 1 0 my ($self, $session, $ref, $cn, $preverify_ok, $x509_store_ctx) = @_;
815              
816 0 0       0 my $cert = $x509_store_ctx
817             ? Net::SSLeay::X509_STORE_CTX_get_current_cert ($x509_store_ctx)
818             : undef;
819 0         0 my $depth = Net::SSLeay::X509_STORE_CTX_get_error_depth ($x509_store_ctx);
820              
821 0 0 0     0 $preverify_ok &&= $self->_verify_hostname ($cn, $cert)
822             unless $depth;
823              
824             $preverify_ok = $self->{verify_cb}->($self, $ref, $cn, $depth, $preverify_ok, $x509_store_ctx, $cert)
825 0 0       0 if $self->{verify_cb};
826              
827 0         0 $preverify_ok
828             }
829              
830             #=item $ssl = $tls->_get_session ($mode[, $ref])
831             #
832             #Creates a new Net::SSLeay::SSL session object, puts it into C<$mode>
833             #(C or C) and optionally associates it with the given
834             #C<$ref>. If C<$mode> is already a C object, then just
835             #associate data with it.
836             #
837             #=cut
838              
839             #our %REF_MAP;
840             our $TLS_SNI_WARNED;
841              
842             sub _get_session($$;$$) {
843 10     10   34 my ($self, $mode, $ref, $cn) = @_;
844              
845 10         16 my $session;
846              
847 10 100       30 if ($mode eq "accept") {
    50          
848 5         64 $session = Net::SSLeay::new ($self->{ctx});
849 5         19 Net::SSLeay::set_accept_state ($session);
850              
851 0         0 Net::SSLeay::set_options ($session, eval { Net::SSLeay::OP_NO_TICKET () })
852 5 50 33     25 unless $self->{session_ticket} || !exists $self->{session_ticket};
853              
854             } elsif ($mode eq "connect") {
855 5         85 $session = Net::SSLeay::new ($self->{ctx});
856              
857 5 50       18 if (defined &Net::SSLeay::set_tlsext_host_name) {
858 5 50       28 Net::SSLeay::set_tlsext_host_name ($session, $cn)
859             if length $cn;
860             } else {
861 0 0       0 AE::log 6 => "TLS SNI not supported by your Net::SSLeay module, connecting without"
862             unless $TLS_SNI_WARNED++;
863             }
864              
865 5         21 Net::SSLeay::set_connect_state ($session);
866              
867 5         93 Net::SSLeay::set_options ($session, eval { Net::SSLeay::OP_NO_TICKET () })
868 5 50       13 unless $self->{session_ticket};
869             } else {
870 0         0 croak "'$mode': unsupported TLS mode (must be either 'connect' or 'accept')"
871             }
872              
873             # # associate data
874             # Net::SSLeay::set_ex_data ($session, $REF_IDX, $ref+0);
875             # Scalar::Util::weaken ($REF_MAP{$ref+0} = $ref)
876             # if ref $ref;
877            
878 10 50       137 if ($self->{debug}) {
879             #d# Net::SSLeay::set_info_callback ($session, 50000);
880             }
881              
882 10 50       29 if ($self->{verify_mode}) {
883 0         0 Scalar::Util::weaken $self;
884 0         0 Scalar::Util::weaken $ref;
885              
886             # we have to provide a dummy callbacks as at least Net::SSLeay <= 1.35
887             # try to call it even if specified as 0 or undef.
888             Net::SSLeay::set_verify
889             $session,
890             $self->{verify_mode},
891 0     0   0 sub { $self->verify ($session, $ref, $cn, @_) };
  0         0  
892             }
893              
894             $session
895 10         31 }
896              
897             sub _put_session($$) {
898 10     10   22 my ($self, $session) = @_;
899              
900             # clear callback, if any
901             # this leaks memoryin Net::SSLeay up to at least 1.35, but there
902             # apparently is no other way.
903 10         67 Net::SSLeay::set_verify $session, 0, undef;
904              
905             # # disassociate data
906             # delete $REF_MAP{Net::SSLeay::get_ex_data ($session, $REF_IDX)};
907              
908 10         683 Net::SSLeay::free ($session);
909             }
910              
911             #sub _ref($) {
912             # $REF_MAP{Net::SSLeay::get_ex_data ($_[0], $REF_IDX)}
913             #}
914              
915             sub DESTROY {
916 0     0   0 my ($self) = @_;
917              
918             # better be safe than sorry with net-ssleay
919 0         0 Net::SSLeay::CTX_set_default_passwd_cb ($self->{ctx});
920              
921 0         0 Net::SSLeay::CTX_free ($self->{ctx});
922             }
923              
924             =item AnyEvent::TLS::init
925              
926             AnyEvent::TLS does on-demand initialisation, and normally there is no need to call an initialise
927             function.
928              
929             As initialisation might take some time (to read e.g. C), this
930             could be annoying in some highly interactive programs. In that case, you can
931             call C to make sure there will be no costly initialisation
932             later. It is harmless to call C multiple times.
933              
934             =cut
935              
936             sub init() {
937 1 50   1 1 4 return if $REF_IDX;
938              
939 1 50       4 AE::log 5 => "Net::SSLeay versions older than 1.33 might malfunction."
940             if $Net::SSLeay::VERSION < 1.33;
941              
942 1         1675 Net::SSLeay::load_error_strings ();
943 1         101 Net::SSLeay::SSLeay_add_ssl_algorithms ();
944 1         12 Net::SSLeay::randomize ();
945              
946 1         865 $REF_IDX = Net::SSLeay::get_ex_new_index (0, 0, 0, 0, 0)
947             until $REF_IDX; # Net::SSLeay uses id #0 for its own stuff without allocating it
948             }
949              
950             =item $certname = AnyEvent::TLS::certname $x509
951              
952             Utility function that returns a user-readable string identifying the X509
953             certificate object.
954              
955             =cut
956              
957             sub certname {
958 0 0   0 1   $_[0]
959             ? Net::SSLeay::X509_NAME_oneline (Net::SSLeay::X509_get_issuer_name ($_[0]))
960             . Net::SSLeay::X509_NAME_oneline (Net::SSLeay::X509_get_subject_name ($_[0]))
961             : undef
962             }
963              
964             our %CN_SCHEME = (
965             # each tuple is [$cn_wildcards, $alt_wildcards, $check_cn]
966             # where *_wildcards is 0 for none allowed, 1 for allowed at beginning and 2 for allowed everywhere
967             # and check_cn is 0 for do not check, 1 for check when no alternate dns names and 2 always
968             # all of this is from IO::Socket::SSL
969              
970             rfc4513 => [0, 1, 2],
971             rfc2818 => [0, 2, 1],
972             rfc3207 => [0, 0, 2], # see IO::Socket::SSL, rfc seems unclear
973             none => [], # do not check
974              
975             ldap => "rfc4513", ldaps => "ldap",
976             http => "rfc2818", https => "http",
977             smtp => "rfc3207", smtps => "smtp",
978              
979             xmpp => "rfc3920", rfc3920 => "http",
980             pop3 => "rfc2595", rfc2595 => "ldap", pop3s => "pop3",
981             imap => "rfc2595", rfc2595 => "ldap", imaps => "imap",
982             acap => "rfc2595", rfc2595 => "ldap",
983             nntp => "rfc4642", rfc4642 => "ldap", nntps => "nntp",
984             ftp => "rfc4217", rfc4217 => "http", ftps => "ftp" ,
985             );
986              
987             sub match_cn($$$) {
988 0     0 0   my ($name, $cn, $type) = @_;
989              
990             # remove leading and trailing garbage
991 0           for ($name, $cn) {
992 0           s/[\x00-\x1f]+$//;
993 0           s/^[\x00-\x1f]+//;
994             }
995              
996 0           my $pattern;
997              
998             ### IMPORTANT!
999             # we accept only a single wildcard and only for a single part of the FQDN
1000             # e.g *.example.org does match www.example.org but not bla.www.example.org
1001             # The RFCs are in this regard unspecific but we don't want to have to
1002             # deal with certificates like *.com, *.co.uk or even *
1003             # see also http://nils.toedtmann.net/pub/subjectAltName.txt
1004 0 0 0       if ($type == 2 and $name =~m{^([^.]*)\*(.+)} ) {
    0 0        
1005 0           $pattern = qr{^\Q$1\E[^.]*\Q$2\E$}i;
1006             } elsif ($type == 1 and $name =~m{^\*(\..+)$} ) {
1007 0           $pattern = qr{^[^.]*\Q$1\E$}i;
1008             } else {
1009 0           $pattern = qr{^\Q$name\E$}i;
1010             }
1011              
1012 0           $cn =~ $pattern
1013             }
1014              
1015             # taken verbatim from IO::Socket::SSL, then changed to take advantage of
1016             # AnyEvent utilities.
1017             sub verify_hostname($$$) {
1018 0     0 0   my ($cn, $cert, $scheme) = @_;
1019              
1020 0           while (!ref $scheme) {
1021 0 0         $scheme = $CN_SCHEME{$scheme}
1022             or return 1;
1023             }
1024              
1025 0           my $cert_cn =
1026             Net::SSLeay::X509_NAME_get_text_by_NID (
1027             Net::SSLeay::X509_get_subject_name ($cert), Net::SSLeay::NID_commonName ());
1028              
1029 0           my @cert_alt = Net::SSLeay::X509_get_subjectAltNames ($cert);
1030              
1031             # rfc2460 - convert to network byte order
1032 0           require AnyEvent::Socket;
1033 0           my $ip = AnyEvent::Socket::parse_address ($cn);
1034              
1035 0           my $alt_dns_count;
1036              
1037 0           while (my ($type, $name) = splice @cert_alt, 0, 2) {
1038 0 0         if ($type == Net::SSLeay::GEN_IPADD ()) {
    0          
1039             # $name is already packed format (inet_xton)
1040 0 0         return 1 if $ip eq $name;
1041             } elsif ($type == Net::SSLeay::GEN_DNS ()) {
1042 0           $alt_dns_count++;
1043              
1044 0 0         return 1 if match_cn $name, $cn, $scheme->[1];
1045             }
1046             }
1047              
1048 0 0 0       if ($scheme->[2] == 2
      0        
1049             || ($scheme->[2] == 1 && !$alt_dns_count)) {
1050 0 0         return 1 if match_cn $cert_cn, $cn, $scheme->[0];
1051             }
1052              
1053             0
1054 0           }
1055              
1056             =back
1057              
1058             =head1 SSL/TLS QUICK FACTS
1059              
1060             Here are some quick facts about TLS/SSL that might help you:
1061              
1062             =over 4
1063              
1064             =item * A certificate is the public key part, a key is the private key part.
1065              
1066             While not strictly true, certificates are the things you can hand around
1067             publicly as a kind of identity, while keys should really be kept private,
1068             as proving that you have the private key is usually interpreted as being
1069             the entity behind the certificate.
1070              
1071             =item * A certificate is signed by a CA (Certificate Authority).
1072              
1073             By signing, the CA basically claims that the certificate it signs
1074             really belongs to the identity named in it, verified according to the
1075             CA policies. For e.g. HTTPS, the CA usually makes some checks that the
1076             hostname mentioned in the certificate really belongs to the company/person
1077             that requested the signing and owns the domain.
1078              
1079             =item * CAs can be certified by other CAs.
1080              
1081             Or by themselves - a certificate that is signed by a CA that is itself
1082             is called a self-signed certificate, a trust chain of length zero. When
1083             you find a certificate signed by another CA, which is in turn signed by
1084             another CA you trust, you have a trust chain of depth two.
1085              
1086             =item * "Trusting" a CA means trusting all certificates it has signed.
1087              
1088             If you "trust" a CA certificate, then all certificates signed by it are
1089             automatically considered trusted as well.
1090              
1091             =item * A successfully verified certificate means that you can be
1092             reasonably sure that whoever you are talking with really is who he claims
1093             he is.
1094              
1095             By verifying certificates against a number of CAs that you trust (meaning
1096             it is signed directly or indirectly by such a CA), you can find out that
1097             the other side really is whoever he claims, according to the CA policies,
1098             and your belief in the integrity of the CA.
1099              
1100             =item * Verifying the certificate signature is not everything.
1101              
1102             Even when the certificate is correct, it might belong to somebody else: if
1103             www.attacker.com can make your computer believe that it is really called
1104             www.mybank.com (by making your DNS server believe this for example),
1105             then it could send you the certificate for www.attacker.com that your
1106             software trusts because it is signed by a CA you trust, and intercept
1107             all your traffic that you think goes to www.mybank.com. This works
1108             because your software sees that the certificate is correctly signed (for
1109             www.attacker.com) and you think you are talking to your bank.
1110              
1111             To thwart this attack vector, peername verification should be used, which
1112             basically checks that the certificate (for www.attacker.com) really
1113             belongs to the host you are trying to talk to (www.mybank.com), which in
1114             this example is not the case, as www.attacker.com (from the certificate)
1115             doesn't match www.mybank.com (the hostname used to create the connection).
1116              
1117             So peername verification is almost as important as checking the CA
1118             signing. Unfortunately, every protocol implements this differently, if at
1119             all...
1120              
1121             =item * Switching off verification is sometimes reasonable.
1122              
1123             You can switch off verification. You still get an encrypted connection
1124             that is protected against eavesdropping and injection - you just lose
1125             protection against man in the middle attacks, i.e. somebody else with
1126             enough abilities to intercept all traffic can masquerade herself as the
1127             other side.
1128              
1129             For many applications, switching off verification is entirely
1130             reasonable. Downloading random stuff from websites using HTTPS for no
1131             reason is such an application. Talking to your bank and entering TANs is
1132             not such an application.
1133              
1134             =item * A SSL/TLS server always needs a certificate/key pair to operate,
1135             for clients this is optional.
1136              
1137             Apart from (usually disabled) anonymous cipher suites, a server always
1138             needs a certificate/key pair to operate.
1139              
1140             Clients almost never use certificates, but if they do, they can be used
1141             to authenticate the client, just as server certificates can be used to
1142             authenticate the server.
1143              
1144             =item * SSL version 2 is very insecure.
1145              
1146             SSL version 2 is old and not only has it some security issues, SSLv2-only
1147             implementations are usually buggy, too, due to their age.
1148              
1149             =item * Sometimes, even losing your "private" key might not expose all your
1150             data.
1151              
1152             With Diffie-Hellman ephemeral key exchange, you can lose the DH parameters
1153             (the "keys"), but all your connections are still protected. Diffie-Hellman
1154             needs special set-up (done by default by AnyEvent::TLS).
1155              
1156             =back
1157              
1158             =head1 SECURITY CONSIDERATIONS
1159              
1160             When you use any of the options that pass in keys or certificates
1161             as strings (e.g. C), then, due to serious shortcomings in
1162             L, this module creates a temporary file to store the string -
1163             see L and possibly its C setting for more details
1164             on what to watch out for.
1165              
1166             =head1 BUGS
1167              
1168             Due to the abysmal code quality of Net::SSLeay, this module will leak small
1169             amounts of memory per TLS connection (currently at least one perl scalar).
1170              
1171             =head1 AUTHORS
1172              
1173             Marc Lehmann .
1174              
1175             Some of the API, documentation and implementation (verify_hostname),
1176             and a lot of ideas/workarounds/knowledge have been taken from the
1177             L module. Care has been taken to keep the API similar to
1178             that and other modules, to the extent possible while providing a sensible
1179             API for AnyEvent.
1180              
1181             =cut
1182              
1183             1
1184