1 # Net::SSLeay.pm - Perl module for using Eric Young's implementation of SSL
3 # Copyright (c) 1996-2003 Sampo Kellomaki <sampo@iki.fi>, All Rights Reserved.
4 # Copyright (C) 2005 Florian Ragwitz <rafl@debian.org>, All Rights Reserved.
5 # Copyright (C) 2005 Mike McCauley <mikem@open.com.au>, All Rights Reserved.
9 # Version 1.04, 31.3.1999
10 # 30.7.1999, Tracking OpenSSL-0.9.3a changes, --Sampo
11 # 31.7.1999, version 1.05 --Sampo
12 # 7.4.2001, fixed input error upon 0, OpenSSL-0.9.6a, version 1.06 --Sampo
13 # 18.4.2001, added TLSv1 support by Stephen C. Koehler
14 # <koehler@securecomputing.com>, version 1.07, --Sampo
15 # 25.4.2001, 64 bit fixes by Marko Asplund <aspa@kronodoc.fi> --Sampo
16 # 17.4.2001, more error codes from aspa --Sampo
17 # 25.9.2001, added heaps and piles of newer OpenSSL auxiliary functions --Sampo
18 # 6.11.2001, got rid of $p_errs madness --Sampo
19 # 9.11.2001, added EGD (entropy gathering daemon) reference info --Sampo
20 # 7.12.2001, Added proxy support by Bruno De Wolf <bruno.dewolf@@pandora._be>
21 # 6.1.2002, cosmetic fix to socket options from Kwindla Hultman Kramer <kwindla@@allafrica_.com>
22 # 25.3.2002, added post_https_cert and friends per patch from
23 # mock@@obscurity.ogr, --Sampo
24 # 3.4.2002, added `use bytes' from Marcus Taylor <marcus@@semantico_.com>
25 # This avoids unicode/utf8 (as may appear in some XML docs)
26 # from fooling the length comuptations. Dropped support for
27 # perl5.005_03 because I do not have opportunity to test it. --Sampo
28 # 5.4.2002, improved Unicode gotcha eliminator to support old perls --Sampo
29 # 8.4.2002, added a small line end fix from Petr Dousa (pdousa@@kerio_.com)
30 # 17.5.2002, Added BIO_s_mem, BIO_new, BIO_free, BIO_write, BIO_read
31 # BIO_eof, BIO_pending, BIO_wpending, RSA_generate_key, RSA_free
32 # --mikem@open._com.au
33 # 10.8.2002, Added SSL_peek patch to ssl_read_until from
34 # Peter Behroozi <peter@@fhpwireless_.com> --Sampo
35 # 21.8.2002, Added SESSION_get_master_key, SSL_get_client_random, SSL_get_server_random
36 # --mikem@open.com_.au
37 # 2.9.2002, Added SSL_CTX_get_cert_store, X509_STORE_add_cert, X509_STORE_add_crl
38 # X509_STORE_set_flags, X509_load_cert_file, X509_load_crl_file
39 # X509_load_cert_crl_file, PEM_read_bio_X509_CRL,
40 # constants for X509_V_FLAG_* in order to support certificate revocation lists.
41 # --mikem@open.com_.au
42 # 6.9.2002, fixed X509_STORE_set_flags to X509_STORE_CTX_set_flags, --Sampo
43 # 19.9.2002, applied patch from Tim Engler <tim@burntcouch_.com>
44 # 18.2.2003, applied patch from Toni Andjelkovic <toni@soth._at>
45 # 13.6.2003, partially applied leak patch by Marian Jancar <mjancar@suse._cz>
46 # 25.6.2003, write_partial() return value patch from
47 # Kim Minh Kaplan <kmkaplan@selfoffice._com>
48 # 17.8.2003, added http support :-) --Sampo
49 # 17.8.2003, started 1.25 dev --Sampo
50 # 30.11.2005, Applied a patch by Peter Behroozi that adds get1_session() for session caching --Florian
51 # 30.11.2005, Applied a patch by ex8k-hbn@asahi-net.or.jp that limits the chunk size for tcp_read_all --Florian
52 # 30.11.2005, Applied a patch by ivan-cpan-rt@420.am that avoids adding a Host header if an own is specified in do_httpx3
53 # 13.12.2005, Added comments re thread safety and resetting of default_passwd_callback after use
56 # The distribution and use of this module are subject to the conditions
57 # listed in LICENSE file at the root of OpenSSL-0.9.7b
58 # distribution (i.e. free, but mandatory attribution and NO WARRANTY).
64 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD $CRLF);
71 # 0=no warns, 1=only errors, 2=ciphers, 3=progress, 4=dump data
72 $Net::SSLeay::trace = 0; # Do not change here, use
73 # $Net::SSLeay::trace = [1-4] in caller
75 # 2 = insist on v2 SSL protocol
76 # 3 = insist on v3 SSL
77 # 10 = insist on TLSv1
78 # 0 or undef = guess (v23)
80 $Net::SSLeay::ssl_version = 0; # don't change here, use
81 # Net::SSLeay::version=[2,3,0] in caller
83 #define to enable the "cat /proc/$$/stat" stuff
84 $Net::SSLeay::linux_debug = 0;
86 # Number of seconds to sleep after sending message and before half
87 # closing connection. Useful with antiquated broken servers.
88 $Net::SSLeay::slowly = 0;
90 # RANDOM NUMBER INITIALIZATION
92 # Edit to your taste. Using /dev/random would be more secure, but may
93 # block if randomness is not available, thus the default is
94 # /dev/urandom. $how_random determines how many bits of randomness to take
95 # from the device. You should take enough (read SSLeay/doc/rand), but
96 # beware that randomness is limited resource so you should not waste
97 # it either or you may end up with randomness depletion (situation where
98 # /dev/random would block and /dev/urandom starts to return predictable
101 # N.B. /dev/urandom does not exit on all systems, such as Solaris 2.6. In that
102 # case you should get a third party package that emulates /dev/urandom
103 # (e.g. via named pipe) or supply a random number file. Some such
104 # packages are documented in Caveat section of the POD documentation.
106 $Net::SSLeay::random_device = '/dev/urandom';
107 $Net::SSLeay::how_random = 512;
112 AT_MD5_WITH_RSA_ENCRYPTION
117 CK_DES_192_EDE3_CBC_WITH_MD5
118 CK_DES_192_EDE3_CBC_WITH_SHA
119 CK_DES_64_CBC_WITH_MD5
120 CK_DES_64_CBC_WITH_SHA
121 CK_DES_64_CFB64_WITH_MD5_1
122 CK_IDEA_128_CBC_WITH_MD5
125 CK_RC2_128_CBC_EXPORT40_WITH_MD5
126 CK_RC2_128_CBC_WITH_MD5
127 CK_RC4_128_EXPORT40_WITH_MD5
136 ERROR_WANT_X509_LOOKUP
145 F_GET_CLIENT_FINISHED
147 F_GET_CLIENT_MASTER_KEY
148 F_GET_SERVER_FINISHED
153 F_REQUEST_CERTIFICATE
158 F_SSL_ENC_DES_CBC_INIT
159 F_SSL_ENC_DES_CFB_INIT
160 F_SSL_ENC_DES_EDE3_CBC_INIT
161 F_SSL_ENC_IDEA_CBC_INIT
163 F_SSL_ENC_RC2_CBC_INIT
165 F_SSL_GET_NEW_SESSION
166 F_SSL_MAKE_CIPHER_LIST
169 F_SSL_RSA_PRIVATE_DECRYPT
170 F_SSL_RSA_PUBLIC_ENCRYPT
172 F_SSL_SESSION_PRINT_FP
173 F_SSL_SET_CERTIFICATE
178 F_SSL_USE_CERTIFICATE
179 F_SSL_USE_CERTIFICATE_ASN1
180 F_SSL_USE_CERTIFICATE_FILE
182 F_SSL_USE_PRIVATEKEY_ASN1
183 F_SSL_USE_PRIVATEKEY_FILE
184 F_SSL_USE_RSAPRIVATEKEY
185 F_SSL_USE_RSAPRIVATEKEY_ASN1
186 F_SSL_USE_RSAPRIVATEKEY_FILE
197 MAX_MASTER_KEY_LENGTH_IN_BITS
198 MAX_RECORD_LENGTH_2_BYTE_HEADER
199 MAX_RECORD_LENGTH_3_BYTE_HEADER
200 MAX_SSL_SESSION_ID_LENGTH_IN_BYTES
201 MIN_RSA_MODULUS_LENGTH_IN_BYTES
202 MT_CLIENT_CERTIFICATE
207 MT_REQUEST_CERTIFICATE
220 NID_md2WithRSAEncryption
221 NID_md5WithRSAEncryption
222 NID_pbeWithMD2AndDES_CBC
223 NID_pbeWithMD5AndDES_CBC
229 NID_stateOrProvinceName
231 NID_organizationalUnitName
237 NID_pkcs7_signedAndEnveloped
255 NID_shaWithRSAEncryption
261 NID_pkcs9_emailAddress
262 NID_pkcs9_unstructuredName
263 NID_pkcs9_contentType
264 NID_pkcs9_messageDigest
265 NID_pkcs9_signingTime
266 NID_pkcs9_countersignature
267 NID_pkcs9_challengePassword
268 NID_pkcs9_unstructuredAddress
269 NID_pkcs9_extCertAttributes
271 NID_netscape_cert_extension
272 NID_netscape_data_type
278 NID_sha1WithRSAEncryption
281 NID_pbeWithSHA1AndRC2_CBC
284 NID_netscape_cert_type
285 NID_netscape_base_url
286 NID_netscape_revocation_url
287 NID_netscape_ca_revocation_url
288 NID_netscape_renewal_url
289 NID_netscape_ca_policy_url
290 NID_netscape_ssl_server_name
292 NID_netscape_cert_sequence
295 NID_subject_key_identifier
297 NID_private_key_usage_period
300 NID_basic_constraints
302 NID_certificate_policies
303 NID_authority_key_identifier
316 NID_crl_distribution_points
325 NID_pbeWithMD5AndCast5_CBC
356 NID_pbe_WithSHA1And128BitRC4
357 NID_pbe_WithSHA1And40BitRC4
358 NID_pbe_WithSHA1And3_Key_TripleDES_CBC
359 NID_pbe_WithSHA1And2_Key_TripleDES_CBC
360 NID_pbe_WithSHA1And128BitRC2_CBC
361 NID_pbe_WithSHA1And40BitRC2_CBC
363 NID_pkcs8ShroudedKeyBag
379 NID_SMIMECapabilities
380 NID_pbeWithMD2AndRC2_CBC
381 NID_pbeWithMD5AndRC2_CBC
382 NID_pbeWithSHA1AndDES_CBC
393 OPENSSL_VERSION_NUMBER
397 PE_UNSUPPORTED_CERTIFICATE_TYPE
400 RWERR_BAD_WRITE_RETRY
402 R_BAD_AUTHENTICATION_TYPE
405 R_BAD_RESPONSE_ARGUMENT
407 R_BAD_SSL_SESSION_ID_LENGTH
410 R_CHALLENGE_IS_DIFFERENT
411 R_CIPHER_CODE_TOO_LONG
412 R_CIPHER_TABLE_SRC_ERROR
413 R_CONECTION_ID_IS_DIFFERENT
414 R_INVALID_CHALLENGE_LENGTH
416 R_NO_CERTIFICATE_SPECIFIED
423 R_NO_WRITE_METHOD_SET
425 R_PEER_DID_NOT_RETURN_A_CERTIFICATE
427 R_PEER_ERROR_CERTIFICATE
428 R_PEER_ERROR_NO_CIPHER
429 R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
430 R_PERR_ERROR_NO_CERTIFICATE
431 R_PUBLIC_KEY_ENCRYPT_ERROR
432 R_PUBLIC_KEY_IS_NOT_RSA
434 R_READ_WRONG_PACKET_TYPE
435 R_REVERSE_KEY_ARG_LENGTH_IS_WRONG
436 R_REVERSE_MASTER_KEY_LENGTH_IS_WRONG
437 R_REVERSE_SSL_SESSION_ID_LENGTH_IS_WRONG
439 R_SSL_SESSION_ID_IS_DIFFERENT
440 R_UNABLE_TO_EXTRACT_PUBLIC_KEY
441 R_UNDEFINED_INIT_STATE
442 R_UNKNOWN_REMOTE_ERROR_TYPE
445 R_WRONG_PUBLIC_KEY_TYPE
454 ST_CLIENT_START_ENCRYPTION
456 ST_GET_CLIENT_FINISHED_A
457 ST_GET_CLIENT_FINISHED_B
458 ST_GET_CLIENT_HELLO_A
459 ST_GET_CLIENT_HELLO_B
460 ST_GET_CLIENT_MASTER_KEY_A
461 ST_GET_CLIENT_MASTER_KEY_B
462 ST_GET_SERVER_FINISHED_A
463 ST_GET_SERVER_FINISHED_B
464 ST_GET_SERVER_HELLO_A
465 ST_GET_SERVER_HELLO_B
466 ST_GET_SERVER_VERIFY_A
467 ST_GET_SERVER_VERIFY_B
472 ST_SEND_CLIENT_CERTIFICATE_A
473 ST_SEND_CLIENT_CERTIFICATE_B
474 ST_SEND_CLIENT_CERTIFICATE_C
475 ST_SEND_CLIENT_CERTIFICATE_D
476 ST_SEND_CLIENT_FINISHED_A
477 ST_SEND_CLIENT_FINISHED_B
478 ST_SEND_CLIENT_HELLO_A
479 ST_SEND_CLIENT_HELLO_B
480 ST_SEND_CLIENT_MASTER_KEY_A
481 ST_SEND_CLIENT_MASTER_KEY_B
482 ST_SEND_REQUEST_CERTIFICATE_A
483 ST_SEND_REQUEST_CERTIFICATE_B
484 ST_SEND_REQUEST_CERTIFICATE_C
485 ST_SEND_REQUEST_CERTIFICATE_D
486 ST_SEND_SERVER_FINISHED_A
487 ST_SEND_SERVER_FINISHED_B
488 ST_SEND_SERVER_HELLO_A
489 ST_SEND_SERVER_HELLO_B
490 ST_SEND_SERVER_VERIFY_A
491 ST_SEND_SERVER_VERIFY_B
492 ST_SERVER_START_ENCRYPTION
493 ST_X509_GET_CLIENT_CERTIFICATE
494 ST_X509_GET_SERVER_CERTIFICATE
495 TXT_DES_192_EDE3_CBC_WITH_MD5
496 TXT_DES_192_EDE3_CBC_WITH_SHA
497 TXT_DES_64_CBC_WITH_MD5
498 TXT_DES_64_CBC_WITH_SHA
499 TXT_DES_64_CFB64_WITH_MD5_1
500 TXT_IDEA_128_CBC_WITH_MD5
503 TXT_RC2_128_CBC_EXPORT40_WITH_MD5
504 TXT_RC2_128_CBC_WITH_MD5
505 TXT_RC4_128_EXPORT40_WITH_MD5
508 VERIFY_FAIL_IF_NO_PEER_CERT
513 X509_V_FLAG_CB_ISSUER_CHECK
514 X509_V_FLAG_USE_CHECK_TIME
515 X509_V_FLAG_CRL_CHECK
516 X509_V_FLAG_CRL_CHECK_ALL
517 X509_V_FLAG_IGNORE_CRITICAL
536 use_RSAPrivateKey_ASN1
537 use_RSAPrivateKey_file
538 CTX_use_RSAPrivateKey_file
545 CTX_use_certificate_file
548 ERR_load_RAND_strings
594 X509_get_subject_name
596 X509_NAME_get_text_by_NID
600 X509_STORE_CTX_set_flags
603 X509_load_cert_crl_file
604 PEM_read_bio_X509_CRL
609 set_server_cert_and_key
640 dump_peer_certificate
644 SESSION_get_master_key
650 # This AUTOLOAD is used to 'autoload' constants from the constant()
651 # XS function. If a constant is not found then control is passed
652 # to the AUTOLOAD in AutoLoader.
655 ($constname = $AUTOLOAD) =~ s/.*:://;
656 my $val = constant($constname);
658 if ($! =~ /((Invalid)|(not valid))/i || $!{EINVAL}) {
659 $AutoLoader::AUTOLOAD = $AUTOLOAD;
660 goto &AutoLoader::AUTOLOAD;
663 croak "Your vendor has not defined SSLeay macro $constname";
666 eval "sub $AUTOLOAD { $val }";
672 XSLoader::load('Net::SSLeay', $VERSION);
676 push @ISA, 'DynaLoader';
677 bootstrap Net::SSLeay $VERSION;
680 # Preloaded methods go here.
682 $CRLF = "\x0d\x0a"; # because \r\n is not fully portable
684 ### Print SSLeay error stack
688 my ($count, $err, $errs, $e) = (0,0,'');
689 while ($err = ERR_get_error()) {
691 $e = "$msg $$: $count - " . ERR_error_string($err) . "\n";
693 warn $e if $Net::SSLeay::trace;
698 # Death is conditional to SSLeay errors existing, i.e. this function checks
699 # for errors and only dies in affirmative.
700 # usage: Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
702 sub die_if_ssl_error {
704 die "$$: $msg\n" if print_errs($msg);
707 # Unconditional death. Used to print SSLeay errors before dying.
708 # usage: Net::SSLeay::connect($ssl) or die_now("Failed SSL connect ($!)");
716 # Perl 5.6.* unicode support causes that length() no longer reliably
717 # reflects the byte length of a string. This eval is to fix that.
718 # Thanks to Sean Burke for the snippet.
721 eval 'use bytes; sub blength ($) { length $_[0] }';
722 $@ and eval ' sub blength ($) { length $_[0] }' ;
725 # Autoload methods go after =cut, and are processed by the autosplit program.
729 # Documentation. Use `perl-root/pod/pod2html SSLeay.pm` to output html
733 Net::SSLeay - Perl extension for using OpenSSL
737 use Net::SSLeay qw(get_https post_https sslcat make_headers make_form);
739 ($page) = get_https('www.bacus.pt', 443, '/'); # 1
741 ($page, $response, %reply_headers)
742 = get_https('www.bacus.pt', 443, '/', # 2
743 make_headers(User-Agent => 'Cryptozilla/5.0b1',
744 Referer => 'https://www.bacus.pt'
747 ($page, $result, %headers) = # 2b
748 = get_https('www.bacus.pt', 443, '/protected.html',
749 make_headers(Authorization =>
750 'Basic ' . MIME::Base64::encode("$user:$pass",''))
753 ($page, $response, %reply_headers)
754 = post_https('www.bacus.pt', 443, '/foo.cgi', '', # 3
759 $reply = sslcat($host, $port, $request); # 4
761 ($reply, $err, $server_cert) = sslcat($host, $port, $request); # 5
763 $Net::SSLeay::trace = 2; # 0=no debugging, 1=ciphers, 2=trace, 3=dump data
767 There is a related module called C<Net::SSLeay::Handle> included in this
768 distribution that you might want to use instead. It has its own pod
771 This module offers some high level convinience functions for accessing
772 web pages on SSL servers (for symmetry, same API is offered for
773 accessing http servers, too), a C<sslcat()> function for writing your own
774 clients, and finally access to the SSL api of SSLeay/OpenSSL package
775 so you can write servers or clients for more complicated applications.
777 For high level functions it is most convinient to import them to your
778 main namespace as indicated in the synopsis.
780 Case 1 demonstrates typical invocation of get_https() to fetch an HTML
781 page from secure server. The first argument provides host name or ip
782 in dotted decimal notation of the remote server to contact. Second
783 argument is the TCP port at the remote end (your own port is picked
784 arbitrarily from high numbered ports as usual for TCP). The third
785 argument is the URL of the page without the host name part. If in
786 doubt consult HTTP specifications at L<http://www.w3c.org>.
788 Case 2 demonstrates full fledged use of C<get_https()>. As can be seen,
789 C<get_https()> parses the response and response headers and returns them as
790 a list, which can be captured in a hash for later reference. Also a
791 fourth argument to C<get_https()> is used to insert some additional headers
792 in the request. C<make_headers()> is a function that will convert a list or
793 hash to such headers. By default C<get_https()> supplies C<Host> (make virtual
794 hosting easy) and C<Accept> (reportedly needed by IIS) headers.
796 Case 2b demonstrates how to get password protected page. Refer to
797 HTTP protocol specifications for further details (e.g. RFC-2617).
799 Case 3 invokes C<post_https()> to submit a HTML/CGI form to secure
800 server. First four arguments are equal to C<get_https()> (note that empty
801 string (C<''>) is passed as header argument). The fifth argument is the
802 contents of the form formatted according to CGI specification. In this
803 case the helper function C<make_https()> is used to do the formatting,
804 but you could pass any string. The C<post_https()> automatically adds
805 C<Content-Type> and C<Content-Length> headers to the request.
807 Case 4 shows the fundamental C<sslcat()> function (inspired in spirit by
808 C<netcat> utility :-). Its your swiss army knife that allows you to
809 easily contact servers, send some data, and then get the response. You
810 are responsible for formatting the data and parsing the response -
811 C<sslcat()> is just a transport.
813 Case 5 is a full invocation of C<sslcat()> which allows return of errors
814 as well as the server (peer) certificate.
816 The C<$trace> global variable can be used to control the verbosity of high
817 level functions. Level 0 guarantees silence, level 1 (the default)
818 only emits error messages.
820 =head2 Alternate versions of the API
822 The above mentioned functions actually return the response headers as
823 a list, which only gets converted to hash upon assignment (this
824 assignment looses information if the same header occurs twice, as may
825 be the case with cookies). There are also other variants of the
826 functions that return unprocessed headers and that return a reference
829 ($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
830 for ($i = 0; $i < $#headers; $i+=2) {
831 print "$headers[$i] = " . $headers[$i+1] . "\n";
834 ($page, $response, $headers, $server_cert)
835 = get_https3('www.bacus.pt', 443, '/');
838 ($page, $response, %headers_ref, $server_cert)
839 = get_https4('www.bacus.pt', 443, '/');
840 for $k (sort keys %{headers_ref}) {
841 for $v (@{$headers_ref{$k}}) {
846 All of the above code fragments accomplish the same thing: display all
847 values of all headers. The API functions ending in "3" return the
848 headers simply as a scalar string and it is up to the application to
849 split them up. The functions ending in "4" return a reference to
850 hash of arrays (see L<perlref> and L<perllol> if you are
851 not familiar with complex perl data structures). To access single value
852 of such header hash you would do something like
854 print $headers_ref{COOKIE}[0];
856 The variants 3 and 4 also allow you to discover the server certificate
857 in case you would like to store or display it, e.g.
859 ($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
860 if (!defined($server_cert) || ($server_cert == 0)) {
861 warn "Subject Name: undefined, Issuer Name: undefined";
863 warn 'Subject Name: '
864 . Net::SSLeay::X509_NAME_oneline(
865 Net::SSLeay::X509_get_subject_name($server_cert))
867 . Net::SSLeay::X509_NAME_oneline(
868 Net::SSLeay::X509_get_issuer_name($server_cert));
871 Beware that this method only allows after the fact verification of
872 the certificate: by the time C<get_https3()> has returned the https
873 request has already been sent to the server, whether you decide to
874 tryst it or not. To do the verification correctly you must either
875 employ the OpenSSL certificate verification framework or use
876 the lower level API to first connect and verify the certificate
877 and only then send the http data. See implementation of C<ds_https3()>
878 for guidance on how to do this.
880 =head2 Using client certificates
882 Secure web communications are encrypted using symmetric crypto keys
883 exchanged using encryption based on the certificate of the
884 server. Therefore in all SSL connections the server must have a
885 certificate. This serves both to authenticate the server to the
886 clients and to perform the key exchange.
888 Sometimes it is necessary to authenticate the client as well. Two
889 options are available: HTTP basic authentication and client side
890 certificate. The basic authentication over HTTPS is actually quite
891 safe because HTTPS guarantees that the password will not travel in
892 clear. Never-the-less, problems like easily guessable passwords
893 remain. The client certificate method involves authentication of the
894 client at SSL level using a certificate. For this to work, both the
895 client and the server will have certificates (which typically are
896 different) and private keys.
898 The API functions outlined above accept additional arguments that
899 allow one to supply the client side certificate and key files. The
900 format of these files is the same as used for server certificates and
901 the caveat about encrypting private key applies.
903 ($page, $result, %headers) = # 2c
904 = get_https('www.bacus.pt', 443, '/protected.html',
905 make_headers(Authorization =>
906 'Basic ' . MIME::Base64::encode("$user:$pass",'')),
907 '', $mime_type6, $path_to_crt7, $path_to_key8);
909 ($page, $response, %reply_headers)
910 = post_https('www.bacus.pt', 443, '/foo.cgi', # 3b
911 make_headers('Authorization' =>
912 'Basic ' . MIME::Base64::encode("$user:$pass",'')),
913 make_form(OK => '1', name => 'Sampo'),
914 $mime_type6, $path_to_crt7, $path_to_key8);
916 Case 2c demonstrates getting password protected page that also requires
917 client certificate, i.e. it is possible to use both authentication
918 methods simultaneously.
920 Case 3b is full blown post to secure server that requires both password
921 authentication and client certificate, just like in case 2c.
923 Note: Client will not send a certificate unless the server requests one.
924 This is typically achieved by setting verify mode to C<VERIFY_PEER> on the
927 Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);
929 See C<perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod> for full description.
931 =head2 Working through Web proxy
933 C<Net::SSLeay> can use a web proxy to make its connections. You need to
934 first set the proxy host and port using C<set_proxy()> and then just
935 use the normal API functions, e.g:
937 Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
938 ($page) = get_https('www.bacus.pt', 443, '/');
940 If your proxy requires authentication, you can supply username and
943 Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
944 ($page, $result, %headers) =
945 = get_https('www.bacus.pt', 443, '/protected.html',
946 make_headers(Authorization =>
947 'Basic ' . MIME::Base64::encode("susie:pass",''))
950 This example demonstrates case where we authenticate to the proxy as
951 C<"joe"> and to the final web server as C<"susie">. Proxy authentication
952 requires C<MIME::Base64> module to work.
954 =head2 Certificate verification and Certificate Revoocation Lists (CRLs)
956 OpenSSL supports the ability to verify peer certificates. It can also
957 optionally check the peer certificate against a Certificate Revocation
958 List (CRL) from the certificates issuer. A CRL is a file, created by
959 the certificate issuer that lists all the certificates that it
960 previously signed, but which it now revokes. CRLs are in PEM format.
962 You can enable C<Net::SSLeay CRL> checking like this:
964 &Net::SSLeay::X509_STORE_CTX_set_flags
965 (&Net::SSLeay::CTX_get_cert_store($ssl),
966 &Net::SSLeay::X509_V_FLAG_CRL_CHECK);
968 After setting this flag, if OpenSSL checks a peer's certificate, then
969 it will attempt to find a CRL for the issuer. It does this by looking
970 for a specially named file in the search directory specified by
971 CTX_load_verify_locations. CRL files are named with the hash of the
972 issuer's subject name, followed by C<.r0>, C<.r1> etc. For example
973 C<ab1331b2.r0>, C<ab1331b2.r1>. It will read all the .r files for the
974 issuer, and then check for a revocation of the peer cerificate in all
975 of them. (You can also force it to look in a specific named CRL
976 file., see below). You can find out the hash of the issuer subject
979 openssl crl -in crl.pem -hash -noout
981 If the peer certificate does not pass the revocation list, or if no
982 CRL is found, then the handshaking fails with an error.
984 You can also force OpenSSL to look for CRLs in one or more arbitrarily
987 my $bio = Net::SSLeay::BIO_new_file($crlfilename, 'r');
988 my $crl = Net::SSLeay::PEM_read_bio_X509_CRL($bio);
990 Net::SSLeay::X509_STORE_add_crl(Net::SSLeay::CTX_get_cert_store($ssl, $crl);
992 error reading CRL....
996 =head2 Convenience routines
998 To be used with Low level API
1000 Net::SSLeay::randomize($rn_seed_file,$additional_seed);
1001 Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
1002 $cert = Net::SSLeay::dump_peer_certificate($ssl);
1003 Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
1004 $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
1006 $got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
1007 $got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
1008 Net::SSLeay::ssl_write_CRLF($ssl, $message);
1010 C<randomize()> seeds the eay PRNG with C</dev/urandom> (see top of C<SSLeay.pm>
1011 for how to change or configure this) and optionally with user provided
1012 data. It is very important to properly seed your random numbers, so
1013 do not forget to call this. The high level API functions automatically
1014 call C<randomize()> so it is not needed with them. See also caveats.
1016 C<set_cert_and_key()> takes two file names as arguments and sets
1017 the certificate and private key to those. This can be used to
1018 set either cerver certificates or client certificates.
1020 C<dump_peer_certificate()> allows you to get plaintext description of the
1021 certificate the peer (usually server) presented to us.
1023 C<ssl_read_all()> and C<ssl_write_all()> provide true blocking semantics for
1024 these operations (see limitation, below, for explanation). These are
1025 much preferred to the low level API equivalents (which implement BSD
1026 blocking semantics). The message argument to C<ssl_write_all()> can be
1027 reference. This is helpful to avoid unnecessary copy when writing
1030 $data = 'A' x 1000000000;
1031 Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
1033 C<ssl_read_CRLF()> uses C<ssl_read_all()> to read in a line terminated with a
1034 carriage return followed by a linefeed (CRLF). The CRLF is included in
1035 the returned scalar.
1037 C<ssl_read_until()> uses C<ssl_read_all()> to read from the SSL input
1038 stream until it encounters a programmer specified delimiter.
1039 If the delimiter is undefined, C<$/> is used. If C<$/> is undefined,
1040 C<\n> is used. One can optionally set a maximum length of bytes to read
1041 from the SSL input stream.
1043 C<ssl_write_CRLF()> writes C<$message> and appends CRLF to the SSL output stream.
1045 =head2 Low level API
1047 In addition to the high level functions outlined above, this module
1048 contains straight forward access to SSL part of OpenSSL C api. Only the SSL
1049 subpart of OpenSSL is implemented (if anyone wants to implement other
1050 parts, feel free to submit patches).
1052 See C<ssl.h> header from OpenSSL C distribution for list of low lever
1053 SSLeay functions to call (to check if some function has been
1054 implemented see directly in SSLeay.xs). The module strips SSLeay names
1055 of the initial C<"SSL_">, generally you should use C<Net::SSLeay::> in
1062 err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
1063 &your_call_back_here);
1069 $err = Net::SSLeay::set_verify ($ssl,
1070 Net::SSLeay::VERIFY_CLIENT_ONCE,
1071 \&your_call_back_here);
1073 If the function does not start by C<SSL_> you should use the full
1074 function name, e.g.:
1076 $err = Net::SSLeay::ERR_get_error;
1078 Following new functions behave in perlish way:
1080 $got = Net::SSLeay::read($ssl);
1081 # Performs SSL_read, but returns $got
1082 # resized according to data received.
1083 # Returns undef on failure.
1085 Net::SSLeay::write($ssl, $foo) || die;
1086 # Performs SSL_write, but automatically
1087 # figures out the size of $foo
1089 In order to use the low level API you should start your programs with
1090 the following incantation:
1092 use Net::SSLeay qw(die_now die_if_ssl_error);
1093 Net::SSLeay::load_error_strings();
1094 Net::SSLeay::SSLeay_add_ssl_algorithms(); # Important!
1095 Net::SSLeay::ENGINE_load_builtin_engines(); # If you want built-in engines
1096 Net::SSLeay::ENGINE_register_all_complete(); # If you want built-in engines
1097 Net::SSLeay::randomize();
1099 C<die_now()> and C<die_if_ssl_error()> are used to conveniently print SSLeay error
1100 stack when something goes wrong, thusly:
1102 Net::SSLeay::connect($ssl) or die_now("Failed SSL connect ($!)");
1103 Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
1105 You can also use C<Net::SSLeay::print_errs()> to dump the error stack without
1106 exiting the program. As can be seen, your code becomes much more readable
1107 if you import the error reporting functions to your main name space.
1109 I can not emphasize enough the need to check error returns. Use these
1110 functions even in most simple programs, they will reduce debugging
1111 time greatly. Do not ask questions in mailing list without having
1112 first sprinkled these in your code.
1116 Perl uses file handles for all I/O. While SSLeay has quite flexible BIO
1117 mechanism and perl has evolved PerlIO mechanism, this module still
1118 sticks to using file descriptors. Thus to attach SSLeay to socket you
1119 should use C<fileno()> to extract the underlying file descriptor:
1121 Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
1123 You should also set C<$|> to 1 to eliminate STDIO buffering so you do not
1124 get confused if you use perl I/O functions to manipulate your socket
1127 If you need to C<select(2)> on the socket, go right ahead, but be warned
1128 that OpenSSL does some internal buffering so SSL_read does not always
1129 return data even if socket selected for reading (just keep on
1130 selecting and trying to read). C<Net::SSLeay> is no different from the
1131 C language OpenSSL in this respect.
1135 At this moment the implementation of verify_callback is crippeled in
1136 the sense that at any given time there can be only one call back which
1137 is shared by all SSL contexts, sessions and connections. This is
1138 due to having to keep the reference to the perl call back in a
1139 static variable so that the callback C glue can find it. To remove
1140 this restriction would require either a more complex data structure
1141 (like a hash?) in XSUB to map the call backs to their owners or,
1142 cleaner, adding a context pointer in the SSL structure. This context would
1143 then be passed to the C callback, which in our case would be the glue
1144 to look up the proper Perl function from the context and call it.
1146 ---- inaccurate ----
1147 The verify call back looks like this in C:
1149 int (*callback)(int ok,X509 *subj_cert,X509 *issuer_cert,
1150 int depth,int errorcode,char *arg,STACK *cert_chain)
1152 The corresponding Perl function should be something like this:
1155 my ($ok, $subj_cert, $issuer_cert, $depth, $errorcode,
1157 print "Verifying certificate...\n";
1162 It is used like this:
1164 Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);
1166 Callbacks for decrypting private keys are implemented, but have the
1167 same limitation as the verify_callback implementation (one password
1168 callback shared between all contexts.) You might use it something
1171 Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
1172 Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
1173 Net::SSLeay::FILETYPE_PEM)
1174 or die "Error reading private key";
1175 Net::SSLeay::CTX_set_default_passwd_cb($ctx, undef);
1177 No other callbacks are implemented. You do not need to use any
1178 callback for simple (i.e. normal) cases where the SSLeay built-in
1179 verify mechanism satisfies your needs.
1181 It is desirable to reset these callbacks to undef immediately after use to prevent
1182 thread safety problems and crashes on exit that can occur if different threads
1183 set different callbacks.
1185 ---- end inaccurate ----
1187 If you want to use callback stuff, see examples/callback.pl! Its the
1188 only one I am able to make work reliably.
1190 =head2 X509 and RAND stuff
1192 This module largely lacks interface to the X509 and RAND routines, but
1193 as I was lazy and needed them, the following kludges are implemented:
1195 $x509_name = Net::SSLeay::X509_get_subject_name($x509_cert);
1196 $x509_name = Net::SSLeay::X509_get_issuer_name($x509_cert);
1197 print Net::SSLeay::X509_NAME_oneline($x509_name);
1198 $text = Net::SSLeay::X509_NAME_get_text_by_NID($name, $nid);
1200 ($type1, $subject1, $type2, $subject2, ...) =
1201 Net::SSLeay::X509_get_subjectAltNames($x509_cert)
1203 subjectAltName types as per x509v3.h GEN_*, for example
1204 GEN_DNS or GEN_IPADD which can be imported.
1206 Net::SSLeay::RAND_seed($buf); # Perlishly figures out buf size
1207 Net::SSLeay::RAND_bytes($buf, $num);
1208 Net::SSLeay::RAND_pseudo_bytes($buf, $num);
1209 Net::SSLeay::RAND_add($buf, $num, $entropy);
1210 Net::SSLeay::RAND_poll();
1211 Net::SSLeay::RAND_status();
1212 Net::SSLeay::RAND_cleanup();
1213 Net::SSLeay::RAND_file_name($num);
1214 Net::SSLeay::RAND_load_file($file_name, $how_many_bytes);
1215 Net::SSLeay::RAND_write_file($file_name);
1216 Net::SSLeay::RAND_egd($path);
1217 Net::SSLeay::RAND_egd_bytes($path, $bytes);
1219 Actually you should consider using the following helper functions:
1221 print Net::SSLeay::dump_peer_certificate($ssl);
1222 Net::SSLeay::randomize();
1224 =head2 RSA interface
1226 Some RSA functions are available:
1228 $rsakey = Net::SSLeay::RSA_generate_key();
1229 Net::SSLeay::CTX_set_tmp_rsa($ctx, $rsakey);
1230 Net::SSLeay::RSA_free($rsakey);
1232 =head2 BIO interface
1234 Some BIO functions are available:
1236 Net::SSLeay::BIO_s_mem();
1237 $bio = Net::SSLeay::BIO_new(BIO_s_mem())
1238 $bio = Net::SSLeay::BIO_new_file($filename, $mode);
1239 Net::SSLeay::BIO_free($bio)
1240 $count = Net::SSLeay::BIO_write($data);
1241 $data = Net::SSLeay::BIO_read($bio);
1242 $data = Net::SSLeay::BIO_read($bio, $maxbytes);
1243 $is_eof = Net::SSLeay::BIO_eof($bio);
1244 $count = Net::SSLeay::BIO_pending($bio);
1245 $count = Net::SSLeay::BIO_wpending ($bio);
1247 =head2 Low level API
1249 Some very low level API functions are available:
1251 $client_random = Net::SSLeay::get_client_random($ssl);
1252 $server_random = Net::SSLeay::get_server_random($ssl);
1253 $session = Net::SSLeay::get_session($ssl);
1254 $master_key = Net::SSLeay::SESSION_get_master_key($session);
1255 Net::SSLeay::SESSION_set_master_key($session, $master_secret);
1256 $keyblocksize = Net::SSLeay::get_keyblock_size($session);
1258 =head2 HTTP (without S) API
1260 Over the years it has become clear that it would be convenient to use
1261 the light weight flavour API of C<Net::SSLeay> also for normal HTTP (see
1262 LWP for heavy weight object oriented approach). In fact it would be
1263 nice to be able to flip https on and off on the fly. Thus regular HTTP
1264 support was evolved.
1266 use Net::SSLeay qw(get_http post_http tcpcat
1267 get_httpx post_httpx tcpxcat
1268 make_headers make_form);
1270 ($page, $result, %headers) =
1271 = get_http('www.bacus.pt', 443, '/protected.html',
1272 make_headers(Authorization =>
1273 'Basic ' . MIME::Base64::encode("$user:$pass",''))
1276 ($page, $response, %reply_headers)
1277 = post_http('www.bacus.pt', 443, '/foo.cgi', '',
1278 make_form(OK => '1',
1282 ($reply, $err) = tcpcat($host, $port, $request);
1284 ($page, $result, %headers) =
1285 = get_httpx($usessl, 'www.bacus.pt', 443, '/protected.html',
1286 make_headers(Authorization =>
1287 'Basic ' . MIME::Base64::encode("$user:$pass",''))
1290 ($page, $response, %reply_headers)
1291 = post_httpx($usessl, 'www.bacus.pt', 443, '/foo.cgi', '',
1292 make_form(OK => '1', name => 'Sampo' ));
1294 ($reply, $err, $server_cert) = tcpxcat($usessl, $host, $port, $request);
1296 As can be seen, the C<"x"> family of APIs takes as first argument a flag
1297 which indicated whether SSL is used or not.
1301 One very good example is to look at the implementation of C<sslcat()> in the
1304 Following is a simple SSLeay client (with too little error checking :-(
1306 #!/usr/local/bin/perl
1308 use Net::SSLeay qw(die_now die_if_ssl_error) ;
1309 Net::SSLeay::load_error_strings();
1310 Net::SSLeay::SSLeay_add_ssl_algorithms();
1311 Net::SSLeay::randomize();
1313 ($dest_serv, $port, $msg) = @ARGV; # Read command line
1314 $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
1315 $dest_ip = gethostbyname ($dest_serv);
1316 $dest_serv_params = sockaddr_in($port, $dest_ip);
1318 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
1319 connect (S, $dest_serv_params) or die "connect: $!";
1320 select (S); $| = 1; select (STDOUT); # Eliminate STDIO buffering
1322 # The network connection is now open, lets fire up SSL
1324 $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
1325 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
1326 and die_if_ssl_error("ssl ctx set options");
1327 $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
1328 Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
1329 $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
1330 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
1334 $res = Net::SSLeay::write($ssl, $msg); # Perl knows how long $msg is
1335 die_if_ssl_error("ssl write");
1336 CORE::shutdown S, 1; # Half close --> No more output, sends EOF to server
1337 $got = Net::SSLeay::read($ssl); # Perl returns undef on failure
1338 die_if_ssl_error("ssl read");
1341 Net::SSLeay::free ($ssl); # Tear down connection
1342 Net::SSLeay::CTX_free ($ctx);
1345 Following is a simple SSLeay echo server (non forking):
1347 #!/usr/local/bin/perl -w
1349 use Net::SSLeay qw(die_now die_if_ssl_error);
1350 Net::SSLeay::load_error_strings();
1351 Net::SSLeay::SSLeay_add_ssl_algorithms();
1352 Net::SSLeay::randomize();
1354 $our_ip = "\0\0\0\0"; # Bind to all interfaces
1356 $sockaddr_template = 'S n a4 x8';
1357 $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);
1359 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
1360 bind (S, $our_serv_params) or die "bind: $!";
1361 listen (S, 5) or die "listen: $!";
1362 $ctx = Net::SSLeay::CTX_new () or die_now("CTX_new ($ctx): $!");
1363 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
1364 and die_if_ssl_error("ssl ctx set options");
1366 # Following will ask password unless private key is not encrypted
1367 Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
1368 &Net::SSLeay::FILETYPE_PEM);
1369 die_if_ssl_error("private key");
1370 Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
1371 &Net::SSLeay::FILETYPE_PEM);
1372 die_if_ssl_error("certificate");
1375 print "Accepting connections...\n";
1376 ($addr = accept (NS, S)) or die "accept: $!";
1377 select (NS); $| = 1; select (STDOUT); # Piping hot!
1379 ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
1380 @inetaddr = unpack('C4',$client_ip);
1381 print "$af connection from " .
1382 join ('.', @inetaddr) . ":$client_port\n";
1384 # We now have a network connection, lets fire up SSLeay...
1386 $ssl = Net::SSLeay::new($ctx) or die_now("SSL_new ($ssl): $!");
1387 Net::SSLeay::set_fd($ssl, fileno(NS));
1389 $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
1390 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
1392 # Connected. Exchange some data.
1394 $got = Net::SSLeay::read($ssl); # Returns undef on fail
1395 die_if_ssl_error("ssl read");
1396 print "Got `$got' (" . length ($got) . " chars)\n";
1398 Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
1399 die_if_ssl_error("ssl write");
1401 Net::SSLeay::free ($ssl); # Tear down connection
1405 Yet another echo server. This one runs from C</etc/inetd.conf> so it avoids
1406 all the socket code overhead. Only caveat is opening rsa key file -
1407 it had better be without any encryption or else it will not know where
1408 to ask for the password. Note how C<STDIN> and C<STDOUT> are wired to SSL.
1410 #!/usr/local/bin/perl
1412 # ssltst stream tcp nowait root /path/to/server.pl server.pl
1416 use Net::SSLeay qw(die_now die_if_ssl_error);
1417 Net::SSLeay::load_error_strings();
1418 Net::SSLeay::SSLeay_add_ssl_algorithms();
1419 Net::SSLeay::randomize();
1421 chdir '/key/dir' or die "chdir: $!";
1422 $| = 1; # Piping hot!
1423 open LOG, ">>/dev/console" or die "Can't open log file $!";
1424 select LOG; print "server.pl started\n";
1426 $ctx = Net::SSLeay::CTX_new() or die_now "CTX_new ($ctx) ($!)";
1427 $ssl = Net::SSLeay::new($ctx) or die_now "new ($ssl) ($!)";
1428 Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
1429 and die_if_ssl_error("ssl set options");
1431 # We get already open network connection from inetd, now we just
1432 # need to attach SSLeay to STDIN and STDOUT
1433 Net::SSLeay::set_rfd($ssl, fileno(STDIN));
1434 Net::SSLeay::set_wfd($ssl, fileno(STDOUT));
1436 Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
1437 Net::SSLeay::FILETYPE_PEM);
1438 die_if_ssl_error("private key");
1439 Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
1440 Net::SSLeay::FILETYPE_PEM);
1441 die_if_ssl_error("certificate");
1443 Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
1444 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
1446 $got = Net::SSLeay::read($ssl);
1447 die_if_ssl_error("ssl read");
1448 print "Got `$got' (" . length ($got) . " chars)\n";
1450 Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
1451 die_if_ssl_error("ssl write");
1453 Net::SSLeay::free ($ssl); # Tear down the connection
1454 Net::SSLeay::CTX_free ($ctx);
1457 There are also a number of example/test programs in the examples directory:
1459 sslecho.pl - A simple server, not unlike the one above
1460 minicli.pl - Implements a client using low level SSLeay routines
1461 sslcat.pl - Demonstrates using high level sslcat utility function
1462 get_page.pl - Is a utility for getting html pages from secure servers
1463 callback.pl - Demonstrates certificate verification and callback usage
1464 stdio_bulk.pl - Does SSL over Unix pipes
1465 ssl-inetd-serv.pl - SSL server that can be invoked from inetd.conf
1466 httpd-proxy-snif.pl - Utility that allows you to see how a browser
1467 sends https request to given server and what reply
1468 it gets back (very educative :-)
1469 makecert.pl - Creates a self signed cert (does not use this module)
1473 C<Net::SSLeay::read()> uses internal buffer of 32KB, thus no single read
1474 will return more. In practice one read returns much less, usually
1475 as much as fits in one network packet. To work around this,
1476 you should use a loop like this:
1479 while ($got = Net::SSLeay::read($ssl)) {
1480 last if print_errs('SSL_read');
1484 Although there is no built-in limit in C<Net::SSLeay::write()>, the network
1485 packet size limitation applies here as well, thus use:
1489 while ($written < length($message)) {
1490 $written += Net::SSLeay::write($ssl, substr($message, $written));
1491 last if print_errs('SSL_write');
1494 Or alternatively you can just use the following convinence functions:
1496 Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
1497 $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
1499 =head1 KNOWN BUGS AND CAVEATS
1503 Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'
1505 warning if die_if_ssl_error is made autoloadable. If you figure out why,
1508 Callback set using C<SSL_set_verify()> does not appear to work. This may
1509 well be eay problem (e.g. see C<ssl/ssl_lib.c> line 1029). Try using
1510 C<SSL_CTX_set_verify()> instead and do not be surprised if even this stops
1511 working in future versions.
1513 Callback and certificate verification stuff is generally too little tested.
1515 Random numbers are not initialized randomly enough, especially if you
1516 do not have C</dev/random> and/or C</dev/urandom> (such as in Solaris
1517 platforms - but I've been suggested that cryptorand daemon from SUNski
1518 package solves this). In this case you should investigate third party
1519 software that can emulate these devices, e.g. by way of a named pipe
1522 Another gotcha with random number initialization is randomness
1523 depletion. This phenomenon, which has been extensively discussed in
1524 OpenSSL, Apache-SSL, and Apache-mod_ssl forums, can cause your
1525 script to block if you use C</dev/random> or to operate insecurely
1526 if you use C</dev/urandom>. What happens is that when too much
1527 randomness is drawn from the operating system's randomness pool
1528 then randomness can temporarily be unavailable. C</dev/random> solves
1529 this problem by waiting until enough randomness can be gathered - and
1530 this can take a long time since blocking reduces activity in the
1531 machine and less activity provides less random events: a vicious circle.
1532 C</dev/urandom> solves this dilemma more pragmatically by simply returning
1533 predictable "random" numbers. SomeC< /dev/urandom> emulation software
1534 however actually seems to implement C</dev/random> semantics. Caveat emptor.
1536 I've been pointed to two such daemons by Mik Firestone <mik@@speed.stdio._com>
1537 who has used them on Solaris 8:
1543 Entropy Gathering Daemon (EGD) at L<http://www.lothar.com/tech/crypto/>
1547 Pseudo-random number generating daemon (PRNGD) at
1548 L<http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
1552 If you are using the low level API functions to communicate with other
1553 SSL implementations, you would do well to call
1555 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
1556 and die_if_ssl_error("ssl ctx set options");
1558 to cope with some well know bugs in some other SSL
1559 implementations. The high level API functions always set all known
1560 compatibility options.
1562 Sometimes C<sslcat()> (and the high level HTTPS functions that build on it)
1563 is too fast in signaling the EOF to legacy HTTPS servers. This causes
1564 the server to return empty page. To work around this problem you can
1567 $Net::SSLeay::slowly = 1; # Add sleep so broken servers can keep up
1569 HTTP/1.1 is not supported. Specifically this module does not know to
1570 issue or serve multiple http requests per connection. This is a serious
1571 short coming, but using SSL session cache on your server helps to
1572 alleviate the CPU load somewhat.
1574 As of version 1.09 many newer OpenSSL auxiliary functions were
1575 added (from C<REM_AUTOMATICALLY_GENERATED_1_09> onwards in C<SSLeay.xs>).
1576 Unfortunately I have not had any opportunity to test these. Some of
1577 them are trivial enough that I believe they "just work", but others
1578 have rather complex interfaces with function pointers and all. In these
1579 cases you should proceed wit great caution.
1581 This module defaults to using OpenSSL automatic protocol negotiation
1582 code for automatically detecting the version of the SSL protocol
1583 that the other end talks. With most web servers this works just
1584 fine, but once in a while I get complaints from people that the module
1585 does not work with some web servers. Usually this can be solved
1586 by explicitly setting the protocol version, e.g.
1588 $Net::SSLeay::ssl_version = 2; # Insist on SSLv2
1589 $Net::SSLeay::ssl_version = 3; # Insist on SSLv3
1590 $Net::SSLeay::ssl_version = 10; # Insist on TLSv1
1592 Although the autonegotiation is nice to have, the SSL standards
1593 do not formally specify any such mechanism. Most of the world has
1594 accepted the SSLeay/OpenSSL way of doing it as the de facto standard. But
1595 for the few that think differently, you have to explicitly speak
1596 the correct version. This is not really a bug, but rather a deficiency
1597 in the standards. If a site refuses to respond or sends back some
1598 nonsensical error codes (at SSL handshake level), try this option
1601 The high level API returns the certificate of the peer, thus allowing
1602 one to check what certificate was supplied. However, you will only be
1603 able to check the certificate after the fact, i.e. you already sent
1604 your form data by the time you find out that you did not trust them,
1607 So, while being able to know the certificate after the fact is surely
1608 useful, the security minded would still choose to do the connection
1609 and certificate verification first and only after that exchange data
1610 with the site. Currently none of the high level API functions do
1611 this, thus you would have to program it using the low level API. A
1612 good place to start is to see how C<Net::SSLeay::http_cat()> function
1615 The high level API functions use a global file handle C<SSLCAT_S>
1616 internally. This really should not be a problem because there is no
1617 way to interleave the high level API functions, unless you use threads
1618 (but threads are not very well supported in perl anyway (as of version
1619 5.6.1). However, you may run into problems if you call undocumented
1620 internal functions in an interleaved fashion.
1626 =item Random number generator not seeded!!!
1628 B<(W)> This warning indicates that C<randomize()> was not able to read
1629 C</dev/random> or C</dev/urandom>, possibly because your system does not
1630 have them or they are differently named. You can still use SSL, but
1631 the encryption will not be as strong.
1633 =item open_tcp_connection: destination host not found:`server' (port 123) ($!)
1635 Name lookup for host named C<server> failed.
1637 =item open_tcp_connection: failed `server', 123 ($!)
1639 The name was resolved, but establising the TCP connection failed.
1641 =item msg 123: 1 - error:140770F8:SSL routines:SSL23_GET_SERVER_HELLO:unknown proto
1643 SSLeay error string. First (123) number is PID, second number (1) indicates
1644 the position of the error message in SSLeay error stack. You often see
1645 a pile of these messages as errors cascade.
1647 =item msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)
1649 The same as above, but you didn't call load_error_strings() so SSLeay
1650 couldn't verbosely explain the error. You can still find out what it
1651 means with this command:
1653 /usr/local/ssl/bin/ssleay errstr 02001002
1655 =item Password is being asked for private key
1657 This is normal behaviour if your private key is encrypted. Either
1658 you have to supply the password or you have to use unencrypted
1659 private key. Scan OpenSSL.org for the FAQ that explains how to
1660 do this (or just study examples/makecert.pl which is used
1661 during C<make test> to do just that).
1665 =head1 REPORTING BUGS AND SUPPORT
1667 Bug reports, patch submission, feature requests, subversion access to the latest
1668 source code etc can be obtained at
1669 L<http://alioth.debian.org/projects/net-ssleay>
1671 The developer mailing list (for people interested in contributin to the source code)
1673 L<http://lists.alioth.debian.org/mailman/listinfo/net-ssleay-devel>
1675 Commercial support for Net::SSLeay may be obtained from
1677 Symlabs (netssleay@symlabs.com)
1678 Tel: +351-214.222.630
1679 Fax: +351-214.222.637
1683 There are currently two perl modules for using OpenSSL C
1684 library: C<Net::SSLeay> (maintaned by me) and C<SSLeay> (maintained by OpenSSL
1685 team). This module is the C<Net::SSLeay> variant.
1687 At the time of making this release, Eric's module was still quite
1688 sketchy and could not be used for real work, thus I felt motivated to
1689 make this maintenance release. This module is not planned to evolve to
1690 contain any further functionality, i.e. I will concentrate on just
1691 making a simple SSL connection over TCP socket. Presumably Eric's own
1692 module will offer full SSLeay API one day.
1694 This module uses OpenSSL-0.9.6c. It does not work with any earlier
1695 version and there is no guarantee that it will work with later
1696 versions either, though as long as C API does not change, it
1697 should. This module requires Perl 5.005 or newer, though I
1698 believe it would build with Perl 5.002 or newer.
1702 Please report any bugs or feature requests to
1703 C<bug-net_ssleay.pm at rt.cpan.org>, or through the web interface at
1704 L<http://rt.cpan.org/Public/Dist/Display.html?Name=Net_SSLeay.pm>.
1705 I will be notified, and then you'll automatically be notified of progress on
1706 your bug as I make changes.
1710 You can find documentation for this module with the C<perldoc> command.
1714 You can also look for information at:
1718 =item * AnnoCPAN: Annotated CPAN documentation
1720 L<http://annocpan.org/dist/Net_SSLeay.pm>
1722 =item * CPAN Ratings
1724 L<http://cpanratings.perl.org/d/Net_SSLeay.pm>
1726 =item * RT: CPAN's request tracker
1728 L<http://rt.cpan.org/Public/Dist/Display.html?Name=Net_SSLeay.pm>
1732 L<http://search.cpan.org/dist/Net_SSLeay.pm>
1738 Maintained by Mike McCauley and Florian Ragwitz since November 2005
1740 Originally written by Sampo Kellomäki <sampo@symlabs.com>
1744 Copyright (c) 1996-2003 Sampo Kellomäki <sampo@symlabs.com>
1746 Copyright (C) 2005-2006 Florian Ragwitz <rafl@debian.org>
1748 Copyright (C) 2005 Mike McCauley <mikem@open.com.au>
1750 All Rights Reserved.
1752 Distribution and use of this module is under the same terms as the
1753 OpenSSL package itself (i.e. free, but mandatory attribution; NO
1754 WARRANTY). Please consult LICENSE file in the root of the OpenSSL
1757 While the source distribution of this perl module does not contain
1758 Eric's or OpenSSL's code, if you use this module you will use OpenSSL
1759 library. Please give Eric and OpenSSL team credit (as required by
1762 And remember, you, and nobody else but you, are responsible for
1763 auditing this module and OpenSSL library for security problems,
1764 backdoors, and general suitability for your application.
1768 Net::SSLeay::Handle - File handle interface
1769 ./Net_SSLeay/examples - Example servers and a clients
1770 <http://symlabs.com/Net_SSLeay/index.html> - Net::SSLeay.pm home
1771 <http://symlabs.com/Net_SSLeay/smime.html> - Another module using OpenSSL
1772 <http://www.openssl.org/> - OpenSSL source, documentation, etc
1773 openssl-users-request@openssl.org - General OpenSSL mailing list
1774 <http://home.netscape.com/newsref/std/SSL.html> - SSL Draft specification
1775 <http://www.w3c.org> - HTTP specifications
1776 <http://www.ietf.org/rfc/rfc2617.txt> - How to send password
1777 <http://www.lothar.com/tech/crypto/> - Entropy Gathering Daemon (EGD)
1778 <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
1779 - pseudo-random number generating daemon (PRNGD)
1783 perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
1789 ### Some methods that are macros in C
1791 sub want_nothing { want(shift) == 1 }
1792 sub want_read { want(shift) == 2 }
1793 sub want_write { want(shift) == 3 }
1794 sub want_X509_lookup { want(shift) == 4 }
1797 ### Open TCP stream to given host and port, looking up the details
1798 ### from system databases or DNS.
1801 sub open_tcp_connection {
1802 my ($dest_serv, $port) = @_;
1805 $port = getservbyname($port, 'tcp') unless $port =~ /^\d+$/;
1806 my $dest_serv_ip = gethostbyname($dest_serv);
1807 unless (defined($dest_serv_ip)) {
1808 $errs = "$0 $$: open_tcp_connection: destination host not found:"
1809 . " `$dest_serv' (port $port) ($!)\n";
1810 warn $errs if $trace;
1811 return wantarray ? (0, $errs) : 0;
1813 my $sin = sockaddr_in($port, $dest_serv_ip);
1815 warn "Opening connection to $dest_serv:$port (" .
1816 inet_ntoa($dest_serv_ip) . ")" if $trace>2;
1818 my $proto = getprotobyname('tcp');
1819 if (socket (SSLCAT_S, &PF_INET(), &SOCK_STREAM(), $proto)) {
1820 warn "next connect" if $trace>3;
1821 if (CORE::connect (SSLCAT_S, $sin)) {
1822 my $old_out = select (SSLCAT_S); $| = 1; select ($old_out);
1823 warn "connected to $dest_serv, $port" if $trace>3;
1824 return wantarray ? (1, undef) : 1; # Success
1827 $errs = "$0 $$: open_tcp_connection: failed `$dest_serv', $port ($!)\n";
1828 warn $errs if $trace;
1830 return wantarray ? (0, $errs) : 0; # Fail
1833 ### Open connection via standard web proxy, if one was defined
1834 ### using set_proxy().
1836 sub open_proxy_tcp_connection {
1837 my ($dest_serv, $port) = @_;
1838 return open_tcp_connection($dest_serv, $port) if !$proxyhost;
1840 warn "Connect via proxy: $proxyhost:$proxyport" if $trace>2;
1841 my ($ret, $errs) = open_tcp_connection($proxyhost, $proxyport);
1842 return wantarray ? (0, $errs) : 0 if !$ret; # Connection fail
1844 warn "Asking proxy to connect to $dest_serv:$port" if $trace>2;
1845 #print SSLCAT_S "CONNECT $dest_serv:$port HTTP/1.0$proxyauth$CRLF$CRLF";
1846 #my $line = <SSLCAT_S>; # *** bug? Mixing stdio with syscall read?
1848 tcp_write_all("CONNECT $dest_serv:$port HTTP/1.0$proxyauth$CRLF$CRLF");
1849 return wantarray ? (0,$errs) : 0 if $errs;
1850 ($line, $errs) = tcp_read_until($CRLF . $CRLF, 1024);
1851 warn "Proxy response: $line" if $trace>2;
1852 return wantarray ? (0,$errs) : 0 if $errs;
1853 return wantarray ? (1,'') : 1; # Success
1857 ### read and write helpers that block
1861 my ($replyr, $gotr) = @_;
1862 my $vm = $trace>2 && $linux_debug ?
1863 (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
1864 warn " got " . blength($$gotr) . ':'
1865 . blength($$replyr) . " bytes (VM=$vm).\n" if $trace == 3;
1866 warn " got `$$gotr' (" . blength($$gotr) . ':'
1867 . blength($$replyr) . " bytes, VM=$vm)\n" if $trace>3;
1871 my ($ssl,$how_much) = @_;
1872 $how_much = 2000000000 unless $how_much;
1876 while ($how_much > 0) {
1877 $got = Net::SSLeay::read($ssl,
1878 ($how_much > 32768) ? 32768 : $how_much
1880 last if $errs = print_errs('SSL_read');
1881 $how_much -= blength($got);
1882 debug_read(\$reply, \$got) if $trace>1;
1883 last if $got eq ''; # EOF
1887 return wantarray ? ($reply, $errs) : $reply;
1891 my ($how_much) = @_;
1892 $how_much = 2000000000 unless $how_much;
1893 my ($n, $got, $errs);
1896 my $bsize = 0x10000;
1897 while ($how_much > 0) {
1898 $n = sysread(SSLCAT_S,$got, (($bsize < $how_much) ? $bsize : $how_much));
1899 warn "Read error: $! ($n,$how_much)" unless defined $n;
1902 debug_read(\$reply, \$got) if $trace>1;
1905 return wantarray ? ($reply, $errs) : $reply;
1910 my ($data_ref, $errs);
1916 my ($wrote, $written, $to_write) = (0,0, blength($$data_ref));
1917 my $vm = $trace>2 && $linux_debug ?
1918 (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
1919 warn " write_all VM at entry=$vm\n" if $trace>2;
1921 #sleep 1; # *** DEBUG
1922 warn "partial `$$data_ref'\n" if $trace>3;
1923 $wrote = write_partial($ssl, $written, $to_write, $$data_ref);
1924 if (defined $wrote && ($wrote > 0)) { # write_partial can return -1
1926 $to_write -= $wrote;
1928 $vm = $trace>2 && $linux_debug ?
1929 (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
1930 warn " written so far $wrote:$written bytes (VM=$vm)\n" if $trace>2;
1932 $errs .= print_errs('SSL_write');
1933 return (wantarray ? (undef, $errs) : undef) if $errs;
1935 return wantarray ? ($written, $errs) : $written;
1939 my ($data_ref, $errs);
1945 my ($wrote, $written, $to_write) = (0,0, blength($$data_ref));
1946 my $vm = $trace>2 && $linux_debug ?
1947 (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
1948 warn " write_all VM at entry=$vm to_write=$to_write\n" if $trace>2;
1950 warn "partial `$$data_ref'\n" if $trace>3;
1951 $wrote = syswrite(SSLCAT_S, $$data_ref, $to_write, $written);
1952 if (defined $wrote && ($wrote > 0)) { # write_partial can return -1
1954 $to_write -= $wrote;
1955 } elsif (!defined($wrote)) {
1956 warn "tcp_write_all: $!";
1957 return (wantarray ? (undef, "$!") : undef);
1959 $vm = $trace>2 && $linux_debug ?
1960 (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
1961 warn " written so far $wrote:$written bytes (VM=$vm)\n" if $trace>2;
1963 return wantarray ? ($written, '') : $written;
1966 ### from patch by Clinton Wong <clintdw@netcom.com>
1968 # ssl_read_until($ssl [, $delimit [, $max_length]])
1969 # if $delimit missing, use $/ if it exists, otherwise use \n
1970 # read until delimiter reached, up to $max_length chars if defined
1972 sub ssl_read_until ($;$$) {
1973 my ($ssl,$delim, $max_length) = @_;
1976 # guess the delim string if missing
1977 if ( ! defined $delim ) {
1978 if ( defined $/ && length $/ ) { $delim = $/ }
1979 else { $delim = "\n" } # Note: \n,$/ value depends on the platform
1981 my $len_delim = length $delim;
1986 # If we have OpenSSL 0.9.6a or later, we can use SSL_peek to
1988 # N.B. 0.9.6a has security problems, so the support for
1989 # anything earlier than 0.9.6e will be dropped soon.
1990 if (&Net::SSLeay::OPENSSL_VERSION_NUMBER >= 0x0090601f) {
1991 $max_length = 2000000000 unless (defined $max_length);
1992 my ($pending, $peek_length, $found, $done);
1993 while (blength($reply) < $max_length and !$done) {
1994 #Block if necessary until we get some data
1995 $got = Net::SSLeay::peek($ssl,1);
1996 last if print_errs('SSL_peek');
1998 $pending = Net::SSLeay::pending($ssl) + blength($reply);
1999 $peek_length = ($pending > $max_length) ? $max_length : $pending;
2000 $peek_length -= blength($reply);
2001 $got = Net::SSLeay::peek($ssl, $peek_length);
2002 last if print_errs('SSL_peek');
2003 $peek_length = blength($got);
2005 #$found = index($got, $delim); # Old and broken
2007 # the delimiter may be split across two gets, so we prepend
2008 # a little from the last get onto this one before we check
2011 if(blength($reply) >= blength($delim) - 1) {
2012 #if what we've read so far is greater or equal
2013 #in length of what we need to prepatch
2014 $match = substr $reply, blength($reply) - blength($delim) + 1;
2020 $found = index($match, $delim);
2023 #$got = Net::SSLeay::read($ssl, $found+$len_delim);
2024 #read up to the end of the delimiter
2025 $got = Net::SSLeay::read($ssl,
2027 - ((blength $match) - (blength $got)));
2030 $got = Net::SSLeay::read($ssl, $peek_length);
2031 $done = 1 if ($peek_length == $max_length - blength($reply));
2034 last if print_errs('SSL_read');
2035 debug_read(\$reply, \$got) if $trace>1;
2040 while (!defined $max_length || length $reply < $max_length) {
2041 $got = Net::SSLeay::read($ssl,1); # one by one
2042 last if print_errs('SSL_read');
2043 debug_read(\$reply, \$got) if $trace>1;
2047 && substr($reply, blength($reply)-$len_delim) eq $delim;
2053 sub tcp_read_until {
2054 my ($delim, $max_length) = @_;
2057 # guess the delim string if missing
2058 if ( ! defined $delim ) {
2059 if ( defined $/ && length $/ ) { $delim = $/ }
2060 else { $delim = "\n" } # Note: \n,$/ value depends on the platform
2062 my $len_delim = length $delim;
2067 while (!defined $max_length || length $reply < $max_length) {
2068 $n = sysread(SSLCAT_S, $got, 1); # one by one
2069 warn "tcp_read_until: $!" if !defined $n;
2070 debug_read(\$reply, \$got) if $trace>1;
2074 && substr($reply, blength($reply)-$len_delim) eq $delim;
2079 # ssl_read_CRLF($ssl [, $max_length])
2080 sub ssl_read_CRLF ($;$) { ssl_read_until($_[0], $CRLF, $_[1]) }
2081 sub tcp_read_CRLF { tcp_read_until($CRLF, $_[0]) }
2083 # ssl_write_CRLF($ssl, $message) writes $message and appends CRLF
2084 sub ssl_write_CRLF ($$) {
2085 # the next line uses less memory but might use more network packets
2086 return ssl_write_all($_[0], $_[1]) + ssl_write_all($_[0], $CRLF);
2088 # the next few lines do the same thing at the expense of memory, with
2089 # the chance that it will use less packets, since CRLF is in the original
2090 # message and won't be sent separately.
2093 #if (ref $_[1]) { $data_ref = $_[1] }
2094 # else { $data_ref = \$_[1] }
2095 #my $message = $$data_ref . $CRLF;
2096 #return ssl_write_all($_[0], \$message);
2099 sub tcp_write_CRLF {
2100 # the next line uses less memory but might use more network packets
2101 return tcp_write_all($_[0]) + tcp_write_all($CRLF);
2103 # the next few lines do the same thing at the expense of memory, with
2104 # the chance that it will use less packets, since CRLF is in the original
2105 # message and won't be sent separately.
2108 #if (ref $_[1]) { $data_ref = $_[1] }
2109 # else { $data_ref = \$_[1] }
2110 #my $message = $$data_ref . $CRLF;
2111 #return tcp_write_all($_[0], \$message);
2114 ### Quickly print out with whom we're talking
2116 sub dump_peer_certificate ($) {
2118 my $cert = get_peer_certificate($ssl);
2119 return if print_errs('get_peer_certificate');
2120 print "no cert defined\n" if !defined($cert);
2121 # Cipher=NONE with empty cert fix
2122 if (!defined($cert) || ($cert == 0)) {
2123 warn "cert = `$cert'\n" if $trace;
2124 return "Subject Name: undefined\nIssuer Name: undefined\n";
2126 my $x = 'Subject Name: '
2127 . X509_NAME_oneline(X509_get_subject_name($cert)) . "\n"
2129 . X509_NAME_oneline(X509_get_issuer_name($cert)) . "\n";
2130 Net::SSLeay::X509_free($cert);
2135 ### Arrange some randomness for eay PRNG
2137 sub randomize (;$$) {
2138 my ($rn_seed_file, $seed, $egd_path) = @_;
2139 my $rnsf = defined($rn_seed_file) && -r $rn_seed_file;
2142 $egd_path = $ENV{'EGD_PATH'} if $ENV{'EGD_PATH'};
2144 RAND_seed(rand() + $$); # Stir it with time and pid
2146 unless ($rnsf || -r $Net::SSLeay::random_device || $seed || -S $egd_path) {
2147 warn "Random number generator not seeded!!!" if $trace;
2150 RAND_load_file($rn_seed_file, -s _) if $rnsf;
2151 RAND_seed($seed) if $seed;
2152 RAND_seed($ENV{RND_SEED}) if $ENV{RND_SEED};
2153 RAND_egd($egd_path) if -e $egd_path && -S _;
2154 RAND_load_file($Net::SSLeay::random_device, $Net::SSLeay::how_random/8)
2155 if -r $Net::SSLeay::random_device;
2159 if ($ssl_version == 2) { $ctx = CTX_v2_new(); }
2160 elsif ($ssl_version == 3) { $ctx = CTX_v3_new(); }
2161 elsif ($ssl_version == 10) { $ctx = CTX_tlsv1_new(); }
2162 else { $ctx = CTX_new(); }
2167 ### Basic request - response primitive (don't use for https)
2170 sub sslcat { # address, port, message, $crt, $key --> reply / (reply,errs,cert)
2171 my ($dest_serv, $port, $out_message, $crt_path, $key_path) = @_;
2172 my ($ctx, $ssl, $got, $errs, $written);
2174 ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
2175 return (wantarray ? (undef, $errs) : undef) unless $got;
2177 ### Do SSL negotiation stuff
2179 warn "Creating SSL $ssl_version context...\n" if $trace>2;
2180 load_error_strings(); # Some bloat, but I'm after ease of use
2181 SSLeay_add_ssl_algorithms(); # and debuggability.
2185 goto cleanup2 if $errs = print_errs('CTX_new') or !$ctx;
2187 CTX_set_options($ctx, &OP_ALL);
2188 goto cleanup2 if $errs = print_errs('CTX_set_options');
2190 warn "Cert `$crt_path' given without key" if $crt_path && !$key_path;
2191 set_cert_and_key($ctx, $crt_path, $key_path) if $crt_path;
2193 warn "Creating SSL connection (context was '$ctx')...\n" if $trace>2;
2195 goto cleanup if $errs = print_errs('SSL_new') or !$ssl;
2197 warn "Setting fd (ctx $ctx, con $ssl)...\n" if $trace>2;
2198 set_fd($ssl, fileno(SSLCAT_S));
2199 goto cleanup if $errs = print_errs('set_fd');
2201 warn "Entering SSL negotiation phase...\n" if $trace>2;
2206 my $cipher_list = 'Cipher list: ';
2207 $p=Net::SSLeay::get_cipher_list($ssl,$i);
2208 $cipher_list .= $p if $p;
2211 $cipher_list .= ', ' . $p if $p;
2212 $p=Net::SSLeay::get_cipher_list($ssl,$i);
2214 $cipher_list .= '\n';
2218 $got = Net::SSLeay::connect($ssl);
2219 warn "SSLeay connect returned $got\n" if $trace>2;
2220 goto cleanup if $errs = print_errs('SSL_connect');
2222 my $server_cert = get_peer_certificate($ssl);
2223 print_errs('get_peer_certificate');
2225 warn "Cipher `" . get_cipher($ssl) . "'\n";
2226 print_errs('get_ciper');
2227 warn dump_peer_certificate($ssl);
2230 ### Connected. Exchange some data (doing repeated tries if necessary).
2232 warn "sslcat $$: sending " . blength($out_message) . " bytes...\n"
2234 warn "sslcat $$: sending `$out_message' (" . blength($out_message)
2235 . " bytes)...\n" if $trace>3;
2236 ($written, $errs) = ssl_write_all($ssl, $out_message);
2237 goto cleanup unless $written;
2239 sleep $slowly if $slowly; # Closing too soon can abort broken servers
2240 CORE::shutdown SSLCAT_S, 1; # Half close --> No more output, send EOF to server
2242 warn "waiting for reply...\n" if $trace>2;
2243 ($got, $errs) = ssl_read_all($ssl);
2244 warn "Got " . blength($got) . " bytes.\n" if $trace==3;
2245 warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
2249 $errs .= print_errs('SSL_free');
2252 $errs .= print_errs('CTX_free');
2254 return wantarray ? ($got, $errs, $server_cert) : $got;
2257 sub tcpcat { # address, port, message, $crt, $key --> reply / (reply,errs,cert)
2258 my ($dest_serv, $port, $out_message) = @_;
2259 my ($got, $errs, $written);
2261 ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
2262 return (wantarray ? (undef, $errs) : undef) unless $got;
2264 ### Connected. Exchange some data (doing repeated tries if necessary).
2266 warn "tcpcat $$: sending " . blength($out_message) . " bytes...\n"
2268 warn "tcpcat $$: sending `$out_message' (" . blength($out_message)
2269 . " bytes)...\n" if $trace>3;
2270 ($written, $errs) = tcp_write_all($out_message);
2271 goto cleanup unless $written;
2273 sleep $slowly if $slowly; # Closing too soon can abort broken servers
2274 CORE::shutdown SSLCAT_S, 1; # Half close --> No more output, send EOF to server
2276 warn "waiting for reply...\n" if $trace>2;
2277 ($got, $errs) = tcp_read_all($ssl);
2278 warn "Got " . blength($got) . " bytes.\n" if $trace==3;
2279 warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
2283 return wantarray ? ($got, $errs) : $got;
2287 my ($usessl, $site, $port, $req, $crt_path, $key_path) = @_;
2289 return sslcat($site, $port, $req, $crt_path, $key_path);
2291 return tcpcat($site, $port, $req);
2296 ### Basic request - response primitive, this is different from sslcat
2297 ### because this does not shutdown the connection.
2300 sub https_cat { # address, port, message --> returns reply / (reply,errs,cert)
2301 my ($dest_serv, $port, $out_message, $crt_path, $key_path) = @_;
2302 my ($ctx, $ssl, $got, $errs, $written);
2304 ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
2305 return (wantarray ? (undef, $errs) : undef) unless $got;
2307 ### Do SSL negotiation stuff
2309 warn "Creating SSL $ssl_version context...\n" if $trace>2;
2310 load_error_strings(); # Some bloat, but I'm after ease of use
2311 SSLeay_add_ssl_algorithms(); # and debuggability.
2315 goto cleanup2 if $errs = print_errs('CTX_new') or !$ctx;
2317 CTX_set_options($ctx, &OP_ALL);
2318 goto cleanup2 if $errs = print_errs('CTX_set_options');
2320 warn "Cert `$crt_path' given without key" if $crt_path && !$key_path;
2321 set_cert_and_key($ctx, $crt_path, $key_path) if $crt_path;
2323 warn "Creating SSL connection (context was '$ctx')...\n" if $trace>2;
2325 goto cleanup if $errs = print_errs('SSL_new') or !$ssl;
2327 warn "Setting fd (ctx $ctx, con $ssl)...\n" if $trace>2;
2328 set_fd($ssl, fileno(SSLCAT_S));
2329 goto cleanup if $errs = print_errs('set_fd');
2331 warn "Entering SSL negotiation phase...\n" if $trace>2;
2336 my $cipher_list = 'Cipher list: ';
2337 $p=Net::SSLeay::get_cipher_list($ssl,$i);
2338 $cipher_list .= $p if $p;
2341 $cipher_list .= ', ' . $p if $p;
2342 $p=Net::SSLeay::get_cipher_list($ssl,$i);
2344 $cipher_list .= '\n';
2348 $got = Net::SSLeay::connect($ssl);
2349 warn "SSLeay connect failed" if $trace>2 && $got==0;
2350 goto cleanup if $errs = print_errs('SSL_connect');
2352 my $server_cert = get_peer_certificate($ssl);
2353 print_errs('get_peer_certificate');
2355 warn "Cipher `" . get_cipher($ssl) . "'\n";
2356 print_errs('get_ciper');
2357 warn dump_peer_certificate($ssl);
2360 ### Connected. Exchange some data (doing repeated tries if necessary).
2362 warn "https_cat $$: sending " . blength($out_message) . " bytes...\n"
2364 warn "https_cat $$: sending `$out_message' (" . blength($out_message)
2365 . " bytes)...\n" if $trace>3;
2366 ($written, $errs) = ssl_write_all($ssl, $out_message);
2367 goto cleanup unless $written;
2369 warn "waiting for reply...\n" if $trace>2;
2370 ($got, $errs) = ssl_read_all($ssl);
2371 warn "Got " . blength($got) . " bytes.\n" if $trace==3;
2372 warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
2376 $errs .= print_errs('SSL_free');
2379 $errs .= print_errs('CTX_free');
2381 return wantarray ? ($got, $errs, $server_cert) : $got;
2384 sub http_cat { # address, port, message --> returns reply / (reply,errs,cert)
2385 my ($dest_serv, $port, $out_message) = @_;
2386 my ($got, $errs, $written);
2388 ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
2389 return (wantarray ? (undef, $errs) : undef) unless $got;
2391 ### Connected. Exchange some data (doing repeated tries if necessary).
2393 warn "http_cat $$: sending " . blength($out_message) . " bytes...\n"
2395 warn "http_cat $$: sending `$out_message' (" . blength($out_message)
2396 . " bytes)...\n" if $trace>3;
2397 ($written, $errs) = tcp_write_all($out_message);
2398 goto cleanup unless $written;
2400 warn "waiting for reply...\n" if $trace>2;
2401 ($got, $errs) = tcp_read_all(200000);
2402 warn "Got " . blength($got) . " bytes.\n" if $trace==3;
2403 warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
2407 return wantarray ? ($got, $errs) : $got;
2411 my ($usessl, $site, $port, $req, $crt_path, $key_path) = @_;
2412 warn "httpx_cat: usessl=$usessl ($site:$port)" if $trace;
2414 return https_cat($site, $port, $req, $crt_path, $key_path);
2416 return http_cat($site, $port, $req);
2421 ### Easy set up of private key and certificate
2424 sub set_cert_and_key ($$$) {
2425 my ($ctx, $cert_path, $key_path) = @_;
2427 # Following will ask password unless private key is not encrypted
2428 CTX_use_RSAPrivateKey_file ($ctx, $key_path, &FILETYPE_PEM);
2429 $errs .= print_errs("private key `$key_path' ($!)");
2430 CTX_use_certificate_file ($ctx, $cert_path, &FILETYPE_PEM);
2431 $errs .= print_errs("certificate `$cert_path' ($!)");
2432 return wantarray ? (undef, $errs) : ($errs eq '');
2435 ### Old deprecated API
2437 sub set_server_cert_and_key ($$$) { &set_cert_and_key }
2439 ### Set up to use web proxy
2441 sub set_proxy ($$;**) {
2442 ($proxyhost, $proxyport, $proxyuser, $proxypass) = @_;
2443 require MIME::Base64 if $proxyuser;
2444 $proxyauth = $CRLF . 'Proxy-authorization: Basic '
2445 . MIME::Base64::encode("$proxyuser:$proxypass", '')
2450 ### Easy https manipulation routines
2457 my ($name, $data) = (shift(@fields), shift(@fields));
2458 $data =~ s/([^\w\-.\@\$ ])/sprintf("%%%2.2x",ord($1))/gse;
2460 $form .= "$name=$data&";
2470 my $header = shift(@headers);
2471 my $value = shift(@headers);
2473 $value =~ s/\x0d?\x0a$//; # because we add it soon, see below
2474 $headers .= "$header: $value$CRLF";
2480 my ($method, $usessl, $site, $port, $path, $headers,
2481 $content, $mime_type, $crt_path, $key_path) = @_;
2482 my ($response, $page, $h,$v);
2485 $mime_type = "application/x-www-form-urlencoded" unless $mime_type;
2486 my $len = blength($content);
2487 $content = "Content-Type: $mime_type$CRLF"
2488 . "Content-Length: $len$CRLF$CRLF$content";
2490 $content = "$CRLF$CRLF";
2492 my $req = "$method $path HTTP/1.0$CRLF";
2493 unless (defined $headers && $headers =~ /^Host:/m) {
2494 $req .= "Host: $site";
2495 unless (($port == 80 && !$usessl) || ($port == 443 && $usessl)) {
2500 $req .= (defined $headers ? $headers : '') . "Accept: */*$CRLF$content";
2502 warn "do_httpx3($method,$usessl,$site:$port)" if $trace;
2503 my ($http, $errs, $server_cert)
2504 = httpx_cat($usessl, $site, $port, $req, $crt_path, $key_path);
2505 return (undef, "HTTP/1.0 900 NET OR SSL ERROR$CRLF$CRLF$errs") if $errs;
2507 $http = '' if !defined $http;
2508 ($headers, $page) = split /\s?\n\s?\n/, $http, 2;
2509 warn "headers >$headers< page >>$page<< http >>>$http<<<" if $trace>1;
2510 ($response, $headers) = split /\s?\n/, $headers, 2;
2511 return ($page, $response, $headers, $server_cert);
2514 sub do_https3 { splice(@_,1,0) = 1; do_httpx3; } # Legacy undocumented
2516 ### do_https2() is a legacy version in the sense that it is unable
2517 ### to return all instances of duplicate headers.
2520 my ($page, $response, $headers, $server_cert) = &do_httpx3;
2521 X509_free($server_cert) if defined $server_cert;
2522 return ($page, $response,
2523 map( { ($h,$v)=/^(\S+)\:\s*(.*)$/; (uc($h),$v); }
2524 split(/\s?\n/, $headers)
2529 sub do_https2 { splice(@_,1,0) = 1; do_httpx2; } # Legacy undocumented
2531 ### Returns headers as a hash where multiple instances of same header
2532 ### are handled correctly.
2535 my ($page, $response, $headers, $server_cert) = &do_httpx3;
2536 X509_free($server_cert) if defined $server_cert;
2538 for my $hh (split /\s?\n/, $headers) {
2539 my ($h,$v)=/^(\S+)\:\s*(.*)$/;
2540 push @{$hr{uc($h)}}, $v;
2542 return ($page, $response, \%hr);
2545 sub do_https4 { splice(@_,1,0) = 1; do_httpx4; } # Legacy undocumented
2549 sub get_https { do_httpx2(GET => 1, @_) }
2550 sub post_https { do_httpx2(POST => 1, @_) }
2551 sub put_https { do_httpx2(PUT => 1, @_) }
2552 sub head_https { do_httpx2(HEAD => 1, @_) }
2554 sub get_https3 { do_httpx3(GET => 1, @_) }
2555 sub post_https3 { do_httpx3(POST => 1, @_) }
2556 sub put_https3 { do_httpx3(PUT => 1, @_) }
2557 sub head_https3 { do_httpx3(HEAD => 1, @_) }
2559 sub get_https4 { do_httpx4(GET => 1, @_) }
2560 sub post_https4 { do_httpx4(POST => 1, @_) }
2561 sub put_https4 { do_httpx4(PUT => 1, @_) }
2562 sub head_https4 { do_httpx4(HEAD => 1, @_) }
2566 sub get_http { do_httpx2(GET => 0, @_) }
2567 sub post_http { do_httpx2(POST => 0, @_) }
2568 sub put_http { do_httpx2(PUT => 0, @_) }
2569 sub head_http { do_httpx2(HEAD => 0, @_) }
2571 sub get_http3 { do_httpx3(GET => 0, @_) }
2572 sub post_http3 { do_httpx3(POST => 0, @_) }
2573 sub put_http3 { do_httpx3(PUT => 0, @_) }
2574 sub head_http3 { do_httpx3(HEAD => 0, @_) }
2576 sub get_http4 { do_httpx4(GET => 0, @_) }
2577 sub post_http4 { do_httpx4(POST => 0, @_) }
2578 sub put_http4 { do_httpx4(PUT => 0, @_) }
2579 sub head_http4 { do_httpx4(HEAD => 0, @_) }
2581 # Either https or http
2583 sub get_httpx { do_httpx2(GET => @_) }
2584 sub post_httpx { do_httpx2(POST => @_) }
2585 sub put_httpx { do_httpx2(PUT => @_) }
2586 sub head_httpx { do_httpx2(HEAD => @_) }
2588 sub get_httpx3 { do_httpx3(GET => @_) }
2589 sub post_httpx3 { do_httpx3(POST => @_) }
2590 sub put_httpx3 { do_httpx3(PUT => @_) }
2591 sub head_httpx3 { do_httpx3(HEAD => @_) }
2593 sub get_httpx4 { do_httpx4(GET => @_) }
2594 sub post_httpx4 { do_httpx4(POST => @_) }
2595 sub put_httpx4 { do_httpx4(PUT => @_) }
2596 sub head_httpx4 { do_httpx4(HEAD => @_) }
2598 ### Legacy, don't use
2599 # ($page, $respone_or_err, %headers) = do_https(...);
2602 my ($site, $port, $path, $method, $headers,
2603 $content, $mime_type, $crt_path, $key_path) = @_;
2605 do_https2($method, $site, $port, $path, $headers,
2606 $content, $mime_type, $crt_path, $key_path);