stream_socket_client with TLS 1.2

Viewed 307

I'm trying to create a connection between the client and the server (with 2-way TLS).

Client.php

$stream_context = stream_context_create(['ssl' => [
            'local_cert' => "path/to/cer.pem",
            'verify_peer' => true,
            'verify_peer_name' => false,
            'passphrase' => "password to cert",
            'verify_depth' => 0
        ]]);
$socket = stream_socket_client("tlsv1.2://127.0.0.1:8000", $errno, $errstr, 3, STREAM_CLIENT_CONNECT, $stream_context);

if ($socket === false) {
      return false;
 }

$req = "POST /Serwer.php HTTP/1.1\r\n" .
       "Content-Type: text/xml;charset=UTF-8\r\n" .
       "Host: 127.0.0.1\r\n" .
       "Connection: Close\r\n" .
       "Hello world!\r\n";

 $start = time();
 fwrite($socket, $req);
 $resp = '';

 while (!feof($socket)) {
    if (time() - $start > 15) {
        break;
    }

    $f = fgets($socket);
    $resp .= $f;
}

fclose($socket);
echo $resp;

Server.php

$stream_context = stream_context_create(['ssl' => [
    'local_cert' => "path/to/cert.pem",
    'passphrase' => "password to cert",
    'allow_self_signed' => true,
    'verify_peer' => true
]]);

$server = stream_socket_server("tlsv1.2://0.0.0.0:8000",$errno, $error, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $stream_context);

if ($server === false) {
    return false;
}

$connects = array();
while (true) {
    $read = $connects;
    $read []= $server;
    $write = $except = null;

    $mod_fd = stream_select($read, $write, $except, 3); // return always 0, I don't know why
    if ($mod_fd === false) {
        break;
    }

    if (in_array($server, $read)) {
        $connect = stream_socket_accept($server, -1);
        $connects[] = $connect;
        unset($read[ array_search($server, $read) ]);
    }

    foreach($read as $connect) {
        $headers = '';
        while ($buffer = rtrim(fgets($connect))) {
            $headers .= $buffer;
        }
        fwrite($connect, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\nHello!");
        fclose($connect);
        unset($connects[ array_search($connect, $connects) ]);
    }

fclose($server);

In this example server and client are on different machines.

  1. I must to use TLS v 1.2.
  2. Address and port on the client and the server must be the same or different? (For example in server.php I use address 0.0.0.0 and port 8000, but in client.php 127.0.0.1 and port 8000)
  3. How the server and the client must accept the certificates TLS?
  4. How read on server side phrase "Hello world" from client?
0 Answers
Related