Showing posts with label SSL. Show all posts
Showing posts with label SSL. Show all posts

Oct 5, 2020

Verify Client SSL at Server side

Restricting client to hit the server from unknown origins and allow to access server resources after verifying their SSL.

Pre-requisites:

You need to define “Access-Control-Allow-Origin” in your request.

Here we define the client request with “Access-Control-Allow-Origin”

Client side Request:

<?php

// Call server API using cURL

$curl = curl_init(); // Initialize the cURL

// Define cURL options

curl_setopt_array($curl, array(

  CURLOPT_URL => "https://server.com/test-ssl.php",

  CURLOPT_RETURNTRANSFER => true,

  CURLOPT_ENCODING => "",

  CURLOPT_MAXREDIRS => 10,

  CURLOPT_TIMEOUT => 30,

  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

  CURLOPT_CUSTOMREQUEST => "POST",

  CURLOPT_POSTFIELDS => "",

  CURLOPT_SSL_VERIFYHOST => 0,

  CURLOPT_SSL_VERIFYPEER => 0,

  CURLOPT_HTTPHEADER => array('Access-Control-Allow-Origin: https://abc.com'),

));

$response  = curl_exec($curl); // Execute request and get response

echo $response; // Print response

curl_close($curl); // Close cURL

 

At server side you need to get the request headers and verify the SSL using domain name.

Server Side Code:

<?php

$header_info = getallheaders(); //Get all request headers

$url = $header_info['Access-Control-Allow-Origin']; //Get request origin, request domain must be define in origin (https://www.abc.com)

$orignal_parse = parse_url($url, PHP_URL_HOST); //Host URL

$ssl_options = array("capture_peer_cert" => TRUE, "capture_peer_cert_chain" => true, "allow_self_signed"=> false, "CN_match" => $orignal_parse, "verify_peer" => true, "SNI_enabled" => true, "SNI_server_name" => $orignal_parse);

$get = stream_context_create(array("ssl" => $ssl_options)); // Create Stream

$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get); // Connect

$cert = stream_context_get_params($read); //Read response

$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); //Get certificate details

// check if certificate exists

if($certinfo) {

  $fromDate = date('Y-m-d H:i:s', $certinfo['validFrom_time_t']); // Certificate valid from

  $toDate = date('Y-m-d H:i:s', $certinfo['validTo_time_t']); // Certificate expiry

  // If current date is between $fromDate to $toDate then certificate is valid and you can do your process

  // Your process here...

}

Output: