- Php socket transport tls
- SSL context options
- Changelog
- Notes
- See Also
- User Contributed Notes 9 notes
- Saved searches
- Use saved searches to filter your results more quickly
- License
- InitPHP/Socket
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Unable to find the socket transport «tls» — did you forget to enable it when you configured PHP
- Related videos on Youtube
- venu
- Comments
Php socket transport tls
Замечание: Если транспортный протокол не указан, будет использован tcp:// .
- 127.0.0.1
- fe80::1
- www.example.com
- tcp://127.0.0.1
- tcp://fe80::1
- tcp://www.example.com
- udp://www.example.com
- ssl://www.example.com
- sslv2://www.example.com
- sslv3://www.example.com
- tls://www.example.com
Интернет-сокеты требуют указания порта в дополнение к адресу. В случае fsockopen() , порт передаётся вторым параметром и не затрагивает строку адреса. При работе с stream_socket_client() и другими близкими функциями, как и в случае со стандартными URL, порт указывается в конце адреса, отделённый двоеточием.
Замечание: IPv6 численные адреса с указанием порта
Во втором примере выше, в то время как IPv4 и имя хоста не изменились, за исключением добавления номера порта после двоеточия, адрес IPv6 заключён в квадратные скобки: [fe80::1] . Это сделано для того, чтобы отличить двоеточие в адресе от двоеточия при указании порта.
Протоколы ssl:// и tls:// (доступны, только если поддержка openssl включена в PHP) являются расширениями tcp:// , дополняющими его SSL-шифрованием.
ssl:// будет пытаться использовать соединение SSL V2 или SSL V3, в зависимости от возможностей и настроек удалённого хоста. sslv2:// и sslv3:// позволяют явно указать использование SSL V2 или SSL V3.
SSL context options
Peer name to be used. If this value is not set, then the name is guessed based on the hostname used when opening the stream.
Require verification of SSL certificate used.
Defaults to true .
Require verification of peer name.
Defaults to true .
Allow self-signed certificates. Requires verify_peer .
Defaults to false
Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.
If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.
Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers. The private key also may be contained in a separate file specified by local_pk .
Path to local private key file on filesystem in case of separate files for certificate ( local_cert ) and private key.
Passphrase with which your local_cert file was encoded.
Abort if the certificate chain is too deep.
Defaults to no verification.
Sets the list of available ciphers. The format of the string is described in » ciphers(1).
If set to true a peer_certificate context option will be created containing the peer certificate.
If set to true a peer_certificate_chain context option will be created containing the certificate chain.
If set to true server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.
If set, disable TLS compression. This can help mitigate the CRIME attack vector.
peer_fingerprint string | array
Aborts when the remote certificate digest doesn’t match the specified hash.
When a string is used, the length will determine which hashing algorithm is applied, either «md5» (32) or «sha1» (40).
When an array is used, the keys indicate the hashing algorithm name and each corresponding value is the expected digest.
Sets the security level. If not specified the library default security level is used. The security levels are described in » SSL_CTX_get_security_level(3).
Available as of PHP 7.2.0 and OpenSSL 1.1.0.
Changelog
Version | Description |
---|---|
7.2.0 | Added security_level . Requires OpenSSL >= 1.1.0. |
Notes
Note: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps:// .
Note: For SNI (Server Name Indication) to be available, then PHP must be compiled with OpenSSL 0.9.8j or greater. Use the OPENSSL_TLSEXT_SERVER_NAME to determine whether SNI is supported.
See Also
User Contributed Notes 9 notes
There is also a crypto_type context. In older versions this was crypto_method. This is referenced on http://php.net/manual/en/function.stream-socket-enable-crypto.php
Enable SNI (Server Name Indication):
PEM must be contains certificate and private key.
$context = stream_context_create ([
‘ssl’ => [
‘SNI_enabled’ => true ,
‘SNI_server_certs’ => [
‘host1.com’ => ‘/path/host1.com.pem’ ,
‘host2.com’ => ‘/path/host2.com.pem’ ,
],
]]);
?>
I am unable to load a PEM that was generated with the stunnel tools. However, I am able to use PHP calls to generate a working PEM that is recognized both by stunnel and php, as outlined here:
This code fragment is now working for me, and with stunnel verify=4, both sides confirm the fingerprint. Oddly, if «tls://» is set below, then TLSv1 is forced, but using «ssl://» allows TLSv1.2:
$stream_context = stream_context_create([ ‘ssl’ => [
‘local_cert’ => ‘/path/to/key.pem’,
‘peer_fingerprint’ => openssl_x509_fingerprint(file_get_contents(‘/path/to/key.crt’)),
‘verify_peer’ => false,
‘verify_peer_name’ => false,
‘allow_self_signed’ => true,
‘verify_depth’ => 0 ]]);
$fp = stream_socket_client(‘ssl://ssl.server.com:12345’,
$errno, $errstr, 30, STREAM_CLIENT_CONNECT, $stream_context);
fwrite($fp, «foo bar\n»);
while($line = fgets($fp, 8192)) echo $line;
CN_match works contrary to intuitive thinking. I came across this when I was developing SSL server implemented in PHP. I stated (in code):
— do not allow self signed certs (works)
— verify peer certs against CA cert (works)
— verify the client’s CN against CN_match (does not work), like this:
stream_context_set_option($context, ‘ssl’, ‘CN_match’, ‘*.example.org’);
I presumed this would match any client with CN below .example.org domain.
Unfortunately this is NOT the case. The option above does not do that.
What it really does is this:
— it takes client’s CN and compares it to CN_match
— IF CLIENT’s CN CONTAINS AN ASTERISK like *.example.org, then it is matched against CN_match in wildcard matching fashion
Examples to illustrate behaviour:
(CNM = server’s CN_match)
(CCN = client’s CN)
— CNM=host.example.org, CCN=host.example.org —> OK
— CNM=host.example.org, CCN=*.example.org —> OK
— CNM=.example.org, CCN=*.example.org —> OK
— CNM=example.org, CCN=*.example.org —> ERROR
— CNM=*.example.org, CCN=host.example.org —> ERROR
— CNM=*.example.org, CCN=*.example.org —> OK
According to PHP sources I believe that the same applies if you are trying to act as Client and the server contains a wildcard certificate. If you set CN_match to myserver.example.org and server presents itself with *.example.org, the connection is allowed.
Everything above applies to PHP version 5.2.12.
I will supply a patch to support CN_match starting with asterisk.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHP Socket (TCP, TLS, UDP, SSL) Server/Client Library
License
InitPHP/Socket
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Socket (TCP, TLS, UDP, SSL) Server/Client Library
composer require initphp/socket
Supported Types :
\InitPHP\Socket\Socket::class It allows you to easily create socket server or client.
public static function server(int $handler = Socket::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketServerInterface
- $handler : Socket::SSL , Socket::TCP , Socket::TLS or Socket::UDP
- $host : Identifies the socket host. If not defined or left blank, it will throw an error.
- $port : Identifies the socket port. If not defined or left blank, it will throw an error.
- $argument : This value is the value that will be sent as 3 parameters to the constructor method of the handler.
- SSL or TLS = (float) Defines the timeout period.
- UDP or TCP = (string) Defines the protocol family to be used by the socket. «v4», «v6» or «unix»
public static function client(int $handler = self::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketClientInterface
- $handler : Socket::SSL , Socket::TCP , Socket::TLS or Socket::UDP
- $host : Identifies the socket host. If not defined or left blank, it will throw an error.
- $port : Identifies the socket port. If not defined or left blank, it will throw an error.
- $argument : This value is the value that will be sent as 3 parameters to the constructor method of the handler.
- SSL or TLS = (float) Defines the timeout period.
- UDP or TCP = (string) Defines the protocol family to be used by the socket. «v4», «v6» or «unix»
connection() : Initiates the socket connection.
public function connection(): self;
disconnect() : Terminates the connection.
public function disconnect(): bool;
read() : Reads data from socket.
public function read(int $length = 1024): ?string;
write() : Writes data to the socket
public function write(string $string): ?int;
public function live(callable $callback): void;
public function wait(int $second): void;
Special methods for TLS and SSL.
TLS and SSL work similarly.
There are some additional methods you can use from TLS and SSL sockets.
timeout() : Defines the timeout period of the current.
public function timeout(int $second): self;
blocking() : Sets the blocking mode of the current.
public function blocking(bool $mode = true): self;
crypto() : Turns encryption on or off on a connected socket.
public function crypto(?string $method = null): self;
Possible values for $method are;
- «sslv2»
- «sslv3»
- «sslv23»
- «any»
- «tls»
- «tlsv1.0»
- «tlsv1.1»
- «tlsv1.2»
- NULL
option() : Defines connection options for SSL and TLS. see; https://www.php.net/manual/en/context.ssl.php
public function option(string $key, mixed $value): self;
require_once "../vendor/autoload.php"; use \InitPHP\Socket\Socket; use \InitPHP\Socket\Interfaces\SocketServerInterface; $server = Socket::server(Socket::TLS, '127.0.0.1', 8080); $server->connection(); $server->live(function (SocketServerInterface $socket) < switch ($socket->read()) < case 'exit' : $socket->write('Goodbye!'); return; case 'write' : $socket->write('Run write command.'); break; case 'read' : $socket->write('Run read command.'); break; default: return; > >);
require_once "../vendor/autoload.php"; use \InitPHP\Socket\Socket; $client = Socket::client(Socket::SSL, 'smtp.gmail.com', 465); $client->option('verify_peer', false) ->option('verify_peer_name', false); $client->connection(); $client->write('EHLO [127.0.0.1]'); echo $client->read();
In the above example, a simple smtp connection to gmail is made.
Unable to find the socket transport «tls» — did you forget to enable it when you configured PHP
If you’re using WAMP on Windows you can left click on the green W in the notifications pane.
Then goto: PHP -> PHP Extensions -> php_openssl
Once you do that WAMP should auto restart and everything should work.
Related videos on Youtube
venu
Comments
Warning: fsockopen() [function.fsockopen]: unable to connect to tls://smtp.gmail.com:465 (Unable to find the socket transport «tls» — did you forget to enable it when you configured PHP?) in C:\wamp\www\mail\testemail.php on line 24 Unable to find the socket transport «tls» — did you forget to enable it when you configured PHP?