master
ブランチ master
LittleBeast / src / Std / Lib / Tls.php
7 KB、165行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib;
39
40use Std\Lib\Tls\Connection;
41use Std\Lib\Tls\Stream;
42use Std\Lib\Tls\TlsException;
43
44/**
45 * PHP純正のTLS 1.3・1.2(php-opensslが不要、GMPは必要)
46 *
47 * 結果はPHPのストリームなので、fread・fgets・fwrite・feof・fclose・stream_set_timeoutがそのまま使える。
48 *
49 * クライアント:
50 * $s = Tls::connect('example.com', 443, ['alpn' => ['http/1.1']]);
51 * fwrite($s, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
52 * STARTTLS(既に接続しているソケット):
53 * $s = Tls::enable($socket, ['peer_name' => 'smtp.example.com']);
54 * サーバー(テスト等):
55 * $s = Tls::accept($client, ['cert' => $certPem, 'key' => $keyPem]);
56 *
57 * オプション(PHPのsslコンテキストと同じ名前):
58 * peer_name 確認するホスト名(SNIにも使う)
59 * verify_peer 証明書を確認する(既定true)
60 * verify_peer_name ホスト名を確認する(既定true)
61 * allow_self_signed 自己署名の証明書を許す(既定false)
62 * cafile 信頼する証明書のPEMファイル(省略するとTLS_CAFILE、又はシステムの証明書)
63 * SNI_enabled SNIを送る(既定true)
64 * alpn ALPNのプロトコルの配列(例:['http/1.1'])
65 * groups 鍵交換のグループ(既定['x25519', 'P-256', 'P-384']、最初の鍵を最初に送る)
66 * min_version・max_version 使うバージョン('1.2'又は'1.3'、既定は1.2から1.3)
67 * ciphers 暗号スイートの番号の配列(Connection::SUITES・SUITES12のキー、既定は全部)
68 * cert・key サーバーの証明書(チェーン)と秘密鍵(PEM又はファイル、local_cert・local_pkも可)
69 */
70class Tls {
71 /**
72 * TCPで接続してTLSを開始する
73 *
74 * @param string $host ホスト名又はIPアドレス
75 * @param int $port ポート
76 * @param array $opt オプション(peer_nameを省略すると$host)
77 * @param float $timeout 接続と読み込みのタイムアウト(秒)
78 * @return resource ストリーム
79 * @throws TlsException 接続又はハンドシェイクに失敗した場合
80 */
81 public static function connect(string $host, int $port, array $opt = [], float $timeout = 10) {
82 $addr = str_contains($host, ':') && !str_starts_with($host, '[') ? "[{$host}]" : $host;
83 $errno = 0;
84 $errstr = '';
85 $sock = @stream_socket_client("tcp://{$addr}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create());
86 if ($sock === false) throw new TlsException("接続出来ません:{$errstr}({$errno})", Connection::ALERT_INTERNAL_ERROR, true);
87 stream_set_timeout($sock, (int)$timeout, (int)(fmod($timeout, 1) * 1000000));
88 $opt += ['peer_name' => trim($host, '[]')];
89 try {
90 return self::enable($sock, $opt);
91 } catch (\Throwable $e) {
92 @fclose($sock);
93 throw $e;
94 }
95 }
96
97 /**
98 * 既に接続しているソケットでTLSを開始する(クライアント、STARTTLS等)
99 *
100 * @param resource $socket ソケット(返したストリームを閉じると、これも閉じる)
101 * @param array $opt オプション
102 * @return resource ストリーム
103 * @throws TlsException
104 */
105 public static function enable($socket, array $opt = []) {
106 $conn = new Connection($socket, $opt, false);
107 $conn->handshake();
108 return Stream::wrap($conn);
109 }
110
111 /**
112 * 既に接続しているソケットでTLSを開始する(サーバー)
113 *
114 * @param resource $socket 受け付けたソケット
115 * @param array $opt オプション(cert・keyが必要)
116 * @return resource ストリーム
117 * @throws TlsException
118 */
119 public static function accept($socket, array $opt) {
120 $conn = new Connection($socket, $opt, true);
121 $conn->handshake();
122 return Stream::wrap($conn);
123 }
124
125 /**
126 * TLSのストリームの情報
127 *
128 * @param resource $stream
129 * @return array|null version、cipher、group、alpn、peer_certificates、server_name、TLSでなければnull
130 */
131 public static function info($stream): ?array {
132 return Stream::connection($stream)?->info();
133 }
134
135 /**
136 * 読み込み中のエラー(feof()がtrueになった理由)
137 *
138 * @param resource $stream
139 * @return TlsException|null
140 */
141 public static function error($stream): ?TlsException {
142 return Stream::connection($stream)?->lastError();
143 }
144
145 /**
146 * 読んでいないデータが残っているかどうか(stream_select()を使うサーバー用:TLSの中に溜まったデータは見えない)
147 *
148 * @param resource $stream
149 * @return bool
150 */
151 public static function pending($stream): bool {
152 if (!is_resource($stream)) return false;
153 return (stream_get_meta_data($stream)['unread_bytes'] ?? 0) > 0 || (bool)Stream::connection($stream)?->pending();
154 }
155
156 /**
157 * 最後の読み込みがタイムアウトしたかどうか
158 *
159 * @param resource $stream
160 * @return bool
161 */
162 public static function timedOut($stream): bool {
163 return (bool)Stream::connection($stream)?->timedOut();
164 }
165}