<?PHP
	#.htgenerateCertificate.inc.php
	#This is a set of routines for generating certificates.
	#Their general form will be osbrfunction() where os and br are the operating system and browser
	#which the surfer is using.
	
	#define constants for the openssl stuff.  Apparently, none of this is in opensslwrap.
	if (!defined("OPENSSLDIR")) define ("OPENSSLDIR","/usr/bin");	#Location of openssl binary
	if (!defined("CERTSDIR")) define ("CERTSDIR","/home/phadley/websites/certs/1");
	if (!defined("CNFFILE")) define ("CNFFILE",CERTSDIR."/config.cnf");
	if (!defined("CAFILE")) define ("CAFILE",CERTSDIR."/root.pem");
	if (!defined("KEYFILE")) define ("KEYFILE",CERTSDIR."/rootkey.pem");
	if (!defined("CAPASSWORD")) define("CAPASSWORD","1273!Main");
	if (!defined("REQPARTS")) define ("REQPARTS","commonName,emailAddress,organizationName,organizationalUnitName,localityName,stateOrProvinceName,countryName");

	#osbrcertform returns HTML for the start of a form which generates the key pair and sends it in.
if (!function_exists("maffcertform"))
{
	function maffcertform($action=".",$command="makecert",$method="post",$name="genRecForm",$id="keygen")
	{
		$a="<form action=\"$action\" method=\"$method\" name=\"$name\" id=\"$id\">";
		$a.="\n<input type=hidden name=\"cmd\" value=\"$command\">";
		return $a;
	}
}
	
	#osbrcertkeysize returns HTML for the submit button (KEYGEN for FF)
	if (!function_exists ("maffcertkeysize"))
	{
		function maffcertkeysize($name="SPKAC",$challenge="challengePassword")
		{
			$a="<KEYGEN NAME=\"$name\" CHALLENGE=\"$challenge\">";
			return $a;
		}
	}
	
	#osbrcertsubmit returns HTML for the submit button
	if (!function_exists ("maffcertsubmit"))
	{
		function maffcertsubmit($name="command",$value="Request a Certificate")
		{
			$a="<input type=submit name=\"$name\" value=\"$value\">";
			return $a;
		}
	}
	
	$certsdir="/home/phadley/websites/certs/1";
	$req_file = "$certsdir/$count.req"; # certificate request filename
/*	
	# The configuration file made on the fly.
	function maffconfig($filename,$count,$dir,$email)
	{
		$certs_dir=$dir;
	
		$ERRORFILE = "$certs_dir/errors";
		$srlfile="$certs_dir/$count.srl";
		$srlfile="$certs_dir/serial";
		if (defined("CNFFILE"))
			$cnffile=CNFFILE;
		else
			$cnffile="$certs_dir/$count.cnf";
		$crlfile="$certs_dir/crl.pem";
		$req_file = "$certs_dir/$count.req"; # certificate request filename
		$result_file = "$certs_dir/$count.result"; # certificate filename
		$pkcs7_file = "$certs_dir/$count.pkcs";
		$dbfile="$certs_dir/$count.txt";
		
		$cnfp=fopen($filename,"w");
		fwrite($cnfp,"[ ca ]\n");									##Lazim mi?
		fwrite($cnfp,"default_ca	= $count"."ca\n\n");
		
		fwrite($cnfp,"[ $count"."ca ]\n");							##Lazim mi?
		fwrite($cnfp,"certificate      = $dir/root.pem\n");
		fwrite($cnfp,"new_certs_dir    = $certs_dir\n");
		fwrite($cnfp,"database		  = $certs_dir/$count.txt\n");
		fwrite($cnfp,"private_key      = $dir/rootkey.pem\n");
		fwrite($cnfp,"serial           = $srlfile\n");
		
		fwrite($cnfp,"default_crl_days = 7\n");
		fwrite($cnfp,"default_days     = 365\n");
		fwrite($cnfp,"default_md       = sha1\n");
		
		fwrite($cnfp,"policy           = $count"."_policy\n");
		fwrite($cnfp,"x509_extensions  = certificate_extensions\n");	##Belki lazim, no, it's in the cmd line
		
		fwrite($cnfp,"[ $count"."_policy ]\n");						##Lazim mi?  I think so.
		fwrite($cnfp,"countryName            = optional\n");
		fwrite($cnfp,"stateOrProvinceName    = optional\n");
		fwrite($cnfp,"localityName           = optional\n");
		fwrite($cnfp,"organizationName       = optional\n");
		fwrite($cnfp,"organizationalUnitName = optional\n");
		fwrite($cnfp,"commonName             = supplied\n");
		fwrite($cnfp,"emailAddress           = optional\n");
		
		fwrite($cnfp,"[ req ]\n");
		fwrite($cnfp,"default_bits		= 2048\n");
		fwrite($cnfp,"default_keyfile 	= privkey.pem\n");
		fwrite($cnfp,"default_md              = sha1\n");
		
		fwrite($cnfp,"prompt                  = no\n");
		fwrite($cnfp,"distinguished_name	= req_distinguished_name\n");
		fwrite($cnfp,"x509_extensions		= req_extensions\n");
		
		# the following sections are specific to the request we're building
		
		fwrite($cnfp,"[ certificate_extensions ]\n");
		fwrite($cnfp,"basicConstraints = CA:false\n");
		fwrite($cnfp,"keyUsage = digitalSignature, keyEncipherment, dataEncipherment\n");
		fwrite($cnfp,"extendedKeyUsage = clientAuth, emailProtection\n");
		#fwrite($cnfp,"subjectAltName = CN:Village Registrant,email:$email\n");
		
		fwrite($cnfp,"[ req_distinguished_name ]\n");					##Lazim mi?
		fwrite($cnfp,"countryName         	= US\n");
		fwrite($cnfp,"stateOrProvinceName 	= New York\n");
		fwrite($cnfp,"localityName        	= Wantagh\n");
		fwrite($cnfp,"organizationName    	= Suffolk County\n");
		fwrite($cnfp,"organizationalUnitName	= Birth Certificates\n");
		fwrite($cnfp,"commonName          	= William F. Schmitt\n");
		
		fwrite($cnfp,"[ req_extensions ]\n");							##Lazim mi?
		fwrite($cnfp,"basicConstraints = CA:true\n");
		fwrite($cnfp,"subjectAltName = DNS:Bill Schmitt\n");
		#subjectAltName = DNS:splat.zork.org,DNS:localhost\n");
		fclose($cnfp);
		return;
	}
*/
	
	#osbrmakereqfile makes the request out of the SPKAC and name parts
if (!function_exists("maffmakereqfile"))
	{
		function maffmakereqfile($filename,$parts=REQPARTS)
		{
			$a="";
			$partses=explode(",",$parts);
			foreach ($partses as $key)
			{
				$value=fromREQUESt($key);
				if (!is_null($value) && (strlen($value) > 0)) $a.="$key	=	$value\n";
			}
			$a.="SPKAC	=	".str_replace("\r\n","",fromREQUEST("SPKAC"))."\n";
			return file_put_contents($filename,$a);
		}
	}

	#osbrmakecert actualy generates a certificate by assembling a command line and then executing it.
	#
if (!function_exists("maffmakecert"))
{
	function maffmakecert($count=4,$CAFILE=CAFILE,$KEYFILE=CAKEYFILE,$certs_dir=CERTSDIR,$days=731,$CApassword=CAPASSWORD)
	{
		$openssldir=OPENSSLDIR;
		#$os="ma";$br="ff";$osbr="maff";

		if (defined("CNFFILE"))
			$cnffile=CNFFILE;
		else
			$cnffile=$certs_dir."/$count.cnf";
		
		$email=fromREQUEST("email");
		if (is_null($email)) $email="unknown  $count";

		/*
		 #	header("Content-Length: ".strlen($cert));
		 #	header("Location: $PHP_SELF?command=info");
		 */

		$CA="$openssldir/openssl ca";
		$CRL2PKCS7 = "$openssldir/openssl crl2pkcs7";
		$ERRORFILE = "$certs_dir/errors";
		###$srlfile="$certs_dir/$count.srl";
		$srlfile="$certs_dir/serial";
		#$cnffile="$certs_dir/$count.cnf";
		$cnffile="$certs_dir/config.cnf";
		$crlfile="$certs_dir/crl.pem";
		$req_file = "$certs_dir/$count.req"; # certificate request filename
		$result_file = "$certs_dir/$count.result"; # certificate filename	?????
		$pkcs7_file = "$certs_dir/$count.pkcs";								#????
		###$dbfile="$certs_dir/$count.txt";
		
		file_put_contents($srlfile,dechex($count));
		###shell_exec("touch $dbfile");
		#	config should be a static file and I think I've achieved that with config.cnf and that
		#	makes the function for creating a config file superfluous.
		#maffconfig($cnffile,$count,$certs_dir,$email);
		
		$CRL = "$certs_dir/crl.pem";
		##$CACERT = "-cert $CAFILE";
		##$CAKEY = "-key $CApassword";
		##$part="makecert";

	/*
		##echo "<br/>We are about to make the certificate with $osbr.inc.php.";
		$req_names = array('commonName', 'emailAddress', 'organizationName',
						   'organizationalUnitName', 'localityName', 'stateOrProvinceName',
						   'countryName');
		$reqp=fopen($req_file,"w");
		/*
		 $nnames=count($req_names);
		 for ($i=0;$i<$nnames;$i++)
		 {
		 $id=$req_names[$i];
		 $value=str_replace("\r\n","",$_REQUEST[$id]);
		 fwrite($reqp,sprintf("%s = %s\n",$id,$value));
		 }
		 * /
		fwrite($reqp,sprintf("%s = %s\n","emailAddress",$email));
		fwrite($reqp,sprintf("%s = %s\n","commonName",$email));
		fwrite($reqp,sprintf("SPKAC = %s\n",str_replace("\r\n","",$_REQUEST["SPKAC"])));
		fclose($reqp);
	*/
		##$req=file_get_contents($req_file);
		$cmd="$CA -batch -config $cnffile -extensions certificate_extensions "
		."-cert $CAFILE "
		."-key $CApassword "
		."-verbose -spkac $req_file -days $days "
		."2>>$ERRORFILE";
		$cert = shell_exec ($cmd);
		return $count;
		#header("Content-Type: application/x-x509-user-cert");
		#echo $cert;
	}
}

if (!function_exists("UDECHEX"))
{
	function UDECHEX($in)
	{
		return strtoupper(dechex($in));
	}
}

	#This picks up the certificate and sends it out with a proper header
if (!function_exists('maffcertsend'))
{
	function maffcertsend($serial)
	{
		header("Content-Type: application/x-x509-user-cert");
		$fred=sprintf("%08X",$serial);
		while (substr($fred,0,2) == "00") $fred=substr($fred,2);
		$filename=CERTSDIR."/$fred.pem";
		$n=readfile($filename);
		if ($n > 0)
			return true;
		else
			return false;
	}
}

if (!function_exists('maffautocertsend'))
	{
		function maffautocertsend($serial,$formid="grabit")
		{
			$a="<form action=. method=post id=\"$formid\">";
			$a.="<input type=hidden name=cmd value=certsend>";
			$a.="<input type=hidden name=id value=$serial";
			$a.="</form>";
			$a.="\n<script type=text/javascript>";
			$a.="\nvar keygen=document.getElementById(\"$formid\");";
			$a.="\nkeygen.submit();";
			$a.="\n</script>";
			return $a;
		}
	}

	#This goes up after certsubmit but is down here to make indentation work properly.
	#osbrcertautosubmit will submit the certificate request without the user clicking anything.
	if (!function_exists("maffcertautosubmit"))
	{
		function maffcertautosubmit($id="keygen")
		{
			$a="<script type=text/javascript>
			var keygen=document.getElementById(\"$id\");
											   keygen.submit();
											   </script>";
											   return $a;
											   }
											   }

?>