function cert_serial($raw_cert_data)
{
    $cert_data = openssl_x509_parse($raw_cert_data);
    if (isset($cert_data['serialNumber'])) {
        $serial = [];
        $sn = str_split(strtoupper(bcdechex($cert_data['serialNumber'])), 2);
        $sn_len = count($sn);
        foreach ($sn as $key => $s) {
            $serial[] = htmlspecialchars($s);
            if ($key != $sn_len - 1) {
                $serial[] = ":";
            }
        }
        $result = implode("", $serial);
        return $result;
    }
}
     } else {
         $fixed_diff = floatval($hash_rate * $CheckShareData * 4);
     }
     $fixed_diff = $fixed_diff * $miner_diff;
     $fixed_diff = new Math_BigInteger($fixed_diff);
     $current .= "\nFixed diff value:" . $fixed_diff;
 } else {
     die('You need to specify your hashrate!');
 }
 $a256 = new Math_BigInteger('115792089237316195423570985008687907853269984665640564039457584007913129639936');
 //2^256
 //Convert diff decimal to hex 256bit
 $new_block_diff = new Math_BigInteger($fixed_diff);
 list($quotient, $remainder) = $a256->divide($new_block_diff);
 $target_diff = $quotient->toString();
 $target_diff = bcdechex($target_diff);
 $currentLenght = strlen($target_diff);
 $desiredLenght = 64;
 if ($currentLenght < $desiredLenght) {
     $toadd = $desiredLenght - $currentLenght;
     for ($i = 0; $i < $toadd; $i++) {
         $fix .= '0';
     }
     $target_diff = '0x' . $fix . $target_diff;
 }
 //Save Getwork for user to validate later with submit work
 $appKey = md5($hash_rate . $payout_addr);
 $current .= "\nAPPKEY:" . $appKey;
 $block_number = hexdec($block_number) + 1;
 $dataWrite = array($payout_addr, $target_diff, $fixed_diff, $last_block_diff, $targetBlockResult[0], $targetBlockResult[2], $block_number, $targetBlockResult[1]);
 //$m->set($appKey,$dataWrite,120);
while ($row = mysqli_fetch_row($existResult)) {
    $payer_adr = $row[0];
    echo "\n-------------------------------------------";
    echo "\n" . $payer_adr;
    echo "\nBalance: " . sprintf('%f', $row[1]) . " wei";
    echo "\nBalance: " . sprintf('%f', $row[1] / $ether_wei) . " ether";
    $current .= "\n-------------------------------------------";
    $current .= "\n" . $payer_adr;
    $current .= "\nBalance: " . sprintf('%f', $row[1]) . " wei";
    $current .= "\nBalance: " . sprintf('%f', $row[1] / $ether_wei) . " ether";
    if ($row[1] / $ether_wei >= 0.5) {
        $escapeDot = explode('.', sprintf('%f', $row[1]));
        $balancetopay = new Math_BigInteger($escapeDot[0]);
        $free2pay = new Math_BigInteger($gasprice);
        $resultPayment = $balancetopay->subtract($free2pay);
        $validBigHex = bcdechex($resultPayment->toString());
        echo "HexReverse:\n\n" . sprintf('%f', hexdec($validBigHex));
        $current .= "HexReverse:\n\n" . sprintf('%f', hexdec($validBigHex));
        $sendValue = '0x' . $validBigHex;
        $transactionState = 0;
        $transaction = array("from" => $coinbase, "to" => $payer_adr, "value" => $sendValue);
        $data = array("jsonrpc" => "2.0", "method" => "eth_sendTransaction", "params" => [$transaction], "id" => 1);
        $data_string = json_encode($data);
        $ch1 = curl_init('http://127.0.0.1:8983');
        curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
        $result3 = curl_exec($ch1);
        $block_info_last = json_decode($result3, true);
        $txid = $block_info_last['result'];
Exemple #4
0
function crl_verify_json($raw_cert_data)
{
    global $random_blurp, $timeout;
    $result = [];
    $cert_data = openssl_x509_parse($raw_cert_data);
    $cert_serial_nm = strtoupper(bcdechex($cert_data['serialNumber']));
    $crl_uris = [];
    $crl_uri = explode("\nFull Name:\n ", $cert_data['extensions']['crlDistributionPoints']);
    foreach ($crl_uri as $key => $uri) {
        if (isset($uri)) {
            $uri = explode("URI:", $uri);
            $uri = $uri[1];
            if (isset($uri)) {
                $crl_uris[] = preg_replace('/\\s+/', '', $uri);
            }
        }
    }
    foreach ($crl_uris as $key => $uri) {
        $crl_no = $key + 1;
        if (0 === strpos($uri, 'http')) {
            $result[$crl_no]["crl_uri"] = $uri;
            $fp = fopen("/tmp/" . $random_blurp . "." . $key . ".crl", 'w+');
            $ch = curl_init($uri);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_FAILONERROR, true);
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if (curl_exec($ch) === false) {
                $result[$crl_no]["error"] = 'Curl error: ' . htmlspecialchars(curl_error($ch));
            }
            curl_close($ch);
            if (stat("/tmp/" . $random_blurp . "." . escapeshellcmd($key) . ".crl")['size'] < 10) {
                $result[$crl_no]["error"] = "crl could not be retreived";
            }
            $crl_text = shell_exec("openssl crl -noout -text -inform der -in /tmp/" . $random_blurp . "." . escapeshellcmd($key) . ".crl 2>&1");
            $crl_last_update = shell_exec("openssl crl -noout -lastupdate -inform der -in /tmp/" . $random_blurp . "." . escapeshellcmd($key) . ".crl");
            $crl_last_update = explode("=", $crl_last_update)[1];
            $crl_next_update = shell_exec("openssl crl -noout -nextupdate -inform der -in /tmp/" . $random_blurp . "." . escapeshellcmd($key) . ".crl");
            $crl_next_update = explode("=", $crl_next_update)[1];
            unlink("/tmp/" . $random_blurp . "." . escapeshellcmd($key) . ".crl");
            if (strpos($crl_text, "unable to load CRL") === 0) {
                $result[$crl_no]["status"] = "invalid";
            }
            $crl_info = explode("Revoked Certificates:", $crl_text)[0];
            $crl_certificates = explode("Revoked Certificates:", $crl_text)[1];
            $crl_certificates = explode("Serial Number:", $crl_certificates);
            $revcert = array();
            foreach ($crl_certificates as $key => $revoked_certificate) {
                if (!empty($revoked_certificate)) {
                    $revcert[str_replace(" ", "", explode("\n", $revoked_certificate)[0])] = str_replace("        Revocation Date: ", "", explode("\n", $revoked_certificate)[1]);
                }
            }
            if (array_key_exists($cert_serial_nm, $revcert)) {
                $result[$crl_no]["status"] = "revoked";
                $result[$crl_no]["revoked_on"] = $revcert[$cert_serial_nm];
                $result[$crl_no]["crl_last_update"] = $crl_last_update;
                $result[$crl_no]["crl_next_update"] = $crl_next_update;
            } else {
                $result[$crl_no]["status"] = "ok";
                $result[$crl_no]["crl_last_update"] = $crl_last_update;
                $result[$crl_no]["crl_next_update"] = $crl_next_update;
            }
        }
    }
    return $result;
}
Exemple #5
0
function bcdechex($dec)
{
    $last = bcmod($dec, 16);
    $remain = bcdiv(bcsub($dec, $last), 16);
    if ($remain == 0) {
        return dechex($last);
    } else {
        return bcdechex($remain) . dechex($last);
    }
}
function cert_parse_json($raw_cert_data, $raw_next_cert_data = null, $host = null, $validate_hostname = false)
{
    global $random_blurp;
    global $ev_oids;
    $result = array();
    $cert_data = openssl_x509_parse($raw_cert_data);
    if (isset($raw_next_cert_data)) {
        $next_cert_data = openssl_x509_parse($raw_next_cert_data);
    }
    $today = date("Y-m-d");
    //cert
    if (isset($cert_data)) {
        // purposes
        $purposes = array();
        foreach ($cert_data['purposes'] as $key => $purpose) {
            $purposes[$purpose[2]]["ca"] = $purpose[1];
            $purposes[$purpose[2]]["general"] = $purpose[0];
        }
        unset($cert_data['purposes']);
        $cert_data['purposes'] = $purposes;
        $result["cert_data"] = $cert_data;
    }
    // valid from
    if (!empty($result['cert_data']['validFrom_time_t'])) {
        if ($today < date(DATE_RFC2822, $result['cert_data']['validFrom_time_t'])) {
            $result['cert_issued_in_future'] = false;
        } else {
            $result['cert_issued_in_future'] = true;
            $result['warning'][] = "Certificate issue date is in the future: " . date(DATE_RFC2822, $data['cert_data']['validFrom_time_t']);
        }
    }
    // expired
    if (!empty($cert_data['validTo_time_t'])) {
        if ($today > date(DATE_RFC2822, $cert_data['validFrom_time_t']) || strtotime($today) < strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']))) {
            $result['cert_expired'] = false;
        } else {
            $result['cert_expired'] = true;
            $result['warning'][] = "Certificate expired! Expiration date: " . date(DATE_RFC2822, $cert_data['validTo_time_t']);
        }
    }
    // almost expired
    if (!empty($cert_data['validTo_time_t'])) {
        $certExpiryDate = strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']));
        $certExpiryDiff = $certExpiryDate - strtotime($today);
        if ($certExpiryDiff < 2592000) {
            $result['cert_expires_in_less_than_thirty_days'] = true;
            $result['warning'][] = "Certificate expires in " . round($certExpiryDiff / 84600) . " days!. Expiration date: " . date(DATE_RFC2822, $certExpiryDate);
        } else {
            $result['cert_expires_in_less_than_thirty_days'] = false;
        }
    }
    if (array_search(explode("Policy: ", explode("\n", $cert_data['extensions']['certificatePolicies'])[0])[1], $ev_oids)) {
        $result["validation_type"] = "extended";
    } else {
        if (isset($cert_data['subject']['O'])) {
            $result["validation_type"] = "organization";
        } else {
            if (isset($cert_data['subject']['CN'])) {
                $result["validation_type"] = "domain";
            }
        }
    }
    // issuer
    if ($raw_next_cert_data) {
        if (verify_cert_issuer_by_subject_hash($raw_cert_data, $raw_next_cert_data)) {
            $result["issuer_valid"] = true;
        } else {
            $result["issuer_valid"] = false;
            $result['warning'][] = "Provided certificate issuer does not match issuer in certificate. Sent chain order wrong.";
        }
    }
    // crl
    if (isset($cert_data['extensions']['crlDistributionPoints'])) {
        $result["crl"] = crl_verify_json($raw_cert_data);
        if (is_array($result["crl"])) {
            foreach ($result["crl"] as $key => $value) {
                if ($value["status"] == "revoked") {
                    $result['warning'][] = "Certificate revoked on CRL: " . $value['crl_uri'] . ". Revocation time: " . $value['revoked_on'] . ".";
                }
            }
        }
    } else {
        $result["crl"] = "No CRL URI found in certificate";
    }
    // ocsp
    if (isset($cert_data['extensions']['authorityInfoAccess'])) {
        $ocsp_uris = explode("OCSP - URI:", $cert_data['extensions']['authorityInfoAccess']);
        unset($ocsp_uris[0]);
        if (isset($ocsp_uris)) {
            if (isset($raw_next_cert_data)) {
                foreach ($ocsp_uris as $key => $ocsp_uri) {
                    $ocsp_uri = explode("\n", $ocsp_uri)[0];
                    $ocsp_uri = explode(" ", $ocsp_uri)[0];
                    $result["ocsp"]["{$key}"] = ocsp_verify_json($raw_cert_data, $raw_next_cert_data, $ocsp_uri);
                    if ($result['ocsp'][$key]["status"] == "revoked") {
                        $result['warning'][] = "Certificate revoked on OCSP: " . $result['ocsp'][$key]['ocsp_uri'] . ". Revocation time: " . $result['ocsp'][$key]['revocation_time'] . ".";
                    } elseif ($result['ocsp'][$key]["status"] == "unknown") {
                        $result['warning'][] = "OCSP error on: " . $result['ocsp'][$key]['ocsp_uri'] . ".";
                    }
                }
            } else {
                $result["ocsp"] = "No issuer cert provided. Unable to send OCSP request.";
            }
        } else {
            $result["ocsp"] = "No OCSP URI found in certificate";
        }
    } else {
        $result["ocsp"] = "No OCSP URI found in certificate";
    }
    // hostname validation
    if ($validate_hostname == true) {
        $result["hostname_checked"] = $host;
        if (isset($cert_data['subject']['CN'])) {
            if (verify_certificate_hostname($raw_cert_data, $host)) {
                $result["hostname_in_san_or_cn"] = "true";
            } else {
                $result["hostname_in_san_or_cn"] = "false";
                $result['warning'][] = "Hostname " . $host . " not found in certificate.";
            }
        }
    } else {
        $result["hostname_in_san_or_cn"] = "n/a; ca signing certificate";
    }
    //serial number
    if (isset($cert_data['serialNumber'])) {
        $serial = [];
        $sn = str_split(strtoupper(bcdechex($cert_data['serialNumber'])), 2);
        $sn_len = count($sn);
        foreach ($sn as $key => $s) {
            $serial[] = htmlspecialchars($s);
            if ($key != $sn_len - 1) {
                $serial[] = ":";
            }
        }
        $result["serialNumber"] = implode("", $serial);
    }
    // key details
    $key_details = openssl_pkey_get_details(openssl_pkey_get_public($raw_cert_data));
    $export_pem = "";
    openssl_x509_export($raw_cert_data, $export_pem);
    if (isset($key_details['rsa'])) {
        $result["key"]["type"] = "rsa";
        $result["key"]["bits"] = $key_details['bits'];
        if ($key_details['bits'] < 2048) {
            $result['warning'][] = $key_details['bits'] . " bit RSA key is not safe. Upgrade to at least 4096 bits.";
        }
    } else {
        if (isset($key_details['dsa'])) {
            $result["key"]["type"] = "dsa";
            $result["key"]["bits"] = $key_details['bits'];
        } else {
            if (isset($key_details['dh'])) {
                $result["key"]["type"] = "dh";
                $result["key"]["bits"] = $key_details['bits'];
            } else {
                if (isset($key_details['ec'])) {
                    $result["key"]["type"] = "ecdsa";
                    $result["key"]["bits"] = $key_details['bits'];
                } else {
                    $result["key"]["type"] = "unknown";
                    $result["key"]["bits"] = $key_details['bits'];
                }
            }
        }
    }
    // signature algorithm
    $result["key"]["signature_algorithm"] = cert_signature_algorithm($raw_cert_data);
    if ($result["key"]["signature_algorithm"] == "sha1WithRSAEncryption") {
        $result['warning'][] = "SHA-1 certificate. Upgrade (re-issue) to SHA-256 or better.";
    }
    if (isset($export_pem)) {
        $result["key"]["certificate_pem"] = $export_pem;
    }
    if (isset($key_details['key'])) {
        $result["key"]["public_key_pem"] = $key_details['key'];
        $result["key"]["spki_hash"] = spki_hash($export_pem);
    }
    return $result;
}
Exemple #7
0
function rsa_decrypt($input)
{
    global $private_key;
    $check = bchexdec($input);
    $modulus = bin2int($private_key["modulus"]);
    $exponent = bchexdec("010001");
    $result = bcpowmod($check, $exponent, $modulus);
    $rb = bcdechex($result);
    return strtoupper(padstr($rb));
}
function cert_parse_json($raw_cert_data, $raw_next_cert_data = null, $host = null, $validate_hostname = false)
{
    global $random_blurp;
    global $ev_oids;
    $result = array();
    $cert_data = openssl_x509_parse($raw_cert_data);
    if (isset($raw_next_cert_data)) {
        $next_cert_data = openssl_x509_parse($raw_next_cert_data);
    }
    $today = date("Y-m-d");
    //cert
    if (isset($cert_data)) {
        // purposes
        $purposes = array();
        foreach ($cert_data['purposes'] as $key => $purpose) {
            $purposes[$purpose[2]]["ca"] = $purpose[1];
            $purposes[$purpose[2]]["general"] = $purpose[0];
        }
        unset($cert_data['purposes']);
        $cert_data['purposes'] = $purposes;
        $result["cert_data"] = $cert_data;
    }
    // valid from
    if (!empty($result['cert_data']['validFrom_time_t'])) {
        if ($today < date(DATE_RFC2822, $result['cert_data']['validFrom_time_t'])) {
            $result['cert_issued_in_future'] = false;
        } else {
            $result['cert_issued_in_future'] = true;
            $result['warning'][] = "Certificate issue date is in the future: " . date(DATE_RFC2822, $data['cert_data']['validFrom_time_t']);
        }
    }
    // expired
    if (!empty($cert_data['validTo_time_t'])) {
        if ($today > date(DATE_RFC2822, $cert_data['validFrom_time_t']) || strtotime($today) < strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']))) {
            $result['cert_expired'] = false;
        } else {
            $result['cert_expired'] = true;
            $result['warning'][] = "Certificate expired! Expiration date: " . date(DATE_RFC2822, $cert_data['validTo_time_t']);
        }
    }
    // almost expired
    if (!empty($cert_data['validTo_time_t'])) {
        $certExpiryDate = strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']));
        $certExpiryDiff = $certExpiryDate - strtotime($today);
        if ($certExpiryDiff < 2592000) {
            $result['cert_expires_in_less_than_thirty_days'] = true;
            $result['warning'][] = "Certificate expires in " . round($certExpiryDiff / 84600) . " days!. Expiration date: " . date(DATE_RFC2822, $certExpiryDate);
        } else {
            $result['cert_expires_in_less_than_thirty_days'] = false;
        }
    }
    if (array_search(explode("Policy: ", explode("\n", $cert_data['extensions']['certificatePolicies'])[0])[1], $ev_oids)) {
        $result["validation_type"] = "extended";
    } else {
        if (isset($cert_data['subject']['O'])) {
            $result["validation_type"] = "organization";
        } else {
            if (isset($cert_data['subject']['CN'])) {
                $result["validation_type"] = "domain";
            }
        }
    }
    // issuer
    if ($raw_next_cert_data) {
        if (verify_cert_issuer_by_subject_hash($raw_cert_data, $raw_next_cert_data)) {
            $result["issuer_valid"] = true;
        } else {
            $result["issuer_valid"] = false;
            $result['warning'][] = "Provided certificate issuer does not match issuer in certificate. Sent chain order wrong.";
        }
    }
    // crl
    if (isset($cert_data['extensions']['crlDistributionPoints'])) {
        $result["crl"] = crl_verify_json($raw_cert_data);
        if (is_array($result["crl"])) {
            foreach ($result["crl"] as $key => $value) {
                if ($value["status"] == "revoked") {
                    $result['warning'][] = "Certificate revoked on CRL: " . $value['crl_uri'] . ". Revocation time: " . $value['revoked_on'] . ".";
                }
            }
        }
    } else {
        $result["crl"] = "No CRL URI found in certificate";
    }
    // ocsp
    if (isset($cert_data['extensions']['authorityInfoAccess'])) {
        $ocsp_uris = explode("OCSP - URI:", $cert_data['extensions']['authorityInfoAccess']);
        unset($ocsp_uris[0]);
        if (isset($ocsp_uris)) {
            if (isset($raw_next_cert_data)) {
                foreach ($ocsp_uris as $key => $ocsp_uri) {
                    $ocsp_uri = explode("\n", $ocsp_uri)[0];
                    $ocsp_uri = explode(" ", $ocsp_uri)[0];
                    $result["ocsp"]["{$key}"] = ocsp_verify_json($raw_cert_data, $raw_next_cert_data, $ocsp_uri);
                    if ($result['ocsp'][$key]["status"] == "revoked") {
                        $result['warning'][] = "Certificate revoked on OCSP: " . $result['ocsp'][$key]['ocsp_uri'] . ". Revocation time: " . $result['ocsp'][$key]['revocation_time'] . ".";
                    } elseif ($result['ocsp'][$key]["status"] == "unknown") {
                        $result['warning'][] = "OCSP error on: " . $result['ocsp'][$key]['ocsp_uri'] . ".";
                    }
                }
            } else {
                $result["ocsp"] = "No issuer cert provided. Unable to send OCSP request.";
            }
        } else {
            $result["ocsp"] = "No OCSP URI found in certificate";
        }
    } else {
        $result["ocsp"] = "No OCSP URI found in certificate";
    }
    // hostname validation
    if ($validate_hostname == true) {
        $result["hostname_checked"] = $host;
        if (isset($cert_data['subject']['CN'])) {
            if (verify_certificate_hostname($raw_cert_data, $host)) {
                $result["hostname_in_san_or_cn"] = "true";
            } else {
                $result["hostname_in_san_or_cn"] = "false";
                $result['warning'][] = "Hostname " . $host . " not found in certificate.";
            }
        }
    } else {
        $result["hostname_in_san_or_cn"] = "n/a; ca signing certificate";
    }
    //serial number
    if (isset($cert_data['serialNumber'])) {
        $serial = [];
        $sn = str_split(strtoupper(bcdechex($cert_data['serialNumber'])), 2);
        $sn_len = count($sn);
        foreach ($sn as $key => $s) {
            $serial[] = htmlspecialchars($s);
            if ($key != $sn_len - 1) {
                $serial[] = ":";
            }
        }
        $result["serialNumber"] = implode("", $serial);
    }
    // key details
    $key_details = openssl_pkey_get_details(openssl_pkey_get_public($raw_cert_data));
    $export_pem = "";
    openssl_x509_export($raw_cert_data, $export_pem);
    if (isset($key_details['rsa'])) {
        $result["key"]["type"] = "rsa";
        $result["key"]["bits"] = $key_details['bits'];
        if ($key_details['bits'] < 2048) {
            $result['warning'][] = $key_details['bits'] . " bit RSA key is not safe. Upgrade to at least 4096 bits.";
        }
        // weak debian key check
        $bin_modulus = $key_details['rsa']['n'];
        # blacklist format requires sha1sum of output from "openssl x509 -noout -modulus" including the Modulus= and newline.
        # create the blacklist:
        # https://packages.debian.org/source/squeeze/openssl-blacklist
        # svn co svn://svn.debian.org/pkg-openssl/openssl-blacklist/
        # find openssl-blacklist/trunk/blacklists/ -iname "*.db" -exec cat {} >> unsorted_blacklist.db \;
        # sort -u unsorted_blacklist.db > debian_blacklist.db
        $mod_sha1sum = sha1("Modulus=" . strtoupper(bin2hex($bin_modulus)) . "\n");
        #pre_dump($mod_sha1sum);
        $blacklist_file = fopen('inc/debian_blacklist.db', 'r');
        $key_in_blacklist = false;
        while (($buffer = fgets($blacklist_file)) !== false) {
            if (strpos($buffer, $mod_sha1sum) !== false) {
                $key_in_blacklist = true;
                break;
            }
        }
        fclose($blacklist_file);
        if ($key_in_blacklist == true) {
            $result["key"]["weak_debian_rsa_key"] = "true";
            $result['warning'][] = "Weak Debian key found. Remove this key right now and create a new one.";
        }
    } else {
        if (isset($key_details['dsa'])) {
            $result["key"]["type"] = "dsa";
            $result["key"]["bits"] = $key_details['bits'];
        } else {
            if (isset($key_details['dh'])) {
                $result["key"]["type"] = "dh";
                $result["key"]["bits"] = $key_details['bits'];
            } else {
                if (isset($key_details['ec'])) {
                    $result["key"]["type"] = "ecdsa";
                    $result["key"]["bits"] = $key_details['bits'];
                } else {
                    $result["key"]["type"] = "unknown";
                    $result["key"]["bits"] = $key_details['bits'];
                }
            }
        }
    }
    // signature algorithm
    $result["key"]["signature_algorithm"] = cert_signature_algorithm($raw_cert_data);
    if ($result["key"]["signature_algorithm"] == "sha1WithRSAEncryption") {
        $result['warning'][] = "SHA-1 certificate. Upgrade (re-issue) to SHA-256 or better.";
    }
    if (isset($export_pem)) {
        $result["key"]["certificate_pem"] = $export_pem;
    }
    if (isset($key_details['key'])) {
        $result["key"]["public_key_pem"] = $key_details['key'];
        $result["key"]["spki_hash"] = spki_hash($export_pem);
    }
    return $result;
}
Exemple #9
0
function bcashex($operation, $x, $y)
{
    $x = bchexdec($x);
    $y = bchexdec($y);
    return bcdechex($operation($x, $y));
}
/**
 * Get the hash code of the specified SSL certificate
 * @param string $cert String containing the certificate data.
 * @param boolean $pkcs12 Set this variable to true if the certificate is in PKCS12 format.
 * @return array containing the hash code and the validity end date in unix epoch.
 * @author Nicola Asuni
 * @since 2013-07-01
 */
function F_getSSLCertificateHash($cert, $pkcs12 = false)
{
    if ($pkcs12) {
        $certs = array();
        openssl_pkcs12_read($cert, $certs, '');
        $cert = $certs['cert'];
    }
    $ssldata = openssl_x509_parse($cert);
    $sslhash = '';
    $sslhash .= isset($ssldata['serialNumber']) ? bcdechex($ssldata['serialNumber']) : '';
    $sslhash .= isset($ssldata['issuer']['C']) ? $ssldata['issuer']['C'] : '';
    $sslhash .= isset($ssldata['issuer']['ST']) ? $ssldata['issuer']['ST'] : '';
    $sslhash .= isset($ssldata['issuer']['O']) ? $ssldata['issuer']['O'] : '';
    $sslhash .= isset($ssldata['issuer']['OU']) ? $ssldata['issuer']['OU'] : '';
    $sslhash .= isset($ssldata['issuer']['CN']) ? $ssldata['issuer']['CN'] : '';
    $sslhash .= isset($ssldata['issuer']['emailAddress']) ? $ssldata['issuer']['emailAddress'] : '';
    $sslhash .= isset($ssldata['subject']['C']) ? $ssldata['subject']['C'] : '';
    $sslhash .= isset($ssldata['subject']['ST']) ? $ssldata['subject']['ST'] : '';
    $sslhash .= isset($ssldata['subject']['O']) ? $ssldata['subject']['O'] : '';
    $sslhash .= isset($ssldata['subject']['OU']) ? $ssldata['subject']['OU'] : '';
    $sslhash .= isset($ssldata['subject']['CN']) ? $ssldata['subject']['CN'] : '';
    $sslhash .= isset($ssldata['subject']['emailAddress']) ? $ssldata['subject']['emailAddress'] : '';
    if (isset($ssldata['validTo_time_t'])) {
        $endtime = $ssldata['validTo_time_t'];
    } else {
        $endtime = time();
    }
    $sslhash .= $endtime;
    return array(md5($sslhash), date(K_TIMESTAMP_FORMAT, $endtime));
}
        return strrev($hex);
    }
    for ($i = 0; $isset($hex[$i]); $i++) {
        $hex[$i] = dechex(15 - hexdec($hex[$i]));
    }
    for ($i = 0; isset($hex[$i]) && $hex[$i] == 'f'; $i++) {
        $hex[$i] = '0';
    }
    if (isset($hex[$i])) {
        $hex[$i] = dechex(hexdec($hex[$i]) + 1);
    }
    return strrev($hex);
}
function uint256_from_compact($c)
{
    $nbytes = $c >> 24 & 0xff;
    return bcmul($c & 0xffffff, bcpow(2, 8 * ($nbytes - 3)));
}
unset($data);
while (!isset($data) || $data == "") {
    $data = file("blockdata", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    sleep(0.1);
}
array_pop($data);
$last = array_pop($data);
strtok($last, " ");
strtok(" ");
strtok(" ");
$data = strtok(" ");
echo "0x" . bcdechex(uint256_from_compact($data));
Exemple #12
0
 function hash2location($hash)
 {
     $value = bchexdec($hash);
     $bits128 = $this->bits128;
     $location = bcxor(bcrightshift($value, 128), bcand($value, $bits128));
     return $this->leftPadHex(bcdechex($location), 32);
 }
function cert_parse_json($raw_cert_data, $raw_next_cert_data = null, $host = null, $validate_hostname = false, $port = "443", $include_chain = null)
{
    global $random_blurp;
    global $ev_oids;
    global $timeout;
    $result = array();
    $cert_data = openssl_x509_parse($raw_cert_data);
    if (isset($raw_next_cert_data)) {
        $next_cert_data = openssl_x509_parse($raw_next_cert_data);
    }
    $today = date("Y-m-d");
    //cert
    if (isset($cert_data)) {
        // purposes
        $purposes = array();
        foreach ($cert_data['purposes'] as $key => $purpose) {
            $purposes[$purpose[2]]["ca"] = $purpose[1];
            $purposes[$purpose[2]]["general"] = $purpose[0];
        }
        unset($cert_data['purposes']);
        $cert_data['purposes'] = $purposes;
        $result["cert_data"] = $cert_data;
    }
    // valid from
    if (!empty($result['cert_data']['validFrom_time_t'])) {
        if ($today < date(DATE_RFC2822, $result['cert_data']['validFrom_time_t'])) {
            $result['cert_issued_in_future'] = false;
        } else {
            $result['cert_issued_in_future'] = true;
            $result['warning'][] = "Certificate issue date is in the future: " . date(DATE_RFC2822, $data['cert_data']['validFrom_time_t']);
        }
    }
    // expired
    if (!empty($cert_data['validTo_time_t'])) {
        if ($today > date(DATE_RFC2822, $cert_data['validFrom_time_t']) || strtotime($today) < strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']))) {
            $result['cert_expired'] = false;
        } else {
            $result['cert_expired'] = true;
            $result['warning'][] = "Certificate expired! Expiration date: " . date(DATE_RFC2822, $cert_data['validTo_time_t']);
        }
    }
    // almost expired
    if (!empty($cert_data['validTo_time_t'])) {
        $certExpiryDate = strtotime(date(DATE_RFC2822, $cert_data['validTo_time_t']));
        $certExpiryDiff = $certExpiryDate - strtotime($today);
        if ($certExpiryDiff < 2592000) {
            $result['cert_expires_in_less_than_thirty_days'] = true;
            $result['warning'][] = "Certificate expires in " . round($certExpiryDiff / 84600) . " days!. Expiration date: " . date(DATE_RFC2822, $certExpiryDate);
        } else {
            $result['cert_expires_in_less_than_thirty_days'] = false;
        }
    }
    if (array_search(explode("Policy: ", explode("\n", $cert_data['extensions']['certificatePolicies'])[0])[1], $ev_oids)) {
        $result["validation_type"] = "extended";
    } else {
        if (isset($cert_data['subject']['O'])) {
            $result["validation_type"] = "organization";
        } else {
            if (isset($cert_data['subject']['CN'])) {
                $result["validation_type"] = "domain";
            }
        }
    }
    // issuer
    if ($raw_next_cert_data) {
        if (verify_cert_issuer_by_subject_hash($raw_cert_data, $raw_next_cert_data)) {
            $result["issuer_valid"] = true;
        } else {
            $result["issuer_valid"] = false;
            $result['warning'][] = "Provided certificate issuer does not match issuer in certificate. Sent chain order wrong.";
        }
    }
    // crl
    if (isset($cert_data['extensions']['crlDistributionPoints'])) {
        $result["crl"] = crl_verify_json($raw_cert_data);
        if (is_array($result["crl"])) {
            foreach ($result["crl"] as $key => $value) {
                if ($value["status"] == "revoked") {
                    $result['warning'][] = "Certificate revoked on CRL: " . $value['crl_uri'] . ". Revocation time: " . $value['revoked_on'] . ".";
                }
            }
        }
    } else {
        $result["crl"] = "No CRL URI found in certificate";
    }
    // ocsp
    if (isset($cert_data['extensions']['authorityInfoAccess'])) {
        $ocsp_uris = explode("OCSP - URI:", $cert_data['extensions']['authorityInfoAccess']);
        unset($ocsp_uris[0]);
        if (isset($ocsp_uris)) {
            if (isset($raw_next_cert_data)) {
                foreach ($ocsp_uris as $key => $ocsp_uri) {
                    $ocsp_uri = explode("\n", $ocsp_uri)[0];
                    $ocsp_uri = explode(" ", $ocsp_uri)[0];
                    $result["ocsp"]["{$key}"] = ocsp_verify_json($raw_cert_data, $raw_next_cert_data, $ocsp_uri);
                    if ($result['ocsp'][$key]["status"] == "revoked") {
                        $result['warning'][] = "Certificate revoked on OCSP: " . $result['ocsp'][$key]['ocsp_uri'] . ". Revocation time: " . $result['ocsp'][$key]['revocation_time'] . ".";
                    } elseif ($result['ocsp'][$key]["status"] == "unknown") {
                        $result['warning'][] = "OCSP error on: " . $result['ocsp'][$key]['ocsp_uri'] . ".";
                    }
                }
            } else {
                $result["ocsp"] = "No issuer cert provided. Unable to send OCSP request.";
            }
        } else {
            $result["ocsp"] = "No OCSP URI found in certificate";
        }
    } else {
        $result["ocsp"] = "No OCSP URI found in certificate";
    }
    // hostname validation
    if ($validate_hostname == true) {
        $result["hostname_checked"] = $host;
        if (isset($cert_data['subject']['CN'])) {
            if (verify_certificate_hostname($raw_cert_data, $host)) {
                $result["hostname_in_san_or_cn"] = "true";
            } else {
                $result["hostname_in_san_or_cn"] = "false";
                $result['warning'][] = "Hostname " . $host . " not found in certificate.";
            }
        }
    } else {
        $result["hostname_in_san_or_cn"] = "n/a; ca signing certificate";
    }
    //serial number
    if (isset($cert_data['serialNumber'])) {
        $serial = [];
        $sn = str_split(strtoupper(bcdechex($cert_data['serialNumber'])), 2);
        $sn_len = count($sn);
        foreach ($sn as $key => $s) {
            $serial[] = htmlspecialchars($s);
            if ($key != $sn_len - 1) {
                $serial[] = ":";
            }
        }
        $result["serialNumber"] = implode("", $serial);
    }
    // key details
    $key_details = openssl_pkey_get_details(openssl_pkey_get_public($raw_cert_data));
    $export_pem = "";
    openssl_x509_export($raw_cert_data, $export_pem);
    // save pem. this because the reconstruct chain function works better
    // this way. not all certs have authorityinfoaccess. We first check if
    // we already have a matching cert.
    if (!is_dir('crt_hash')) {
        mkdir('crt_hash');
    }
    // filenames of saved certs are hashes of the asort full subject.
    $sort_subject = $cert_data['subject'];
    asort($sort_subject);
    foreach ($sort_subject as $key => $value) {
        $name_full = "/" . $key . "=" . $value . $name_full;
    }
    $crt_hash = hash("sha256", $name_full);
    $crt_hash_folder = "crt_hash/";
    $crt_hash_file = $crt_hash_folder . $crt_hash . ".pem";
    if (file_exists($crt_hash_file)) {
        if (time() - filemtime($crt_hash_file) > 5 * 84600) {
            // file older than 5 days. crt might have changed, retry.
            $content_hash = sha1_file($crt_hash_file);
            rename($crt_hash_file, $crt_hash_folder . $content_hash . "content_hash_save.pem");
            file_put_contents($crt_hash_file, $export_pem);
        }
    } else {
        file_put_contents($crt_hash_file, $export_pem);
    }
    if (stat($crt_hash_file)['size'] < 10) {
        //probably a corrupt file. sould be at least +100KB.
        unlink($crt_hash_file);
    }
    //chain reconstruction
    if ($include_chain && $raw_cert_data) {
        $return_chain = array();
        $export_pem = "";
        openssl_x509_export($raw_cert_data, $export_pem);
        $crt_cn = openssl_x509_parse($raw_cert_data)['name'];
        $export_pem = "#start " . $crt_cn . "\n" . $export_pem . "\n#end " . $crt_cn . "\n";
        array_push($return_chain, $export_pem);
        $certificate_chain = array();
        $issuer_crt = get_issuer_chain($raw_cert_data);
        if (count($issuer_crt['certs']) >= 1) {
            $issuercrts = array_unique($issuer_crt['certs']);
            foreach ($issuercrts as $key => $value) {
                array_push($return_chain, $value);
            }
        }
        $return_chain = array_unique($return_chain);
        if (count($return_chain) > 1) {
            $result["correct_chain"]["cns"] = array();
            $crt_cn = array();
            foreach ($return_chain as $retc_key => $retc_value) {
                $issuer_full = "";
                $subject_full = "";
                $sort_issuer = openssl_x509_parse($retc_value)['issuer'];
                $sort_subject = openssl_x509_parse($retc_value)['subject'];
                asort($sort_subject);
                foreach ($sort_subject as $sub_key => $sub_value) {
                    $subject_full = "/" . $sub_key . "=" . $sub_value . $subject_full;
                }
                asort($sort_issuer);
                foreach ($sort_issuer as $iss_key => $iss_value) {
                    $issuer_full = "/" . $iss_key . "=" . $iss_value . $issuer_full;
                }
                $crt_cn['cn'] = $subject_full;
                $crt_cn['issuer'] = $issuer_full;
                array_push($result["correct_chain"]["cns"], $crt_cn);
            }
            $result["correct_chain"]["chain"] = $return_chain;
        }
    }
    //hashes
    $string = $export_pem;
    $pattern = '/-----(.*)-----/';
    $replacement = '';
    $string = preg_replace($pattern, $replacement, $string);
    $pattern = '/\\n/';
    $replacement = '';
    $export_pem_preg = preg_replace($pattern, $replacement, $string);
    $export_pem_preg = wordwrap($export_pem_preg, 77, "\n", TRUE);
    $result['hash']['md5'] = cert_hash('md5', $export_pem_preg);
    $result['hash']['sha1'] = cert_hash('sha1', $export_pem_preg);
    $result['hash']['sha256'] = cert_hash('sha256', $export_pem_preg);
    $result['hash']['sha384'] = cert_hash('sha384', $export_pem_preg);
    $result['hash']['sha512'] = cert_hash('sha512', $export_pem_preg);
    //TLSA check
    if (!empty($cert_data['subject']['CN']) && !empty($host)) {
        if ($validate_hostname == true) {
            $tlsa_record = shell_exec("timeout " . $timeout . " dig +short +dnssec +time=" . $timeout . " TLSA _" . escapeshellcmd($port) . "._tcp." . escapeshellcmd($host) . " 2>&1 | head -n 1");
            if (!empty($tlsa_record)) {
                $tlsa = explode(" ", $tlsa_record, 4);
                $pattern = '/ /';
                $replacement = '';
                $result['tlsa']['tlsa_hash'] = trim(strtolower(preg_replace($pattern, $replacement, $tlsa[3])));
                $result['tlsa']['tlsa_usage'] = $tlsa[0];
                $result['tlsa']['tlsa_selector'] = $tlsa[1];
                $result['tlsa']['tlsa_matching_type'] = $tlsa[2];
                $result['tlsa']['error'] = 'none';
            } else {
                $result['tlsa']['error'] = 'No TLSA record found.';
                $result['tlsa']['example'] = '_' . htmlspecialchars($port) . '._tcp.' . htmlspecialchars($host) . ' IN TLSA 3 0 1 ' . $result['hash']['sha256'] . ';';
            }
        } else {
            $result['tlsa']['error'] = 'CA certificate, TLSA not applicable.';
        }
    }
    if (isset($key_details['rsa'])) {
        $result["key"]["type"] = "rsa";
        $result["key"]["bits"] = $key_details['bits'];
        if ($key_details['bits'] < 2048) {
            $result['warning'][] = $key_details['bits'] . " bit RSA key is not safe. Upgrade to at least 4096 bits.";
        }
        // weak debian key check
        $bin_modulus = $key_details['rsa']['n'];
        # blacklist format requires sha1sum of output from "openssl x509 -noout -modulus" including the Modulus= and newline.
        # create the blacklist:
        # https://packages.debian.org/source/squeeze/openssl-blacklist
        # svn co svn://svn.debian.org/pkg-openssl/openssl-blacklist/
        # find openssl-blacklist/trunk/blacklists/ -iname "*.db" -exec cat {} >> unsorted_blacklist.db \;
        # sort -u unsorted_blacklist.db > debian_blacklist.db
        $mod_sha1sum = sha1("Modulus=" . strtoupper(bin2hex($bin_modulus)) . "\n");
        $blacklist_file = fopen('inc/debian_blacklist.db', 'r');
        $key_in_blacklist = false;
        while (($buffer = fgets($blacklist_file)) !== false) {
            if (strpos($buffer, $mod_sha1sum) !== false) {
                $key_in_blacklist = true;
                break;
            }
        }
        fclose($blacklist_file);
        if ($key_in_blacklist == true) {
            $result["key"]["weak_debian_rsa_key"] = "true";
            $result['warning'][] = "Weak debian key found. Remove this key right now and create a new one.";
        }
    } else {
        if (isset($key_details['dsa'])) {
            $result["key"]["type"] = "dsa";
            $result["key"]["bits"] = $key_details['bits'];
        } else {
            if (isset($key_details['dh'])) {
                $result["key"]["type"] = "dh";
                $result["key"]["bits"] = $key_details['bits'];
            } else {
                if (isset($key_details['ec'])) {
                    $result["key"]["type"] = "ecdsa";
                    $result["key"]["bits"] = $key_details['bits'];
                } else {
                    $result["key"]["type"] = "unknown";
                    $result["key"]["bits"] = $key_details['bits'];
                }
            }
        }
    }
    // signature algorithm
    $result["key"]["signature_algorithm"] = cert_signature_algorithm($raw_cert_data);
    if ($result["key"]["signature_algorithm"] == "sha1WithRSAEncryption") {
        $result['warning'][] = "SHA-1 certificate. Upgrade (re-issue) to SHA-256 or better.";
    }
    if (isset($export_pem)) {
        $result["key"]["certificate_pem"] = $export_pem;
    }
    if (isset($key_details['key'])) {
        $result["key"]["public_key_pem"] = $key_details['key'];
        $result["key"]["spki_hash"] = spki_hash($export_pem);
    }
    return $result;
}