名前¶
Net::SSLeay - Perl extension for using OpenSSL
Net::SSLeay - OpenSSL を使うための Perl 拡張
概要¶
use Net::SSLeay qw(get_https post_https sslcat make_headers make_form);
($page) = get_https('www.bacus.pt', 443, '/'); # 1
($page, $response, %reply_headers)
= get_https('www.bacus.pt', 443, '/', # 2
make_headers(User-Agent => 'Cryptozilla/5.0b1',
Referer => 'https://www.bacus.pt'
));
($page, $result, %headers) = # 2b
= get_https('www.bacus.pt', 443, '/protected.html',
make_headers(Authorization =>
'Basic ' . MIME::Base64::encode("$user:$pass",''))
);
($page, $response, %reply_headers)
= post_https('www.bacus.pt', 443, '/foo.cgi', '', # 3
make_form(OK => '1',
name => 'Sampo'
));
$reply = sslcat($host, $port, $request); # 4
($reply, $err, $server_cert) = sslcat($host, $port, $request); # 5
$Net::SSLeay::trace = 2; # 0=no debugging, 1=ciphers, 2=trace, 3=dump data
説明¶
There is a related module called Net::SSLeay::Handle included in this distribution that you might want to use instead. It has its own pod documentation.
あなたが代わりに使いたいかもしれない、この配布に 含まれている Net::SSLeay::Handle という関連するモジュールがあります。 それは、それ独自の POD ドキュメントを持っています。
This module offers some high level convenience functions for accessing web pages on SSL servers (for symmetry, the same API is offered for accessing http servers, too), an sslcat() function for writing your own clients, and finally access to the SSL api of the SSLeay/OpenSSL package so you can write servers or clients for more complicated applications.
このモジュールは、SSL サーバ上の Web ページにアクセスするためのいくつかの 高レベルで便利な関数 (対称性のために、同じ API で http サーバへのアクセスも提供します)、 独自のクライアントを書くための sslcat() 関数、そして最終的には より複雑なアプリケーションのためにサーバやクライアントを書くことが できるような SSLeay/OpenSSL パッケージの SSL api への アクセスを提供します。
For high level functions it is most convenient to import them into your main namespace as indicated in the synopsis.
高レベルの関数については、概要で示したように、あなたの main 名前空間に インポートすることが、とても便利でしょう。
Case 1 demonstrates the typical invocation of get_https() to fetch an HTML page from secure server. The first argument provides the hostname or IP in dotted decimal notation of the remote server to contact. The second argument is the TCP port at the remote end (your own port is picked arbitrarily from high numbered ports as usual for TCP). The third argument is the URL of the page without the host name part. If in doubt consult the HTTP specifications at http://www.w3c.org.
ケース 1 はセキュアなサーバから HTML ページを取り出すための get_https() の 典型的な呼び出しを示しています。 最初の引数は接続するリモートのサーバの ホスト名あるいは IP をドット区切られた数字による書き方によって与えます。 2 番目の引数はリモート側の TCP ポートです(あなた自身のポートは通常の TCP のための大きな番号が振られたものから勝手に選択されます)。 3 番目の引数はホスト名の部分を抜いたページの URL です。 もし疑問があれば、http://www.w3c.org にある HTTP の仕様を あたってみてください。
Case 2 demonstrates full fledged use of get_https(). As can be seen, get_https() parses the response and response headers and returns them as a list, which can be captured in a hash for later reference. Also a fourth argument to get_https() is used to insert some additional headers in the request. make_headers() is a function that will convert a list or hash to such headers. By default get_https() supplies Host (to make virtual hosting easy) and Accept (reportedly needed by IIS) headers.
ケース 2 は、完全に一人前の get_https() の使い方を示しています。 ご覧になった通り、 get_https() は応答と応答のヘッダを解析し、それをリストで返しています。 それらはハッシュや後者のリファレンスで捉えることができます。 また get_https() の 4 番目の引数は、応答での追加のヘッダを挿入するために 使われます。 make_headers() はリストやハッシュを、そのようなヘッダに変換する関数です。 デフォルトでは get_https() は Host(バーチャルホストを簡単に 行えるように)と Accept (IIS が必要としているとのこと)ヘッダを提供します。
Case 2b demonstrates how to get a password protected page. Refer to the HTTP protocol specifications for further details (e.g. RFC-2617).
ケース 2b はパスワードで保護されているページを取得する方法を示しています。 更なる詳細に関しては、HTTP プロトコルの仕様を参照してください (例えば RFC-2617)。
Case 3 invokes post_https() to submit a HTML/CGI form to a secure server. The first four arguments are equal to get_https() (note that the empty string ('') is passed as header argument). The fifth argument is the contents of the form formatted according to CGI specification. In this case the helper function make_https() is used to do the formatting, but you could pass any string. post_https() automatically adds Content-Type and Content-Length headers to the request.
ケース 3 は HTML/CGI フォームをセキュアなサーバで実行するために post_https() を呼び出します。 最初の 4 つの引数は get_https() と同じです (空文字列('')が ヘッダの引数として渡されていることに注意してください)。 5 番目の引数は CGI の仕様に従って形式が整えられたフォームの内容です。 この場合、そのように形式を整えるためにヘルパー関数 make_https() が 使われますが、どのような文字列でも渡すことができます。 post_https() は自動的にリクエストに Content-Type と Content-Length ヘッダを付与します。
Case 4 shows the fundamental sslcat() function (inspired in spirit by the netcat utility :-). It's your swiss army knife that allows you to easily contact servers, send some data, and then get the response. You are responsible for formatting the data and parsing the response - sslcat() is just a transport.
ケース 4 は、基本的な sslcat() 関数を示しています(netcat ユーティリティに心を動かされました :-)。 これは単純にサーバに接続し、データを送信し、 それから応答を取得することを簡単にするスイスアーミーナイフのようなものです。 データの整形と応答の解析についてはあなたの責任です - sslcat() は 単に転送するだけのものです。
Case 5 is a full invocation of sslcat() which allows the return of errors as well as the server (peer) certificate.
ケース 5 は、エラーだけでなくサーバ(相手側)証明書と同様も返すことを 可能にする、sslcat() の完全な呼び出しです。
The $trace global variable can be used to control the verbosity of the high level functions. Level 0 guarantees silence, level 1 (the default) only emits error messages.
$trace グローバル変数は高レベル関数の冗長さを制御するために使うことが 出来ます。 レベル 0 は何もいわないことを保証します。 レベル 1 (デフォルト) はエラーメッセージだけを吐き出します。
API の代替版¶
The above mentioned functions actually return the response headers as a list, which only gets converted to hash upon assignment (this assignment looses information if the same header occurs twice, as may be the case with cookies). There are also other variants of the functions that return unprocessed headers and that return a reference to a hash.
上記の関数は実際には応答ヘッダをリストで返します。 それは代入されたハッシュに変換されます (もしクッキーの場合がそうであるかもしれないように同じヘッダが 2 回発生すると、この代入によって情報が失われるかもしれません)。 処理されていないヘッダとハッシュへのリファレンスを返す別の形の関数もあります。
($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
for ($i = 0; $i < $#headers; $i+=2) {
print "$headers[$i] = " . $headers[$i+1] . "\n";
}
($page, $response, $headers, $server_cert)
= get_https3('www.bacus.pt', 443, '/');
print "$headers\n";
($page, $response, %headers_ref, $server_cert)
= get_https4('www.bacus.pt', 443, '/');
for $k (sort keys %{headers_ref}) {
for $v (@{$headers_ref{$k}}) {
print "$k = $v\n";
}
}
All of the above code fragments accomplish the same thing: display all values of all headers. The API functions ending in "3" return the headers simply as a scalar string and it is up to the application to split them up. The functions ending in "4" return a reference to a hash of arrays (see perlref and perllol if you are not familiar with complex perl data structures). To access a single value of such a header hash you would do something like
上記の全てのちょっとしたコードは、同じ事を実現します: ヘッダの全ての値を 表示します。 "3" で終わる API 関数はヘッダを単なるスカラーの文字列で返します。 アプリケーションがそれを分割することになります。 "4" で終わる関数は配列のハッシュへのリファレンスを返します(複雑な perl データ構造体に精通していなければ perlref と Lperllol マニュアルページをご覧ください)。 そのようなヘッダハッシュの1つの値にアクセスするためには、 以下のようにしてください:
print $headers_ref{COOKIE}[0];
Variants 3 and 4 also allow you to discover the server certificate in case you would like to store or display it, e.g.
3 と 4 の形は、それを格納したり表示したいときサーバ証明書を見つけることも 可能にします。 例えば:
($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
if (!defined($server_cert) || ($server_cert == 0)) {
warn "Subject Name: undefined, Issuer Name: undefined";
} else {
warn 'Subject Name: '
. Net::SSLeay::X509_NAME_oneline(
Net::SSLeay::X509_get_subject_name($server_cert))
. 'Issuer Name: '
. Net::SSLeay::X509_NAME_oneline(
Net::SSLeay::X509_get_issuer_name($server_cert));
}
Beware that this method only allows after the fact verification of the certificate: by the time get_https3() has returned the https request has already been sent to the server, whether you decide to trust it or not. To do the verification correctly you must either employ the OpenSSL certificate verification framework or use the lower level API to first connect and verify the certificate and only then send the http data. See the implementation of ds_https3() for guidance on how to do this.
この方法は証明書の確認の後にだけ可能になるということに注意してください: そのときには、あなたが信用するかどうかに関わらず、get_https3() は サーバに送信された https リクエストを返してしまっています。 正しく確認するためには、OpenSSL 証明書確認フレームワークを採用するか、 最初に接続し、証明書を確認し、そのときにだけ http データを送信するため 低レベル API を利用するかのどちらかをする必要があります。 このやり方についてのガイドは ds_https3() の実装をご覧ください。
クライアント証明書を使う¶
Secure web communications are encrypted using symmetric crypto keys exchanged using encryption based on the certificate of the server. Therefore in all SSL connections the server must have a certificate. This serves both to authenticate the server to the clients and to perform the key exchange.
セキュアな Web 通信はサーバの証明書をベースにした暗号を使って 交換された対称になった暗号鍵を使って暗号化されます。 このため全ての SSL の通信では、サーバは証明書を持っていなければなりません。 これはクライアントへのサーバの認証と鍵の交換の両方を提供します。
Sometimes it is necessary to authenticate the client as well. Two options are available: HTTP basic authentication and a client side certificate. The basic authentication over HTTPS is actually quite safe because HTTPS guarantees that the password will not travel in the clear. Never-the-less, problems like easily guessable passwords remain. The client certificate method involves authentication of the client at the SSL level using a certificate. For this to work, both the client and the server have certificates (which typically are different) and private keys.
場合によってはクライアントも認証する必要があります。 二つの選択を利用できます: HTTP 基本認証とクライアント側の証明書です。 HTTPS がパスワードが平文で流れないことを保証するので、HTTPS 越しの 基本認証は実際には非常に安全です。 しかし、そうであったとしても簡単にわかるようなパスワードのような 問題は残ります。 クライアント証明書の方法には証明書を使った SSL レベルでのクライアントの 認証を意味します。 これが機能するためにはクライアントとサーバの両方が (典型的には異なる)証明書と秘密鍵を持つ必要があります。
The API functions outlined above accept additional arguments that allow one to supply the client side certificate and key files. The format of these files is the same as used for server certificates and the caveat about encrypting private keys applies.
上記で概説された API 関数は、クライアント側の証明書と鍵ファイルを 提供することができる追加の引数を受け取ります。 これらのファイルの形式はサーバ証明書で使われているものと同じです。 そして秘密鍵の暗号化に関する注意も当てはまります。
($page, $result, %headers) = # 2c
= get_https('www.bacus.pt', 443, '/protected.html',
make_headers(Authorization =>
'Basic ' . MIME::Base64::encode("$user:$pass",'')),
'', $mime_type6, $path_to_crt7, $path_to_key8);
($page, $response, %reply_headers)
= post_https('www.bacus.pt', 443, '/foo.cgi', # 3b
make_headers('Authorization' =>
'Basic ' . MIME::Base64::encode("$user:$pass",'')),
make_form(OK => '1', name => 'Sampo'),
$mime_type6, $path_to_crt7, $path_to_key8);
Case 2c demonstrates getting a password protected page that also requires a client certificate, i.e. it is possible to use both authentication methods simultaneously.
ケース 2c はクライアント証明書も必要とする、パスワードで保護された ページを取得することを示しています。 つまり両方の認証方法を同時に使うことも可能です。
Case 3b is a full blown POST to a secure server that requires both password authentication and a client certificate, just like in case 2c.
ケース 3b は、ケース 2c とちょうど同じようにパスワード認証とクライアント 証明書の両方を必要とするセキュアなサーバへの完全に展開された POST です。
Note: The client will not send a certificate unless the server requests one. This is typically achieved by setting the verify mode to VERIFY_PEER on the server:
注意: サーバが要求しなければ、クライアントは証明書を送信しません。 これは典型的にはサーバで確認モードを VERIFY_PEER に設定することにより 実現されます:
Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);
See perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod for a full description.
完全な説明については、perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod を ご覧ください。
Web プロキシを通して動かす¶
Net::SSLeay can use a web proxy to make its connections. You need to first set the proxy host and port using set_proxy() and then just use the normal API functions, e.g:
Net::SSLeay は接続を行うためにWebプロキシを利用することができます。 最初に set_proxy() を使ってプロキシホストとポートを設定したら、 後は通常のAPI関数を使うだけです。 例えば:
Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
($page) = get_https('www.bacus.pt', 443, '/');
If your proxy requires authentication, you can supply a username and password as well
あなたのプロキシが認証を必要とするのであれば、ユーザ名とパスワードも 与えることができます
Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
($page, $result, %headers) =
= get_https('www.bacus.pt', 443, '/protected.html',
make_headers(Authorization =>
'Basic ' . MIME::Base64::encode("susie:pass",''))
);
This example demonstrates the case where we authenticate to the proxy as "joe" and to the final web server as "susie". Proxy authentication requires the MIME::Base64 module to work.
この例は "joe" でプロキシに、最終的なWebサーバには "susie" で認証を 行うケースを示しています。 プロキシの認証は MIME::Base64 が機能することを必要とします。
証明書の検証と証明書失効リスト(CRL)¶
OpenSSL supports the ability to verify peer certificates. It can also optionally check the peer certificate against a Certificate Revocation List (CRL) from the certificates issuer. A CRL is a file, created by the certificate issuer that lists all the certificates that it previously signed, but which it now revokes. CRLs are in PEM format.
OpenSSL はピア証明書の検証に対応しています。 オプションで、証明書発行者からの 証明書失効リスト (CRL) に対する ピア証明書のチェックもできます。 CRL は、証明者の発行者によって作られた、以前に署名したけれども、 今は廃止されている全ての証明書の一覧のファイルです。 CRL は PEM 形式です。
You can enable Net::SSLeay CRL checking like this:
次のようにして Net::SSLeay CRL チェックを有効にします:
&Net::SSLeay::X509_STORE_CTX_set_flags
(&Net::SSLeay::CTX_get_cert_store($ssl),
&Net::SSLeay::X509_V_FLAG_CRL_CHECK);
After setting this flag, if OpenSSL checks a peer's certificate, then it will attempt to find a CRL for the issuer. It does this by looking for a specially named file in the search directory specified by CTX_load_verify_locations. CRL files are named with the hash of the issuer's subject name, followed by .r0, .r1 etc. For example ab1331b2.r0, ab1331b2.r1. It will read all the .r files for the issuer, and then check for a revocation of the peer cerificate in all of them. (You can also force it to look in a specific named CRL file., see below). You can find out the hash of the issuer subject name in a CRL with
このフラグを設定した後、OpenSSL がピア証明書をチェックする場合、 発行元の CRL を見つけようとします。 これは CTX_load_verify_locations で指定された検索ディレクトリから 特定の名前のファイルを探すことで行われます。 CRL ファイルは、発行者のサブジェクト名のハッシュに .r0, .r1 などが引き続く名前を持ちます。 例えば ab1331b2.r0, ab1331b2.r1。 対象の発行者の全ての .r ファイルを読み込み、その全てから ピア証明書の失効をチェックします。 (特定の名前の CRL ファイルを見るように強制することもできます; 後述。) CRL での発行者のサブジェクト名のハッシュは次のようにして見つけられます
openssl crl -in crl.pem -hash -noout
If the peer certificate does not pass the revocation list, or if no CRL is found, then the handshaking fails with an error.
ピア証明書が証明書失効リストを通過しなかった場合、 あるいは CRL が見つからなかった場合、 ハンドシェイクはエラー終了します。
You can also force OpenSSL to look for CRLs in one or more arbitrarily named files.
また、任意の名前の一つまたは複数のファイルにある CRL を探させるように OpenSSL を強制できます。
my $bio = Net::SSLeay::BIO_new_file($crlfilename, 'r');
my $crl = Net::SSLeay::PEM_read_bio_X509_CRL($bio);
if ($crl) {
Net::SSLeay::X509_STORE_add_crl(Net::SSLeay::CTX_get_cert_store($ssl, $crl);
} else {
error reading CRL....
}
便利なルーチン¶
To be used with Low level API
低レベルで使うために:
Net::SSLeay::randomize($rn_seed_file,$additional_seed);
Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
$cert = Net::SSLeay::dump_peer_certificate($ssl);
Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
$got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
$got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
$got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
Net::SSLeay::ssl_write_CRLF($ssl, $message);
randomize() seeds the openssl PRNG with /dev/urandom (see the top of SSLeay.pm for how to change or configure this) and optionally with user provided data. It is very important to properly seed your random numbers, so do not forget to call this. The high level API functions automatically call randomize() so it is not needed with them. See also caveats.
randomize() は /dev/urandom とオプションでユーザに与えられたデータで openssl PRNG に種を設定し(これの変更あるいは設定のやり方については、 SSLeay.pm の先頭をご覧ください)。 適切に乱数の種を設定することは非常に重要です。 ですから、これを呼び出すことを忘れないでください。 高レベルの API 関数は自動的に randomize() を呼び出します。 そのためそれらでは必要ありません。 注意もご覧ください。
set_cert_and_key() takes two file names as arguments and sets the certificate and private key to those. This can be used to set either cerver certificates or client certificates.
set_cert_and_key() は引数として二つのファイル名を取り、 それらを証明書と秘密鍵に設定します。 これはサーバ証明書とクライアント証明書の両方に使えます。
dump_peer_certificate() allows you to get a plaintext description of the certificate the peer (usually the server) presented to us.
dump_peer_certificate() は相手側(通常はサーバ)が提出した 証明書の平文の説明を取得することを可能にします。
ssl_read_all() and ssl_write_all() provide true blocking semantics for these operations (see limitation, below, for explanation). These are much preferred to the low level API equivalents (which implement BSD blocking semantics). The message argument to ssl_write_all() can be a reference. This is helpful to avoid unnecessary copying when writing something big, e.g:
ssl_read_all() と ssl_write_all() は、これらの処理のための 本当のブロック化の意味論で提供します(説明については下記の制限を ご覧ください)。 これらは低レベル API と同じものとして非常に好まれます (これは BSD ブロック化セマンティクを実装しています)。 ssl_write_all() への message 引数はリファレンスにすることができます。 これは何か大きなものを出力するとき、不必要なコピーを避けるために便利です。 例えば:
$data = 'A' x 1000000000;
Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
ssl_read_CRLF() uses ssl_read_all() to read in a line terminated with a carriage return followed by a linefeed (CRLF). The CRLF is included in the returned scalar.
ssl_read_CRLF() は ssl_read_all() を使って改行が後ろについた 復帰(CRLF)で終わる行を読み込みます。 CRLF は返されるスカラーに含まれます。
ssl_read_until() uses ssl_read_all() to read from the SSL input stream until it encounters a programmer specified delimiter. If the delimiter is undefined, $/ is used. If $/ is undefined, \n is used. One can optionally set a maximum length of bytes to read from the SSL input stream.
ssl_read_until() ssl_read_all() を使って SSL 入力から プログラマによって指定された区切り文字まで読み込みます。 区切り文字が未定義であれば$/ が使われます。 $/ が未定義であれば、\n が使われます。 SSL入力ストリームからの読み込む最大バイト長をオプションで 設定することができます。
ssl_write_CRLF() writes $message and appends CRLF to the SSL output stream.
ssl_write_CRLF() は SSL 出力ストリームに $message を出力し、CRLF を 追加します。
低レベル API¶
In addition to the high level functions outlined above, this module contains straight-forward access to SSL part of OpenSSL C api. Only the SSL subpart of OpenSSL is implemented (if anyone wants to implement other parts, feel free to submit patches).
上記で説明した高レベル関数に加えて、このモジュールには OpenSSL C api の SSL 部分にそのままアクセスすることもできます。 OpenSSL の SSL サブパートだけが実装されています(他の部分も実装したければ、 パッチを提供することをためらわないでください)。
See the ssl.h header from OpenSSL C distribution for a list of low level SSLeay functions to call (check SSLeay.xs to see if some function has been implemented). The module strips the initial "SSL_" off of the SSLeay names. Generally you should use Net::SSLeay:: in its place. For example:
低レベル SSLeay 関数の呼び出し方の一覧については、OpenSSL C 配布の ssl.h ヘッダをご覧ください(関数が 実装されているかをチェックするためには、SSLeay.xs をご覧ください)。 このモジュールでは SSLeay の名前から先頭の "SSL_" をはずしています。 一般的にはその場所に Net::SSLeay:: を使わなければなりません。 例えば:
In C:
C では:
#include <ssl.h>
err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
&your_call_back_here);
In Perl:
Perl では:
use Net::SSLeay;
$err = Net::SSLeay::set_verify ($ssl,
Net::SSLeay::VERIFY_CLIENT_ONCE,
\&your_call_back_here);
If the function does not start with SSL_ you should use the full function name, e.g.:
SSL_ で始まらない関数では、関数名全体を使わなければなりません。 例えば:
$err = Net::SSLeay::ERR_get_error;
The following new functions behave in perlish way:
以下の新しい関数は perl 的に振舞います:
$got = Net::SSLeay::read($ssl);
# Performs SSL_read, but returns $got
# resized according to data received.
# Returns undef on failure.
$got = Net::SSLeay::read($ssl);
# SSL_read を行いますが、受信データに
# 従って大きさが変更された $got を返します
# 失敗したときには undef を返します。
Net::SSLeay::write($ssl, $foo) || die;
# Performs SSL_write, but automatically
# figures out the size of $foo
Net::SSLeay::write($ssl, $foo) || die;
# SSL_write を実行します。しかし自動的に
# $foo の大きさを計算します。
In order to use the low level API you should start your programs with the following incantation:
低レベル API を使うためには、あなたのプログラムは以下のように始まらなければ なりません:
use Net::SSLeay qw(die_now die_if_ssl_error);
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms(); # Important!
Net::SSLeay::ENGINE_load_builtin_engines(); # If you want built-in engines
Net::SSLeay::ENGINE_register_all_complete(); # If you want built-in engines
Net::SSLeay::randomize();
use Net::SSLeay qw(die_now die_if_ssl_error);
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms(); # 重要!
Net::SSLeay::ENGINE_load_builtin_engines(); # 組み込みエンジンが必要なら
Net::SSLeay::ENGINE_register_all_complete(); # 組み込みエンジンが必要なら
Net::SSLeay::randomize();
die_now() and die_if_ssl_error() are used to conveniently print the SSLeay error stack when something goes wrong, thusly:
die_now() と die_if_ssl_error() は、以下のように何かがおかしくなったとき 簡単に SSLeay エラースタックを出力するために使用されます:
Net::SSLeay::connect($ssl) or die_now("Failed SSL connect ($!)");
Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
You can also use Net::SSLeay::print_errs() to dump the error stack without exiting the program. As can be seen, your code becomes much more readable if you import the error reporting functions into your main name space.
プログラムを終了させることなくエラースタックをダンプさせるために Net::SSLeay::print_errs() を使うことも出来ます。 今見たように、main 名前空間にエラー報告関数をインポートすれば、 あなたのコードは、さらにとても読みやすくなります。
I can not emphasize the need to check for error enough. Use these functions even in the most simple programs, they will reduce debugging time greatly. Do not ask questions on the mailing list without having first sprinkled these in your code.
エラーの戻り値をチェックする必要性はいくら強調しても足りません。 非常に単純なプログラムであっても、これらの関数を使ってください。 これらはデバッグにかかる時間を大幅に削減します。 先にこれらのものをあなたコードのあちこちに入れることなく、 メーリングリストに質問しないでください。
ソケット¶
Perl uses file handles for all I/O. While SSLeay has a quite flexible BIO mechanism and perl has an evolved PerlIO mechanism, this module still sticks to using file descriptors. Thus to attach SSLeay to a socket you should use fileno() to extract the underlying file descriptor:
Perl は全ての I/O にファイルハンドルを使います。 SSLeay は非常に柔軟性のある BIO 機構を持っていますし、perl は PerlIO 機構を 進化させていますが、 このモジュールはファイル記述子を使うことにこだわっています。 このため SSLeay をソケットにつけるためには、元になっているファイル記述子を 取り出すために fineno() を使わなければなりません:
Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
Net::SSLeay::set_fd($ssl, fileno(S)); # fineno を使わなければなりません
You should also set $| to 1 to eliminate STDIO buffering so you do not get confused if you use perl I/O functions to manipulate your socket handle.
あなたのソケットハンドルを操作するために perl の I/O 関数を使うのであれば、 混乱しないよう、STDIO のバッファリングを止めさせるためには、$| に 1 を 設定しなければなりません。
If you need to select(2) on the socket, go right ahead, but be warned that OpenSSL does some internal buffering so SSL_read does not always return data even if the socket selected for reading (just keep on selecting and trying to read). Net::SSLeay is no different from the C language OpenSSL in this respect.
ソケットに select(2) する必要があれば、すぐに行ってください。 ただし OpenSSL は内部バッファリングを行っていて、そのためソケットが読み込みの ために選択されているときでも(単に選択し、読み込もうとし続けるだけ)、 常にデータを返すわけではないことに注意してください。 この点で Net::SSLeay は C 言語 OpenSSL とは違います。
コールバック¶
You can establish a per-context verify callback function something like this:
以下のようなコンテキスト単位の検証コールバック関数を設定できます:
sub verify {
my ($ok, $x509_store_ctx) = @_;
print "Verifying certificate...\n";
...
return $ok;
}
It is used like this:
これは以下のように使われます:
Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);
Per-context callbacks for decrypting private keys are implemented.
復号化するための秘密鍵のためのコンテキスト単位のコールバックは 実装されています。
Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
Net::SSLeay::FILETYPE_PEM)
or die "Error reading private key";
Net::SSLeay::CTX_set_default_passwd_cb($ctx, undef);
If Hello Extensions are supported by your OpenSSL, a session secret callback can be set up to be called when a session secret is set by openssl.
あなたの OpenSSL が Hello Extensions に対応しているなら、 セッションシークレットコールバックは、 セッションシークレットが openssl によって設定されたときに 呼び出されるように設定できます。
Establish it like this: Net::SSLeay::set_session_secret_cb($ssl, \&session_secret_cb, $somedata);
次のようにしてこれを確立します: Net::SSLeay::set_session_secret_cb($ssl, \&session_secret_cb, $somedata);
It will be called like this:
これは次のようにして呼び出されます:
sub session_secret_cb
{
my ($secret, \@cipherlist, \$preferredcipher, $somedata) = @_;
}
No other callbacks are implemented. You do not need to use any callback for simple (i.e. normal) cases where the SSLeay built-in verify mechanism satisfies your needs.
その他のコールバックは実装されていません。 SSLeay 組み込みの確認機構があなたのニーズを満足させているところでは、 単純な(つまり通常の)ケースでは何もコールバックを使う必要はありません。
It is required to reset these callbacks to undef immediately after use to prevent memory leaks, thread safety problems and crashes on exit that can occur if different threads set different callbacks.
異なるスレッドが異なるコールバックを持つ場合に起きるかもしれない メモリリーク、スレッドセーフ性問題、終了時のクラッシュを防ぐために、 これらのコールバックは使用後直ちに未定義にリセットする必要があります。
If you want to use callback stuff, see examples/callback.pl! Its the only one I am able to make work reliably.
コールバックを使いたければ、examples/callback.pl をご覧ください! それは私が信頼して動かすことができる唯一のものです。
X509 と RAND について¶
This module largely lacks interface to the X509 and RAND routines, but as I was lazy and needed them, the following kludges are implemented:
このモジュールでは X509 と RAND ルーチンへのインターフェースが大きく 欠けていますが、私は怠け者で、それらを必要としていました; 以下のものが実装されています:
$x509_name = Net::SSLeay::X509_get_subject_name($x509_cert);
$x509_name = Net::SSLeay::X509_get_issuer_name($x509_cert);
print Net::SSLeay::X509_NAME_oneline($x509_name);
$text = Net::SSLeay::X509_NAME_get_text_by_NID($name, $nid);
($type1, $subject1, $type2, $subject2, ...) =
Net::SSLeay::X509_get_subjectAltNames($x509_cert)
subjectAltName types as per x509v3.h GEN_*, for example
GEN_DNS or GEN_IPADD which can be imported.
Net::SSLeay::RAND_seed($buf); # Perlishly figures out buf size
Net::SSLeay::RAND_bytes($buf, $num);
Net::SSLeay::RAND_pseudo_bytes($buf, $num);
Net::SSLeay::RAND_add($buf, $num, $entropy);
Net::SSLeay::RAND_poll();
Net::SSLeay::RAND_status();
Net::SSLeay::RAND_cleanup();
Net::SSLeay::RAND_file_name($num);
Net::SSLeay::RAND_load_file($file_name, $how_many_bytes);
Net::SSLeay::RAND_write_file($file_name);
Net::SSLeay::RAND_egd($path);
Net::SSLeay::RAND_egd_bytes($path, $bytes);