inital commit
authorTamas Frank <sitya@niif.hu>
Sun, 19 Feb 2012 15:59:15 +0000 (16:59 +0100)
committerTamas Frank <sitya@niif.hu>
Sun, 19 Feb 2012 15:59:15 +0000 (16:59 +0100)
functions.php [new file with mode: 0644]
index.php [new file with mode: 0644]
mail.php [new file with mode: 0644]
nbproject/private/config.properties [new file with mode: 0644]
nbproject/private/private.properties [new file with mode: 0644]
nbproject/private/private.xml [new file with mode: 0644]
nbproject/project.properties [new file with mode: 0644]
nbproject/project.xml [new file with mode: 0644]
wrapcert.php [new file with mode: 0644]

diff --git a/functions.php b/functions.php
new file mode 100644 (file)
index 0000000..6209290
--- /dev/null
@@ -0,0 +1,185 @@
+<?php
+
+include('dbconfig.php');
+
+$conn = mysql_connect (DBHOST, DBUSER, DBPASSWD);
+mysql_select_db(DBNAME, $conn);
+
+$errorMessages = array(
+    "mail" => array(
+        "invalid_address" => "Please provide a valid e-mail address.",
+    ),
+    "cert" => array(
+        "invalid_cert" => "This certificate cannot be read.",
+        "already_in" => "This certificate is already in our database.",
+        "not_valid_yet" => "This certificate is not valid yet.",
+        "expired" => "This certificate has been already expired.",
+    )
+);
+
+function formatCert($cert) {
+    $cert = ltrim(rtrim($cert));
+    if (strlen($cert)>1) {
+        if (!preg_match("/-----BEGIN CERTIFICATE-----/", $cert)) {
+            $cert = "-----BEGIN CERTIFICATE-----\n" . $cert;
+        }
+        if (!preg_match("/-----END CERTIFICATE-----/", $cert)) {
+            $cert = $cert . "\n-----END CERTIFICATE-----";
+        }
+    }
+    return $cert;
+}
+
+function checkCert($string) {
+
+    $cert = ltrim(rtrim($string));
+    return openssl_x509_parse($cert);
+
+}
+
+function getX509Field($cert, $field = 'subject') {
+    $descriptorspec = array(
+            0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
+            1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
+            2 => array("pipe", "r") // stderr is a file to write to
+    );
+
+
+    // Check field
+    if (
+    $field != 'subject'
+            && $field != 'serial'
+            && $field != 'fingerprint'
+            && $field != 'startdate'
+            && $field != 'issuer'
+            && $field != 'enddate'
+            && $field != 'clean'
+    ) {
+        return false;
+    }
+
+    // Set switches
+    if ($field == 'fingerprint') {
+        $field .= ' -sha1';
+    }
+
+    if ($field == 'clean') {
+        $process = proc_open('/usr/bin/openssl x509', $descriptorspec, $pipes);
+    } else {
+        $process = proc_open('/usr/bin/openssl x509 -noout -'.$field, $descriptorspec, $pipes);
+    }
+
+    if (is_resource($process)) {
+        // $pipes now looks like this:
+        // 0 => writeable handle connected to child stdin
+        // 1 => readable handle connected to child stdout
+        // Any error output will be appended to /tmp/error-output.txt
+
+        fwrite($pipes[0],  $cert);
+        fclose($pipes[0]);
+
+        $result = '';
+        while ($i = fgets($pipes[1])) {
+            $result .= $i;
+        }
+        fclose($pipes[1]);
+
+        // It is important that you close any pipes before calling
+        // proc_close in order to avoid a deadlock
+        $return_value = proc_close($process);
+
+
+        // Returns false on error or the data part after the = in
+        // e.g. Fingerprint=D6:E7:7D:94:51:8C:3E:7C:62:BD:FE:77:E4:CB:B0:0F
+        if(!$return_value && $field == 'clean') {
+            return trim($result);
+        } else if(!$return_value) {
+            return trim(substr($result, (strpos($result, '=')+1)));
+        } else {
+            return false;
+        }
+    }
+}
+
+function getCertNR(){
+    global $conn;
+    $query = mysql_query("SELECT fingerprint FROM main",$conn);
+    return mysql_num_rows($query);
+}
+
+function mailEncode($in_str, $charset) {
+    $out_str = $in_str;
+    if ($out_str && $charset) {
+
+        // define start delimimter, end delimiter and spacer
+        $end = "?=";
+        $start = "=?" . $charset . "?B?";
+        $spacer = $end . "\r\n " . $start;
+
+        // determine length of encoded text within chunks
+        // and ensure length is even
+        $length = 200 - strlen($start) - strlen($end);
+        $length = floor($length/2) * 2;
+
+        // encode the string and split it into chunks
+        // with spacers after each chunk
+        $out_str = base64_encode($out_str);
+        $out_str = chunk_split($out_str, $length, $spacer);
+
+        // remove trailing spacer and
+        // add start and end delimiters
+        $spacer = preg_quote($spacer);
+        $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
+        $out_str = $start . $out_str . $end;
+    }
+    return $out_str;
+}
+
+function sendReminder($email,$fingerprint,$dn,$expire){
+    
+    $eol="\n";
+
+    $headers .= 'From: certwatch <no-reply@niif.hu>' . $eol;
+    $headers .= 'MIME-Version: 1.0' . $eol;
+    $headers .= 'Reply-To: no-reply@niif.hu' . $eol;
+    $headers .= 'Content-type: text/plain; charset=UTF-8' . $eol;
+    $headers .= 'Content-Transfer-Encoding: 8bit' . $eol;
+
+    $subject = "Certificate expiration";
+
+    $body = "Hello,
+
+your certificate (fingerprint: $fingerprint, dn: $dn) will be expired in $expire. After expiring it will be purged form our database.
+
+Cheers,
+certwatch.niif.hu
+
+This is an automatically generated message, please, do not reply.
+    ";
+
+    mail($email,$subject,$body,$headers);
+
+}
+
+function expireDays($dayNR){
+    return ($dayNR==1) ? $dayNR . " day" : $dayNR . " days";
+}
+
+
+function certWrap($attrs){
+       $attrs=preg_replace("/\n|\t| /","",$attrs);
+       if (strlen($attrs)>256){
+               $i=0;
+               $attr="";
+               while ($i<strlen($attrs)){
+                       $attr.=substr($attrs,$i,64)."\n";
+                       $i=$i+64;
+               }
+       } else {
+               $attr=$attrs;
+       }
+       return $attr;
+}
+
+
+?>
diff --git a/index.php b/index.php
new file mode 100644 (file)
index 0000000..8c082e2
--- /dev/null
+++ b/index.php
@@ -0,0 +1,120 @@
+<?php
+
+include('functions.php');
+
+if ( isset($_POST['email']) && isset($_POST['cert']) ) {
+    if ( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL )) {
+
+        //Check e-mail address
+        $error['mail'][] = 'invalid_address';
+
+    } elseif ( $certData = checkCert( $cert = formatCert($_POST['cert']) )  ) {
+        $fingerprint = getX509Field($cert, 'fingerprint');
+        $dn = $certData['name'];
+        $startdate = getX509Field($cert, 'startdate');
+        $enddate = getX509Field($cert, 'enddate');
+
+        if ( strtotime($startdate) > time() ) {
+            $error['cert'][] = "not_valid_yet";
+        } elseif ( strtotime($enddate) < time() ) {
+            $error['cert'][] = "expired";
+        } else {
+
+            $sel = mysql_query("SELECT email FROM main WHERE fingerprint = '".$fingerprint."'") or die(mysql_error());
+            if (mysql_num_rows($sel)>0) {
+                $error['cert'][] = 'already_in';
+            } else {
+                mysql_query("INSERT INTO main SET email='".$_POST['email']."',dn='".$dn."',fingerprint='".$fingerprint."',expire='".date("Y-m-d H:i:s",strtotime($enddate))."'");
+                $inserted = true;
+            }
+        }
+    } else {
+        $error['cert'][] = 'invalid_cert';
+    }
+
+}
+
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="hu">
+<head>
+
+    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+    <title>certwatch.niif.hu</title>
+    <style>
+        <!--
+
+        body {width:640px;margin:10px auto;font-family: arial, helvetica, sans-serif;}
+        .row {clear:both;padding:10px 0;font-size: 14px;width: 480px;}
+        input {font-size:14px;padding:2px;}
+        #email {width: 500px;}
+        #cert {width:500px;height:200px;font-size:12px;padding:6px;font-family: courier;margin: 4px 0;}
+        .error_message {color:red;}
+        .success {color:green;}
+        #header {clear:both;padding:5px 2px;border-bottom:1px solid #e2e2e2;font-weight: bold;font-size:20px;}
+        #main {padding:20px 60px 0 60px;}
+        #footer {margin-top:30px;padding:10px 2px;border-top:1px solid #e2e2e2;font-size:11px;}
+        .hint {color:#a5a5a5;font-size:12px;background-color: #e2e2e2;padding:3px 10px;margin-bottom:20px;}
+
+        -->
+    </style>
+</head>
+<body>
+    <div id="header">
+        certwatch
+    </div>
+<div id="main">
+<? if ($inserted) : ?>
+    <div class="row">
+        <div class="success">Done. We have stored the following data.</div>
+        <ul>
+            <li><b>DN:</b> <?=$dn;?></li>
+            <li><b>Fingerprint:</b> <?=$fingerprint;?></li>
+            <li><b>Expiry date:</b> <?=$enddate;?></li>
+        </ul>
+        <p>We will send a reminder mail on <b><?=date("r",strtotime($enddate)-864000);?></b> to <b><?=$_POST['email'];?></b></p>
+        
+        
+    </div>
+<? else : ?>
+
+<form action="index.php" method="post">
+    <div class="hint">
+        <span style="font-weight:bold">How it works?<br /></span>
+        If you upload your certification and provide your e-mail address, we will notify you 10 days before the certification expires.
+    </div>
+    <div class="row">
+        <label for="email">E-mail</label><br />
+        <input type="text" name="email" id="email" value="<?=( isset($_POST['email']) ) ? $_POST['email'] : "";  ?>" />
+        <? if (count($error['mail'])>0) {
+            foreach ( $error['mail'] as $err ){
+                echo '<div class="error_message">' . $errorMessages['mail'][$err] . '</div>';
+            }
+        } ?>
+    </div>
+    <div class="row">
+        PEM format certification
+        <textarea name="cert" id="cert"><?=( isset($_POST['cert']) ) ? $cert : "";  ?></textarea>
+        
+        <? if (count($error['cert'])>0) {
+            
+            foreach ( $error['cert'] as $err ){
+                echo '<div class="error_message">' . $errorMessages['cert'][$err] . '</div>';
+            }
+        } ?>
+    </div>
+    <div class="row" style="text-align: center">
+        <input type="submit" id="submit" value="Upload" />
+    </div>
+    
+    
+</form>
+
+<? endif; ?>
+</div>
+<div id="footer">
+    <div style="float:left;">Currently we store <?=getCertNR();?> reminders</div>
+    <div style="float:right;">This site is provided by <a href="http://www.niif.hu" target="_blank">NIIF Institute</a></div>
+</div>
+</body>
+</html>
diff --git a/mail.php b/mail.php
new file mode 100644 (file)
index 0000000..c6ee6cf
--- /dev/null
+++ b/mail.php
@@ -0,0 +1,18 @@
+<?php
+
+include('functions.php');
+
+$days = array(1,7,10);
+
+foreach ($days as $day){
+    $sel = mysql_query("SELECT * FROM main WHERE DATE_FORMAT(expire,'%Y-%m-%d') = DATE_FORMAT(NOW() + INTERVAL $day DAY,'%Y-%m-%d')") or die(mysql_error());
+    while ($O=mysql_fetch_object($sel)){
+
+        sendReminder($O->email, $O->fingerprint, $O->dn, expireDays($day));
+        sendReminder("sitya@niif.hu", $O->fingerprint, $O->dn, expireDays($day));
+    }
+}
+
+mysql_query("DELETE FROM main WHERE expire < NOW()");
+
+?>
diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties
new file mode 100644 (file)
index 0000000..4c78373
--- /dev/null
@@ -0,0 +1,8 @@
+copy.src.files=false
+copy.src.target=
+index.file=index.php
+remote.connection=pws_certw
+remote.directory=/www
+remote.upload=ON_SAVE
+run.as=REMOTE
+url=http://localhost/certwatch.niif.hu/
diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml
new file mode 100644 (file)
index 0000000..c1f155a
--- /dev/null
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
+    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/>
+</project-private>
diff --git a/nbproject/project.properties b/nbproject/project.properties
new file mode 100644 (file)
index 0000000..6ffde2f
--- /dev/null
@@ -0,0 +1,7 @@
+include.path=${php.global.include.path}
+php.version=PHP_5
+source.encoding=UTF-8
+src.dir=.
+tags.asp=false
+tags.short=true
+web.root=.
diff --git a/nbproject/project.xml b/nbproject/project.xml
new file mode 100644 (file)
index 0000000..6059a39
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://www.netbeans.org/ns/project/1">
+    <type>org.netbeans.modules.php.project</type>
+    <configuration>
+        <data xmlns="http://www.netbeans.org/ns/php-project/1">
+            <name>certwatch.niif.hu</name>
+        </data>
+    </configuration>
+</project>
diff --git a/wrapcert.php b/wrapcert.php
new file mode 100644 (file)
index 0000000..0ee0ad8
--- /dev/null
@@ -0,0 +1,95 @@
+<?php
+
+include('functions.php');
+
+if ( isset($_POST['cert']) ) {
+    $certData = checkCert( $cert = formatCert($_POST['cert']));
+    
+        $fingerprint = getX509Field($cert, 'fingerprint');
+        $dn = $certData['name'];
+        $startdate = getX509Field($cert, 'startdate');
+        $enddate = getX509Field($cert, 'enddate');
+
+        echo "<pre>" . certWrap($cert) . "</pre>";
+
+        
+
+    
+
+}
+
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="hu">
+<head>
+
+    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+    <title>certwatch.niif.hu</title>
+    <style>
+        <!--
+
+        body {width:640px;margin:10px auto;font-family: arial, helvetica, sans-serif;}
+        .row {clear:both;padding:10px 0;font-size: 14px;width: 480px;}
+        input {font-size:14px;padding:2px;}
+        #email {width: 500px;}
+        #cert {width:500px;height:200px;font-size:12px;padding:6px;font-family: courier;margin: 4px 0;}
+        .error_message {color:red;}
+        .success {color:green;}
+        #header {clear:both;padding:5px 2px;border-bottom:1px solid #e2e2e2;font-weight: bold;font-size:20px;}
+        #main {padding:20px 60px 0 60px;}
+        #footer {margin-top:30px;padding:10px 2px;border-top:1px solid #e2e2e2;font-size:11px;}
+        .hint {color:#a5a5a5;font-size:12px;background-color: #e2e2e2;padding:3px 10px;margin-bottom:20px;}
+
+        -->
+    </style>
+</head>
+<body>
+    <div id="header">
+        certwatch
+    </div>
+<div id="main">
+<? if ($inserted) : ?>
+    <div class="row">
+        <div class="success">Done. We have stored the following data.</div>
+        <ul>
+            <li><b>DN:</b> <?=$dn;?></li>
+            <li><b>Fingerprint:</b> <?=$fingerprint;?></li>
+            <li><b>Expiry date:</b> <?=$enddate;?></li>
+        </ul>
+        <p>We will send a reminder mail on <b><?=date("r",strtotime($enddate)-864000);?></b> to <b><?=$_POST['email'];?></b></p>
+        
+        
+    </div>
+<? else : ?>
+
+<form action="wrapcert.php" method="post">
+    <div class="hint">
+        <span style="font-weight:bold">How it works?<br /></span>
+        If you upload your certification and provide your e-mail address, we will notify you 10 days before the certification expires.
+    </div>
+    <div class="row">
+        PEM format certification
+        <textarea name="cert" id="cert"><?=( isset($_POST['cert']) ) ? $cert : "";  ?></textarea>
+        
+        <? if (count($error['cert'])>0) {
+            
+            foreach ( $error['cert'] as $err ){
+                echo '<div class="error_message">' . $errorMessages['cert'][$err] . '</div>';
+            }
+        } ?>
+    </div>
+    <div class="row" style="text-align: center">
+        <input type="submit" id="submit" value="Upload" />
+    </div>
+    
+    
+</form>
+
+<? endif; ?>
+</div>
+<div id="footer">
+    <div style="float:left;">Currently we store <?=getCertNR();?> reminders</div>
+    <div style="float:right;">This site is provided by <a href="http://www.niif.hu" target="_blank">NIIF Institute</a></div>
+</div>
+</body>
+</html>