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