home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / SSLeay.pm < prev    next >
Encoding:
Perl POD Document  |  2003-08-17  |  78.7 KB  |  2,319 lines

  1. # Net::SSLeay.pm - Perl module for using Eric Young's implementation of SSL
  2. #
  3. # Copyright (c) 1996-2003 Sampo Kellomaki <sampo@iki.fi>, All Rights Reserved.
  4. # $Id: SSLeay.pm,v 1.26 2003/08/17 07:44:47 sampo Exp $
  5. # Version 1.04, 31.3.1999
  6. # 30.7.1999, Tracking OpenSSL-0.9.3a changes, --Sampo
  7. # 31.7.1999, version 1.05 --Sampo
  8. # 7.4.2001,  fixed input error upon 0, OpenSSL-0.9.6a, version 1.06 --Sampo
  9. # 18.4.2001, added TLSv1 support by Stephen C. Koehler
  10. #            <koehler@securecomputing.com>, version 1.07, --Sampo
  11. # 25.4.2001, 64 bit fixes by Marko Asplund <aspa@kronodoc.fi> --Sampo
  12. # 17.4.2001, more error codes from aspa --Sampo
  13. # 25.9.2001, added heaps and piles of newer OpenSSL auxiliary functions --Sampo
  14. # 6.11.2001, got rid of $p_errs madness --Sampo
  15. # 9.11.2001, added EGD (entropy gathering daemon) reference info --Sampo
  16. # 7.12.2001, Added proxy support by Bruno De Wolf <bruno.dewolf@@pandora._be>
  17. # 6.1.2002,  cosmetic fix to socket options from Kwindla Hultman Kramer <kwindla@@allafrica_.com>
  18. # 25.3.2002, added post_https_cert and friends per patch from
  19. #            mock@@obscurity.ogr, --Sampo
  20. # 3.4.2002,  added `use bytes' from Marcus Taylor <marcus@@semantico_.com>
  21. #            This avoids unicode/utf8 (as may appear in some XML docs)
  22. #            from fooling the length comuptations. Dropped support for
  23. #            perl5.005_03 because I do not have opportunity to test it. --Sampo
  24. # 5.4.2002,  improved Unicode gotcha eliminator to support old perls --Sampo
  25. # 8.4.2002,  added a small line end fix from Petr Dousa (pdousa@@kerio_.com)
  26. # 17.5.2002, Added BIO_s_mem, BIO_new, BIO_free, BIO_write, BIO_read 
  27. #            BIO_eof, BIO_pending, BIO_wpending, RSA_generate_key, RSA_free
  28. #            --mikem@open._com.au
  29. # 10.8.2002, Added SSL_peek patch to ssl_read_until from 
  30. #            Peter Behroozi <peter@@fhpwireless_.com> --Sampo
  31. # 21.8.2002, Added SESSION_get_master_key, SSL_get_client_random, SSL_get_server_random
  32. #            --mikem@open.com_.au
  33. # 2.9.2002,  Added SSL_CTX_get_cert_store, X509_STORE_add_cert, X509_STORE_add_crl
  34. #            X509_STORE_set_flags, X509_load_cert_file, X509_load_crl_file
  35. #            X509_load_cert_crl_file, PEM_read_bio_X509_CRL,
  36. #            constants for X509_V_FLAG_* in order to support certificate revocation lists.
  37. #            --mikem@open.com_.au
  38. # 6.9.2002,  fixed X509_STORE_set_flags to X509_STORE_CTX_set_flags, --Sampo
  39. # 19.9.2002, applied patch from Tim Engler <tim@burntcouch_.com>
  40. # 18.2.2003, applied patch from Toni Andjelkovic <toni@soth._at>
  41. # 13.6.2003, partially applied leak patch by Marian Jancar <mjancar@suse._cz>
  42. # 25.6.2003, write_partial() return value patch from 
  43. #            Kim Minh Kaplan <kmkaplan@selfoffice._com>
  44. # 17.8.2003, added http support :-) --Sampo
  45. # 17.8.2003, started 1.25 dev --Sampo
  46. #
  47. # The distribution and use of this module are subject to the conditions
  48. # listed in LICENSE file at the root of OpenSSL-0.9.7b
  49. # distribution (i.e. free, but mandatory attribution and NO WARRANTY).
  50.  
  51. package Net::SSLeay;
  52.  
  53. use strict;
  54. use Carp;
  55. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD $CRLF);
  56. use Socket;
  57. use Errno;
  58.  
  59. require Exporter;
  60. require DynaLoader;
  61. use AutoLoader;
  62.  
  63. # 0=no warns, 1=only errors, 2=ciphers, 3=progress, 4=dump data
  64. $Net::SSLeay::trace = 0;  # Do not change here, use
  65.                           # $Net::SSLeay::trace = [1-4]  in caller
  66.  
  67. # 2 = insist on v2 SSL protocol
  68. # 3 = insist on v3 SSL
  69. # 10 = insist on TLSv1
  70. # 0 or undef = guess (v23)
  71. #
  72. $Net::SSLeay::ssl_version = 0;  # don't change here, use 
  73.                                 # Net::SSLeay::version=[2,3,0] in caller
  74.  
  75. #define to enable the "cat /proc/$$/stat" stuff
  76. $Net::SSLeay::linux_debug = 0;
  77.  
  78. # Number of seconds to sleep after sending message and before half
  79. # closing connection. Useful with antiquated broken servers.
  80. $Net::SSLeay::slowly = 0;
  81.  
  82. # RANDOM NUMBER INITIALIZATION
  83. #
  84. # Edit to your taste. Using /dev/random would be more secure, but may
  85. # block if randomness is not available, thus the default is
  86. # /dev/urandom. $how_random determines how many bits of randomness to take
  87. # from the device. You should take enough (read SSLeay/doc/rand), but
  88. # beware that randomness is limited resource so you should not waste
  89. # it either or you may end up with randomness depletion (situation where
  90. # /dev/random would block and /dev/urandom starts to return predictable
  91. # numbers).
  92. #
  93. # N.B. /dev/urandom does not exit on all systems, such as Solaris 2.6. In that
  94. #      case you should get a third party package that emulates /dev/urandom
  95. #      (e.g. via named pipe) or supply a random number file. Some such
  96. #      packages are documented in Caveat section of the POD documentation.
  97.  
  98. $Net::SSLeay::random_device = '/dev/urandom';
  99. $Net::SSLeay::how_random = 512;
  100.  
  101. $VERSION = '1.25';
  102. @ISA = qw(Exporter DynaLoader);
  103. @EXPORT_OK = qw(
  104.     AT_MD5_WITH_RSA_ENCRYPTION
  105.     CB_ACCEPT_EXIT
  106.     CB_ACCEPT_LOOP
  107.     CB_CONNECT_EXIT
  108.     CB_CONNECT_LOOP
  109.     CK_DES_192_EDE3_CBC_WITH_MD5
  110.     CK_DES_192_EDE3_CBC_WITH_SHA
  111.     CK_DES_64_CBC_WITH_MD5
  112.     CK_DES_64_CBC_WITH_SHA
  113.     CK_DES_64_CFB64_WITH_MD5_1
  114.     CK_IDEA_128_CBC_WITH_MD5
  115.     CK_NULL
  116.     CK_NULL_WITH_MD5
  117.     CK_RC2_128_CBC_EXPORT40_WITH_MD5
  118.     CK_RC2_128_CBC_WITH_MD5
  119.     CK_RC4_128_EXPORT40_WITH_MD5
  120.     CK_RC4_128_WITH_MD5
  121.     CLIENT_VERSION
  122.     ERROR_NONE
  123.     ERROR_SSL
  124.     ERROR_SYSCALL
  125.     ERROR_WANT_CONNECT
  126.     ERROR_WANT_READ
  127.     ERROR_WANT_WRITE
  128.     ERROR_WANT_X509_LOOKUP
  129.     ERROR_ZERO_RETURN
  130.     CT_X509_CERTIFICATE
  131.     FILETYPE_ASN1
  132.     FILETYPE_PEM
  133.     F_CLIENT_CERTIFICATE
  134.     F_CLIENT_HELLO
  135.     F_CLIENT_MASTER_KEY
  136.     F_D2I_SSL_SESSION
  137.     F_GET_CLIENT_FINISHED
  138.     F_GET_CLIENT_HELLO
  139.     F_GET_CLIENT_MASTER_KEY
  140.     F_GET_SERVER_FINISHED
  141.     F_GET_SERVER_HELLO
  142.     F_GET_SERVER_VERIFY
  143.     F_I2D_SSL_SESSION
  144.     F_READ_N
  145.     F_REQUEST_CERTIFICATE
  146.     F_SERVER_HELLO
  147.     F_SSL_ACCEPT
  148.     F_SSL_CERT_NEW
  149.     F_SSL_CONNECT
  150.     F_SSL_ENC_DES_CBC_INIT
  151.     F_SSL_ENC_DES_CFB_INIT
  152.     F_SSL_ENC_DES_EDE3_CBC_INIT
  153.     F_SSL_ENC_IDEA_CBC_INIT
  154.     F_SSL_ENC_NULL_INIT
  155.     F_SSL_ENC_RC2_CBC_INIT
  156.     F_SSL_ENC_RC4_INIT
  157.     F_SSL_GET_NEW_SESSION
  158.     F_SSL_MAKE_CIPHER_LIST
  159.     F_SSL_NEW
  160.     F_SSL_READ
  161.     F_SSL_RSA_PRIVATE_DECRYPT
  162.     F_SSL_RSA_PUBLIC_ENCRYPT
  163.     F_SSL_SESSION_NEW
  164.     F_SSL_SESSION_PRINT_FP
  165.     F_SSL_SET_CERTIFICATE
  166.     F_SSL_SET_FD
  167.     F_SSL_SET_RFD
  168.     F_SSL_SET_WFD
  169.     F_SSL_STARTUP
  170.     F_SSL_USE_CERTIFICATE
  171.     F_SSL_USE_CERTIFICATE_ASN1
  172.     F_SSL_USE_CERTIFICATE_FILE
  173.     F_SSL_USE_PRIVATEKEY
  174.     F_SSL_USE_PRIVATEKEY_ASN1
  175.     F_SSL_USE_PRIVATEKEY_FILE
  176.     F_SSL_USE_RSAPRIVATEKEY
  177.     F_SSL_USE_RSAPRIVATEKEY_ASN1
  178.     F_SSL_USE_RSAPRIVATEKEY_FILE
  179.     F_WRITE_PENDING
  180.     MAX_MASTER_KEY_LENGTH_IN_BITS
  181.     MAX_RECORD_LENGTH_2_BYTE_HEADER
  182.     MAX_RECORD_LENGTH_3_BYTE_HEADER
  183.     MAX_SSL_SESSION_ID_LENGTH_IN_BYTES
  184.     MIN_RSA_MODULUS_LENGTH_IN_BYTES
  185.     MT_CLIENT_CERTIFICATE
  186.     MT_CLIENT_FINISHED
  187.     MT_CLIENT_HELLO
  188.     MT_CLIENT_MASTER_KEY
  189.     MT_ERROR
  190.     MT_REQUEST_CERTIFICATE
  191.     MT_SERVER_FINISHED
  192.     MT_SERVER_HELLO
  193.     MT_SERVER_VERIFY
  194.     NOTHING
  195.     OPENSSL_VERSION_NUMBER
  196.     PE_BAD_CERTIFICATE
  197.     PE_NO_CERTIFICATE
  198.     PE_NO_CIPHER
  199.     PE_UNSUPPORTED_CERTIFICATE_TYPE
  200.     READING
  201.     RWERR_BAD_MAC_DECODE
  202.     RWERR_BAD_WRITE_RETRY
  203.     RWERR_INTERNAL_ERROR
  204.     R_BAD_AUTHENTICATION_TYPE
  205.     R_BAD_CHECKSUM
  206.     R_BAD_MAC_DECODE
  207.     R_BAD_RESPONSE_ARGUMENT
  208.     R_BAD_SSL_FILETYPE
  209.     R_BAD_SSL_SESSION_ID_LENGTH
  210.     R_BAD_STATE
  211.     R_BAD_WRITE_RETRY
  212.     R_CHALLENGE_IS_DIFFERENT
  213.     R_CIPHER_CODE_TOO_LONG
  214.     R_CIPHER_TABLE_SRC_ERROR
  215.     R_CONECTION_ID_IS_DIFFERENT
  216.     R_INVALID_CHALLENGE_LENGTH
  217.     R_NO_CERTIFICATE_SET
  218.     R_NO_CERTIFICATE_SPECIFIED
  219.     R_NO_CIPHER_LIST
  220.     R_NO_CIPHER_MATCH
  221.     R_NO_CIPHER_WE_TRUST
  222.     R_NO_PRIVATEKEY
  223.     R_NO_PUBLICKEY
  224.     R_NO_READ_METHOD_SET
  225.     R_NO_WRITE_METHOD_SET
  226.     R_NULL_SSL_CTX
  227.     R_PEER_DID_NOT_RETURN_A_CERTIFICATE
  228.     R_PEER_ERROR
  229.     R_PEER_ERROR_CERTIFICATE
  230.     R_PEER_ERROR_NO_CIPHER
  231.     R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
  232.     R_PERR_ERROR_NO_CERTIFICATE
  233.     R_PUBLIC_KEY_ENCRYPT_ERROR
  234.     R_PUBLIC_KEY_IS_NOT_RSA
  235.     R_PUBLIC_KEY_NO_RSA
  236.     R_READ_WRONG_PACKET_TYPE
  237.     R_REVERSE_KEY_ARG_LENGTH_IS_WRONG
  238.     R_REVERSE_MASTER_KEY_LENGTH_IS_WRONG
  239.     R_REVERSE_SSL_SESSION_ID_LENGTH_IS_WRONG
  240.     R_SHORT_READ
  241.     R_SSL_SESSION_ID_IS_DIFFERENT
  242.     R_UNABLE_TO_EXTRACT_PUBLIC_KEY
  243.     R_UNDEFINED_INIT_STATE
  244.     R_UNKNOWN_REMOTE_ERROR_TYPE
  245.     R_UNKNOWN_STATE
  246.     R_UNSUPORTED_CIPHER
  247.     R_WRONG_PUBLIC_KEY_TYPE
  248.     R_X509_LIB
  249.     SERVER_VERSION
  250.     SESSION
  251.     SESSION_ASN1_VERSION
  252.     ST_ACCEPT
  253.     ST_BEFORE
  254.     ST_CLIENT_START_ENCRYPTION
  255.     ST_CONNECT
  256.     ST_GET_CLIENT_FINISHED_A
  257.     ST_GET_CLIENT_FINISHED_B
  258.     ST_GET_CLIENT_HELLO_A
  259.     ST_GET_CLIENT_HELLO_B
  260.     ST_GET_CLIENT_MASTER_KEY_A
  261.     ST_GET_CLIENT_MASTER_KEY_B
  262.     ST_GET_SERVER_FINISHED_A
  263.     ST_GET_SERVER_FINISHED_B
  264.     ST_GET_SERVER_HELLO_A
  265.     ST_GET_SERVER_HELLO_B
  266.     ST_GET_SERVER_VERIFY_A
  267.     ST_GET_SERVER_VERIFY_B
  268.     ST_INIT
  269.     ST_OK
  270.     ST_READ_BODY
  271.     ST_READ_HEADER
  272.     ST_SEND_CLIENT_CERTIFICATE_A
  273.     ST_SEND_CLIENT_CERTIFICATE_B
  274.     ST_SEND_CLIENT_CERTIFICATE_C
  275.     ST_SEND_CLIENT_CERTIFICATE_D
  276.     ST_SEND_CLIENT_FINISHED_A
  277.     ST_SEND_CLIENT_FINISHED_B
  278.     ST_SEND_CLIENT_HELLO_A
  279.     ST_SEND_CLIENT_HELLO_B
  280.     ST_SEND_CLIENT_MASTER_KEY_A
  281.     ST_SEND_CLIENT_MASTER_KEY_B
  282.     ST_SEND_REQUEST_CERTIFICATE_A
  283.     ST_SEND_REQUEST_CERTIFICATE_B
  284.     ST_SEND_REQUEST_CERTIFICATE_C
  285.     ST_SEND_REQUEST_CERTIFICATE_D
  286.     ST_SEND_SERVER_FINISHED_A
  287.     ST_SEND_SERVER_FINISHED_B
  288.     ST_SEND_SERVER_HELLO_A
  289.     ST_SEND_SERVER_HELLO_B
  290.     ST_SEND_SERVER_VERIFY_A
  291.     ST_SEND_SERVER_VERIFY_B
  292.     ST_SERVER_START_ENCRYPTION
  293.     ST_X509_GET_CLIENT_CERTIFICATE
  294.     ST_X509_GET_SERVER_CERTIFICATE
  295.     TXT_DES_192_EDE3_CBC_WITH_MD5
  296.     TXT_DES_192_EDE3_CBC_WITH_SHA
  297.     TXT_DES_64_CBC_WITH_MD5
  298.     TXT_DES_64_CBC_WITH_SHA
  299.     TXT_DES_64_CFB64_WITH_MD5_1
  300.     TXT_IDEA_128_CBC_WITH_MD5
  301.     TXT_NULL
  302.     TXT_NULL_WITH_MD5
  303.     TXT_RC2_128_CBC_EXPORT40_WITH_MD5
  304.     TXT_RC2_128_CBC_WITH_MD5
  305.     TXT_RC4_128_EXPORT40_WITH_MD5
  306.     TXT_RC4_128_WITH_MD5
  307.     VERIFY_CLIENT_ONCE
  308.     VERIFY_FAIL_IF_NO_PEER_CERT
  309.     VERIFY_NONE
  310.     VERIFY_PEER
  311.     WRITING
  312.     X509_LOOKUP
  313.     X509_V_FLAG_CB_ISSUER_CHECK
  314.     X509_V_FLAG_USE_CHECK_TIME
  315.     X509_V_FLAG_CRL_CHECK
  316.     X509_V_FLAG_CRL_CHECK_ALL
  317.     X509_V_FLAG_IGNORE_CRITICAL
  318.     CTX_new
  319.     CTX_v2_new
  320.     CTX_v3_new
  321.     CTX_v23_new
  322.     CTX_free
  323.     new
  324.     free
  325.     accept
  326.     clear
  327.     connect
  328.     set_fd
  329.     set_rfd
  330.     set_wfd
  331.     get_fd
  332.     read
  333.     write
  334.     peek
  335.     use_RSAPrivateKey
  336.     use_RSAPrivateKey_ASN1
  337.     use_RSAPrivateKey_file
  338.     CTX_use_RSAPrivateKey_file
  339.     use_PrivateKey
  340.     use_PrivateKey_ASN1
  341.     use_PrivateKey_file
  342.     use_certificate
  343.     use_certificate_ASN1
  344.     use_certificate_file
  345.     CTX_use_certificate_file
  346.     load_error_strings
  347.     ERR_load_SSL_strings
  348.     ERR_load_RAND_strings
  349.     state_string
  350.     rstate_string
  351.     state_string_long
  352.     rstate_string_long
  353.     get_time
  354.     set_time
  355.     get_timeout
  356.     set_timeout
  357.     copy_session_id
  358.     set_read_ahead
  359.     get_read_ahead
  360.     pending
  361.     get_cipher_list
  362.     set_cipher_list
  363.     get_cipher
  364.     get_shared_ciphers
  365.     get_peer_certificate
  366.     set_verify
  367.     flush_sessions
  368.     set_bio
  369.     get_rbio
  370.     get_wbio
  371.     SESSION_new
  372.     SESSION_print
  373.     SESSION_free
  374.     i2d_SSL_SESSION
  375.     set_session
  376.     add_session
  377.     remove_session
  378.     d2i_SSL_SESSION
  379.     BIO_f_ssl
  380.     BIO_new
  381.     BIO_new_file
  382.         BIO_s_mem
  383.         BIO_free
  384.         BIO_read
  385.         BIO_write
  386.     BIO_eof
  387.     BIO_pending
  388.     BIO_wpending
  389.     ERR_get_error
  390.     ERR_error_string
  391.     err
  392.     clear_error
  393.     X509_get_issuer_name
  394.     X509_get_subject_name
  395.         X509_NAME_oneline
  396.     X509_NAME_get_text_by_NID
  397.     CTX_get_cert_store
  398.     X509_STORE_add_cert
  399.     X509_STORE_add_crl
  400.     X509_STORE_CTX_set_flags
  401.     X509_load_cert_file
  402.     X509_load_crl_file
  403.     X509_load_cert_crl_file
  404.     PEM_read_bio_X509_CRL
  405.     die_if_ssl_error
  406.     die_now
  407.     print_errs
  408.     set_cert_and_key
  409.     set_server_cert_and_key
  410.         make_form
  411.         make_headers
  412.     do_https
  413.     get_https
  414.         post_https
  415.     get_https4
  416.         post_https4
  417.         sslcat
  418.     ssl_read_CRLF
  419.     ssl_read_all
  420.     ssl_read_until
  421.     ssl_write_CRLF
  422.         ssl_write_all
  423.     get_http
  424.         post_http
  425.     get_httpx
  426.         post_httpx
  427.     get_http4
  428.         post_http4
  429.     get_httpx4
  430.         post_httpx4
  431.         tcpcat
  432.         tcpxcat
  433.     tcp_read_CRLF
  434.     tcp_read_all
  435.     tcp_read_until
  436.     tcp_write_CRLF
  437.         tcp_write_all
  438.         dump_peer_certificate
  439.     RSA_generate_key
  440.     RSA_free
  441.     X509_free
  442.     SESSION_get_master_key
  443.     get_client_random
  444.     get_server_random
  445. );
  446.  
  447. sub AUTOLOAD {
  448.     # This AUTOLOAD is used to 'autoload' constants from the constant()
  449.     # XS function.  If a constant is not found then control is passed
  450.     # to the AUTOLOAD in AutoLoader.
  451.  
  452.     my $constname;
  453.     ($constname = $AUTOLOAD) =~ s/.*:://;
  454.     my $val = constant($constname);
  455.     if ($! != 0) {
  456.     if ($! =~ /((Invalid)|(not valid))/i || $!{EINVAL}) {
  457.         $AutoLoader::AUTOLOAD = $AUTOLOAD;
  458.         goto &AutoLoader::AUTOLOAD;
  459.     }
  460.     else {
  461.       croak "Your vendor has not defined SSLeay macro $constname";
  462.     }
  463.     }
  464.     eval "sub $AUTOLOAD { $val }";
  465.     goto &$AUTOLOAD;
  466. }
  467.  
  468. bootstrap Net::SSLeay $VERSION;
  469.  
  470. # Preloaded methods go here.
  471.  
  472. $CRLF = "\x0d\x0a";  # because \r\n is not fully portable
  473.  
  474. ### Print SSLeay error stack
  475.  
  476. sub print_errs {
  477.     my ($msg) = @_;
  478.     my ($count, $err, $errs, $e) = (0,0,'');
  479.     while ($err = ERR_get_error()) {
  480.         $count ++;
  481.     $e = "$msg $$: $count - " . ERR_error_string($err) . "\n";
  482.     $errs .= $e;
  483.     warn $e if $Net::SSLeay::trace;
  484.     }
  485.     return $errs;
  486. }
  487.  
  488. # Death is conditional to SSLeay errors existing, i.e. this function checks
  489. # for errors and only dies in affirmative.
  490. # usage: Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
  491.  
  492. sub die_if_ssl_error {
  493.     my ($msg) = @_;    
  494.     die "$$: $msg\n" if print_errs($msg);
  495. }
  496.  
  497. # Unconditional death. Used to print SSLeay errors before dying.
  498. # usage: Net::SSLeay:connect($ssl) or die_now("Failed SSL connect ($!)");
  499.  
  500. sub die_now {
  501.     my ($msg) = @_;    
  502.     print_errs($msg);
  503.     die "$$: $msg\n";
  504. }
  505.  
  506. # Perl 5.6.* unicode support causes that length() no longer reliably
  507. # reflects the byte length of a string. This eval is to fix that.
  508. # Thanks to Sean Burke for the snippet.
  509.  
  510. BEGIN{ 
  511. eval 'use bytes; sub blength ($) { length $_[0] }'; 
  512. $@ and eval '    sub blength ($) { length $_[0] }' ; 
  513. }
  514.  
  515. # Autoload methods go after =cut, and are processed by the autosplit program.
  516.  
  517. 1;
  518. __END__
  519. # Documentation. Use `perl-root/pod/pod2html SSLeay.pm` to output html
  520.  
  521. =head1 NAME
  522.  
  523. Net::SSLeay - Perl extension for using OpenSSL
  524.  
  525. =head1 SYNOPSIS
  526.  
  527.   use Net::SSLeay, qw(get_https post_https sslcat make_headers make_form);
  528.  
  529.   ($page) = get_https('www.bacus.pt', 443, '/');                 # 1
  530.  
  531.   ($page, $response, %reply_headers)
  532.      = get_https('www.bacus.pt', 443, '/',                   # 2
  533.          make_headers(User-Agent => 'Cryptozilla/5.0b1',
  534.                  Referer    => 'https://www.bacus.pt'
  535.         ));
  536.  
  537.   ($page, $result, %headers) =                                   # 2b
  538.          = get_https('www.bacus.pt', 443, '/protected.html',
  539.           make_headers(Authorization =>
  540.                'Basic ' . MIME::Base64::encode("$user:$pass",''))
  541.           );
  542.  
  543.   ($page, $response, %reply_headers)
  544.      = post_https('www.bacus.pt', 443, '/foo.cgi', '',       # 3
  545.         make_form(OK   => '1',
  546.               name => 'Sampo'
  547.         ));
  548.  
  549.   $reply = sslcat($host, $port, $request);                       # 4
  550.  
  551.   ($reply, $err, $server_cert) = sslcat($host, $port, $request); # 5
  552.  
  553.   $Net::SSLeay::trace = 2;  # 0=no debugging, 1=ciphers, 2=trace, 3=dump data
  554.  
  555. =head1 DESCRIPTION
  556.  
  557. There is a related module called Net::SSLeay::Handle included in this
  558. distribution that you might want to use instead. It has its own pod
  559. documentation.
  560.  
  561. This module offers some high level convinience functions for accessing
  562. web pages on SSL servers (for symmetry, same API is offered for
  563. accessing http servers, too), a sslcat() function for writing your own
  564. clients, and finally access to the SSL api of SSLeay/OpenSSL package
  565. so you can write servers or clients for more complicated applications.
  566.  
  567. For high level functions it is most convinient to import them to your
  568. main namespace as indicated in the synopsis.
  569.  
  570. Case 1 demonstrates typical invocation of get_https() to fetch an HTML
  571. page from secure server. The first argument provides host name or ip
  572. in dotted decimal notation of the remote server to contact. Second
  573. argument is the TCP port at the remote end (your own port is picked
  574. arbitrarily from high numbered ports as usual for TCP). The third
  575. argument is the URL of the page without the host name part. If in
  576. doubt consult HTTP specifications at <http://www.w3c.org>
  577.  
  578. Case 2 demonstrates full fledged use of get_https(). As can be seen,
  579. get_https() parses the response and response headers and returns them as
  580. a list, which can be captured in a hash for later reference. Also a
  581. fourth argument to get_https() is used to insert some additional headers
  582. in the request. make_headers() is a function that will convert a list or
  583. hash to such headers. By default get_https() supplies Host (make virtual
  584. hosting easy) and Accept (reportedly needed by IIS) headers.
  585.  
  586. Case 2b demonstrates how to get password protected page. Refer to
  587. HTTP protocol specifications for further details (e.g. RFC2617).
  588.  
  589. Case 3 invokes post_https() to submit a HTML/CGI form to secure
  590. server. First four arguments are equal to get_https() (note that empty
  591. string ('') is passed as header argument). The fifth argument is the
  592. contents of the form formatted according to CGI specification. In this
  593. case the helper function make_https() is used to do the formatting,
  594. but you could pass any string. The post_https() automatically adds
  595. Content-Type and Content-Length headers to the request.
  596.  
  597. Case 4 shows the fundamental sslcat() function (inspired in spirit by
  598. netcat utility :-). Its your swiss army knife that allows you to
  599. easily contact servers, send some data, and then get the response. You
  600. are responsible for formatting the data and parsing the response -
  601. sslcat() is just a transport.
  602.  
  603. Case 5 is a full invocation of sslcat() which allows return of errors
  604. as well as the server (peer) certificate.
  605.  
  606. The $trace global variable can be used to control the verbosity of high
  607. level functions. Level 0 guarantees silence, level 1 (the default)
  608. only emits error messages.
  609.  
  610. =head2 Alternate versions of the API
  611.  
  612. The above mentioned functions actually return the response headers as
  613. a list, which only gets converted to hash upon assignment (this
  614. assignment looses information if the same header occurs twice, as may
  615. be the case with cookies). There are also other variants of the
  616. functions that return unprocessed headers and that return a reference
  617. to a hash.
  618.  
  619.   ($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
  620.   for ($i = 0; $i < $#headers; $i+=2) {
  621.       print "$headers[$i] = " . $headers[$i+1] . "\n";
  622.   }
  623.   
  624.   ($page, $response, $headers, $server_cert)
  625.     = get_https3('www.bacus.pt', 443, '/');
  626.   print "$headers\n";
  627.  
  628.   ($page, $response, %headers_ref, $server_cert)
  629.     = get_https4('www.bacus.pt', 443, '/');
  630.   for $k (sort keys %{headers_ref}) {
  631.       for $v (@{$headers_ref{$k}}) {
  632.       print "$k = $v\n";
  633.       }
  634.   }
  635.  
  636. All of the above code fragments accomplish the same thing: display all
  637. values of all headers. The API functions ending in "3" return the
  638. headers simply as a scalar string and it is up to the application to
  639. split them up. The functions ending in "4" return a reference to
  640. hash of arrays (see perlref and perllol manual pages if you are
  641. not familiar with complex perl data structures). To access single value
  642. of such header hash you would do something like
  643.  
  644.   print $headers_ref{COOKIE}[0];
  645.  
  646. The variants 3 and 4 also allow you to discover the server certificate
  647. in case you would like to store or display it, e.g.
  648.  
  649.   ($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
  650.   if (!defined($server_cert) || ($server_cert == 0)) {
  651.       warn "Subject Name: undefined, Issuer  Name: undefined";
  652.   } else {
  653.       warn 'Subject Name: '
  654.       . Net::SSLeay::X509_NAME_oneline(
  655.          Net::SSLeay::X509_get_subject_name($server_cert))
  656.           . 'Issuer  Name: '
  657.           . Net::SSLeay::X509_NAME_oneline(
  658.                          Net::SSLeay::X509_get_issuer_name($server_cert));
  659.   }
  660.  
  661. Beware that this method only allows after the fact verification of
  662. the certificate: by the time get_https3() has returned the https
  663. request has already been sent to the server, whether you decide to
  664. tryst it or not. To do the verification correctly you must either
  665. employ the OpenSSL certificate verification framework or use
  666. the lower level API to first connect and verify the certificate
  667. and only then send the http data. See implementation of ds_https3()
  668. for guidance on how to do this.
  669.  
  670. =head2 Using client certificates
  671.  
  672. Secure web communications are encrypted using symmetric crypto keys
  673. exchanged using encryption based on the certificate of the
  674. server. Therefore in all SSL connections the server must have a
  675. certificate. This serves both to authenticate the server to the
  676. clients and to perform the key exchange.
  677.  
  678. Sometimes it is necessary to authenticate the client as well. Two
  679. options are available: http basic authentication and client side
  680. certificate. The basic authentication over https is actually quite
  681. safe because https guarantees that the password will not travel in
  682. clear. Never-the-less, problems like easily guessable passwords
  683. remain. The client certificate method involves authentication of the
  684. client at SSL level using a certificate. For this to work, both the
  685. client and the server will have certificates (which typically are
  686. different) and private keys.
  687.  
  688. The API functions outlined above accept additional arguments that
  689. allow one to supply the client side certificate and key files. The
  690. format of these files is the same as used for server certificates and
  691. the caveat about encrypting private key applies.
  692.  
  693.   ($page, $result, %headers) =                                   # 2c
  694.          = get_https('www.bacus.pt', 443, '/protected.html',
  695.           make_headers(Authorization =>
  696.                'Basic ' . MIME::Base64::encode("$user:$pass",'')),
  697.           '', $mime_type6, $path_to_crt7, $path_to_key8);
  698.  
  699.   ($page, $response, %reply_headers)
  700.      = post_https('www.bacus.pt', 443, '/foo.cgi',           # 3b
  701.           make_headers('Authorization' =>
  702.                'Basic ' . MIME::Base64::encode("$user:$pass",'')),
  703.           make_form(OK   => '1', name => 'Sampo'),
  704.           $mime_type6, $path_to_crt7, $path_to_key8);
  705.  
  706. Case 2c demonstrates getting password protected page that also requires
  707. client certificate, i.e. it is possible to use both authentication
  708. methods simultaneously.
  709.  
  710. Case 3b is full blown post to secure server that requires both password
  711. authentication and client certificate, just like in case 2c.
  712.  
  713. Note: Client will not send a certificate unless the server requests one.
  714. This is typically achieved by setting verify mode to VERIFY_PEER on the
  715. server:
  716.  
  717.   Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);
  718.  
  719. See perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod for full description.
  720.  
  721. =head2 Working through Web proxy
  722.  
  723. Net::SSLeay can use a web proxy to make its connections. You need to
  724. first set the proxy host and port using set_proxy() and then just
  725. use the normal API functions, e.g:
  726.  
  727.   Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
  728.   ($page) = get_https('www.bacus.pt', 443, '/');
  729.  
  730. If your proxy requires authentication, you can supply username and
  731. password as well
  732.  
  733.   Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
  734.   ($page, $result, %headers) =
  735.          = get_https('www.bacus.pt', 443, '/protected.html',
  736.           make_headers(Authorization =>
  737.                'Basic ' . MIME::Base64::encode("susie:pass",''))
  738.           );
  739.  
  740. This example demonstrates case where we authenticate to the proxy as
  741. "joe" and to the final web server as "susie". Proxy authentication
  742. requires MIME::Base64 module to work.
  743.  
  744. =head2 Certificate verification and Certificate Revoocation Lists (CRLs)
  745.  
  746. OpenSSL supports the ability to verify peer certificates. It can also
  747. optionally check the peer certificate against a Certificate Revocation
  748. List (CRL) from the certificates issuer. A CRL is a file, created by
  749. the certificate issuer that lists all the certificates that it
  750. previously signed, but which it now revokes. CRLs are in PEM format.
  751.  
  752. You can enable Net::SSLeay CRL checking like this:
  753.  
  754.         &Net::SSLeay::X509_STORE_CTX_set_flags
  755.         (&Net::SSLeay::CTX_get_cert_store($ssl), 
  756.          &Net::SSLeay::X509_V_FLAG_CRL_CHECK); 
  757.  
  758. After setting this flag, if OpenSSL checks a peer's certificate, then
  759. it will attempt to find a CRL for the issuer. It does this by looking
  760. for a specially named file in the search directory specified by
  761. CTX_load_verify_locations.  CRL files are named with the hash of the
  762. issuer's subject name, followed by .r0, .r1 etc.  For example
  763. ab1331b2.r0, ab1331b2.r1. It will read all the .r files for the
  764. issuer, and then check for a revocation of the peer cerificate in all
  765. of them.  (You can also force it to look in a specific named CRL
  766. file., see below).  You can find out the hash of the issuer subject
  767. name in a CRL with
  768.  
  769.     openssl crl -in crl.pem -hash -noout
  770.  
  771. If the peer certificate does not pass the revocation list, or if no
  772. CRL is found, then the handshaking fails with an error.
  773.  
  774. You can also force OpenSSL to look for CRLs in one or more arbitrarily
  775. named files.
  776.  
  777. my $bio = &Net::SSLeay::BIO_new_file($crlfilename, 'r');
  778. my $crl = &Net::SSLeay::PEM_read_bio_X509_CRL($bio);
  779. if ($crl)
  780. {
  781.     &Net::SSLeay::X509_STORE_add_crl(&Net::SSLeay::CTX_get_cert_store($ssl, $crl);
  782. }
  783. else
  784. {
  785.     error reading CRL....
  786. }
  787.  
  788.  
  789. =head2 Convenience routines
  790.  
  791. To be used with Low level API
  792.  
  793.     Net::SSLeay::randomize($rn_seed_file,$additional_seed);
  794.     Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
  795.     $cert = Net::SSLeay::dump_peer_certificate($ssl);
  796.     Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
  797.     $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
  798.  
  799.     $got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
  800.     $got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
  801.     Net::SSLeay::ssl_write_CRLF($ssl, $message);
  802.  
  803. randomize() seeds the eay PRNG with /dev/urandom (see top of SSLeay.pm
  804. for how to change or configure this) and optionally with user provided
  805. data. It is very important to properly seed your random numbers, so
  806. do not forget to call this. The high level API functions automatically
  807. call randomize() so it is not needed with them. See also caveats.
  808.  
  809. set_cert_and_key() takes two file names as arguments and sets
  810. the certificate and private key to those. This can be used to
  811. set either cerver certificates or client certificates.
  812.  
  813. dump_peer_certificate() allows you to get plaintext description of the
  814. certificate the peer (usually server) presented to us.
  815.  
  816. ssl_read_all() and ssl_write_all() provide true blocking semantics for
  817. these operations (see limitation, below, for explanation). These are
  818. much preferred to the low level API equivalents (which implement BSD
  819. blocking semantics). The message argument to ssl_write_all() can be
  820. reference. This is helpful to avoid unnecessary copy when writing
  821. something big, e.g:
  822.  
  823.     $data = 'A' x 1000000000;
  824.     Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
  825.  
  826. ssl_read_CRLF() uses ssl_read_all() to read in a line terminated with a
  827. carriage return followed by a linefeed (CRLF).  The CRLF is included in
  828. the returned scalar.
  829.  
  830. ssl_read_until() uses ssl_read_all() to read from the SSL input
  831. stream until it encounters a programmer specified delimiter.
  832. If the delimiter is undefined, $/ is used.  If $/ is undefined,
  833. \n is used.  One can optionally set a maximum length of bytes to read
  834. from the SSL input stream.
  835.  
  836. ssl_write_CRLF() writes $message and appends CRLF to the SSL output stream.
  837.  
  838. =head2 Low level API
  839.  
  840. In addition to the high level functions outlined above, this module
  841. contains straight forward access to SSL part of OpenSSL C api. Only the SSL
  842. subpart of OpenSSL is implemented (if anyone wants to implement other
  843. parts, feel free to submit patches).
  844.  
  845. See ssl.h header from OpenSSL C distribution for list of low lever
  846. SSLeay functions to call (to check if some function has been
  847. implemented see directly in SSLeay.xs). The module strips SSLeay names
  848. of the initial "SSL_", generally you should use Net::SSLeay:: in
  849. place. For example:
  850.  
  851. In C:
  852.  
  853.     #include <ssl.h>
  854.     
  855.     err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
  856.                    &your_call_back_here);
  857.     
  858. In perl:
  859.  
  860.     use Net::SSLeay;
  861.  
  862.     $err = Net::SSLeay::set_verify ($ssl,
  863.                     &Net::SSLeay::VERIFY_CLIENT_ONCE,
  864.                     \&your_call_back_here);
  865.  
  866. If the function does not start by SSL_ you should use the full
  867. function name, e.g.:
  868.  
  869.     $err = &Net::SSLeay::ERR_get_error;
  870.  
  871. Following new functions behave in perlish way:
  872.  
  873.     $got = Net::SSLeay::read($ssl);
  874.                                     # Performs SSL_read, but returns $got
  875.                                     # resized according to data received.
  876.                                     # Returns undef on failure.
  877.  
  878.     Net::SSLeay::write($ssl, $foo) || die;
  879.                                     # Performs SSL_write, but automatically
  880.                                     # figures out the size of $foo
  881.  
  882. In order to use the low level API you should start your programs with
  883. the following encantation:
  884.  
  885.     use Net::SSLeay qw(die_now die_if_ssl_error);
  886.     Net::SSLeay::load_error_strings();
  887.     Net::SSLeay::SSLeay_add_ssl_algorithms();   # Important!
  888.         Net::SSLeay::randomize();
  889.  
  890. die_now() and die_if_ssl_error() are used to conveniently print SSLeay error
  891. stack when something goes wrong, thusly:
  892.  
  893.     Net::SSLeay:connect($ssl) or die_now("Failed SSL connect ($!)");
  894.     Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
  895.  
  896. You can also use Net::SSLeay::print_errs() to dump the error stack without
  897. exiting the program. As can be seen, your code becomes much more readable
  898. if you import the error reporting functions to your main name space.
  899.  
  900. I can not emphasize enough the need to check error returns. Use these
  901. functions even in most simple programs, they will reduce debugging
  902. time greatly. Do not ask questions in mailing list without having
  903. first sprinkled these in your code.
  904.  
  905. =head2 Sockets
  906.  
  907. Perl uses file handles for all I/O. While SSLeay has quite flexible BIO
  908. mechanism and perl has evolved PerlIO mechanism, this module still
  909. sticks to using file descriptors. Thus to attach SSLeay to socket you
  910. should use fileno() to extract the underlying file descriptor:
  911.  
  912.     Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
  913.  
  914. You should also use "$|=1;" to eliminate STDIO buffering so you do not
  915. get confused if you use perl I/O functions to manipulate your socket
  916. handle.
  917.  
  918. If you need to select(2) on the socket, go right ahead, but be warned
  919. that OpenSSL does some internal buffering so SSL_read does not always
  920. return data even if socket selected for reading (just keep on
  921. selecting and trying to read). Net::SSLeay.pm is no different from the
  922. C language OpenSSL in this respect.
  923.  
  924. =head2 Callbacks
  925.  
  926. WARNING: as of 1.04 the callbacks have changed and have not been tested.
  927.  
  928. At this moment the implementation of verify_callback is crippeled in
  929. the sense that at any given time there can be only one call back which
  930. is shared by all SSL contexts, sessions and connections. This is
  931. due to having to keep the reference to the perl call back in a
  932. static variable so that the callback C glue can find it. To remove
  933. this restriction would require either a more complex data structure
  934. (like a hash?) in XSUB to map the call backs to their owners or,
  935. cleaner, adding a context pointer in the SSL structure. This context would
  936. then be passed to the C callback, which in our case would be the glue
  937. to look up the proper Perl function from the context and call it.
  938.  
  939. ---- inaccurate ----
  940. The verify call back looks like this in C:
  941.  
  942.     int (*callback)(int ok,X509 *subj_cert,X509 *issuer_cert,
  943.                         int depth,int errorcode,char *arg,STACK *cert_chain)
  944.  
  945. The corresponding Perl function should be something like this:
  946.  
  947.     sub verify {
  948.         my ($ok, $subj_cert, $issuer_cert, $depth, $errorcode,
  949.         $arg, $chain) = @_;
  950.         print "Verifying certificate...\n";
  951.         ...
  952.         return $ok;
  953.     }
  954.  
  955. It is used like this:
  956.  
  957.     Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);
  958.  
  959. Callbacks for decrypting private keys are implemented, but have the
  960. same limitation as the verify_callback implementation (one password
  961. callback shared between all contexts.)  You might use it something
  962. like this:
  963.  
  964.         Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
  965.         Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
  966.                          Net::SSLeay::FILETYPE_PEM)
  967.             or die "Error reading private key";
  968.  
  969. No other callbacks are implemented. You do not need to use any
  970. callback for simple (i.e. normal) cases where the SSLeay built-in
  971. verify mechanism satisfies your needs.
  972. ---- end inaccurate ----
  973.  
  974. If you want to use callback stuff, see examples/callback.pl! Its the
  975. only one I am able to make work reliably.
  976.  
  977. =head2 X509 and RAND stuff
  978.  
  979. This module largely lacks interface to the X509 and RAND routines, but
  980. as I was lazy and needed them, the following kludges are implemented:
  981.  
  982.     $x509_name = Net::SSLeay::X509_get_subject_name($x509_cert);
  983.     $x509_name = Net::SSLeay::X509_get_issuer_name($x509_cert);
  984.     print Net::SSLeay::X509_NAME_oneline($x509_name);
  985.     $text = Net::SSLeay::X509_NAME_get_text_by_NID($name, $nid);
  986.  
  987.     Net::SSLeay::RAND_seed($buf);   # Perlishly figures out buf size
  988.     Net::SSLeay::RAND_bytes($buf, $num);
  989.     Net::SSLeay::RAND_pseudo_bytes($buf, $num);
  990.     Net::SSLeay::RAND_add($buf, $num, $entropy);
  991.     Net::SSLeay::RAND_poll();
  992.     Net::SSLeay::RAND_status();
  993.     Net::SSLeay::RAND_cleanup();
  994.     Net::SSLeay::RAND_file_name($num);
  995.     Net::SSLeay::RAND_load_file($file_name, $how_many_bytes);
  996.     Net::SSLeay::RAND_write_file($file_name);
  997.     Net::SSLeay::RAND_egd($path);
  998.     Net::SSLeay::RAND_egd_bytes($path, $bytes);
  999.  
  1000. Actually you should consider using the following helper functions:
  1001.  
  1002.     print Net::SSLeay::dump_peer_certificate($ssl);
  1003.     Net::SSLeay::randomize();
  1004.  
  1005. =head2 RSA interface
  1006.  
  1007. Some RSA functions are available:
  1008.  
  1009. $rsakey = Net::SSLeay::RSA_generate_key();
  1010. Net::SSLeay::CTX_set_tmp_rsa($ctx, $rsakey);
  1011. Net::SSLeay::RSA_free($rsakey);
  1012.  
  1013. =head2 BIO interface
  1014.  
  1015. Some BIO functions are available:
  1016.  
  1017.   Net::SSLeay::BIO_s_mem();
  1018.   $bio = Net::SSLeay::BIO_new(BIO_s_mem())
  1019.   $bio = Net::SSLeay::BIO_new_file($filename, $mode);
  1020.   Net::SSLeay::BIO_free($bio)
  1021.   $count = Net::SSLeay::BIO_write($data);
  1022.   $data = Net::SSLeay::BIO_read($bio);
  1023.   $data = Net::SSLeay::BIO_read($bio, $maxbytes);
  1024.   $is_eof = Net::SSLeay::BIO_eof($bio);
  1025.   $count = Net::SSLeay::BIO_pending($bio);
  1026.   $count = Net::SSLeay::BIO_wpending ($bio);
  1027.  
  1028. =head2 Low level API
  1029.  
  1030. Some very low level API functions are available:
  1031.     $client_random = &Net::SSLeay::get_client_random($ssl);
  1032.     $server_random = &Net::SSLeay::get_server_random($ssl);
  1033.     $session = &Net::SSLeay::get_session($ssl);
  1034.     $master_key = &Net::SSLeay::SESSION_get_master_key($session);
  1035.  
  1036. =head2 HTTP (without S) API
  1037.  
  1038. Over the years it has become clear that it would be convenient to use
  1039. the light weight flavour API of Net::SSLeay also for normal http (see
  1040. LWP for heavy weight object oriented approach). In fact it would be
  1041. nice to be able to flip https on and off on the fly. Thus regular http
  1042. support was evolved.
  1043.  
  1044.   use Net::SSLeay, qw(get_http post_http tcpcat
  1045.                       get_httpx post_httpx tcpxcat
  1046.                       make_headers make_form);
  1047.  
  1048.   ($page, $result, %headers) =
  1049.          = get_http('www.bacus.pt', 443, '/protected.html',
  1050.           make_headers(Authorization =>
  1051.                'Basic ' . MIME::Base64::encode("$user:$pass",''))
  1052.           );
  1053.  
  1054.   ($page, $response, %reply_headers)
  1055.      = post_http('www.bacus.pt', 443, '/foo.cgi', '',
  1056.         make_form(OK   => '1',
  1057.               name => 'Sampo'
  1058.         ));
  1059.  
  1060.   ($reply, $err) = tcpcat($host, $port, $request);
  1061.  
  1062.   ($page, $result, %headers) =
  1063.          = get_httpx($usessl, 'www.bacus.pt', 443, '/protected.html',
  1064.           make_headers(Authorization =>
  1065.                'Basic ' . MIME::Base64::encode("$user:$pass",''))
  1066.           );
  1067.  
  1068.   ($page, $response, %reply_headers)
  1069.      = post_httpx($usessl, 'www.bacus.pt', 443, '/foo.cgi', '',
  1070.         make_form(OK   => '1',  name => 'Sampo'    ));
  1071.  
  1072.   ($reply, $err, $server_cert) = tcpxcat($usessl, $host, $port, $request);
  1073.  
  1074. As can be seen, the "x" family of APIs takes as first argument a flag
  1075. which indicated whether SSL is used or not.
  1076.  
  1077. =head1 EXAMPLES
  1078.  
  1079. One very good example is to look at the implementation of sslcat() in the
  1080. SSLeay.pm file.
  1081.  
  1082. Following is a simple SSLeay client (with too little error checking :-(
  1083.  
  1084.     #!/usr/local/bin/perl
  1085.     use Socket;
  1086.     use Net::SSLeay qw(die_now die_if_ssl_error) ;
  1087.     Net::SSLeay::load_error_strings();
  1088.     Net::SSLeay::SSLeay_add_ssl_algorithms();
  1089.     Net::SSLeay::randomize();
  1090.  
  1091.     ($dest_serv, $port, $msg) = @ARGV;      # Read command line
  1092.     $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
  1093.     $dest_ip = gethostbyname ($dest_serv);
  1094.     $dest_serv_params  = sockaddr_in($port, $dest_ip);
  1095.     
  1096.     socket  (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
  1097.     connect (S, $dest_serv_params)          or die "connect: $!";
  1098.     select  (S); $| = 1; select (STDOUT);   # Eliminate STDIO buffering
  1099.     
  1100.     # The network connection is now open, lets fire up SSL    
  1101.  
  1102.     $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
  1103.     Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
  1104.          and die_if_ssl_error("ssl ctx set options");
  1105.     $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
  1106.     Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
  1107.     $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
  1108.     print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
  1109.     
  1110.     # Exchange data
  1111.     
  1112.     $res = Net::SSLeay::write($ssl, $msg);  # Perl knows how long $msg is
  1113.     die_if_ssl_error("ssl write");
  1114.     CORE::shutdown S, 1;  # Half close --> No more output, sends EOF to server
  1115.     $got = Net::SSLeay::read($ssl);         # Perl returns undef on failure
  1116.     die_if_ssl_error("ssl read");
  1117.     print $got;
  1118.         
  1119.     Net::SSLeay::free ($ssl);               # Tear down connection
  1120.     Net::SSLeay::CTX_free ($ctx);
  1121.     close S;
  1122.  
  1123. Following is a simple SSLeay echo server (non forking):
  1124.  
  1125.     #!/usr/local/bin/perl -w
  1126.     use Socket;
  1127.     use Net::SSLeay qw(die_now die_if_ssl_error);
  1128.     Net::SSLeay::load_error_strings();
  1129.     Net::SSLeay::SSLeay_add_ssl_algorithms();
  1130.     Net::SSLeay::randomize();
  1131.  
  1132.     $our_ip = "\0\0\0\0"; # Bind to all interfaces
  1133.     $port = 1235;                             
  1134.     $sockaddr_template = 'S n a4 x8';
  1135.     $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);
  1136.     
  1137.     socket (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
  1138.     bind (S, $our_serv_params)             or die "bind:   $!";
  1139.     listen (S, 5)                          or die "listen: $!";
  1140.     $ctx = Net::SSLeay::CTX_new ()         or die_now("CTX_new ($ctx): $!");
  1141.     Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
  1142.          and die_if_ssl_error("ssl ctx set options");
  1143.  
  1144.     # Following will ask password unless private key is not encrypted
  1145.     Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
  1146.                                              &Net::SSLeay::FILETYPE_PEM);
  1147.     die_if_ssl_error("private key");
  1148.     Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
  1149.                             &Net::SSLeay::FILETYPE_PEM);
  1150.     die_if_ssl_error("certificate");
  1151.     
  1152.     while (1) {    
  1153.         print "Accepting connections...\n";
  1154.         ($addr = accept (NS, S))           or die "accept: $!";
  1155.         select (NS); $| = 1; select (STDOUT);  # Piping hot!
  1156.     
  1157.         ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
  1158.         @inetaddr = unpack('C4',$client_ip);
  1159.         print "$af connection from " .
  1160.         join ('.', @inetaddr) . ":$client_port\n";
  1161.     
  1162.     # We now have a network connection, lets fire up SSLeay...
  1163.  
  1164.         $ssl = Net::SSLeay::new($ctx)      or die_now("SSL_new ($ssl): $!");
  1165.         Net::SSLeay::set_fd($ssl, fileno(NS));
  1166.     
  1167.         $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
  1168.         print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
  1169.     
  1170.         # Connected. Exchange some data.
  1171.     
  1172.         $got = Net::SSLeay::read($ssl);     # Returns undef on fail
  1173.         die_if_ssl_error("ssl read");
  1174.         print "Got `$got' (" . length ($got) . " chars)\n";
  1175.         
  1176.         Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
  1177.         die_if_ssl_error("ssl write");
  1178.     
  1179.         Net::SSLeay::free ($ssl);           # Tear down connection
  1180.         close NS;
  1181.     }
  1182.  
  1183. Yet another echo server. This one runs from /etc/inetd.conf so it avoids
  1184. all the socket code overhead. Only caveat is opening rsa key file -
  1185. it had better be without any encryption or else it will not know where
  1186. to ask for the password. Note how STDIN and STDOUT are wired to SSL.
  1187.  
  1188.     #!/usr/local/bin/perl
  1189.     # /etc/inetd.conf
  1190.     #    ssltst stream tcp nowait root /path/to/server.pl server.pl
  1191.     # /etc/services
  1192.     #    ssltst        1234/tcp
  1193.  
  1194.     use Net::SSLeay qw(die_now die_if_ssl_error);
  1195.     Net::SSLeay::load_error_strings();
  1196.     Net::SSLeay::SSLeay_add_ssl_algorithms();
  1197.     Net::SSLeay::randomize();
  1198.  
  1199.     chdir '/key/dir' or die "chdir: $!";
  1200.     $| = 1;  # Piping hot!
  1201.     open LOG, ">>/dev/console" or die "Can't open log file $!";
  1202.     select LOG; print "server.pl started\n";
  1203.     
  1204.     $ctx = Net::SSLeay::CTX_new()     or die_now "CTX_new ($ctx) ($!)";
  1205.     $ssl = Net::SSLeay::new($ctx)     or die_now "new ($ssl) ($!)";
  1206.     Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
  1207.          and die_if_ssl_error("ssl set options");
  1208.  
  1209.     # We get already open network connection from inetd, now we just
  1210.     # need to attach SSLeay to STDIN and STDOUT
  1211.     Net::SSLeay::set_rfd($ssl, fileno(STDIN));
  1212.     Net::SSLeay::set_wfd($ssl, fileno(STDOUT));
  1213.  
  1214.     Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
  1215.                                          &Net::SSLeay::FILETYPE_PEM);
  1216.     die_if_ssl_error("private key");
  1217.     Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
  1218.                         &Net::SSLeay::FILETYPE_PEM);
  1219.     die_if_ssl_error("certificate");
  1220.  
  1221.     Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
  1222.     print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
  1223.     
  1224.     $got = Net::SSLeay::read($ssl);
  1225.     die_if_ssl_error("ssl read");
  1226.     print "Got `$got' (" . length ($got) . " chars)\n";
  1227.  
  1228.     Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
  1229.     die_if_ssl_error("ssl write");
  1230.  
  1231.     Net::SSLeay::free ($ssl);         # Tear down the connection
  1232.     Net::SSLeay::CTX_free ($ctx);
  1233.     close LOG;
  1234.  
  1235. There are also a number of example/test programs in the examples directory:
  1236.  
  1237.     sslecho.pl   -  A simple server, not unlike the one above
  1238.     minicli.pl   -  Implements a client using low level SSLeay routines
  1239.     sslcat.pl    -  Demonstrates using high level sslcat utility function
  1240.     get_page.pl  -  Is a utility for getting html pages from secure servers
  1241.     callback.pl  -  Demonstrates certificate verification and callback usage
  1242.     stdio_bulk.pl       - Does SSL over Unix pipes
  1243.     ssl-inetd-serv.pl   - SSL server that can be invoked from inetd.conf
  1244.     httpd-proxy-snif.pl - Utility that allows you to see how a browser
  1245.                           sends https request to given server and what reply
  1246.                           it gets back (very educative :-)
  1247.     makecert.pl  -  Creates a self signed cert (does not use this module)
  1248.  
  1249. =head1 LIMITATIONS
  1250.  
  1251. Net::SSLeay::read uses internal buffer of 32KB, thus no single read
  1252. will return more. In practice one read returns much less, usually
  1253. as much as fits in one network packet. To work around this,
  1254. you should use a loop like this:
  1255.  
  1256.     $reply = '';
  1257.     while ($got = Net::SSLeay::read($ssl)) {
  1258.     last if print_errs('SSL_read');
  1259.     $reply .= $got;
  1260.     }
  1261.  
  1262. Although there is no built-in limit in Net::SSLeay::write, the network
  1263. packet size limitation applies here as well, thus use:
  1264.  
  1265.     $written = 0;
  1266.  
  1267.     while ($written < length($message)) {
  1268.     $written += Net::SSLeay::write($ssl, substr($message, $written));
  1269.     last if print_errs('SSL_write');
  1270.     }
  1271.  
  1272. Or alternatively you can just use the following convinence functions:
  1273.  
  1274.     Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
  1275.     $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
  1276.  
  1277. =head1 KNOWN BUGS AND CAVEATS
  1278.  
  1279. Autoloader emits
  1280.  
  1281.     Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'
  1282.  
  1283. warning if die_if_ssl_error is made autoloadable. If you figure out why,
  1284. drop me a line.
  1285.  
  1286. Callback set using SSL_set_verify() does not appear to work. This may
  1287. well be eay problem (e.g. see ssl/ssl_lib.c line 1029). Try using
  1288. SSL_CTX_set_verify() instead and do not be surprised if even this stops
  1289. working in future versions.
  1290.  
  1291. Callback and certificate verification stuff is generally too little tested.
  1292.  
  1293. Random numbers are not initialized randomly enough, especially if you
  1294. do not have /dev/random and/or /dev/urandom (such as in Solaris
  1295. platforms - but I've been suggested that cryptorand daemon from SUNski
  1296. package solves this). In this case you should investigate third party
  1297. software that can emulate these devices, e.g. by way of a named pipe
  1298. to some program.
  1299.  
  1300. Another gotcha with random number initialization is randomness
  1301. depletion. This phenomenon, which has been extensively discussed in
  1302. OpenSSL, Apache-SSL, and Apache-mod_ssl forums, can cause your
  1303. script to block if you use /dev/random or to operate insecurely
  1304. if you use /dev/urandom. What happens is that when too much
  1305. randomness is drawn from the operating system's randomness pool
  1306. then randomness can temporarily be unavailable. /dev/random solves
  1307. this problem by waiting until enough randomness can be gathered - and
  1308. this can take a long time since blocking reduces activity in the
  1309. machine and less activity provides less random events: a vicious circle.
  1310. /dev/urandom solves this dilemma more pragmatically by simply returning
  1311. predictable "random" numbers. Some /dev/urandom emulation software
  1312. however actually seems to implement /dev/random semantics. Caveat emptor.
  1313.  
  1314. I've been pointed to two such daemons by Mik Firestone <mik@@speed.stdio._com>
  1315. who has used them on Solaris 8
  1316.  
  1317.    1. Entropy Gathering Daemon (EGD) at http://www.lothar.com/tech/crypto/
  1318.    2. Pseudo-random number generating daemon (PRNGD) at
  1319.         http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html
  1320.  
  1321. If you are using the low level API functions to communicate with other
  1322. SSL implementations, you would do well to call
  1323.  
  1324.     Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
  1325.          and die_if_ssl_error("ssl ctx set options");
  1326.  
  1327. to cope with some well know bugs in some other SSL
  1328. implementations. The high level API functions always set all known
  1329. compatibility options.
  1330.  
  1331. Sometimes sslcat (and the high level https functions that build on it)
  1332. is too fast in signaling the EOF to legacy https servers. This causes
  1333. the server to return empty page. To work around this problem you can
  1334. set global variable
  1335.  
  1336.     $Net::SSLeay::slowly = 1;   # Add sleep so broken servers can keep up
  1337.  
  1338. http/1.1 is not supported. Specifically this module does not know to
  1339. issue or serve multiple http requests per connection. This is a serious
  1340. short coming, but using SSL session cache on your server helps to
  1341. alleviate the CPU load somewhat.
  1342.  
  1343. As of version 1.09 many newer OpenSSL auxiliary functions were
  1344. added (from REM_AUTOMATICALLY_GENERATED_1_09 onwards in SSLeay.xs).
  1345. Unfortunately I have not had any opportunity to test these. Some of
  1346. them are trivial enough that I believe they "just work", but others
  1347. have rather complex interfaces with function pointers and all. In these
  1348. cases you should proceed wit great caution.
  1349.  
  1350. This module defaults to using OpenSSL automatic protocol negotiation
  1351. code for automatically detecting the version of the SSL protocol
  1352. that the other end talks. With most web servers this works just
  1353. fine, but once in a while I get complaints from people that the module
  1354. does not work with some web servers. Usually this can be solved
  1355. by explicitly setting the protocol version, e.g.
  1356.  
  1357.    $Net::SSLeay::ssl_version = 2;  # Insist on SSLv2
  1358.    $Net::SSLeay::ssl_version = 3;  # Insist on SSLv3
  1359.    $Net::SSLeay::ssl_version = 10; # Insist on TLSv1
  1360.  
  1361. Although the autonegotiation is nice to have, the SSL standards
  1362. do not formally specify any such mechanism. Most of the world has
  1363. accepted the SSLeay/OpenSSL way of doing it as the de facto standard. But
  1364. for the few that think differently, you have to explicitly speak
  1365. the correct version. This is not really a bug, but rather a deficiency
  1366. in the standards. If a site refuses to respond or sends back some
  1367. nonsensical error codes (at SSL handshake level), try this option
  1368. before mailing me.
  1369.  
  1370. The high level API returns the certificate of the peer, thus allowing
  1371. one to check what certificate was supplied. However, you will only be
  1372. able to check the certificate after the fact, i.e. you already sent
  1373. your form data by the time you find out that you did not trust them,
  1374. oops.
  1375.  
  1376. So, while being able to know the certificate after the fact is surely
  1377. useful, the security minded would still choose to do the connection
  1378. and certificate verification first and only after that exchange data
  1379. with the site. Currently none of the high level API functions do
  1380. this, thus you would have to program it using the low level API. A
  1381. good place to start is to see how Net::SSLeay::http_cat() function
  1382. is implemented.
  1383.  
  1384. The high level API functions use a global file handle SSLCAT_S
  1385. internally. This really should not be a problem because there is no
  1386. way to interleave the high level API functions, unless you use threads
  1387. (but threads are not very well supported in perl anyway (as of version
  1388. 5.6.1). However, you may run into problems if you call undocumented
  1389. internal functions in an interleaved fashion.
  1390.  
  1391. =head1 DIAGNOSTICS
  1392.  
  1393. "Random number generator not seeded!!!"
  1394.   This warning indicates that randomize() was not able to read
  1395.   /dev/random or /dev/urandom, possibly because your system does not
  1396.   have them or they are differently named. You can still use SSL, but
  1397.   the encryption will not be as strong.
  1398.  
  1399. "open_tcp_connection: destination host not found:`server' (port 123) ($!)"
  1400.   Name lookup for host named `server' failed.
  1401.  
  1402. "open_tcp_connection: failed `server', 123 ($!)"
  1403.   The name was resolved, but establising the TCP connection failed.
  1404.  
  1405. "msg 123: 1 - error:140770F8:SSL routines:SSL23_GET_SERVER_HELLO:unknown proto"
  1406.   SSLeay error string. First (123) number is PID, second number (1) indicates
  1407.   the position of the error message in SSLeay error stack. You often see
  1408.   a pile of these messages as errors cascade.
  1409.  
  1410. "msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)"
  1411.   The same as above, but you didn't call load_error_strings() so SSLeay
  1412.   couldn't verbosely explain the error. You can still find out what it
  1413.   means with this command:
  1414.  
  1415.      /usr/local/ssl/bin/ssleay errstr 02001002
  1416.  
  1417. Password is being asked for private key
  1418.   This is normal behaviour if your private key is encrypted. Either
  1419.   you have to supply the password or you have to use unencrypted
  1420.   private key. Scan OpenSSL.org for the FAQ that explains how to
  1421.   do this (or just study examples/makecert.pl which is used
  1422.   during `make test' to do just that).
  1423.  
  1424. =head1 REPORTING BUGS AND SUPPORT
  1425.  
  1426. Please see README for full bug reporting instructions. In general I do
  1427. not answer for free stupid questions or questions where you did not
  1428. do your home work.
  1429.  
  1430. Commercial support for Net::SSLeay may be obtained from
  1431.  
  1432.    Symlabs (netssleay@symlabs.com)
  1433.    Tel: +351-214.222.630
  1434.    Fax: +351-214.222.637
  1435.  
  1436. =head1 VERSION
  1437.  
  1438. This man page documents version 1.24, released on 18.8.2003.
  1439.  
  1440. There are currently two perl modules for using OpenSSL C
  1441. library: Net::SSLeay (maintaned by me) and SSLeay (maintained by OpenSSL
  1442. team). This module is the Net::SSLeay variant.
  1443.  
  1444. At the time of making this release, Eric's module was still quite
  1445. sketchy and could not be used for real work, thus I felt motivated to
  1446. make this maintenance release. This module is not planned to evolve to
  1447. contain any further functionality, i.e. I will concentrate on just
  1448. making a simple SSL connection over TCP socket. Presumably Eric's own
  1449. module will offer full SSLeay API one day.
  1450.  
  1451. This module uses OpenSSL-0.9.6c. It does not work with any earlier
  1452. version and there is no guarantee that it will work with later
  1453. versions either, though as long as C API does not change, it
  1454. should. This module requires perl5.005, or 5.6.0 (or better?) though I
  1455. believe it would build with any perl5.002 or newer.
  1456.  
  1457. =head1 AUTHOR
  1458.  
  1459. Sampo KellomΣki <sampo@symlabs.com>
  1460.  
  1461. Please send bug reports to the above address. General questions should be
  1462. sent either to me or to the mailing list (subscribe by sending mail
  1463. to openssl-users-request@openssl.org or using web interface at
  1464. http://www.openssl.org/support/).
  1465.  
  1466. =head1 COPYRIGHT
  1467.  
  1468. Copyright (c) 1996-2003 Sampo KellomΣki <sampo@symlabs.com>
  1469. All Rights Reserved.
  1470.  
  1471. Distribution and use of this module is under the same terms as the
  1472. OpenSSL package itself (i.e. free, but mandatory attribution; NO
  1473. WARRANTY). Please consult LICENSE file in the root of the OpenSSL
  1474. distribution.
  1475.  
  1476. While the source distribution of this perl module does not contain
  1477. Eric's or OpenSSL's code, if you use this module you will use OpenSSL
  1478. library. Please give Eric and OpenSSL team credit (as required by
  1479. their licenses).
  1480.  
  1481. And remember, you, and nobody else but you, are responsible for
  1482. auditing this module and OpenSSL library for security problems,
  1483. backdoors, and general suitability for your application.
  1484.  
  1485. =head1 SEE ALSO
  1486.  
  1487.   Net::SSLeay::Handle                      - File handle interface
  1488.   ./Net_SSLeay/examples                    - Example servers and a clients
  1489.   <http://symlabs.com/Net_SSLeay/index.html>  - Net::SSLeay.pm home
  1490.   <http://symlabs.com/Net_SSLeay/smime.html>  - Another module using OpenSSL
  1491.   <http://www.openssl.org/>                - OpenSSL source, documentation, etc
  1492.   openssl-users-request@openssl.org        - General OpenSSL mailing list
  1493.   <http://home.netscape.com/newsref/std/SSL.html>  - SSL Draft specification
  1494.   <http://www.w3c.org>                     - HTTP specifications
  1495.   <http://www.ietf.org/rfc/rfc2617.txt>    - How to send password
  1496.   <http://www.lothar.com/tech/crypto/>     - Entropy Gathering Daemon (EGD)
  1497.   <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
  1498.                            - pseudo-random number generating daemon (PRNGD)
  1499.   perl(1)
  1500.   perlref(1)
  1501.   perllol(1)
  1502.   perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
  1503.  
  1504. =cut
  1505.  
  1506. # ';
  1507.  
  1508. ### Some methods that are macros in C
  1509.  
  1510. sub want_nothing { want(shift) == 1 }
  1511. sub want_read { want(shift) == 2 }
  1512. sub want_write { want(shift) == 3 }
  1513. sub want_X509_lookup { want(shift) == 4 }
  1514.  
  1515. ###
  1516. ### Open TCP stream to given host and port, looking up the details
  1517. ### from system databases or DNS.
  1518. ###
  1519.  
  1520. sub open_tcp_connection {
  1521.     my ($dest_serv, $port) = @_;
  1522.     my ($errs);
  1523.     
  1524.     $port = getservbyname($port, 'tcp') unless $port =~ /^\d+$/;
  1525.     my $dest_serv_ip = gethostbyname($dest_serv);
  1526.     unless (defined($dest_serv_ip)) {
  1527.     $errs = "$0 $$: open_tcp_connection: destination host not found:"
  1528.             . " `$dest_serv' (port $port) ($!)\n";
  1529.     warn $errs if $trace;
  1530.         return wantarray ? (0, $errs) : 0;
  1531.     }
  1532.     my $sin = sockaddr_in($port, $dest_serv_ip);
  1533.     
  1534.     warn "Opening connection to $dest_serv:$port (" .
  1535.     inet_ntoa($dest_serv_ip) . ")" if $trace>2;
  1536.     
  1537.     my $proto = getprotobyname('tcp');
  1538.     if (socket (SSLCAT_S, &PF_INET(), &SOCK_STREAM(), $proto)) {
  1539.         warn "next connect" if $trace>3;
  1540.         if (CORE::connect (SSLCAT_S, $sin)) {
  1541.             my $old_out = select (SSLCAT_S); $| = 1; select ($old_out);
  1542.             warn "connected to $dest_serv, $port" if $trace>3;
  1543.             return wantarray ? (1, undef) : 1; # Success
  1544.         }
  1545.     }
  1546.     $errs = "$0 $$: open_tcp_connection: failed `$dest_serv', $port ($!)\n";
  1547.     warn $errs if $trace;
  1548.     close SSLCAT_S;
  1549.     return wantarray ? (0, $errs) : 0; # Fail
  1550. }
  1551.  
  1552. ### Open connection via standard web proxy, if one was defined
  1553. ### using set_proxy().
  1554.  
  1555. sub open_proxy_tcp_connection {
  1556.     my ($dest_serv, $port) = @_;
  1557.     return open_tcp_connection($dest_serv, $port) if !$proxyhost;
  1558.     
  1559.     warn "Connect via proxy: $proxyhost:$proxyport" if $trace>2;
  1560.     my ($ret, $errs) = open_tcp_connection($proxyhost, $proxyport);
  1561.     return wantarray ? (0, $errs) : 0 if !$ret;  # Connection fail
  1562.     
  1563.     warn "Asking proxy to connect to $dest_serv:$port" if $trace>2;
  1564.     #print SSLCAT_S "CONNECT $dest_serv:$port HTTP/1.0$proxyauth$CRLF$CRLF";
  1565.     #my $line = <SSLCAT_S>;   # *** bug? Mixing stdio with syscall read?
  1566.     ($ret, $errs) =
  1567.     tcp_write_all("CONNECT $dest_serv:$port HTTP/1.0$proxyauth$CRLF$CRLF");
  1568.     return wantarray ? (0,$errs) : 0 if $errs;
  1569.     ($line, $errs) = tcp_read_until("\n", 1024);
  1570.     warn "Proxy response: $line" if $trace>2;
  1571.     return wantarray ? (0,$errs) : 0 if $errs;
  1572.     return wantarray ? (1,'') : 1;  # Success
  1573. }
  1574.  
  1575. ###
  1576. ### read and write helpers that block
  1577. ###
  1578.  
  1579. sub debug_read {
  1580.     my ($replyr, $gotr) = @_;
  1581.     my $vm = $trace>2 && $linux_debug ?
  1582.     (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
  1583.     warn "  got " . blength($$gotr) . ':'
  1584.     . blength($$replyr) . " bytes (VM=$vm).\n" if $trace == 3;
  1585.     warn "  got `$$gotr' (" . blength($$gotr) . ':'
  1586.     . blength($$replyr) . " bytes, VM=$vm)\n" if $trace>3;
  1587. }
  1588.  
  1589. sub ssl_read_all {
  1590.     my ($ssl,$how_much) = @_;
  1591.     $how_much = 2000000000 unless $how_much;
  1592.     my ($got, $errs);
  1593.     my $reply = '';
  1594.  
  1595.     while ($how_much > 0) {
  1596.     $got = Net::SSLeay::read($ssl,$how_much);
  1597.     last if $errs = print_errs('SSL_read');
  1598.     $how_much -= blength($got);
  1599.     debug_read(\$reply, \$got) if $trace>1;
  1600.     last if $got eq '';  # EOF
  1601.     $reply .= $got;
  1602.     }
  1603.     return wantarray ? ($reply, $errs) : $reply;
  1604. }
  1605.  
  1606. sub tcp_read_all {
  1607.     my ($how_much) = @_;
  1608.     $how_much = 2000000000 unless $how_much;
  1609.     my ($n, $got, $errs);
  1610.     my $reply = '';
  1611.  
  1612.     while ($how_much > 0) {
  1613.     $n = sysread(SSLCAT_S,$got,$how_much);
  1614.     warn "Read error: $! ($n,$how_much)" unless defined $n;
  1615.     last if !$n;  # EOF
  1616.     $how_much -= $n;
  1617.     debug_read(\$reply, \$got) if $trace>1;
  1618.     $reply .= $got;
  1619.     }
  1620.     return wantarray ? ($reply, $errs) : $reply;
  1621. }
  1622.  
  1623. sub ssl_write_all {
  1624.     my $ssl = $_[0];    
  1625.     my ($data_ref, $errs);
  1626.     if (ref $_[1]) {
  1627.     $data_ref = $_[1];
  1628.     } else {
  1629.     $data_ref = \$_[1];
  1630.     }
  1631.     my ($wrote, $written, $to_write) = (0,0, blength($$data_ref));
  1632.     my $vm = $trace>2 && $linux_debug ?
  1633.     (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
  1634.     warn "  write_all VM at entry=$vm\n" if $trace>2;
  1635.     while ($to_write) {
  1636.     #sleep 1; # *** DEBUG
  1637.     warn "partial `$$data_ref'\n" if $trace>3;
  1638.     $wrote = write_partial($ssl, $written, $to_write, $$data_ref);
  1639.     if (defined $wrote && ($wrote > 0)) {  # write_partial can return -1
  1640.         $written += $wrote;
  1641.         $to_write -= $wrote;
  1642.     }
  1643.     $vm = $trace>2 && $linux_debug ?
  1644.         (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
  1645.     warn "  written so far $wrote:$written bytes (VM=$vm)\n" if $trace>2;
  1646.     
  1647.     $errs .= print_errs('SSL_write');
  1648.     return (wantarray ? (undef, $errs) : undef) if $errs;
  1649.     }
  1650.     return wantarray ? ($written, $errs) : $written;
  1651. }
  1652.  
  1653. sub tcp_write_all {
  1654.     my ($data_ref, $errs);
  1655.     if (ref $_[0]) {
  1656.     $data_ref = $_[0];
  1657.     } else {
  1658.     $data_ref = \$_[0];
  1659.     }
  1660.     my ($wrote, $written, $to_write) = (0,0, blength($$data_ref));
  1661.     my $vm = $trace>2 && $linux_debug ?
  1662.     (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
  1663.     warn "  write_all VM at entry=$vm to_write=$to_write\n" if $trace>2;
  1664.     while ($to_write) {
  1665.     warn "partial `$$data_ref'\n" if $trace>3;
  1666.     $wrote = syswrite(SSLCAT_S, $$data_ref, $to_write, $written);
  1667.     if (defined $wrote && ($wrote > 0)) {  # write_partial can return -1
  1668.         $written += $wrote;
  1669.         $to_write -= $wrote;
  1670.     } elsif (!defined($wrote)) {
  1671.         warn "tcp_write_all: $!";
  1672.         return (wantarray ? (undef, "$!") : undef);
  1673.     }
  1674.     $vm = $trace>2 && $linux_debug ?
  1675.         (split ' ', `cat /proc/$$/stat`)[22] : 'vm_unknown';
  1676.     warn "  written so far $wrote:$written bytes (VM=$vm)\n" if $trace>2;
  1677.     }
  1678.     return wantarray ? ($written, '') : $written;
  1679. }
  1680.  
  1681. ### from patch by Clinton Wong <clintdw@netcom.com>
  1682.  
  1683. # ssl_read_until($ssl [, $delimit [, $max_length]])
  1684. #  if $delimit missing, use $/ if it exists, otherwise use \n
  1685. #  read until delimiter reached, up to $max_length chars if defined
  1686.  
  1687. sub ssl_read_until ($;$$) {
  1688.     my ($ssl,$delim, $max_length) = @_;
  1689.     local $[;
  1690.  
  1691.     # guess the delim string if missing
  1692.     if ( ! defined $delim ) {           
  1693.       if ( defined $/ && length $/  ) { $delim = $/ }
  1694.       else { $delim = "\n" }      # Note: \n,$/ value depends on the platform
  1695.     }
  1696.     my $len_delim = length $delim;
  1697.  
  1698.     my ($got);
  1699.     my $reply = '';
  1700.     
  1701.     # If we have OpenSSL 0.9.6a or later, we can use SSL_peek to
  1702.     # speed things up.
  1703.     # N.B. 0.9.6a has security problems, so the support for
  1704.     #      anything earlier than 0.9.6e will be dropped soon.
  1705.     if (&Net::SSLeay::OPENSSL_VERSION_NUMBER >= 0x0090601f) {
  1706.     $max_length = 2000000000 unless (defined $max_length);
  1707.     my ($pending, $peek_length, $found, $done);
  1708.     while (blength($reply) < $max_length and !$done) {
  1709.         #Block if necessary until we get some data
  1710.         $got = Net::SSLeay::peek($ssl,1);
  1711.         last if print_errs('SSL_peek');
  1712.  
  1713.         $pending = Net::SSLeay::pending($ssl) + blength($reply);
  1714.         $peek_length = ($pending > $max_length) ? $max_length : $pending;
  1715.         $peek_length -= blength($reply);
  1716.         $got = Net::SSLeay::peek($ssl, $peek_length);
  1717.         last if print_errs('SSL_peek');
  1718.         $peek_length = blength($got);
  1719.         
  1720.         #$found = index($got, $delim);  # Old and broken
  1721.         
  1722.         # the delimiter may be split across two gets, so we prepend
  1723.         # a little from the last get onto this one before we check
  1724.         # for a match
  1725.         my $match;
  1726.         if(blength($reply) >= blength($delim) - 1) {
  1727.         #if what we've read so far is greater or equal
  1728.         #in length of what we need to prepatch
  1729.         $match = substr $reply, blength($reply) - blength($delim) + 1;
  1730.         } else {
  1731.         $match = $reply;
  1732.         }
  1733.  
  1734.         $match .= $got;
  1735.         $found = index($match, $delim);
  1736.  
  1737.         if ($found > -1) {
  1738.         #$got = Net::SSLeay::read($ssl, $found+$len_delim);
  1739.         #read up to the end of the delimiter
  1740.         $got = Net::SSLeay::read($ssl,
  1741.                      $found + $len_delim
  1742.                      - ((blength $match) - (blength $got)));
  1743.         $done = 1;
  1744.         } else {
  1745.         $got = Net::SSLeay::read($ssl, $peek_length);
  1746.         $done = 1 if ($peek_length == $max_length - blength($reply));
  1747.         } 
  1748.  
  1749.         last if print_errs('SSL_read');
  1750.         debug_read(\$reply, \$got) if $trace>1;
  1751.         last if $got eq '';
  1752.         $reply .= $got;
  1753.     }
  1754.     } else {
  1755.     while (!defined $max_length || length $reply < $max_length) {
  1756.         $got = Net::SSLeay::read($ssl,1);  # one by one
  1757.         last if print_errs('SSL_read');
  1758.         debug_read(\$reply, \$got) if $trace>1;
  1759.         last if $got eq '';
  1760.         $reply .= $got;
  1761.         last if $len_delim
  1762.         && substr($reply, blength($reply)-$len_delim) eq $delim;
  1763.     }
  1764.     }
  1765.     return $reply;
  1766. }
  1767.  
  1768. sub tcp_read_until {
  1769.     my ($delim, $max_length) = @_;
  1770.     local $[;
  1771.  
  1772.     # guess the delim string if missing
  1773.     if ( ! defined $delim ) {           
  1774.       if ( defined $/ && length $/  ) { $delim = $/ }
  1775.       else { $delim = "\n" }      # Note: \n,$/ value depends on the platform
  1776.     }
  1777.     my $len_delim = length $delim;
  1778.  
  1779.     my ($n,$got);
  1780.     my $reply = '';
  1781.     
  1782.     while (!defined $max_length || length $reply < $max_length) {
  1783.     $n = sysread(SSLCAT_S, $got, 1);  # one by one
  1784.     warn "tcp_read_until: $!" if !defined $n;
  1785.     debug_read(\$reply, \$got) if $trace>1;
  1786.     last if !$n;  # EOF
  1787.     $reply .= $got;
  1788.     last if $len_delim
  1789.         && substr($reply, blength($reply)-$len_delim) eq $delim;
  1790.     }
  1791.     return $reply;
  1792. }
  1793.  
  1794. # ssl_read_CRLF($ssl [, $max_length])
  1795. sub ssl_read_CRLF ($;$) { ssl_read_until($_[0], $CRLF, $_[1]) }
  1796. sub tcp_read_CRLF { tcp_read_until($CRLF, $_[0]) }
  1797.  
  1798. # ssl_write_CRLF($ssl, $message) writes $message and appends CRLF
  1799. sub ssl_write_CRLF ($$) { 
  1800.   # the next line uses less memory but might use more network packets
  1801.   return ssl_write_all($_[0], $_[1]) + ssl_write_all($_[0], $CRLF);
  1802.  
  1803.   # the next few lines do the same thing at the expense of memory, with
  1804.   # the chance that it will use less packets, since CRLF is in the original
  1805.   # message and won't be sent separately.
  1806.  
  1807.   #my $data_ref;
  1808.   #if (ref $_[1]) { $data_ref = $_[1] }
  1809.   # else { $data_ref = \$_[1] }
  1810.   #my $message = $$data_ref . $CRLF;
  1811.   #return ssl_write_all($_[0], \$message);
  1812. }
  1813.  
  1814. sub tcp_write_CRLF { 
  1815.   # the next line uses less memory but might use more network packets
  1816.   return tcp_write_all($_[0]) + tcp_write_all($CRLF);
  1817.  
  1818.   # the next few lines do the same thing at the expense of memory, with
  1819.   # the chance that it will use less packets, since CRLF is in the original
  1820.   # message and won't be sent separately.
  1821.  
  1822.   #my $data_ref;
  1823.   #if (ref $_[1]) { $data_ref = $_[1] }
  1824.   # else { $data_ref = \$_[1] }
  1825.   #my $message = $$data_ref . $CRLF;
  1826.   #return tcp_write_all($_[0], \$message);
  1827. }
  1828.  
  1829. ### Quickly print out with whom we're talking
  1830.  
  1831. sub dump_peer_certificate ($) {
  1832.     my ($ssl) = @_;
  1833.     my $cert = get_peer_certificate($ssl);
  1834.     return if print_errs('get_peer_certificate');
  1835.     print "no cert defined\n" if !defined($cert);
  1836.     # Cipher=NONE with empty cert fix
  1837.     if (!defined($cert) || ($cert == 0)) {
  1838.     warn "cert = `$cert'\n" if $trace;
  1839.     return "Subject Name: undefined\nIssuer  Name: undefined\n";
  1840.     } else {
  1841.     my $x = 'Subject Name: '
  1842.         . X509_NAME_oneline(X509_get_subject_name($cert)) . "\n"
  1843.         . 'Issuer  Name: '
  1844.             . X509_NAME_oneline(X509_get_issuer_name($cert))  . "\n";
  1845.     Net::SSLeay::X509_free($cert);
  1846.     return $x;
  1847.     }
  1848. }
  1849.  
  1850. ### Arrange some randomness for eay PRNG
  1851.  
  1852. sub randomize (;$$) {
  1853.     my ($rn_seed_file, $seed, $egd_path) = @_;
  1854.     my $rnsf = defined($rn_seed_file) && -r $rn_seed_file;
  1855.  
  1856.     $egd_path = $ENV{'EGD_PATH'} if $ENV{'EGD_PATH'};
  1857.     $egd_path = '/tmp/entropy'   unless $egd_path;
  1858.     
  1859.     RAND_seed(rand() + $$);  # Stir it with time and pid
  1860.     
  1861.     unless ($rnsf || -r $Net::SSLeay::random_device || $seed || -S $egd_path) {
  1862.     warn "Random number generator not seeded!!!" if $trace;
  1863.     }
  1864.     
  1865.     RAND_load_file($rn_seed_file, -s _) if $rnsf;
  1866.     RAND_seed($seed) if $seed;
  1867.     RAND_seed($ENV{RND_SEED}) if $ENV{RND_SEED};
  1868.     RAND_egd($egd_path) if -S $egd_path;
  1869.     RAND_load_file($Net::SSLeay::random_device, $Net::SSLeay::how_random/8)
  1870.     if -r $Net::SSLeay::random_device;
  1871. }
  1872.  
  1873. sub new_x_ctx {
  1874.     if    ($ssl_version == 2)  { $ctx = CTX_v2_new(); }
  1875.     elsif ($ssl_version == 3)  { $ctx = CTX_v3_new(); }
  1876.     elsif ($ssl_version == 10) { $ctx = CTX_tlsv1_new(); }
  1877.     else                       { $ctx = CTX_new(); }
  1878.     return $ctx;
  1879. }
  1880.  
  1881. ###
  1882. ### Basic request - response primitive (don't use for https)
  1883. ###
  1884.  
  1885. sub sslcat { # address, port, message, $crt, $key --> reply / (reply,errs,cert)
  1886.     my ($dest_serv, $port, $out_message, $crt_path, $key_path) = @_;
  1887.     my ($ctx, $ssl, $got, $errs, $written);
  1888.     
  1889.     ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
  1890.     return (wantarray ? (undef, $errs) : undef) unless $got;
  1891.     
  1892.     ### Do SSL negotiation stuff
  1893.         
  1894.     warn "Creating SSL $ssl_version context...\n" if $trace>2;
  1895.     load_error_strings();         # Some bloat, but I'm after ease of use
  1896.     SSLeay_add_ssl_algorithms();  # and debuggability.
  1897.     randomize();
  1898.     
  1899.     $ctx = new_x_ctx();
  1900.     goto cleanup2 if $errs = print_errs('CTX_new') or !$ctx;
  1901.  
  1902.     CTX_set_options($ctx, &OP_ALL);
  1903.     goto cleanup2 if $errs = print_errs('CTX_set_options');
  1904.  
  1905.     warn "Cert `$crt_path' given without key" if $crt_path && !$key_path;
  1906.     set_cert_and_key($ctx, $crt_path, $key_path) if $crt_path;
  1907.     
  1908.     warn "Creating SSL connection (context was '$ctx')...\n" if $trace>2;
  1909.     $ssl = new($ctx);
  1910.     goto cleanup if $errs = print_errs('SSL_new') or !$ssl;
  1911.     
  1912.     warn "Setting fd (ctx $ctx, con $ssl)...\n" if $trace>2;
  1913.     set_fd($ssl, fileno(SSLCAT_S));
  1914.     goto cleanup if $errs = print_errs('set_fd');
  1915.     
  1916.     warn "Entering SSL negotiation phase...\n" if $trace>2;
  1917.  
  1918.     if ($trace>2) {
  1919.     my $i = 0;
  1920.     my $p = '';
  1921.     my $cipher_list = 'Cipher list: ';
  1922.     $p=Net::SSLeay::get_cipher_list($ssl,$i);
  1923.     $cipher_list .= $p if $p;
  1924.     do {
  1925.         $i++;
  1926.         $cipher_list .= ', ' . $p if $p;
  1927.         $p=Net::SSLeay::get_cipher_list($ssl,$i);
  1928.     } while $p;
  1929.     $cipher_list .= '\n';
  1930.     warn $cipher_list;
  1931.     }
  1932.     
  1933.     $got = Net::SSLeay::connect($ssl);
  1934.     warn "SSLeay connect returned $got\n" if $trace>2;
  1935.     goto cleanup if $errs = print_errs('SSL_connect');
  1936.     
  1937.     my $server_cert = get_peer_certificate($ssl);
  1938.     print_errs('get_peer_certificate');
  1939.     if ($trace>1) {        
  1940.     warn "Cipher `" . get_cipher($ssl) . "'\n";
  1941.     print_errs('get_ciper');
  1942.     warn dump_peer_certificate($ssl);
  1943.     }
  1944.     
  1945.     ### Connected. Exchange some data (doing repeated tries if necessary).
  1946.         
  1947.     warn "sslcat $$: sending " . blength($out_message) . " bytes...\n"
  1948.     if $trace==3;
  1949.     warn "sslcat $$: sending `$out_message' (" . blength($out_message)
  1950.     . " bytes)...\n" if $trace>3;
  1951.     ($written, $errs) = ssl_write_all($ssl, $out_message);
  1952.     goto cleanup unless $written;
  1953.     
  1954.     sleep $slowly if $slowly;  # Closing too soon can abort broken servers
  1955.     CORE::shutdown SSLCAT_S, 1;  # Half close --> No more output, send EOF to server
  1956.     
  1957.     warn "waiting for reply...\n" if $trace>2;
  1958.     ($got, $errs) = ssl_read_all($ssl);
  1959.     warn "Got " . blength($got) . " bytes.\n" if $trace==3;
  1960.     warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
  1961.  
  1962. cleanup:        
  1963.     free ($ssl);
  1964.     $errs .= print_errs('SSL_free');
  1965. cleanup2:
  1966.     CTX_free ($ctx);
  1967.     $errs .= print_errs('CTX_free');
  1968.     close SSLCAT_S;    
  1969.     return wantarray ? ($got, $errs, $server_cert) : $got;
  1970. }
  1971.  
  1972. sub tcpcat { # address, port, message, $crt, $key --> reply / (reply,errs,cert)
  1973.     my ($dest_serv, $port, $out_message) = @_;
  1974.     my ($got, $errs, $written);
  1975.     
  1976.     ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
  1977.     return (wantarray ? (undef, $errs) : undef) unless $got;
  1978.     
  1979.     ### Connected. Exchange some data (doing repeated tries if necessary).
  1980.         
  1981.     warn "tcpcat $$: sending " . blength($out_message) . " bytes...\n"
  1982.     if $trace==3;
  1983.     warn "tcpcat $$: sending `$out_message' (" . blength($out_message)
  1984.     . " bytes)...\n" if $trace>3;
  1985.     ($written, $errs) = tcp_write_all($out_message);
  1986.     goto cleanup unless $written;
  1987.     
  1988.     sleep $slowly if $slowly;  # Closing too soon can abort broken servers
  1989.     CORE::shutdown SSLCAT_S, 1;  # Half close --> No more output, send EOF to server
  1990.     
  1991.     warn "waiting for reply...\n" if $trace>2;
  1992.     ($got, $errs) = tcp_read_all($ssl);
  1993.     warn "Got " . blength($got) . " bytes.\n" if $trace==3;
  1994.     warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
  1995.  
  1996. cleanup:
  1997.     close SSLCAT_S;    
  1998.     return wantarray ? ($got, $errs) : $got;
  1999. }
  2000.  
  2001. sub tcpxcat {
  2002.     my ($usessl, $site, $port, $req, $crt_path, $key_path) = @_;
  2003.     if ($usessl) {
  2004.     return sslcat($site, $port, $req, $crt_path, $key_path);
  2005.     } else {
  2006.     return tcpcat($site, $port, $req);
  2007.     }
  2008. }
  2009.  
  2010. ###
  2011. ### Basic request - response primitive, this is different from sslcat
  2012. ###                 because this does not shutdown the connection.
  2013. ###
  2014.  
  2015. sub https_cat { # address, port, message --> returns reply / (reply,errs,cert)
  2016.     my ($dest_serv, $port, $out_message, $crt_path, $key_path) = @_;
  2017.     my ($ctx, $ssl, $got, $errs, $written);
  2018.     
  2019.     ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
  2020.     return (wantarray ? (undef, $errs) : undef) unless $got;
  2021.         
  2022.     ### Do SSL negotiation stuff
  2023.         
  2024.     warn "Creating SSL $ssl_version context...\n" if $trace>2;
  2025.     load_error_strings();         # Some bloat, but I'm after ease of use
  2026.     SSLeay_add_ssl_algorithms();  # and debuggability.
  2027.     randomize();
  2028.  
  2029.     $ctx = new_x_ctx();
  2030.     goto cleanup2 if $errs = print_errs('CTX_new') or !$ctx;
  2031.  
  2032.     CTX_set_options($ctx, &OP_ALL);
  2033.     goto cleanup2 if $errs = print_errs('CTX_set_options');
  2034.     
  2035.     warn "Cert `$crt_path' given without key" if $crt_path && !$key_path;
  2036.     set_cert_and_key($ctx, $crt_path, $key_path) if $crt_path;
  2037.     
  2038.     warn "Creating SSL connection (context was '$ctx')...\n" if $trace>2;
  2039.     $ssl = new($ctx);
  2040.     goto cleanup if $errs = print_errs('SSL_new') or !$ssl;
  2041.     
  2042.     warn "Setting fd (ctx $ctx, con $ssl)...\n" if $trace>2;
  2043.     set_fd($ssl, fileno(SSLCAT_S));
  2044.     goto cleanup if $errs = print_errs('set_fd');
  2045.     
  2046.     warn "Entering SSL negotiation phase...\n" if $trace>2;
  2047.     
  2048.     if ($trace>2) {
  2049.     my $i = 0;
  2050.     my $p = '';
  2051.     my $cipher_list = 'Cipher list: ';
  2052.     $p=Net::SSLeay::get_cipher_list($ssl,$i);
  2053.     $cipher_list .= $p if $p;
  2054.     do {
  2055.         $i++;
  2056.         $cipher_list .= ', ' . $p if $p;
  2057.         $p=Net::SSLeay::get_cipher_list($ssl,$i);
  2058.     } while $p;
  2059.     $cipher_list .= '\n';
  2060.     warn $cipher_list;
  2061.     }
  2062.  
  2063.     $got = Net::SSLeay::connect($ssl);
  2064.     warn "SSLeay connect failed" if $trace>2 && $got==0;
  2065.     goto cleanup if $errs = print_errs('SSL_connect');
  2066.     
  2067.     my $server_cert = get_peer_certificate($ssl);
  2068.     print_errs('get_peer_certificate');
  2069.     if ($trace>1) {        
  2070.     warn "Cipher `" . get_cipher($ssl) . "'\n";
  2071.     print_errs('get_ciper');
  2072.     warn dump_peer_certificate($ssl);
  2073.     }
  2074.     
  2075.     ### Connected. Exchange some data (doing repeated tries if necessary).
  2076.         
  2077.     warn "https_cat $$: sending " . blength($out_message) . " bytes...\n"
  2078.     if $trace==3;
  2079.     warn "https_cat $$: sending `$out_message' (" . blength($out_message)
  2080.     . " bytes)...\n" if $trace>3;
  2081.     ($written, $errs) = ssl_write_all($ssl, $out_message);
  2082.     goto cleanup unless $written;
  2083.     
  2084.     warn "waiting for reply...\n" if $trace>2;
  2085.     ($got, $errs) = ssl_read_all($ssl);
  2086.     warn "Got " . blength($got) . " bytes.\n" if $trace==3;
  2087.     warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
  2088.  
  2089. cleanup:
  2090.     free ($ssl);
  2091.     $errs .= print_errs('SSL_free');
  2092. cleanup2:
  2093.     CTX_free ($ctx);
  2094.     $errs .= print_errs('CTX_free');
  2095.     close SSLCAT_S;    
  2096.     return wantarray ? ($got, $errs, $server_cert) : $got;
  2097. }
  2098.  
  2099. sub http_cat { # address, port, message --> returns reply / (reply,errs,cert)
  2100.     my ($dest_serv, $port, $out_message) = @_;
  2101.     my ($got, $errs, $written);
  2102.     
  2103.     ($got, $errs) = open_proxy_tcp_connection($dest_serv, $port);
  2104.     return (wantarray ? (undef, $errs) : undef) unless $got;
  2105.         
  2106.     ### Connected. Exchange some data (doing repeated tries if necessary).
  2107.         
  2108.     warn "http_cat $$: sending " . blength($out_message) . " bytes...\n"
  2109.     if $trace==3;
  2110.     warn "http_cat $$: sending `$out_message' (" . blength($out_message)
  2111.     . " bytes)...\n" if $trace>3;
  2112.     ($written, $errs) = tcp_write_all($out_message);
  2113.     goto cleanup unless $written;
  2114.     
  2115.     warn "waiting for reply...\n" if $trace>2;
  2116.     ($got, $errs) = tcp_read_all(200000);
  2117.     warn "Got " . blength($got) . " bytes.\n" if $trace==3;
  2118.     warn "Got `$got' (" . blength($got) . " bytes)\n" if $trace>3;
  2119.  
  2120. cleanup:
  2121.     close SSLCAT_S;    
  2122.     return wantarray ? ($got, $errs) : $got;
  2123. }
  2124.  
  2125. sub httpx_cat {
  2126.     my ($usessl, $site, $port, $req, $crt_path, $key_path) = @_;
  2127.     warn "httpx_cat: usessl=$usessl ($site:$port)" if $trace;
  2128.     if ($usessl) {
  2129.     return https_cat($site, $port, $req, $crt_path, $key_path);
  2130.     } else {
  2131.     return http_cat($site, $port, $req);
  2132.     }
  2133. }
  2134.  
  2135. ###
  2136. ### Easy set up of private key and certificate
  2137. ###
  2138.  
  2139. sub set_cert_and_key ($$$) {
  2140.     my ($ctx, $cert_path, $key_path) = @_;    
  2141.     my $errs = '';
  2142.     # Following will ask password unless private key is not encrypted
  2143.     CTX_use_RSAPrivateKey_file ($ctx, $key_path, &FILETYPE_PEM);
  2144.     $errs .= print_errs("private key `$key_path' ($!)");
  2145.     CTX_use_certificate_file ($ctx, $cert_path, &FILETYPE_PEM);
  2146.     $errs .= print_errs("certificate `$cert_path' ($!)");
  2147.     return wantarray ? (undef, $errs) : ($errs eq '');
  2148. }
  2149.  
  2150. ### Old deprecated API
  2151.  
  2152. sub set_server_cert_and_key ($$$) { &set_cert_and_key }
  2153.  
  2154. ### Set up to use web proxy
  2155.  
  2156. sub set_proxy ($$;**) {
  2157.     ($proxyhost, $proxyport, $proxyuser, $proxypass) = @_;
  2158.     require MIME::Base64 if $proxyuser;
  2159.     $proxyauth = $CRLF . 'Proxy-authorization: Basic '
  2160.     . MIME::Base64::encode("$proxyuser:$proxypass", '')
  2161.         if $proxyuser;
  2162. }
  2163.  
  2164. ###
  2165. ### Easy https manipulation routines
  2166. ###
  2167.  
  2168. sub make_form {
  2169.     my (@fields) = @_;
  2170.     my $form;
  2171.     while (@fields) {
  2172.     my ($name, $data) = (shift(@fields), shift(@fields));
  2173.     $data =~ s/([^\w\-.\@\$ ])/sprintf("%%%2.2x",ord($1))/gse;
  2174.         $data =~ tr[ ][+];
  2175.     $form .= "$name=$data&";
  2176.     }
  2177.     chop $form;
  2178.     return $form;
  2179. }
  2180.  
  2181. sub make_headers {
  2182.     my (@headers) = @_;
  2183.     my $headers;
  2184.     while (@headers) {
  2185.     my $header = shift(@headers);
  2186.     my $value = shift(@headers);
  2187.     $header =~ s/:$//;
  2188.     $value =~ s/\x0d?\x0a$//; # because we add it soon, see below
  2189.     $headers .= "$header: $value$CRLF";
  2190.     }
  2191.     return $headers;
  2192. }
  2193.  
  2194. sub do_httpx3 {
  2195.     my ($method, $usessl, $site, $port, $path, $headers,
  2196.     $content, $mime_type, $crt_path, $key_path) = @_;
  2197.     my ($response, $page, $h,$v);
  2198.  
  2199.     if ($content) {
  2200.     $mime_type = "application/x-www-form-urlencoded" unless $mime_type;
  2201.     my $len = blength($content);
  2202.     $content = "Content-Type: $mime_type$CRLF"
  2203.         . "Content-Length: $len$CRLF$CRLF$content";
  2204.     } else {
  2205.     $content = "$CRLF$CRLF";
  2206.     }
  2207.     my $req = "$method $path HTTP/1.0$CRLF"."Host: $site:$port$CRLF"
  2208.       . (defined $headers ? $headers : '') . "Accept: */*$CRLF$content";    
  2209.  
  2210.     warn "do_httpx3($method,$usessl,$site:$port)" if $trace;
  2211.     my ($http, $errs, $server_cert)
  2212.     = httpx_cat($usessl, $site, $port, $req, $crt_path, $key_path);
  2213.     return (undef, "HTTP/1.0 900 NET OR SSL ERROR$CRLF$CRLF$errs") if $errs;
  2214.     
  2215.     $http = '' if !defined $http;
  2216.     ($headers, $page) = split /\s?\n\s?\n/, $http, 2;
  2217.     warn "headers >$headers< page >>$page<< http >>>$http<<<" if $trace>1;
  2218.     ($response, $headers) = split /\s?\n/, $headers, 2;
  2219.     return ($page, $response, $headers, $server_cert);
  2220. }
  2221.  
  2222. sub do_https3 { splice(@_,1,0) = 1; do_httpx3; }  # Legacy undocumented
  2223.  
  2224. ### do_https2() is a legacy version in the sense that it is unable
  2225. ### to return all instances of duplicate headers.
  2226.  
  2227. sub do_httpx2 {
  2228.     my ($page, $response, $headers, $server_cert) = &do_httpx3;
  2229.     X509_free($server_cert) if defined $server_cert;
  2230.     return ($page, $response,
  2231.         map( { ($h,$v)=/^(\S+)\:\s*(.*)$/; (uc($h),$v); }
  2232.         split(/\s?\n/, $headers)
  2233.         )
  2234.         );
  2235. }
  2236.  
  2237. sub do_https2 { splice(@_,1,0) = 1; do_httpx2; }  # Legacy undocumented
  2238.  
  2239. ### Returns headers as a hash where multiple instances of same header
  2240. ### are handled correctly.
  2241.  
  2242. sub do_httpx4 {
  2243.     my ($page, $response, $headers, $server_cert) = &do_httpx3;
  2244.     X509_free($server_cert) if defined $server_cert;
  2245.     my %hr = ();
  2246.     for my $hh (split /\s?\n/, $headers) {
  2247.     my ($h,$v)=/^(\S+)\:\s*(.*)$/;
  2248.     push @{$hr{uc($h)}}, $v;
  2249.     }
  2250.     return ($page, $response, \%hr);
  2251. }
  2252.  
  2253. sub do_https4 { splice(@_,1,0) = 1; do_httpx4; }  # Legacy undocumented
  2254.  
  2255. # https
  2256.  
  2257. sub get_https  ($$$;***) { do_httpx2(GET  => 1, @_) }
  2258. sub post_https ($$$;***) { do_httpx2(POST => 1, @_) }
  2259. sub put_https  ($$$;***) { do_httpx2(PUT  => 1, @_) }
  2260. sub head_https ($$$;***) { do_httpx2(HEAD => 1, @_) }
  2261.  
  2262. sub get_https3  ($$$;***) { do_httpx3(GET  => 1, @_) }
  2263. sub post_https3 ($$$;***) { do_httpx3(POST => 1, @_) }
  2264. sub put_https3  ($$$;***) { do_httpx3(PUT  => 1, @_) }
  2265. sub head_https3 ($$$;***) { do_httpx3(HEAD => 1, @_) }
  2266.  
  2267. sub get_https4  ($$$;***) { do_httpx4(GET  => 1, @_) }
  2268. sub post_https4 ($$$;***) { do_httpx4(POST => 1, @_) }
  2269. sub put_https4  ($$$;***) { do_httpx4(PUT  => 1, @_) }
  2270. sub head_https4 ($$$;***) { do_httpx4(HEAD => 1, @_) }
  2271.  
  2272. # http
  2273.  
  2274. sub get_http  ($$$;***) { do_httpx2(GET  => 0, @_) }
  2275. sub post_http ($$$;***) { do_httpx2(POST => 0, @_) }
  2276. sub put_http  ($$$;***) { do_httpx2(PUT  => 0, @_) }
  2277. sub head_http ($$$;***) { do_httpx2(HEAD => 0, @_) }
  2278.  
  2279. sub get_http3  ($$$;***) { do_httpx3(GET  => 0, @_) }
  2280. sub post_http3 ($$$;***) { do_httpx3(POST => 0, @_) }
  2281. sub put_http3  ($$$;***) { do_httpx3(PUT  => 0, @_) }
  2282. sub head_http3 ($$$;***) { do_httpx3(HEAD => 0, @_) }
  2283.  
  2284. sub get_http4  ($$$;***) { do_httpx4(GET  => 0, @_) }
  2285. sub post_http4 ($$$;***) { do_httpx4(POST => 0, @_) }
  2286. sub put_http4  ($$$;***) { do_httpx4(PUT  => 0, @_) }
  2287. sub head_http4 ($$$;***) { do_httpx4(HEAD => 0, @_) }
  2288.  
  2289. # Either https or http
  2290.  
  2291. sub get_httpx  ($$$;***) { do_httpx2(GET  => @_) }
  2292. sub post_httpx ($$$;***) { do_httpx2(POST => @_) }
  2293. sub put_httpx  ($$$;***) { do_httpx2(PUT  => @_) }
  2294. sub head_httpx ($$$;***) { do_httpx2(HEAD => @_) }
  2295.  
  2296. sub get_httpx3  ($$$;***) { do_httpx3(GET  => @_) }
  2297. sub post_httpx3 ($$$;***) { do_httpx3(POST => @_) }
  2298. sub put_httpx3  ($$$;***) { do_httpx3(PUT  => @_) }
  2299. sub head_httpx3 ($$$;***) { do_httpx3(HEAD => @_) }
  2300.  
  2301. sub get_httpx4  ($$$;***) { do_httpx4(GET  => @_) }
  2302. sub post_httpx4 ($$$;***) { do_httpx4(POST => @_) }
  2303. sub put_httpx4  ($$$;***) { do_httpx4(PUT  => @_) }
  2304. sub head_httpx4 ($$$;***) { do_httpx4(HEAD => @_) }
  2305.  
  2306. ### Legacy, don't use
  2307. # ($page, $respone_or_err, %headers) = do_https(...);
  2308.  
  2309. sub do_https {
  2310.     my ($site, $port, $path, $method, $headers,
  2311.     $content, $mime_type, $crt_path, $key_path) = @_;
  2312.  
  2313.     do_https2($method, $site, $port, $path, $headers,
  2314.          $content, $mime_type, $crt_path, $key_path);
  2315. }
  2316.  
  2317. 1;
  2318. __END__
  2319.