Merge branch 'bug-649' into testserver-stable
authorBenny Baumann <BenBE@geshi.org>
Tue, 2 Jun 2015 18:54:09 +0000 (20:54 +0200)
committerBenny Baumann <BenBE@geshi.org>
Tue, 2 Jun 2015 18:54:09 +0000 (20:54 +0200)
182 files changed:
CommModule/.gitignore [new file with mode: 0644]
CommModule/client.pl
CommModule/readme.txt
CommModule/serial.conf [deleted file]
CommModule/server.pl
CommModule/usbclient.pl [deleted file]
README [deleted file]
README.md [new file with mode: 0644]
cgi-bin/siteseal.cgi [deleted file]
config/ttp.ini [new file with mode: 0644]
crt/DIR [new file with mode: 0644]
csr/DIR [new file with mode: 0644]
includes/account.php
includes/account_stuff.php
includes/general.php
includes/general_stuff.php
includes/keygen.php
includes/lib/account.php
includes/lib/check_weak_key.php
includes/lib/general.php
includes/lib/l10n.php
includes/loggedin.php
includes/mysql.php.sample
includes/notary.inc.php
includes/shutdown.php
includes/tverify_stuff.php [deleted file]
locale/Makefile
pages/account/10.php
pages/account/12.php
pages/account/13.php
pages/account/14.php
pages/account/15.php
pages/account/16.php
pages/account/17.php
pages/account/18.php
pages/account/19.php
pages/account/20.php
pages/account/21.php
pages/account/22.php
pages/account/23.php
pages/account/24.php
pages/account/25.php
pages/account/27.php
pages/account/3.php
pages/account/40.php
pages/account/41.php
pages/account/43.php
pages/account/44.php
pages/account/48.php
pages/account/49.php
pages/account/5.php
pages/account/51.php [deleted file]
pages/account/52.php [deleted file]
pages/account/53.php
pages/account/54.php
pages/account/55.php
pages/account/56.php
pages/account/57.php
pages/account/58.php
pages/account/59.php [new file with mode: 0644]
pages/account/6.php
pages/advertising/1.php
pages/gpg/2.php
pages/index/0.php
pages/index/1.php
pages/index/10.php
pages/index/11.php
pages/index/16.php
pages/index/3.php
pages/index/52.php [new file with mode: 0644]
pages/index/6.php
pages/index/feed.rss [new file with mode: 0644]
pages/wot/1.php
pages/wot/10.php
pages/wot/12.php
pages/wot/13.php
pages/wot/15.php
pages/wot/16.php [new file with mode: 0644]
pages/wot/3.php
pages/wot/4.php
pages/wot/5.php
pages/wot/6.php
pages/wot/8.php
pages/wot/9.php
scripts/54at-ate-linz-email.txt [new file with mode: 0644]
scripts/54at-ate-linz-mail.php.txt [new file with mode: 0644]
scripts/55de-ate-wiesbaden-email.txt [new file with mode: 0644]
scripts/55de-ate-wiesbaden-mail.php.txt [new file with mode: 0644]
scripts/56at-ate-oberwart-email.txt [new file with mode: 0644]
scripts/56at-ate-oberwart-mail.php.txt [new file with mode: 0644]
scripts/57at-ate-graz-email.txt [new file with mode: 0644]
scripts/57at-ate-graz-mail.php.txt [new file with mode: 0644]
scripts/58at-ate-wien-email.txt [new file with mode: 0644]
scripts/58at-ate-wien-mail.php.txt [new file with mode: 0644]
scripts/cron/refresh_stats.php
scripts/cron/updatesort.php
scripts/cron/warning.php
scripts/db_migrations/version5.sh [new file with mode: 0755]
scripts/db_migrations/version6.sh [new file with mode: 0755]
scripts/gpgfillmissingemail.php
scripts/scanforexponents.php
scripts/send_heartbleed.php [new file with mode: 0755]
scripts/send_policy_cca_20140916.php [new file with mode: 0644]
stamp/.htaccess [deleted file]
stamp/certdet.php [deleted file]
stamp/common.php [deleted file]
stamp/displogo.php [deleted file]
stamp/images/CAverify.png [deleted file]
stamp/index.php [deleted file]
stamp/old_showlogo.php.broken [deleted file]
stamp/report.php [deleted file]
stamp/showlogo.php [deleted file]
stamp/style.css [deleted file]
tverify/.htaccess [deleted file]
tverify/favicon.ico [deleted file]
tverify/index.php [deleted file]
tverify/index/0.php [deleted file]
tverify/index/1.php [deleted file]
www/.gitignore [new file with mode: 0644]
www/.htaccess
www/ac.php
www/account.php
www/alert_hash_collision.php
www/api/ccsr.php [deleted file]
www/api/cemails.php [deleted file]
www/api/edu.php
www/cacert1-class3-revoke.crl [new symlink]
www/cacert1-revoke.crl [new symlink]
www/cap.html.php
www/cap.php
www/capnew.php
www/cats/cats_import.php
www/certs/cacert.asc
www/certs/class3.crt
www/certs/class3.der
www/certs/class3.txt
www/certs/root.crt
www/certs/root.der
www/certs/root.txt
www/coap.html.php
www/coapnew.php
www/disputes.php
www/gpg.php
www/images/cacert4.png
www/index.php
www/policy/AssurancePolicy.html [new file with mode: 0644]
www/policy/AssurancePolicy.php
www/policy/CAcertCommunityAgreement.html [new file with mode: 0644]
www/policy/CAcertCommunityAgreement.php
www/policy/CertificationPracticeStatement.html [new file with mode: 0644]
www/policy/CertificationPracticeStatement.php
www/policy/ConfigurationControlSpecification.html [new file with mode: 0644]
www/policy/DisputeResolutionPolicy.html [new file with mode: 0644]
www/policy/DisputeResolutionPolicy.php
www/policy/NRPDisclaimerAndLicence.php [deleted file]
www/policy/OrganisationAssurancePolicy.html [new file with mode: 0644]
www/policy/OrganisationAssurancePolicy.php
www/policy/OrganisationAssurancePolicy_Australia.html [new file with mode: 0644]
www/policy/OrganisationAssurancePolicy_Europe.html [new file with mode: 0644]
www/policy/OrganisationAssurancePolicy_Germany.html [new file with mode: 0644]
www/policy/PolicyOnJuniorAssurersMembers.html [new file with mode: 0644]
www/policy/PolicyOnPolicy.html [new file with mode: 0644]
www/policy/PolicyOnPolicy.php
www/policy/PrivacyPolicy.html
www/policy/PrivacyPolicy.php [new file with mode: 0644]
www/policy/RootDistributionLicense.html [new file with mode: 0644]
www/policy/RootDistributionLicense.php
www/policy/SecurityPolicy.html [new file with mode: 0644]
www/policy/TTPAssistedAssurancePolicy.html [new file with mode: 0644]
www/policy/cacert-draft.png [deleted file]
www/policy/images/cacert-draft.png [new file with mode: 0644]
www/policy/images/cacert-policy.png [new file with mode: 0644]
www/policy/images/valid-html401-blue.png [new file with mode: 0644]
www/policy/images/valid-html50-blue.png [new file with mode: 0644]
www/policy/images/valid-xhtml11-blue.png [new file with mode: 0644]
www/policy/index.php
www/robots.txt [new file with mode: 0644]
www/stats.php
www/styles/default.css
www/tverify/seclayer.php [deleted file]
www/verify.php
www/wot.php

diff --git a/CommModule/.gitignore b/CommModule/.gitignore
new file mode 100644 (file)
index 0000000..40a9309
--- /dev/null
@@ -0,0 +1,19 @@
+# Ignore autogenerated serial conf file
+/serial.conf
+/serialserver.conf
+
+# Ignore *-active files
+/client.pl-active
+/server.pl-active
+
+# Ignore log files
+/logfile20??-??-??.txt
+/nohup.out
+/oldlogs/
+
+# Ignore working files generated by the signer
+/currentcrls/
+/delta?.diff
+/revoke-root?.crl
+/timesync.sh
+/work/
index bd3eb02..24f0abc 100755 (executable)
@@ -31,7 +31,7 @@ use DBI;
 use Locale::gettext;
 use IO::Socket;
 use MIME::Base64;
-use Digest::SHA1 qw(sha1_hex);
+use Digest::SHA qw(sha1_hex);
 
 #Protocol version:
 my $ver=1;
@@ -40,8 +40,8 @@ my $paranoid=1;
 
 my $debug=0;
 
-#my $serialport="/dev/ttyS0";
-my $serialport="/dev/ttyUSB0";
+my $serialport="/dev/ttyS1";
+#my $serialport="/dev/ttyUSB0";
 
 my $gpgbin="/usr/bin/gpg";
 
@@ -172,7 +172,7 @@ else
 $PortObj->baudrate(115200);
 $PortObj->parity("none");
 $PortObj->databits(8);
-$PortObj->stopbits(1);        
+$PortObj->stopbits(1);
 }
 }
 
@@ -286,8 +286,8 @@ sub SendIt($)
   #  {
   #    $PortObj->write(substr($_[0],$_,1));
   #  }
-  
-}  
+
+}
 
 
 my $modus=0;
@@ -313,17 +313,17 @@ sub SendHandshaked($)
       $xor ^= unpack("C",substr($_[0],$_,1));
     }
     #print "XOR: $xor\n";
-  
+
     my $tryagain=1;
     while($tryagain)
     {
       SendIt($_[0].pack("C",$xor)."rie4Ech7");
-  
+
       Error "Packet receipt was not confirmed in 5 seconds. Connection lost!\n" if(!scalar($sel->can_read(5)));
 
       $data="";
       $length=read SER,$data,1;
-    
+
       if($length && $data eq "\x10")
       {
         SysLog "Sent successfully!...\n";
@@ -335,14 +335,14 @@ sub SendHandshaked($)
       }
       else
       {
-        Error "I cannot send! $length ".unpack("C",$data)."\n"; 
+        Error "I cannot send! $length ".unpack("C",$data)."\n";
       }
     }
 
   }
   else
   {
-    print "!Cannot send! $length \n"; 
+    print "!Cannot send! $length \n";
     Error "!Stopped sending.\n";
   }
 }
@@ -423,7 +423,7 @@ sub Request($$$$$$$$$$$)
   my @fields=unpack3array(substr($data,3,-9));
 
   SysLog "Answer from Server: ".hexdump($data)."\n" if($debug);
+
   #if(open OUT,">result.dat")
   #{
   #  print OUT $data;
@@ -441,12 +441,12 @@ sub calculateDays($)
 {
   if($_[0])
   {
-    my @sum = $dbh->selectrow_array("select sum(`points`) as `total` from `notary` where `to`='".$_[0]."' group by `to`");
+    my @sum = $dbh->selectrow_array("select sum(`awarded`) as `total` from `notary` where `to`='".$_[0]."' and `deleted`=0 AND `notary`.`method` != 'Administrative Increase' AND `notary`.`from` != `notary`.`to` group by `to`");
     SysLog("Summe: $sum[0]\n") if($debug);
 
-    return ($sum[0]>=50)?730:180;
+    return ($sum[0]>=50)?30:3;
   }
-  return 180;
+  return 3;
 }
 
 sub X509extractSAN($)
@@ -461,8 +461,8 @@ sub X509extractSAN($)
     {
       $SAN.="," if($SAN ne "");
       $SAN.= trim($bit[1]);
-    } 
-    else 
+    }
+    else
     {
       $newsubject .= "/".$val;
     }
@@ -470,7 +470,7 @@ sub X509extractSAN($)
   $newsubject=~s{^//}{/};
   $newsubject=~s/[\n\r\t\x00"\\']//g;
   $SAN=~s/[ \n\r\t\x00"\\']//g;
-  return($SAN,$newsubject); 
+  return($SAN,$newsubject);
 }
 
 sub X509extractExpiryDate($)
@@ -526,25 +526,25 @@ sub X509extractSerialNumber($)
   return "";
 }
 
-sub OpenPGPextractExpiryDate ($) 
+sub OpenPGPextractExpiryDate ($)
 {
   my $r="";
   my $cts;
   my @date;
+
   open(RGPG, $gpgbin.' -vv '.$_[0].' 2>&1 |') or Error('Can\'t start GnuPG($gpgbin): '.$!."\n");
   open(OUT,  '> infogpg.txt'           ) or Error('Can\'t open output file: infogpg.txt: '.$!);
   $/="\n";
-  while (<RGPG>) 
+  while (<RGPG>)
   {
     print OUT $_;
-    unless ($r) 
+    unless ($r)
     {
       if ( /^\s*version \d+, created (\d+), md5len 0, sigclass (?:0x[0-9a-fA-F]+|\d+)\s*$/ )
       {
         SysLog "Detected CTS: $1\n";
         $cts = int($1);
-      } elsif ( /^\s*critical hashed subpkt \d+ len \d+ \(sig expires after ((\d+)y)?((\d+)d)?((\d+)h)?(\d+)m\)\s*$/ ) 
+      } elsif ( /^\s*critical hashed subpkt \d+ len \d+ \(sig expires after ((\d+)y)?((\d+)d)?((\d+)h)?(\d+)m\)\s*$/ )
       {
         SysLog "Detected FRAME $2 $4 $6 $8\n";
         $cts += $2 * 31536000; # secs per year (60 * 60 * 24 * 365)
@@ -560,19 +560,19 @@ sub OpenPGPextractExpiryDate ($)
     }
   }
 
-  close(OUT );      
+  close(OUT );
   close(RGPG);
 
   SysLog "CTS: $cts  R: $r\n";
-  if ( $r ) 
+
+  if ( $r )
   {
     @date = gmtime($r);
     $r = sprintf('%.4i-%.2i-%.2i %.2i:%.2i:%.2i',            # date format
     $date[5] + 1900, $date[4] + 1, $date[3], # day
     $date[2],        $date[1],     $date[0], # time
     );
-                                                       
+
   }
   SysLog "$r\n";
   return $r;
@@ -605,7 +605,7 @@ sub setUsersLanguage($)
   if($lang ne "")
   {
     $ENV{"LANG"}=$lang;
-    setlocale(LC_ALL, $lang);     
+    setlocale(LC_ALL, $lang);
   } else {
     $ENV{"LANG"}="en_AU";
     setlocale(LC_ALL, "en_AU");
@@ -642,7 +642,7 @@ sub sendmail($$$$$$$)
   my ($to, $subject, $message, $from, $replyto, $toname, $fromname)=@_;
   my $errorsto="returns\@cacert.org";
   my $extra="";
-  
+
 
   # sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
   my @lines=split("\n",$message);
@@ -653,14 +653,14 @@ sub sendmail($$$$$$$)
     if($line eq ".")
     {
       $message .= " .\n";
-    } else 
+    } else
     {
       $message .= $line."\n";
-    } 
+    }
   }
 
   $fromname = $from if($fromname eq "");
-               
+
   my @bits = split(",", $from);
   $from = addslashes($bits['0']);
   $fromname = addslashes($fromname);
@@ -672,7 +672,7 @@ sub sendmail($$$$$$$)
   SysLog "SMTP: ".<$smtp>;
   print $smtp "MAIL FROM:<returns\@cacert.org>\r\n";
   SysLog "MAIL FROM: ".<$smtp>;
+
   @bits = split(",", $to);
   foreach my $user (@bits)
   {
@@ -707,7 +707,7 @@ sub sendmail($$$$$$$)
        print $smtp "Content-Type: text/plain; charset=\"utf-8\"\r\n";
        print $smtp "Content-Transfer-Encoding: 8bit\r\n";
   }
-  else 
+  else
   {
        print $smtp "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
        print $smtp "Content-Transfer-Encoding: quoted-printable\r\n";
@@ -756,7 +756,7 @@ sub HandleCerts($$)
     {
       #Weird SQL structure ...
       my @sqlres=$dbh->selectrow_array("select memid from domains where id='".int($row{'domid'})."'");
-      $row{'memid'}=$sqlres[0]; 
+      $row{'memid'}=$sqlres[0];
       SysLog("Fetched memid: $row{'memid'}\n") if($debug);
     }
 
@@ -832,7 +832,7 @@ sub HandleCerts($$)
       SysLog "SAN: --$SAN--\n" if($debug);
       SysLog "memid: $row{'memid'}\n" if($debug);
 
-      my $days=$org?($server?(365*2):365):calculateDays($row{"memid"});
+      my $days=$org?30:calculateDays($row{"memid"});
 
       my $md_id = 0;
       $md_id = 1 if( $row{'md'} eq "md5");
@@ -857,7 +857,7 @@ sub HandleCerts($$)
           print OUT $crt;
           close OUT;
           system "$opensslbin x509 -in $crtname.der -inform der -out $crtname";
-        }      
+        }
       }
       else
       {
@@ -901,7 +901,7 @@ sub HandleCerts($$)
       $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
       sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
     }
-    else 
+    else
     {
       SysLog("Could not find the issued certificate. $crtname ".$row{"id"}."\n");
       $dbh->do("update `$table` set warning=warning+1 where `id`='".$row{'id'}."'");
@@ -914,7 +914,7 @@ sub DoCRL($$)
 {
   my $crl=$_[0];
   my $crlname=$_[1];
-  
+
   if(length($crl))
   {
     if($crl=~m/^-----BEGIN X509 CRL-----/)
@@ -929,7 +929,7 @@ sub DoCRL($$)
       open OUT,">$crlname.patch";
       print OUT $crl;
       close OUT;
-      my $res=system "xdelta patch $crlname.patch $crlname $crlname.tmp"; 
+      my $res=system "xdelta patch $crlname.patch $crlname $crlname.tmp";
       #print "xdelta res: $res\n";
       if($res==512)
       {
@@ -939,7 +939,7 @@ sub DoCRL($$)
       }
     }
 
-    my $res=`openssl crl -verify -in $crlname.tmp -inform der -noout 2>&1`;    
+    my $res=`openssl crl -verify -in $crlname.tmp -inform der -noout 2>&1`;
     SysLog "verify: $res\n";
     if($res=~m/verify OK/)
     {
@@ -1023,17 +1023,29 @@ sub RevokeCerts($$)
 
       if($result)
       {
-        setUsersLanguage($row{memid});
-
-        my %user=getUserData($row{memid});
-
         $dbh->do("update `$table` set `revoked`=now() where `id`='".$row{'id'}."'");
 
-        my $body = _("Hi")." $user{fname},\n\n";
-        $body .= sprintf(_("Your certificate for %s has been revoked, as per request.")."\n\n", $row{'CN'});
-        $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
-       SysLog("Sending email to ".$user{"email"}."\n") if($debug);
-        sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+        if($org eq "")
+        {
+          if($server)
+          {
+            my @a=$dbh->selectrow_array("select `memid` from `domains` where `id`='".int($row{domid})."'");
+            sendRevokeMail($a[0],  $row{'CN'}, $row{'serial'});
+          }
+          else
+          {
+            sendRevokeMail($row{memid}, $row{'CN'}, $row{'serial'});
+          }
+        }
+        else
+        {
+          my $orgsth = $dbh->prepare("select `memid` from `org` where `orgid`='".int($row{orgid})."'");
+          $orgsth->execute();
+          while ( my ($memid) = $orgsth->fetchrow_array() )
+          {
+            sendRevokeMail($memid, $row{'CN'}, $row{'serial'});
+          }
+        }
       }
 
     }
@@ -1046,6 +1058,21 @@ sub RevokeCerts($$)
 
 }
 
+sub sendRevokeMail()
+{
+    my $memid = $_[0];
+    my $certName = $_[1];
+    my $serial = $_[2];
+    setUsersLanguage($memid);
+
+    my %user=getUserData($memid);
+
+    my $body = _("Hi")." $user{fname},\n\n";
+    $body .= sprintf(_("Your certificate for '%s' with the serial number '%s' has been revoked, as per request.")."\n\n", $certName, $serial);
+    $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+    SysLog("Sending email to ".$user{"email"}."\n") if($debug);
+    sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+}
 
 
 
@@ -1057,25 +1084,30 @@ sub HandleGPG()
   while ( $rowdata = $sth->fetchrow_hashref() )
   {
     my %row=%{$rowdata};
-  
+
     my $prefix="gpg";
     my $short=int($row{'id'}/1000);
-    my $csrname = "../csr/$prefix-".$row{'id'}.".csr";
-    $csrname = "../csr/$prefix/$short/$prefix-".$row{'id'}.".csr" if($newlayout);
-    SysLog("New Layout: "."../csr/$prefix/$short/$prefix-".$row{'id'}.".csr\n");
+
+    my $dirname="../csr";
+    $dirname="../csr/$prefix/$short" if ($newlayout);
+
+    #Ensure the directory exists
+    mkdir $dirname, 0755;
+
+    my $csrname = "$dirname/$prefix-".$row{'id'}.".csr";
+    SysLog("New Layout: $csrname\n");
 
     #my $crtname = "../crt/$prefix-".$row{'id'}.".crt";
     my $crtname=$csrname; $crtname=~s/^\.\.\/csr/..\/crt/; $crtname=~s/\.csr$/.crt/;
     SysLog("New Layout: $crtname\n");
 
-
     #my $csrname = "../csr/gpg-".$row{'id'}.".csr";
     #my $crtname = "../crt/gpg-".$row{'id'}.".crt";
-  
+
     SysLog "Opening $csrname\n";
-  
+
     my $crt="";
-  
+
     if(-s $csrname && open(IN,"<$csrname"))
     {
       undef $/;
@@ -1101,12 +1133,12 @@ sub HandleGPG()
     {
       SysLog "Opening $crtname\n";
       setUsersLanguage($row{memid});
-  
+
       my $date=OpenPGPextractExpiryDate($crtname);
       my %user=getUserData($row{memid});
-  
+
       $dbh->do("update `gpg` set `crt`='$crtname', issued=now(), `expire`='$date' where `id`='".$row{'id'}."'");
-  
+
       my $body = _("Hi")." $user{fname},\n\n";
       $body .= sprintf(_("Your CAcert signed key for %s is available online at:")."\n\n", $row{'email'});
       $body .= "https://www.cacert.org/gpg.php?id=3&cert=$row{id}\n\n";
@@ -1153,5 +1185,5 @@ while ( -f "./client.pl-active" )
   my $timestamp=strftime("%m%d%H%M%Y.%S",gmtime);
   Request($ver,0,0,0,0,0,0,0,$timestamp,"","");
   sleep(1);
-  usleep(1700000); 
+  usleep(1700000);
 }
index 94f09fe..d80c46e 100644 (file)
@@ -2,6 +2,5 @@ client.pl       The real client, running on the webserver
 commdaemon     Script to run client.pl or server.pl
 commmodule     Script for startup/shutdown of CommModule from /etc/init.d
 logclean.sh    Maintenance script for logfiles generated by CommModule
-serial.conf     Serial Port configuration file
+serial.conf    Serial Port configuration file
 server.pl      The real server, running on the signing server
-usbclient.pl   Obsoleted USB version of client.pl above
diff --git a/CommModule/serial.conf b/CommModule/serial.conf
deleted file mode 100755 (executable)
index bd9980c..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-Device::SerialPort_Configuration_File -- DO NOT EDIT --
-/dev/ttyUSB0
-
-C_CFLAG,7346
-C_IFLAG,0
-C_ISPEED,4098
-C_LFLAG,2608
-C_OFLAG,4
-C_OSPEED,4098
-C_VERASE,127
-C_VQUIT,28
-C_VSUSP,26
-C_VINTR,3
-C_VSTOP,19
-C_VSTART,17
-C_VKILL,21
-C_VMIN,0
-C_VEOF,4
-C_VEOL,0
-C_VTIME,0
-CFG_1,none
-RCONST,0
-CFG_2,none
-HNAME,localhost
-ALIAS,/dev/ttyUSB0
-CFG_3,none
-U_MSG,0
-DATYPE,raw
-E_MSG,0
-HADDR,0
-RTOT,0
-DVTYPE,none
index 6084042..abc1a1c 100755 (executable)
@@ -1002,7 +1002,7 @@ my @ready=$sel->can_read($starttime);
 my $count=0;
 
 #As soon as the client connected successfully, the client has to send a request faster than every 10 seconds
-while(@ready = $sel->can_read(15) && -f "./server.pl-active")
+while((@ready = $sel->can_read(15)) && -f "./server.pl-active")
 {
   my $data="";
   #my $length=read SER,$data,1;
diff --git a/CommModule/usbclient.pl b/CommModule/usbclient.pl
deleted file mode 100755 (executable)
index 3cbe2c3..0000000
+++ /dev/null
@@ -1,1019 +0,0 @@
-#!/usr/bin/perl -w
-
-# CommModule - CAcert Communication module
-# Copyright (C) 2004-2008  CAcert Inc.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; version 2 of the License.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-
-# Production Client / CommModule
-
-use strict;
-use Device::USB;
-use POSIX;
-use Time::HiRes q(usleep);
-use File::CounterFile;
-use File::Copy;
-use DBI;
-use Locale::gettext;
-use IO::Socket;
-use MIME::Base64;
-use Digest::SHA1 qw(sha1_hex sha1);
-
-#Protocol version:
-my $ver=1;
-
-#Debugging does not delete work-files for later inspection
-my $debug=0;
-
-#Paranoid exists the program on a malicious request
-my $paranoid=1;
-
-#Location of the openssl and gpg binaries
-my $gpgbin="/usr/bin/gpg";
-my $opensslbin="/usr/bin/openssl";
-
-my $mysqlphp="/home/cacert/www/includes/mysql.php";
-
-my %revokefile=(2=>"../www/class3-revoke.crl",1=>"../www/revoke.crl",0=>"../www/revoke.crl");
-
-#USB-Link settings
-my $PACKETSIZE=0x100;
-my $SALT="Salz";
-my $HASHSIZE=20;
-
-#End of configurations
-
-########################################################
-
-
-#Reads a while file and returns the content
-#Returns undef on failure
-sub readfile($)
-{
-  my $olds=$/;
-  my $content=undef;
-  if(open READIN,"<$_[0]")
-  {
-    binmode READIN;
-    undef $/;
-    $content=<READIN>;
-    close READIN;
-    $/=$olds;
-  }
-  return $content;
-}
-
-#Writes/Overwrites a file with content.
-#Returns 1 on success, 0 on failure.
-sub writefile($$)
-{
-  if(open WRITEOUT,">$_[0]")
-  {
-    binmode WRITEOUT;
-    print WRITEOUT $_[1];
-    close WRITEOUT;
-    return 1;
-  }
-  return 0;
-}
-
-#mkdir "revokehashes";
-foreach (keys %revokefile)
-{
-  my $revokehash=sha1_hex(readfile($revokefile{$_}));
-  print "Root $_: Hash $revokefile{$_} = $revokehash\n";
-}
-
-my %monarr = ("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
-
-my $content=readfile($mysqlphp);
-my $password="";$password=$1 if($content=~m/mysql_connect\("[^"]+",\s*"\w+",\s*"(\w+)"/);
-$content="";
-
-my $dbh = DBI->connect("DBI:mysql:cacert:localhost",$password?"cacert":"",$password, { RaiseError => 1, AutoCommit => 1 }) || die ("Error with the database connection.\n");
-
-
-#Logging functions:
-sub SysLog($)
-{
-  my @ltime=localtime;
-  my $date=strftime("%Y-%m-%d",@ltime);
-  open LOG,">>logfile$date.txt";
-  return if(not defined($_[0]));
-  my $timestamp=strftime("%Y-%m-%d %H:%M:%S",@ltime);
-  #$syslog->write($_[0]."\x00");
-  print LOG "$timestamp $_[0]";
-  print "$timestamp $_[0]";
-  flush LOG;
-  close LOG;
-}
-
-
-sub Error($)
-{
-  SysLog($_[0]);
-  if($paranoid)
-  {
-    die $_[0];
-  }
-}
-
-
-my $timestamp=strftime("%Y-%m-%d %H:%M:%S",localtime);
-
-
-sub mysql_query($)
-{
-  $dbh->do($_[0]);
-}
-
-sub trim($)
-{
-  my $new=$_[0];
-  $new=~s/^\s*//;
-  $new=~s/\s*$//;
-  return($new);
-}
-
-sub addslashes($)
-{
-  my $new=$_[0];
-  $new=~s/['"\\]/\\$1/g;
-  return($new);
-}
-
-sub recode
-{
-  return $_[1];
-}
-
-
-#Hexdump function: Returns the hexdump representation of a string
-sub hexdump($)
-{
-  return "" if(not defined($_[0]));
-  my $content="";
-  $content.=sprintf("%02X ",unpack("C",substr($_[0],$_,1))) foreach (0 .. length($_[0])-1);
-  return $content;
-}
-
-#pack3 packs together the length of the data in 3 bytes and the data itself, size limited to 16MB. In case the data is more than 16 MB, it is ignored, and a 0 Byte block is transferred
-sub pack3
-{
-  return "\x00\x00\x00" if(!defined($_[0]));
-  my $data=(length($_[0]) >= 2**24)? "":$_[0];
-  my $len=pack("N",length($data));
-  #print "len: ".length($data)."\n";
-  return substr($len,1,3).$data;
-}
-
-
-#unpack3 unpacks packed data.
-sub unpack3($)
-{
-  return undef if((not defined($_[0])) or length($_[0])<3);
-  #print "hexdump: ".hexdump("\x00".substr($_[0],0,3))."\n";
-  my $len=unpack("N","\x00".substr($_[0],0,3));
-  #print "len3: $len length(): ".length($_[0])." length()-3: ".(length($_[0])-3)."\n";
-  return undef if(length($_[0])-3 != $len);
-  return substr($_[0],3);
-}
-
-
-#unpack3array extracts a whole array of concatented packed data.
-sub unpack3array($)
-{
-  my @retarr=();
-  if((not defined($_[0])) or length($_[0])<3)
-  {
-    SysLog "Datenanfang kaputt\n";
-    return ();
-  }
-  my $dataleft=$_[0];
-  while(length($dataleft)>=3)
-  {
-    #print "hexdump: ".hexdump("\x00".substr($dataleft,0,3))."\n";
-    my $len=unpack("N","\x00".substr($dataleft,0,3));
-    #print "len3: $len length(): ".length($dataleft)." length()-3: ".(length($dataleft)-3)."\n";
-    if(length($dataleft)-3 < $len)
-    {
-      SysLog "Datensatz abgeschnitten\n";
-      return ();
-    }
-    push @retarr, substr($dataleft,3,$len);
-    $dataleft=substr($dataleft,3+$len);
-  }
-  if(length($dataleft)!=0)
-  {
-    SysLog "Ende abgeschnitten\n";
-    return ();
-  }
-  return @retarr;
-}
-
-#Pack4 packs and secret-key signs some data.
-sub pack4($)
-{
-  return pack("N",length($_[0])).$_[0].sha1($SALT.$_[0]);
-}
-
-
-
-
-
-$timestamp=strftime("%Y-%m-%d %H:%M:%S",localtime);
-
-SysLog("Starting Server at $timestamp\n");
-
-$SALT=readfile(".salt.key");
-
-SysLog("Opening USB-Link interface:\n");
-
-#Opening USB device:
-my $usb = Device::USB->new();
-my @list=$usb->list_devices(0x067b,0x2501);
-my $dev = $list[0];
-if(defined($dev))
-{
-  #print "USB-Link Device found: ", $dev->filename(), "\n";
-  if($dev->open())
-  {
-    #print "\t", $dev->manufacturer(), ": ", $dev->product(), "\n";
-    $dev->claim_interface(0);
-
-    my $buffer="  ";
-
-    $dev->control_msg(0xc0 , 0xfb, 0, 0, $buffer, 2, 1000);
-
-    if($buffer ne "\x04\x08" and $buffer ne "\x0c\x04" and $buffer ne "\x00\x0c" and $buffer ne "\x04\x0c")
-    {
-      print "Please plug the USB-Link cable into the other computer.\n";
-    }
-    else
-    {
-      print "USB-Link ok.\n";
-    }
-  }
-  else
-  {
-    print "Unable to  work with USB-Link device: $!\n";
-  }
-}
-else
-{
-  print "USB-Link Device not found. Please plug the cable into this computer.\n";
-}
-
-
-
-
-
-
-#sends a single packet (pack4 encoded). Returns the returncode
-sub send_packet($)
-{
-  if((14+length($_[0])+$HASHSIZE) > $PACKETSIZE)
-  {
-    return -1;
-  }
-  # 4 Bytes Length, N Bytes Data, 20 Bytes SHA1 Hash, 0 Padding
-  my $data="CommModule".pack4($_[0]);
-  $data.=("\x00"x($PACKETSIZE-length($data)));
-  my $ret=$dev->bulk_write(0x2,$data,length($data),1000);
-  print "Send-result: $ret\n";
-  return $ret;
-}
-
-#Receives several consecutive packets. Returns the concatenated payload
-sub receive_packets()
-{
-  print "Receiving packets ...\n";
-  my $collectedpayload="";
-  my $done=0;
-  while(!$done)
-  {
-    my $data=" "x$PACKETSIZE;
-    my $re=$dev->bulk_read(0x83,$data,length($data),10000);
-    writefile("usbpacket.dat",$data);
-    print "Read: $re Bytes: ".length($data)."\n";
-    if($re > 0)
-    {
-      $data=~s/^.*?CommModule//s;
-      my $len=unpack("N",substr($data,0,4));
-      print "len: $len\n";
-      if($len>=0 and $len<=$PACKETSIZE-$HASHSIZE-4)
-      {
-        my $payload=substr($data,4,$len);
-        if(sha1($SALT.$payload) eq substr($data,4+$len,$HASHSIZE))
-        {
-          print "Hash OK!\n";
-          $collectedpayload.=substr($payload,1);
-          $done=1 if(substr($payload,0,1)eq "0");
-        }
-        else
-        {
-          print "Hash NOT OK: ".sha1_hex($SALT.$payload)." vs. ".hexdump(substr($data,4+$len,$HASHSIZE))." !\n";
-          return "";
-        }
-      }
-    }
-    elsif($re == 0)
-    {
-      print "USB-Link cable disconnected?\n";
-      #return "";
-    }
-  }
-  print "Receiving done.\n";
-  return $collectedpayload;
-}
-
-
-
-
-my $MAXCHUNK=$PACKETSIZE-100;
-
-#Sends data over the USB-Link, without handshaking
-sub SendPackets($)
-{
-  print "Sending Packets ...\n";
-  my $data=pack4($_[0]);
-  my $done=0;
-  return if(!defined($data) or !length($data));
-
-  while(!$done)
-  {
-    while(length($data)>0)
-    {
-      my $d=substr($data,0,$MAXCHUNK);
-      if(length($data)>$MAXCHUNK)
-      {
-        send_packet("1".$d);
-        $data=substr($data,$MAXCHUNK);
-      }
-      else
-      {
-        send_packet("0".$d);
-        $data="";
-      }
-    }
-    $done=1;
-  }
-  print "Sending Packets done.\n";
-}
-
-#Receives several packets, verifies the secret key signature and extracts the payload
-#Returns the payload
-sub Receive
-{
-  my $data=receive_packets();
-  if (!defined($data) or length($data)<4)
-  {
-    print "Received data too short!\n";
-    return "";
-  }
-  my $len=unpack("N",substr($data,0,4));
-  if($len != (length($data)-$HASHSIZE-4))
-  {
-    print "Length field does not match data on Receive!\n";
-    return "";
-  }
-  my $payload=substr($data,4,$len);
-  if(sha1($SALT.$payload) ne substr($data,4+$len,$HASHSIZE))
-  {
-    print "Hash on Receive is BROKEN!\n";
-    return "";
-  }
-  return $payload;
-}
-
-
-
-
-# @result(Version,Action,Errorcode,Response)=Request(Version=1,Action=1,System=1,Root=1,Configuration="...",Parameter="...",Request="...");
-sub Request($$$$$$$$$$$)
-{
-  print "Version: $_[0] Action: $_[1] System: $_[2] Root: $_[3] Config: $_[4]\n";
-  $_[3]=0 if($_[3]<0);
-  SendPackets(pack3(pack3(pack("C*",$_[0],$_[1],$_[2],$_[3],$_[4],$_[5],$_[6]>>8,$_[6]&255,$_[7])).pack3($_[8]).pack3($_[9]).pack3($_[10])));
-  my $data=Receive();
-  if(defined($data) and length($data)>6)
-  {
-    my @fields=unpack3array(substr($data,3));
-
-    SysLog "Answer from Server: ".hexdump($data)."\n" if($debug);
-
-    #writefile("result.dat",$data);
-
-    return $fields[1];
-  }
-  return "";
-}
-
-
-sub calculateDays($)
-{
-  if($_[0])
-  {
-    my @sum = $dbh->selectrow_array("select sum(`points`) as `total` from `notary` where `to`='".$_[0]."' group by `to`");
-    SysLog("Summe: $sum[0]\n") if($debug);
-
-    return ($sum[0]>=50)?730:180;
-  }
-  return 180;
-}
-
-sub X509extractSAN($)
-{
-  my @bits = split("/", $_[0]);
-  my $SAN="";
-  my $newsubject="";
-  foreach my $val(@bits)
-  {
-    my @bit=split("=",$val);
-    if($bit[0] eq "subjectAltName")
-    {
-      $SAN.="," if($SAN ne "");
-      $SAN.= trim($bit[1]);
-    } 
-    else 
-    {
-      $newsubject .= "/".$val;
-    }
-  }
-  $newsubject=~s{^//}{/};
-  $newsubject=~s/[\n\r\t\x00"\\']//g;
-  $SAN=~s/[ \n\r\t\x00"\\']//g;
-  return($SAN,$newsubject); 
-}
-
-sub X509extractExpiryDate($)
-{
-  # TIMEZONE ?!?
-  my $data=`$opensslbin x509 -in "$_[0]" -noout -enddate`;
-
-  #notAfter=Aug  8 10:26:34 2007 GMT
-  if($data=~m/notAfter=(\w{2,4}) *(\d{1,2}) *(\d{1,2}:\d{1,2}:\d{1,2}) (\d{4}) GMT/)
-  {
-    my $date="$4-".$monarr{$1}."-$2 $3";
-    SysLog "Expiry Date found: $date\n" if($debug);
-    return $date;
-  }
-  else
-  {
-    SysLog "Expiry Date not found: $data\n";
-  }
-  return "";
-}
-sub X509extractSerialNumber($)
-{
-  # TIMEZONE ?!?
-  my $data=`$opensslbin x509 -in "$_[0]" -noout -serial`;
-  if($data=~m/serial=([0-9A-F]+)/)
-  {
-    return $1;
-  }
-  return "";
-}
-
-sub OpenPGPextractExpiryDate ($) 
-{
-  my $r="";
-  my $cts;
-  my @date;
-  open(RGPG, $gpgbin.' -vv '.$_[0].' 2>&1 |') or Error('Can\'t start GnuPG($gpgbin): '.$!."\n");
-  open(OUT,  '> infogpg.txt'           ) or Error('Can\'t open output file: infogpg.txt: '.$!);
-  $/="\n";
-  while (<RGPG>) 
-  {
-    print OUT $_;
-    unless ($r) 
-    {
-      if ( /^\s*version \d+, created (\d+), md5len 0, sigclass \d+\s*$/ ) 
-      {
-        SysLog "Detected CTS: $1\n";
-        $cts = int($1);
-      } elsif ( /^\s*critical hashed subpkt \d+ len \d+ \(sig expires after ((\d+)y)?((\d+)d)?((\d+)h)?(\d+)m\)\s*$/ ) 
-      {
-        SysLog "Detected FRAME $2 $4 $6 $8\n";
-        $cts += $2 * 31536000; # secs per year (60 * 60 * 24 * 365)
-        $cts += $4 * 86400;    # secs per day  (60 * 60 * 24)
-        $cts += $6 * 3600;     # secs per hour (60 * 60)
-        $cts += $8 * 60;       # secs per min  (60)
-        $r    = $cts;
-      }
-      elsif(/version/)
-      {
-        SysLog "Detected VERSION\n";
-      }
-    }
-  }
-
-  close(OUT );      
-  close(RGPG);
-
-  SysLog "CTS: $cts  R: $r\n";
-  if ( $r ) 
-  {
-    @date = gmtime($r);
-    $r = sprintf('%.4i-%.2i-%.2i %.2i:%.2i:%.2i',            # date format
-    $date[5] + 1900, $date[4] + 1, $date[3], # day
-    $date[2],        $date[1],     $date[0], # time
-    );
-                                                       
-  }
-  SysLog "$r\n";
-  return $r;
-}
-
-
-# Sets the locale according to the users preferred language
-sub setUsersLanguage($)
-{
-  my $lang="de_DE"; 
-  print "Searching for the language of the user $_[0]\n";
-  my @a=$dbh->selectrow_array("select language from users where id='".int($_[0])."'");
-  $lang = $1 if($a[0]=~m/(\w+_[\w.@]+)/);
-
-  SysLog "The users preferred language: $lang\n";
-
-  if($lang ne "")
-  {
-    $ENV{"LANG"}=$lang;
-    setlocale(LC_ALL, $lang);     
-  } else {
-    $ENV{"LANG"}="en_AU";
-    setlocale(LC_ALL, "en_AU");
-  }
-}
-
-
-sub getUserData($)
-{
-  my $sth = $dbh->prepare("select * from users where id='$_[0]'");
-  $sth->execute();
-  #SysLog "USER DUMP:\n";
-  while ( my $rowdata = $sth->fetchrow_hashref() )
-  {
-    my %tmp=%{$rowdata};
-    #foreach (sort keys %tmp)
-    #{
-      #SysLog "  $_ -> $tmp{$_}\n";
-    #}
-    return %tmp;
-  }
-  return ();
-}
-
-
-sub _($)
-{
-  return gettext($_[0]);
-}
-
-sub sendmail($$$$$$$)
-{
-  my ($to, $subject, $message, $from, $replyto, $toname, $fromname)=@_;
-  my $errorsto="returns\@cacert.org";
-  my $extra="";
-  
-
-  # sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
-  my @lines=split("\n",$message);
-  $message = "";
-  foreach my $line (@lines)
-  {
-    $line = trim($line);
-    if($line eq ".")
-    {
-      $message .= " .\n";
-    } else 
-    {
-      $message .= $line."\n";
-    } 
-  }
-
-  $fromname = $from if($fromname eq "");
-               
-  my @bits = split(",", $from);
-  $from = addslashes($bits['0']);
-  $fromname = addslashes($fromname);
-
-  my $smtp = IO::Socket::INET->new(PeerAddr => 'localhost:25');
-  $/="\n";
-  SysLog "SMTP: ".<$smtp>."\n";
-  print $smtp "HELO hlin.cacert.org\r\n";
-  SysLog "SMTP: ".<$smtp>."\n";
-  print $smtp "MAIL FROM: <returns\@cacert.org>\r\n";
-  SysLog "MAIL FROM: ".<$smtp>."\n";
-  @bits = split(",", $to);
-  foreach my $user (@bits)
-  {
-    print $smtp "RCPT TO: <".trim($user).">\r\n";
-    SysLog "RCPT TO: ".<$smtp>."\n";
-  }
-  print $smtp "DATA\r\n";
-  SysLog "DATA: ".<$smtp>."\n";
-
-  print $smtp "X-Mailer: CAcert.org Website\r\n";
-  print $smtp "X-OriginatingIP: ".$ENV{"REMOTE_ADDR"}."\r\n";
-  print $smtp "Sender: $errorsto\r\n";
-  print $smtp "Errors-To: $errorsto\r\n";
-  if($replyto ne "")
-  {
-       print $smtp "Reply-To: $replyto\r\n";
-  }
-  else
-  {
-       print $smtp "Reply-To: $from\r\n";
-  }
-  print $smtp "From: $from ($fromname)\r\n";
-  print $smtp "To: $to\r\n";
-  my $newsubj=encode_base64(recode("html..utf-8", trim($subject)));
-  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
-  $newsubj=~s/\n*$//;
-  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
-  print $smtp "Subject: =?utf-8?B?$newsubj?=\r\n";
-  print $smtp "Mime-Version: 1.0\r\n";
-  if($extra eq "")
-  {
-       print $smtp "Content-Type: text/plain; charset=\"utf-8\"\r\n";
-       print $smtp "Content-Transfer-Encoding: 8bit\r\n";
-  } else {
-       print $smtp "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
-       print $smtp "Content-Transfer-Encoding: quoted-printable\r\n";
-       print $smtp "Content-Disposition: inline\r\n";
-  };
-#      print $smtp "Content-Transfer-Encoding: BASE64\r\n";
-  print $smtp "\r\n";
-#              print $smtp chunk_split(encode_base64(recode("html..utf-8", $message)))."\r\n.\r\n";
-  print $smtp recode("html..utf-8", $message)."\r\n.\r\n";
-  SysLog "ENDOFTEXT: ".<$smtp>."\n";
-  print $smtp "QUIT\n";
-  SysLog "QUIT: ".<$smtp>."\n";
-  close($smtp);
-}
-
-
-sub HandleCerts($$)
-{
-  my $org=$_[0]?"org":"";
-  my $server=$_[1];
-
-  my $table=$org.($server?"domaincerts":"emailcerts");
-
-  my $sth = $dbh->prepare("select * from $table where crt_name='' and csr_name!='' ");
-  $sth->execute();
-  #$rowdata;
-  while ( my $rowdata = $sth->fetchrow_hashref() )
-  {
-    my %row=%{$rowdata};
-
-    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
-    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
-
-
-    if($server)
-    {
-      #Weird SQL structure ...
-      my @sqlres=$dbh->selectrow_array("select memid from domains where id='".int($row{'domid'})."'");
-      $row{'memid'}=$sqlres[0]; 
-      SysLog("Fetched memid: $row{'memid'}\n") if($debug);
-    }
-
-    SysLog "Opening $csrname\n";
-
-    my $crt="";
-
-    my $profile=0;
-
-    #   "0"=>"client.cnf",
-    #   "1"=>"client-org.cnf",
-    #   "2"=>"client-codesign.cnf",
-    #   "3"=>"client-machine.cnf",
-    #   "4"=>"client-ads.cnf",
-    #   "5"=>"server.cnf",
-    #   "6"=>"server-org.cnf",
-    #   "7"=>"server-jabber.cnf",
-    #   "8"=>"server-ocsp.cnf",
-    #   "9"=>"server-timestamp.cnf",
-    #   "10"=>"proxy.cnf",
-    #   "11"=>"subca.cnf"
-
-
-    if($row{"type"} =~ m/^(8|9)$/)
-    {
-      $profile=$row{"type"};
-    }
-    elsif($org)
-    {
-      if($row{'codesign'})
-      {
-        $profile=2; ## TODO!
-      }
-      elsif($server)
-      {
-        $profile=6;
-      }
-      else
-      {
-        $profile=1;
-      }
-    }
-    else
-    {
-      if($row{'codesign'})
-      {
-        $profile=2;
-      }
-      elsif($server)
-      {
-        $profile=5;
-      }
-      else
-      {
-        $profile=0;
-      }
-
-
-    }
-
-
-
-    if(open(IN,"<$csrname"))
-    {
-      undef $/;
-      my $content=<IN>;
-      close IN;
-      SysLog "Read.\n" if($debug);
-      SysLog "Subject: --$row{'subject'}--\n" if($debug);
-
-      my ($SAN,$subject)=X509extractSAN($row{'subject'});
-      SysLog "Subject: --$subject--\n" if($debug);
-      SysLog "SAN: --$SAN--\n" if($debug);
-      SysLog "memid: $row{'memid'}\n" if($debug);
-
-      my $days=$org?($server?(365*2):365):calculateDays($row{"memid"});
-
-
-      $crt=Request($ver,1,1,$row{'rootcert'}-1,$profile,$row{'md'}eq"sha1"?2:0,$days,$row{'keytype'}eq"NS"?1:0,$content,$SAN,$subject);
-      if(length($crt))
-      {
-        if($crt=~m/^-----BEGIN CERTIFICATE-----/)
-        {
-          open OUT,">$crtname";
-          print OUT $crt;
-          close OUT;
-        }
-        else
-        {
-          open OUT,">$crtname.der";
-          print OUT $crt;
-          close OUT;
-          system "$opensslbin x509 -in $crtname.der -inform der -out $crtname";
-        }      
-      }
-
-    }
-    else
-    {
-      print "Error: $! Konnte $csrname nicht laden\n";
-    }
-
-
-
-    if(-s $crtname)
-    {
-      SysLog "Opening $crtname\n";
-
-      my $date=X509extractExpiryDate($crtname);
-      my $serial=X509extractSerialNumber($crtname);
-
-      setUsersLanguage($row{memid});
-
-      my %user=getUserData($row{memid});
-
-      foreach (sort keys %user)
-      {
-        SysLog "  $_ -> $user{$_}\n" if($debug);
-      }
-
-      SysLog("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'\n");
-
-      $dbh->do("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'");
-
-      my $body = _("Hi")." $user{fname},\n\n";
-      $body .= sprintf(_("You can collect your certificate for %s by going to the following location:")."\n\n", $row{'email'});
-      $body .= "https://www.cacert.org/account.php?id=".($server?"15":"6")."&cert=$row{id}\n\n";
-      $body .= _("If you havent imported CAcert´s root certificate, please go to:")."\n";
-      $body .= "https://www.cacert.org/index.php?id=3\n";
-      $body .= "Root cert fingerprint = A6:1B:37:5E:39:0D:9C:36:54:EE:BD:20:31:46:1F:6B\n";
-      $body .= "Root cert fingerprint = 135C EC36 F49C B8E9 3B1A B270 CD80 8846 76CE 8F33\n\n";
-      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
-      sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
-    } else {
-      $dbh->do("delete from `$table` where `id`='".$row{'id'}."'");
-    }
-  }
-}
-
-sub HandleNewCRL($$)
-{
-  my ($crl,$crlname)=@_;
-  if(length($crl))
-  {
-    if($crl=~m/^\%XD/)
-    {
-      writefile("$crlname.patch",$crl);
-      system "xdelta patch $crlname.patch $crlname $crlname.tmp"; 
-    }
-    elsif($crl=~m/^-----BEGIN X509 CRL-----/)
-    {
-      writefile("$crlname.pem",$crl);
-      system "$opensslbin crl -in $crlname.pem -outform der -out $crlname.tmp";
-    }
-    elsif($crl=~m/^\x30/)
-    {
-      writefile("$crlname.tmp",$crl);
-    }
-    else
-    {
-      Error "Unknown CRL format!".(substr($crl,0,5))."\n";
-    }
-    rename "$crlname.tmp","$crlname"; # Atomic move
-  }
-}
-
-
-sub RevokeCerts($$)
-{
-  my $org=$_[0]?"org":"";
-  my $server=$_[1];
-
-  my $table=$org.($server?"domaincerts":"emailcerts");
-
-  my $sth = $dbh->prepare("select * from $table where revoked='1970-01-01 10:00:01'"); # WHICH TIMEZONE?
-  $sth->execute();
-  #$rowdata;
-  while ( my $rowdata = $sth->fetchrow_hashref() )
-  {
-    my %row=%{$rowdata};
-
-    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
-    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
-    my $crlname = $revokefile{$row{'rootcert'}};
-
-    my $crt="";
-
-
-    if(open(IN,"<$crtname"))
-    {
-      undef $/;
-      my $content=<IN>;
-      close IN;
-      my $revokehash=sha1_hex(readfile($crlname));
-
-      my $crl=Request($ver,2,1,$row{'rootcert'}-1,0,0,365,0,$content,"",$revokehash);
-      HandleNewCRL($crl,$crlname);
-
-      if(-s $crlname)
-      {
-        setUsersLanguage($row{memid});
-
-        my %user=getUserData($row{memid});
-
-        $dbh->do("update `$table` set `revoked`=now() where `id`='".$row{'id'}."'");
-
-        my $body = _("Hi")." $user{fname},\n\n";
-        $body .= sprintf(_("Your certificate for %s has been revoked, as per request.")."\n\n", $row{'CN'});
-        $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
-        sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
-      }
-
-    }
-    else
-    {
-      SysLog("Error: $crtname $!\n") if($debug);
-    }
-
-  }
-
-}
-
-
-
-
-
-sub HandleGPG()
-{
-  my $sth = $dbh->prepare("select * from gpg where crt='' and csr!='' ");
-  $sth->execute();
-  my $rowdata;
-  while ( $rowdata = $sth->fetchrow_hashref() )
-  {
-    my %row=%{$rowdata};
-  
-    my $csrname = "../csr/gpg-".$row{'id'}.".csr";
-    my $crtname = "../crt/gpg-".$row{'id'}.".crt";
-  
-    SysLog "Opening $csrname\n";
-  
-    my $crt="";
-  
-    if(-s $csrname && open(IN,"<$csrname"))
-    {
-      undef $/;
-      my $content=<IN>;
-      close IN;
-      SysLog "Read.\n";
-      $crt=Request($ver,1,2,0,0,2,366,0,$content,"","");
-      if(length($crt))
-      {
-        open OUT,">$crtname";
-        print OUT $crt;
-        close OUT;
-      }
-
-    }
-    else
-    {
-      #Error("Error: $!\n");
-      next;
-    }
-
-    if(-s $crtname)
-    {
-      SysLog "Opening $crtname\n";
-      setUsersLanguage($row{memid});
-  
-      my $date=OpenPGPextractExpiryDate($crtname);
-      my %user=getUserData($row{memid});
-  
-      $dbh->do("update `gpg` set `crt`='$crtname', issued=now(), `expire`='$date' where `id`='".$row{'id'}."'");
-  
-      my $body = _("Hi")." $user{fname},\n\n";
-      $body .= sprintf(_("Your CAcert signed key for %s is available online at:")."\n\n", $row{'email'});
-      $body .= "https://www.cacert.org/gpg.php?id=3&cert=$row{id}\n\n";
-      $body .= _("To help improve the trust of CAcert in general, it's appreciated if you could also sign our key and upload it to a key server. Below is a copy of our primary key details:")."\n\n";
-      $body .= "pub 1024D/65D0FD58 2003-07-11 CA Cert Signing Authority (Root CA) <gpg\@cacert.org>\n";
-      $body .= "Key fingerprint = A31D 4F81 EF4E BD07 B456 FA04 D2BB 0D01 65D0 FD58\n\n";
-      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
-      sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
-    } else {
-      $dbh->do("delete from `gpg` where `id`='".$row{'id'}."'");
-    }
-  }
-}
-
-
-# Main program loop
-
-while(1)
-{
-  SysLog("Handling GPG database ...\n");
-#  HandleGPG();
-  SysLog("Issueing certs ...\n");
-#  HandleCerts(0,0); #personal client certs
-#  HandleCerts(0,1); #personal server certs
-#  HandleCerts(1,0); #org client certs
-#  HandleCerts(1,1); #org server certs
-#  SysLog("Revoking certs ...\n");
-#  RevokeCerts(0,0); #personal client certs
-#  RevokeCerts(0,1); #personal server certs
-#  RevokeCerts(1,0); #org client certs
-#  RevokeCerts(1,1); #org server certs
-
-  #print "Sign Request X.509, Root0\n";
-  #my $reqcontent="";
-  #Request($ver,1,1,0,5,2,365,0,$reqcontent,"","/CN=supertest.cacert.at");
-
-  SysLog("NUL Request:\n");
-  my $timestamp=strftime("%m%d%H%M%Y.%S",gmtime);
-  my $ret=Request($ver,0,0,0,0,0,0,0,$timestamp,"","");
-  print "RET: $ret\n";
-
-  SysLog("Generate regular CRLs:\n");
-  foreach my $root ((1,2))
-  {
-    my $crlname = $revokefile{$root};
-    my $revokehash=sha1_hex(readfile($crlname));
-    print "Aktueller Hash am Webserver: $revokehash\n";
-    my $crl=Request($ver,2,1,$root-1,0,0,365,0,"","",$revokehash);
-    HandleNewCRL($crl,$crlname);
-  }
-
-  usleep(700000); 
-}
diff --git a/README b/README
deleted file mode 100644 (file)
index 7f2ca78..0000000
--- a/README
+++ /dev/null
@@ -1,17 +0,0 @@
-LibreSSL Documentation
-
-(c) 2005-2008 by CAcert Inc.
-License: GNU-GPLv2
-
-System Requirements:
-Linux/POSIX
-PHP
-GetText
-UFPDF - PDF generation library from http://acko.net/node/56
-OpenSSL - X.509 toolkit from http://www.openssl.org/
-openssl-vulnkey including blacklists for all common key sizes
-GnuPG - OpenPGP toolkit from http://www.gnupg.org/
-whois - whois client from http://www.linux.it/~md/software/
-XEnroll - Enrollment Active-X control for IE5/6 from Microsoft (search for xenroll.cab)
-CommModule - CAcert Communication Module
-
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..39c9d68
--- /dev/null
+++ b/README.md
@@ -0,0 +1,19 @@
+LibreSSL Documentation
+======================
+
+(c) 2005-2013 by CAcert Inc.
+License: GNU-GPLv2
+
+## System Requirements:
+
+ * Linux/POSIX
+ * PHP 5.3
+ * GetText PECL module for PHP
+ * UFPDF - PDF generation library from http://acko.net/node/56
+ * OpenSSL - X.509 toolkit from http://www.openssl.org/
+ * openssl-vulnkey including blacklists for all common key sizes
+ * GnuPG - OpenPGP toolkit from http://www.gnupg.org/
+ * whois - whois client from http://www.linux.it/~md/software/
+ * XEnroll - Enrollment Active-X control for IE5/6 from Microsoft (search for xenroll.cab)
+ * CommModule - CAcert Communication Module
+
diff --git a/cgi-bin/siteseal.cgi b/cgi-bin/siteseal.cgi
deleted file mode 100755 (executable)
index ac28697..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/php -q
-<?
-/**
- * check site seal
- *
- * @package org.cacert.framework
- * @author Duane Groth <duane@groth.net>
- * @copyright Copyright (C) 2003-2008, {@link http://www.cacert.org/ CAcert Inc.}
- * @license GPL Version 2
- * @version $Id: siteseal.cgi,v 1.4 2008-04-06 19:44:25 root Exp $
- */
-
-if($_SERVER["HTTPS"] == "on")
-  $http = "https";
-else
-  $http = "http";
-
-/* obfuscate var names */
-srand((double)microtime()*1000000);
-$var1 = "ca1-".md5(rand(0,9999999));
-$var2 = "ca2-".md5(rand(0,9999999));
-$var3 = "ca3-".md5(rand(0,9999999));
-$var4 = "ca4-".md5(rand(0,9999999));
-$var5 = "ca5-".md5(rand(0,9999999));
-$var6 = "ca6-".md5(rand(0,9999999));
-$var7 = "ca7-".md5(rand(0,9999999));
-$var8 = "ca8-".md5(rand(0,9999999));
-$var9 = "ca9-".md5(rand(0,9999999));
-$var10 = "caa-".md5(rand(0,9999999));
-$var11 = "cab-".md5(rand(0,9999999));
-
-header("Content-Type: text/javascript");
-header("Content-Disposition: inline; filename=\"siteseal.js\"");
-
-?>
-
-var <?=$var1?> = window.location.href;
-<? // var <?=$var2?> = '<?=$http?>://www.cacert.org/certdetails.php?referer=' + <?=$var1?>; ?>
-var <?=$var2?> = '<?=$http?>://www.cacert.org';
-var <?=$var3?> = (new Date()).getTimezoneOffset();
-
-var <?=$var4?> = navigator.userAgent.toLowerCase();
-var <?=$var5?> = false;
-if (<?=$var4?>.indexOf("msid") != 1) {
-  <?=$var5?> = (<?=$var4?>.indexOf("msie 5") == -1 && <?=$var4?>.indexOf("msie 6") == -1);
-}
-
-function <?=$var6?>(e) {
-  if (document.addEventListener) {
-    if (e.target.name == '<?=$var7?>') {
-      <?=$var8?>();
-      return false;
-    }
-  } else if (document.captureEvents) {
-    if (e.target.toString().indexOf('certdetails') != -1) {
-      <?=$var8?>();
-      return false;
-    }
-  }
-  return true;
-}
-
-function <?=$var9?>() {
-  if (event.button == 1) {
-    if (<?=$var5?>) {
-      return true;
-    } else {
-      <?=$var8?>();
-      return false;
-    }
-  } else if (event.button == 2) {
-    <?=$var8?>();
-    return false;
-  }
-}
-
-function <?=$var8?>() {
-  cacertWindow = window.open(<?=$var2?>, '<?=$var10?>', config='height=420,width=523,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=yes');
-  cacertWindow.focus();
-}
-
-if (document.addEventListener) {
-  document.addEventListener('mouseup', <?=$var6?>, true);
-} else {
-  if (document.layers) {
-    document.captureEvents(Event.MOUSEDOWN);
-    document.onmousedown=<?=$var6?>;
-  }
-}
-
-document.write("<a href='" + <?=$var2?> + "' target='<?=$var10?>'  tabindex='-1' onmousedown='<?=$var9?>(); return false;'><img name='<?=$var7?>' border='0' src='<?=$http?>://www.cacert.org/sealgen.php?cert=<?=$cert?>&referer=" + <?=$var1?> + "' alt='Click to verify' oncontextmenu='return false;' /></a>"); ?>
-
diff --git a/config/ttp.ini b/config/ttp.ini
new file mode 100644 (file)
index 0000000..d0a0913
--- /dev/null
@@ -0,0 +1,6 @@
+; list of countries and the TTP CAP form to be used
+[ttp_country]
+Australia=ttp
+Puerto Rico=ttp
+US Virgin Island=ttp
+USA =ttp
\ No newline at end of file
diff --git a/crt/DIR b/crt/DIR
new file mode 100644 (file)
index 0000000..87975fb
--- /dev/null
+++ b/crt/DIR
@@ -0,0 +1 @@
+# This directory has to be writeable by the web server
diff --git a/csr/DIR b/csr/DIR
new file mode 100644 (file)
index 0000000..87975fb
--- /dev/null
+++ b/csr/DIR
@@ -0,0 +1 @@
+# This directory has to be writeable by the web server
index 497bf58..2eeca73 100644 (file)
@@ -84,6 +84,11 @@ function buildSubjectFromSession() {
        $memid = array_key_exists('memid',$_REQUEST) ? intval($_REQUEST['memid']) : 0;
        $domid = array_key_exists('domid',$_REQUEST) ? intval($_REQUEST['domid']) : 0;
 
+       $actionrequest = array_key_exists('action',$_REQUEST) ? $_REQUEST['action'] : "";
+
+       $ticketno = array_key_exists('ticketno',$_REQUEST) ? $_REQUEST['ticketno'] : "";
+       $ticketvalidation = FALSE;
+
 
        if(!$_SESSION['mconn'])
        {
@@ -146,7 +151,7 @@ function buildSubjectFromSession() {
                        exit;
                }
                $hash = make_hash();
-               $query = "insert into `email` set `email`='".$_REQUEST['email']."',`memid`='".$_SESSION['profile']['id']."',`created`=NOW(),`hash`='$hash'";
+               $query = "insert into `email` set `email`='".$_REQUEST['email']."',`memid`='".intval($_SESSION['profile']['id'])."',`created`=NOW(),`hash`='$hash'";
                mysql_query($query);
                $emailid = mysql_insert_id();
 
@@ -166,7 +171,7 @@ function buildSubjectFromSession() {
        {
                $id = 2;
                $emailid = intval($_REQUEST['emailid']);
-               $query = "select * from `email` where `id`='$emailid' and `memid`='".$_SESSION['profile']['id']."' and `hash` = '' and `deleted`=0";
+               $query = "select * from `email` where `id`='$emailid' and `memid`='".intval($_SESSION['profile']['id'])."' and `hash` = '' and `deleted`=0";
                $res = mysql_query($query);
                if(mysql_num_rows($res) <= 0)
                {
@@ -186,7 +191,7 @@ function buildSubjectFromSession() {
                                "support@cacert.org", "", "", "CAcert Support");
 
                $_SESSION['profile']['email'] = $row['email'];
-               $query = "update `users` set `email`='".$row['email']."' where `id`='".$_SESSION['profile']['id']."'";
+               $query = "update `users` set `email`='".mysql_real_escape_string($row['email'])."' where `id`='".intval($_SESSION['profile']['id'])."'";
                mysql_query($query);
                showheader(_("My CAcert.org Account!"));
                printf(_("Your default email address has been updated to '%s'."), sanitizeHTML($row['email']));
@@ -211,7 +216,7 @@ function buildSubjectFromSession() {
                                }
                                $id = intval($id);
                                $query = "select * from `email` where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."' and
-                                               `email`!='".$_SESSION['profile']['email']."'";
+                                               `email`!='".mysql_real_escape_string($_SESSION['profile']['email'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) > 0)
                                {
@@ -284,6 +289,9 @@ function buildSubjectFromSession() {
                        if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
                                $_SESSION['_config']['rootcert'] = 1;
                }
+
+               $_SESSION['_config']['hash_alg'] = HashAlgorithms::clean($_REQUEST['hash_alg']);
+
                $csr = "";
                if(trim($_REQUEST['optionalCSR']) == "")
                {
@@ -293,11 +301,8 @@ function buildSubjectFromSession() {
                        $_REQUEST['keytype'] = "MS";
                        $csr = clean_csr($_REQUEST['optionalCSR']);
                }
-               if(trim($_REQUEST['description']) != ""){
-                       $_SESSION['_config']['description']= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
-               }else{
-                       $_SESSION['_config']['description']= "";
-               }
+
+               $_SESSION['_config']['description']= trim(stripslashes($_REQUEST['description']));
        }
 
        if($oldid == 4)
@@ -321,7 +326,7 @@ function buildSubjectFromSession() {
                        if(is_array($_SESSION['_config']['addid']))
                        foreach($_SESSION['_config']['addid'] as $id)
                        {
-                               $res = mysql_query("select * from `email` where `memid`='".$_SESSION['profile']['id']."' and `id`='".intval($id)."'");
+                               $res = mysql_query("select * from `email` where `memid`='".intval($_SESSION['profile']['id'])."' and `id`='".intval($id)."'");
                                if(mysql_num_rows($res) > 0)
                                {
                                        $row = mysql_fetch_assoc($res);
@@ -340,7 +345,7 @@ function buildSubjectFromSession() {
                                showfooter();
                                exit;
                        }
-                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."'"));
+                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_SESSION['profile']['id'])."'"));
                        if($_SESSION['_config']['SSO'] == 1)
                                $emails .= "$count.emailAddress = ".$user['uniqueID']."\n";
 
@@ -384,7 +389,8 @@ function buildSubjectFromSession() {
                                                `codesign`='".intval($_SESSION['_config']['codesign'])."',
                                                `disablelogin`='".($_SESSION['_config']['disablelogin']?1:0)."',
                                                `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                        mysql_query($query);
                        $emailid = mysql_insert_id();
                        if(is_array($addys))
@@ -395,7 +401,8 @@ function buildSubjectFromSession() {
                        fputs($fp, $emails);
                        fclose($fp);
                        $challenge=$_SESSION['spkac_hash'];
-                       $res=`openssl spkac -verify -in $CSRname`;
+                       $CSRname_esc = escapeshellarg($CSRname);
+                       $res=shell_exec("openssl spkac -verify -in $CSRname_esc");
                        if(!strstr($res,"Challenge String: ".$challenge))
                        {
                                $id = $oldid;
@@ -457,7 +464,9 @@ function buildSubjectFromSession() {
                                $csrsubject .= "/emailAddress = ".$user['uniqueID'];
 
                        $tmpname = tempnam("/tmp", "id4csr");
-                       $do = `/usr/bin/openssl req -in $tmpfname -out $tmpname`; // -subj "$csr"`;
+                       $tmpfname_esc = escapeshellarg($tmpfname);
+                       $tmpname_esc = escapeshellarg($tmpname);
+                       $do = shell_exec("/usr/bin/openssl req -in $tmpfname_esc -out $tmpname_esc"); // -subj "$csr";
                        @unlink($tmpfname);
                        $csr = "";
                        $fp = fopen($tmpname, "r");
@@ -479,13 +488,14 @@ function buildSubjectFromSession() {
                        $query = "insert into emailcerts set
                                                `CN`='$defaultemail',
                                                `keytype`='".sanitizeHTML($_REQUEST['keytype'])."',
-                                               `memid`='".$_SESSION['profile']['id']."',
+                                               `memid`='".intval($_SESSION['profile']['id'])."',
                                                `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
                                                `subject`='".mysql_real_escape_string($csrsubject)."',
-                                               `codesign`='".$_SESSION['_config']['codesign']."',
+                                               `codesign`='".intval($_SESSION['_config']['codesign'])."',
                                                `disablelogin`='".($_SESSION['_config']['disablelogin']?1:0)."',
-                                               `rootcert`='".$_SESSION['_config']['rootcert']."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                        mysql_query($query);
                        $emailid = mysql_insert_id();
                        if(is_array($addys))
@@ -560,7 +570,7 @@ function buildSubjectFromSession() {
                $addy = array();
                $adds = array();
                if(strtolower(substr($newdom, -4, 3)) != ".jp")
-                       $adds = explode("\n", trim(`/usr/bin/whois $newdom|grep "@"`));
+                       $adds = explode("\n", trim(shell_exec("/usr/bin/whois $newdom|grep \"@\"")));
                if(substr($newdomain, -4) == ".org" || substr($newdomain, -5) == ".info")
                {
                        if(is_array($adds))
@@ -650,7 +660,7 @@ function buildSubjectFromSession() {
 
                $hash = make_hash();
                $query = "insert into `domains` set `domain`='".mysql_real_escape_string($_SESSION['_config']['domain'])."',
-                                       `memid`='".$_SESSION['profile']['id']."',`created`=NOW(),`hash`='$hash'";
+                                       `memid`='".intval($_SESSION['profile']['id'])."',`created`=NOW(),`hash`='$hash'";
                mysql_query($query);
                $domainid = mysql_insert_id();
 
@@ -678,7 +688,7 @@ function buildSubjectFromSession() {
                        foreach($_REQUEST['delid'] as $id)
                        {
                                $id = intval($id);
-                               $query = "select * from `domains` where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                               $query = "select * from `domains` where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) > 0)
                                {
@@ -723,19 +733,15 @@ function buildSubjectFromSession() {
                        exit;
                }
 
-               if(trim($_REQUEST['description']) != ""){
-                       $_SESSION['_config']['description']= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
-               }else{
-                       $_SESSION['_config']['description']= "";
-               }
+               $_SESSION['_config']['description']= trim(stripslashes($_REQUEST['description']));
 
                $_SESSION['_config']['tmpfname'] = tempnam("/tmp", "id10CSR");
                $fp = fopen($_SESSION['_config']['tmpfname'], "w");
                fputs($fp, $CSR);
                fclose($fp);
-               $CSR = $_SESSION['_config']['tmpfname'];
-               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep "Subject:"`);
-               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               $CSR = escapeshellarg($_SESSION['_config']['tmpfname']);
+               $_SESSION['_config']['subject'] = trim(shell_exec("/usr/bin/openssl req -text -noout -in $CSR |tr -d \"\\0\"|grep \"Subject:\""));
+               $bits = explode(",", trim(shell_exec("/usr/bin/openssl req -text -noout -in $CSR |tr -d \"\\0\"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:")));
                foreach($bits as $val)
                {
                        $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
@@ -762,6 +768,8 @@ function buildSubjectFromSession() {
                        if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
                                $_SESSION['_config']['rootcert'] = 1;
                }
+
+               $_SESSION['_config']['hash_alg'] = HashAlgorithms::clean($_REQUEST['hash_alg']);
        }
 
        if($process != "" && $oldid == 11)
@@ -806,14 +814,16 @@ function buildSubjectFromSession() {
                                                `domid`='".mysql_real_escape_string($_SESSION['_config']['rowid']['0'])."',
                                                `created`=NOW(),`subject`='".mysql_real_escape_string($subject)."',
                                                `rootcert`='".mysql_real_escape_string($_SESSION['_config']['rootcert'])."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                } elseif(array_key_exists('0',$_SESSION['_config']['altid']) && $_SESSION['_config']['altid']['0'] > 0) {
                        $query = "insert into `domaincerts` set
                                                `CN`='".mysql_real_escape_string($_SESSION['_config']['altrows']['0'])."',
                                                `domid`='".mysql_real_escape_string($_SESSION['_config']['altid']['0'])."',
                                                `created`=NOW(),`subject`='".mysql_real_escape_string($subject)."',
                                                `rootcert`='".mysql_real_escape_string($_SESSION['_config']['rootcert'])."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                } else {
                        showheader(_("My CAcert.org Account!"));
                        echo _("Domain not verified.");
@@ -867,7 +877,7 @@ function buildSubjectFromSession() {
                                $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`revoked`) as `revoke` from `domaincerts`,`domains`
                                                where `domaincerts`.`id`='$id' and
                                                `domaincerts`.`domid`=`domains`.`id` and
-                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `domains`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -886,22 +896,24 @@ function buildSubjectFromSession() {
 
                                mysql_query("update `domaincerts` set `renewed`='1' where `id`='$id'");
                                $query = "insert into `domaincerts` set
-                                               `domid`='".$row['domid']."',
+                                               `domid`='".intval($row['domid'])."',
                                                `CN`='".mysql_real_escape_string($row['CN'])."',
                                                `subject`='".mysql_real_escape_string($row['subject'])."',".
                                                //`csr_name`='".$row['csr_name']."', // RACE CONDITION
-                                               "`created`='".$row['created']."',
+                                               "`created`='".mysql_real_escape_string($row['created'])."',
                                                `modified`=NOW(),
-                                               `rootcert`='".$row['rootcert']."',
-                                               `type`='".$row['type']."',
-                                               `pkhash`='".$row['pkhash']."',
-                                               `description`='".$row['description']."'";
+                                               `rootcert`='".intval($row['rootcert'])."',
+                                               `type`='".intval($row['type'])."',
+                                               `pkhash`='".mysql_real_escape_string($row['pkhash'])."',
+                                               `description`='".mysql_real_escape_string($row['description'])."',
+                                               `md`='".HashAlgorithms::clean($row['md'])."'";
                                mysql_query($query);
                                $newid = mysql_insert_id();
                                $newfile=generatecertpath("csr","server",$newid);
                                copy($row['csr_name'], $newfile);
-                               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$newfile"|tr -d "\\0"|grep "Subject:"`);
-                               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$newfile"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+                               $newfile_esc = escapeshellarg($newfile);
+                               $_SESSION['_config']['subject'] = trim(shell_exec("/usr/bin/openssl req -text -noout -in $newfile_esc |tr -d \"\\0\"|grep \"Subject:\""));
+                               $bits = explode(",", trim(shell_exec("/usr/bin/openssl req -text -noout -in $newfile_esc |tr -d \"\\0\"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:")));
                                foreach($bits as $val)
                                {
                                        $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
@@ -930,7 +942,8 @@ function buildSubjectFromSession() {
                                        printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
                                } else {
                                        $drow = mysql_fetch_assoc($res);
-                                       $cert = `/usr/bin/openssl x509 -in $drow[crt_name]`;
+                                       $crt_name = escapeshellarg($drow['crt_name']);
+                                       $cert = shell_exec("/usr/bin/openssl x509 -in $crt_name");
                                        echo "<pre>\n$cert\n</pre>\n";
                                }
                        }
@@ -958,7 +971,7 @@ function buildSubjectFromSession() {
                                $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`revoked`) as `revoke` from `domaincerts`,`domains`
                                                where `domaincerts`.`id`='$id' and
                                                `domaincerts`.`domid`=`domains`.`id` and
-                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `domains`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -993,7 +1006,7 @@ function buildSubjectFromSession() {
                                $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`expire`) as `expired` from `domaincerts`,`domains`
                                                where `domaincerts`.`id`='$id' and
                                                `domaincerts`.`domid`=`domains`.`id` and
-                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `domains`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -1044,7 +1057,7 @@ function buildSubjectFromSession() {
                        {
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `emailcerts`
-                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                                               where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -1063,17 +1076,18 @@ function buildSubjectFromSession() {
 
                                mysql_query("update `emailcerts` set `renewed`='1' where `id`='$id'");
                                $query = "insert into emailcerts set
-                                               `memid`='".$row['memid']."',
+                                               `memid`='".intval($row['memid'])."',
                                                `CN`='".mysql_real_escape_string($row['CN'])."',
                                                `subject`='".mysql_real_escape_string($row['subject'])."',
-                                               `keytype`='".$row['keytype']."',
-                                               `csr_name`='".$row['csr_name']."',
-                                               `created`='".$row['created']."',
+                                               `keytype`='".mysql_real_escape_string($row['keytype'])."',
+                                               `csr_name`='".mysql_real_escape_string($row['csr_name'])."',
+                                               `created`='".mysql_real_escape_string($row['created'])."',
                                                `modified`=NOW(),
-                                               `disablelogin`='".$row['disablelogin']."',
-                                               `codesign`='".$row['codesign']."',
-                                               `rootcert`='".$row['rootcert']."',
-                                               `description`='".$row['description']."'";
+                                               `disablelogin`='".intval($row['disablelogin'])."',
+                                               `codesign`='".intval($row['codesign'])."',
+                                               `rootcert`='".intval($row['rootcert'])."',
+                                               `description`='".mysql_real_escape_string($row['description'])."',
+                                               `md`='".HashAlgorithms::clean($row['md'])."'";
                                mysql_query($query);
                                $newid = mysql_insert_id();
                                $newfile=generatecertpath("csr","client",$newid);
@@ -1118,7 +1132,7 @@ function buildSubjectFromSession() {
                        {
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `emailcerts`
-                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                                               where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -1150,7 +1164,7 @@ function buildSubjectFromSession() {
                        {
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`expire`) as `expired` from `emailcerts`
-                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                                               where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -1182,14 +1196,14 @@ function buildSubjectFromSession() {
                        {
                                $cid = intval(substr($id,5));
                                $dis=(array_key_exists('disablelogin_'.$cid,$_REQUEST) && $_REQUEST['disablelogin_'.$cid]=="1")?"0":"1";
-                               mysql_query("update `emailcerts` set `disablelogin`='$dis' where `id`='$cid' and `memid`='".$_SESSION['profile']['id']."'");
+                               mysql_query("update `emailcerts` set `disablelogin`='$dis' where `id`='$cid' and `memid`='".intval($_SESSION['profile']['id'])."'");
                        }
                        if(substr($id,0,14)=="check_comment_")
                        {
                                $cid = intval(substr($id,14));
                                if(!empty($_REQUEST['check_comment_'.$cid])) {
                                        $comment=trim(mysql_real_escape_string(stripslashes($_REQUEST['comment_'.$cid])));
-                                       mysql_query("update `emailcerts` set `description`='$comment' where `id`='$cid' and `memid`='".$_SESSION['profile']['id']."'");
+                                       mysql_query("update `emailcerts` set `description`='$comment' where `id`='$cid' and `memid`='".intval($_SESSION['profile']['id'])."'");
                                }
                        }
                }
@@ -1198,6 +1212,23 @@ function buildSubjectFromSession() {
                exit;
        }
 
+       if($oldid == 6 && $_REQUEST['certid'] != "")
+       {
+               if(trim($_REQUEST['description']) != ""){
+                       $description= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
+               }else{
+                       $description= "";
+               }
+
+               if(trim($_REQUEST['disablelogin']) == "1"){
+                       $disablelogin = 1;
+               }else{
+                       $disablelogin = 0;
+               }
+
+               mysql_query("update `emailcerts` set `disablelogin`='$disablelogin', `description`='$description' where `id`='".$_REQUEST['certid']."' and `memid`='".$_SESSION['profile']['id']."'");
+       }
+
        if($oldid == 13 && $process != "" && $showdetails!="")
        {
                csrf_check("perschange");
@@ -1263,10 +1294,7 @@ function buildSubjectFromSession() {
 
        if($oldid == 13 && $process != "")
        {
-               $ddquery = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
-               $ddres = mysql_query($ddquery);
-               $ddrow = mysql_fetch_assoc($ddres);
-               $_SESSION['profile']['points'] = $ddrow['total'];
+               update_points_in_profile();
 
                if($_SESSION['profile']['points'] == 0)
                {
@@ -1303,7 +1331,7 @@ function buildSubjectFromSession() {
                                                `lname`='".$_SESSION['_config']['user']['lname']."',
                                                `suffix`='".$_SESSION['_config']['user']['suffix']."',
                                                `dob`='".$_SESSION['_config']['user']['year']."-".$_SESSION['_config']['user']['month']."-".$_SESSION['_config']['user']['day']."'
-                                               where `id`='".$_SESSION['profile']['id']."'";
+                                               where `id`='".intval($_SESSION['profile']['id'])."'";
                        mysql_query($query);
                }
                if ($showdetails!="") {
@@ -1317,28 +1345,15 @@ function buildSubjectFromSession() {
                                                        `A3`='".$_SESSION['_config']['user']['A3']."',
                                                        `A4`='".$_SESSION['_config']['user']['A4']."',
                                                        `A5`='".$_SESSION['_config']['user']['A5']."'
-                                                       where `id`='".$_SESSION['profile']['id']."'";
-                       mysql_query($query);
-               }
-
-               //!!!Should be rewritten
-               $_SESSION['_config']['user']['otphash'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['otphash']))));
-               $_SESSION['_config']['user']['otppin'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['otppin']))));
-               if($_SESSION['_config']['user']['otphash'] != "" && $_SESSION['_config']['user']['otppin'] != "")
-               {
-                       $query = "update `users` set `otphash`='".$_SESSION['_config']['user']['otphash']."',
-                                               `otppin`='".$_SESSION['_config']['user']['otppin']."' where `id`='".$_SESSION['profile']['id']."'";
+                                                       where `id`='".intval($_SESSION['profile']['id'])."'";
                        mysql_query($query);
                }
 
                $_SESSION['_config']['user']['set'] = 0;
-               $_SESSION['profile'] = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."'"));
+               $_SESSION['profile'] = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_SESSION['profile']['id'])."'"));
                $_SESSION['profile']['loggedin'] = 1;
 
-               $ddquery = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
-               $ddres = mysql_query($ddquery);
-               $ddrow = mysql_fetch_assoc($ddres);
-               $_SESSION['profile']['points'] = $ddrow['total'];
+               update_points_in_profile();
 
 
                $id = 13;
@@ -1360,7 +1375,7 @@ function buildSubjectFromSession() {
                showheader(_("My CAcert.org Account!"));
                if($_SESSION['_config']['user']['pword1'] == "" || $_SESSION['_config']['user']['pword1'] != $_SESSION['_config']['user']['pword2'])
                {
-                       echo '<h3 style="color:red">', _("Failure: Pass Phrase not Changed"),
+                       echo '<h3 class="error_fatal">', _("Failure: Pass Phrase not Changed"),
                                '</h3>', "\n";
                        echo _("New Pass Phrases specified don't match or were blank.");
                } else {
@@ -1369,7 +1384,7 @@ function buildSubjectFromSession() {
 
                        if($_SESSION['_config']['hostname'] != $_SESSION['_config']['securehostname'])
                        {
-                               $match = mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."' and
+                               $match = mysql_query("select * from `users` where `id`='".intval($_SESSION['profile']['id'])."' and
                                                (`password`=old_password('".$_SESSION['_config']['user']['oldpass']."') or
                                                `password`=sha1('".$_SESSION['_config']['user']['oldpass']."'))");
                                $rc = mysql_num_rows($match);
@@ -1378,20 +1393,20 @@ function buildSubjectFromSession() {
                        }
 
                        if(strlen($_SESSION['_config']['user']['pword1']) < 6) {
-                               echo '<h3 style="color:red">',
+                               echo '<h3 class="error_fatal">',
                                        _("Failure: Pass Phrase not Changed"), '</h3>', "\n";
                                echo _("The Pass Phrase you submitted was too short.");
                        } else if($score < 3) {
-                               echo '<h3 style="color:red">',
+                               echo '<h3 class="error_fatal">',
                                        _("Failure: Pass Phrase not Changed"), '</h3>', "\n";
                                printf(_("The Pass Phrase you submitted failed to contain enough differing characters and/or contained words from your name and/or email address. Only scored %s points out of 6."), $score);
                        } else if($rc <= 0) {
-                               echo '<h3 style="color:red">',
+                               echo '<h3 class="error_fatal">',
                                        _("Failure: Pass Phrase not Changed"), '</h3>', "\n";
                                echo _("You failed to correctly enter your current Pass Phrase.");
                        } else {
                                mysql_query("update `users` set `password`=sha1('".$_SESSION['_config']['user']['pword1']."')
-                                               where `id`='".$_SESSION['profile']['id']."'");
+                                               where `id`='".intval($_SESSION['profile']['id'])."'");
                                echo '<h3>', _("Pass Phrase Changed Successfully"), '</h3>', "\n";
                                echo _("Your Pass Phrase has been updated and your primary email account has been notified of the change.");
                                $body  = sprintf(_("Hi %s,"),$_SESSION['profile']['fname'])."\n\n";
@@ -1433,14 +1448,9 @@ function buildSubjectFromSession() {
                                $_SESSION['_config']['emails'][] = $val;
                }
                $_SESSION['_config']['name'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['name'])));
-               $_SESSION['_config']['OU'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['OU'])));
+               $_SESSION['_config']['OU'] = stripslashes(trim($_REQUEST['OU']));
 
-
-               if(trim($_REQUEST['description']) != ""){
-                       $_SESSION['_config']['description']= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
-               }else{
-                       $_SESSION['_config']['description']= "";
-               }
+               $_SESSION['_config']['description']= trim(stripslashes($_REQUEST['description']));
        }
 
        if($oldid == 16 && (intval(count($_SESSION['_config']['emails'])) + 0) <= 0)
@@ -1469,11 +1479,9 @@ function buildSubjectFromSession() {
                if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
                        $_SESSION['_config']['rootcert'] = 1;
 
-               if(trim($_REQUEST['description']) != ""){
-                       $_SESSION['_config']['description']= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
-               }else{
-                       $_SESSION['_config']['description']= "";
-               }
+               $_SESSION['_config']['hash_alg'] = HashAlgorithms::clean($_REQUEST['hash_alg']);
+
+               $_SESSION['_config']['description']= trim(stripslashes($_REQUEST['description']));
 
                if(@count($_SESSION['_config']['emails']) > 0)
                        $id = 17;
@@ -1509,7 +1517,7 @@ function buildSubjectFromSession() {
                        if($_SESSION['_config']['name'] != "")
                                $emails .= "commonName = ".$_SESSION['_config']['name']."\n";
                        if($_SESSION['_config']['OU'])
-                               $emails .= "organizationalUnitName = ".$_SESSION['_config']['OU']."\n";
+                               $emails .= "organizationalUnitName = ".mysql_real_escape_string($_SESSION['_config']['OU'])."\n";
                        if($org['O'])
                                $emails .= "organizationName = ".$org['O']."\n";
                        if($org['L'])
@@ -1534,13 +1542,14 @@ function buildSubjectFromSession() {
 
                        $query = "insert into `orgemailcerts` set
                                                `CN`='$defaultemail',
-                                               `ou`='".$_SESSION['_config']['OU']."',
+                                               `ou`='".mysql_real_escape_string($_SESSION['_config']['OU'])."',
                                                `keytype`='NS',
-                                               `orgid`='".$org['orgid']."',
+                                               `orgid`='".intval($org['orgid'])."',
                                                `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
-                                               `codesign`='".$_SESSION['_config']['codesign']."',
-                                               `rootcert`='".$_SESSION['_config']['rootcert']."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `codesign`='".intval($_SESSION['_config']['codesign'])."',
+                                               `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                        mysql_query($query);
                        $emailid = mysql_insert_id();
 
@@ -1552,7 +1561,8 @@ function buildSubjectFromSession() {
                        fputs($fp, $emails);
                        fclose($fp);
                        $challenge=$_SESSION['spkac_hash'];
-                       $res=`openssl spkac -verify -in $CSRname`;
+                       $CSRname_esc = escapeshellarg($CSRname);
+                       $res=shell_exec("openssl spkac -verify -in $CSRname_esc");
                        if(!strstr($res,"Challenge String: ".$challenge))
                        {
                                $id = $oldid;
@@ -1563,7 +1573,12 @@ function buildSubjectFromSession() {
                        }
                        mysql_query("update `orgemailcerts` set `csr_name`='$CSRname' where `id`='$emailid'");
                } else if($_REQUEST['keytype'] == "MS" || $_REQUEST['keytype']=="VI") {
-                       $csr = "-----BEGIN CERTIFICATE REQUEST-----\n".clean_csr($_REQUEST['CSR'])."-----END CERTIFICATE REQUEST-----\n";
+                       $csr = clean_csr($_REQUEST['CSR']);
+                       if(strpos($csr,"---BEGIN") === FALSE)
+                       {
+                               // In case the CSR is missing the ---BEGIN lines, add them automatically:
+                               $csr = "-----BEGIN CERTIFICATE REQUEST-----\n".$csr."\n-----END CERTIFICATE REQUEST-----\n";
+                       }
 
                        if (($weakKey = checkWeakKeyCSR($csr)) !== "")
                        {
@@ -1604,7 +1619,9 @@ function buildSubjectFromSession() {
                                $csrsubject .= "/countryName=".$org['C'];
 
                        $tmpname = tempnam("/tmp", "id17csr");
-                       $do = `/usr/bin/openssl req -in $tmpfname -out $tmpname`;
+                       $tmpfname_esc = escapeshellarg($tmpfname);
+                       $tmpname_esc = escapeshellarg($tmpname);
+                       $do = shell_exec("/usr/bin/openssl req -in $tmpfname_esc -out $tmpname_esc");
                        @unlink($tmpfname);
                        $csr = "";
                        $fp = fopen($tmpname, "r");
@@ -1625,14 +1642,15 @@ function buildSubjectFromSession() {
 
                        $query = "insert into `orgemailcerts` set
                                                `CN`='$defaultemail',
-                                               `ou`='".$_SESSION['_config']['OU']."',
+                                               `ou`='".mysql_real_escape_string($_SESSION['_config']['OU'])."',
                                                `keytype`='" . sanitizeHTML($_REQUEST['keytype']) . "',
-                                               `orgid`='".$org['orgid']."',
+                                               `orgid`='".intval($org['orgid'])."',
                                                `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
-                                               `subject`='$csrsubject',
-                                               `codesign`='".$_SESSION['_config']['codesign']."',
-                                               `rootcert`='".$_SESSION['_config']['rootcert']."',
-                                               `description`='".$_SESSION['_config']['description']."'";
+                                               `subject`='".mysql_real_escape_string($csrsubject)."',
+                                               `codesign`='".intval($_SESSION['_config']['codesign'])."',
+                                               `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
+                                               `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                               `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                        mysql_query($query);
                        $emailid = mysql_insert_id();
 
@@ -1674,7 +1692,7 @@ function buildSubjectFromSession() {
                                echo "Renewing certificate #$id ...\n<br/>";
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `orgemailcerts`, `org`
-                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                                `org`.`orgid`=`orgemailcerts`.`orgid`";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
@@ -1699,17 +1717,18 @@ function buildSubjectFromSession() {
                                        continue;
                                }
                                $query = "insert into `orgemailcerts` set
-                                               `orgid`='".$row['orgid']."',
-                                               `CN`='".$row['CN']."',
-                                               `ou`='".$row['ou']."',
-                                               `subject`='".$row['subject']."',
-                                               `keytype`='".$row['keytype']."',
-                                               `csr_name`='".$row['csr_name']."',
-                                               `created`='".$row['created']."',
+                                               `orgid`='".intval($row['orgid'])."',
+                                               `CN`='".mysql_real_escape_string($row['CN'])."',
+                                               `ou`='".mysql_real_escape_string($row['ou'])."',
+                                               `subject`='".mysql_real_escape_string($row['subject'])."',
+                                               `keytype`='".mysql_real_escape_string($row['keytype'])."',
+                                               `csr_name`='".mysql_real_escape_string($row['csr_name'])."',
+                                               `created`='".mysql_real_escape_string($row['created'])."',
                                                `modified`=NOW(),
-                                               `codesign`='".$row['codesign']."',
-                                               `rootcert`='".$row['rootcert']."',
-                                               `description`='".$row['description']."'";
+                                               `codesign`='".intval($row['codesign'])."',
+                                               `rootcert`='".intval($row['rootcert'])."',
+                                               `description`='".mysql_real_escape_string($row['description'])."',
+                                               `md`='".HashAlgorithms::clean($row['md'])."'";
                                mysql_query($query);
                                $newid = mysql_insert_id();
                                $newfile=generatecertpath("csr","orgclient",$newid);
@@ -1747,7 +1766,7 @@ function buildSubjectFromSession() {
                        {
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `orgemailcerts`, `org`
-                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               where `orgemailcerts`.`id`='".intval($id)."' and `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                                `org`.`orgid`=`orgemailcerts`.`orgid`";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
@@ -1780,7 +1799,7 @@ function buildSubjectFromSession() {
                        {
                                $id = intval($id);
                                $query = "select *,UNIX_TIMESTAMP(`expire`) as `expired` from `orgemailcerts`, `org`
-                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               where `orgemailcerts`.`id`='".intval($id)."' and `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                                `org`.`orgid`=`orgemailcerts`.`orgid`";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
@@ -1850,19 +1869,15 @@ function buildSubjectFromSession() {
                        exit;
                }
 
-               if(trim($_REQUEST['description']) != ""){
-                       $_SESSION['_config']['description']= trim(mysql_real_escape_string(stripslashes($_REQUEST['description'])));
-               }else{
-                       $_SESSION['_config']['description']= "";
-               }
+               $_SESSION['_config']['description']= trim(stripslashes($_REQUEST['description']));
 
                $_SESSION['_config']['tmpfname'] = tempnam("/tmp", "id20CSR");
                $fp = fopen($_SESSION['_config']['tmpfname'], "w");
                fputs($fp, $CSR);
                fclose($fp);
-               $CSR = $_SESSION['_config']['tmpfname'];
-               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep "Subject:"`);
-               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               $CSR = escapeshellarg($_SESSION['_config']['tmpfname']);
+               $_SESSION['_config']['subject'] = trim(shell_exec("/usr/bin/openssl req -text -noout -in $CSR |tr -d \"\\0\"|grep \"Subject:\""));
+               $bits = explode(",", trim(shell_exec("/usr/bin/openssl req -text -noout -in $CSR |tr -d \"\\0\"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:")));
                foreach($bits as $val)
                {
                        $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
@@ -1875,16 +1890,16 @@ function buildSubjectFromSession() {
                getalt2();
 
                $query = "select * from `orginfo`,`org`,`orgdomains` where
-                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                               `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                `org`.`orgid`=`orginfo`.`id` and
                                `org`.`orgid`=`orgdomains`.`orgid` and
-                               `orgdomains`.`domain`='".$_SESSION['_config']['0.CN']."'";
+                               `orgdomains`.`domain`='".mysql_real_escape_string($_SESSION['_config']['0.CN'])."'";
                $_SESSION['_config']['CNorg'] = mysql_fetch_assoc(mysql_query($query));
                $query = "select * from `orginfo`,`org`,`orgdomains` where
-                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                               `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                `org`.`orgid`=`orginfo`.`id` and
                                `org`.`orgid`=`orgdomains`.`orgid` and
-                               `orgdomains`.`domain`='".$_SESSION['_config']['0.subjectAltName']."'";
+                               `orgdomains`.`domain`='".mysql_real_escape_string($_SESSION['_config']['0.subjectAltName'])."'";
                $_SESSION['_config']['SANorg'] = mysql_fetch_assoc(mysql_query($query));
 //echo "<pre>"; print_r($_SESSION['_config']); die;
 
@@ -1900,6 +1915,8 @@ function buildSubjectFromSession() {
                $_SESSION['_config']['rootcert'] = intval($_REQUEST['rootcert']);
                if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
                        $_SESSION['_config']['rootcert'] = 1;
+
+               $_SESSION['_config']['hash_alg'] = HashAlgorithms::clean($_REQUEST['hash_alg']);
        }
 
        if($process != "" && $oldid == 21)
@@ -1934,14 +1951,14 @@ function buildSubjectFromSession() {
                if($_SESSION['_config']['rowid']['0'] > 0)
                {
                        $query = "select * from `org`,`orginfo` where
-                                       `orginfo`.`id`='".$_SESSION['_config']['rowid']['0']."' and
+                                       `orginfo`.`id`='".intval($_SESSION['_config']['rowid']['0'])."' and
                                        `orginfo`.`id`=`org`.`orgid` and
-                                       `org`.`memid`='".$_SESSION['profile']['id']."'";
+                                       `org`.`memid`='".intval($_SESSION['profile']['id'])."'";
                } else {
                        $query = "select * from `org`,`orginfo` where
-                                       `orginfo`.`id`='".$_SESSION['_config']['altid']['0']."' and
+                                       `orginfo`.`id`='".intval($_SESSION['_config']['altid']['0'])."' and
                                        `orginfo`.`id`=`org`.`orgid` and
-                                       `org`.`memid`='".$_SESSION['profile']['id']."'";
+                                       `org`.`memid`='".intval($_SESSION['profile']['id'])."'";
                }
                $org = mysql_fetch_assoc(mysql_query($query));
                $csrsubject = "";
@@ -1969,22 +1986,24 @@ function buildSubjectFromSession() {
                if($_SESSION['_config']['rowid']['0'] > 0)
                {
                        $query = "insert into `orgdomaincerts` set
-                                       `CN`='".$_SESSION['_config']['rows']['0']."',
-                                       `orgid`='".$org['id']."',
+                                       `CN`='".mysql_real_escape_string($_SESSION['_config']['rows']['0'])."',
+                                       `orgid`='".intval($org['id'])."',
                                        `created`=NOW(),
-                                       `subject`='$csrsubject',
-                                       `rootcert`='".$_SESSION['_config']['rootcert']."',
-                                       `type`='$type',
-                                       `description`='".$_SESSION['_config']['description']."'";
+                                       `subject`='".mysql_real_escape_string($csrsubject)."',
+                                       `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
+                                       `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                       `type`='".$type."',
+                                       `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                } else {
                        $query = "insert into `orgdomaincerts` set
-                                       `CN`='".$_SESSION['_config']['altrows']['0']."',
-                                       `orgid`='".$org['id']."',
+                                       `CN`='".mysql_real_escape_string($_SESSION['_config']['altrows']['0'])."',
+                                       `orgid`='".intval($org['id'])."',
                                        `created`=NOW(),
-                                       `subject`='$csrsubject',
-                                       `rootcert`='".$_SESSION['_config']['rootcert']."',
-                                       `type`='$type',
-                                       `description`='".$_SESSION['_config']['description']."'";
+                                       `subject`='".mysql_real_escape_string($csrsubject)."',
+                                       `rootcert`='".intval($_SESSION['_config']['rootcert'])."',
+                                       `md`='".mysql_real_escape_string($_SESSION['_config']['hash_alg'])."',
+                                       `type`='".$type."',
+                                       `description`='".mysql_real_escape_string($_SESSION['_config']['description'])."'";
                }
                mysql_query($query);
                $CSRid = mysql_insert_id();
@@ -1995,10 +2014,10 @@ function buildSubjectFromSession() {
                mysql_query("update `orgdomaincerts` set `CSR_name`='$CSRname' where `id`='$CSRid'");
                if(is_array($_SESSION['_config']['rowid']))
                        foreach($_SESSION['_config']['rowid'] as $id)
-                               mysql_query("insert into `orgdomlink` set `orgdomid`='$id', `orgcertid`='$CSRid'");
+                               mysql_query("insert into `orgdomlink` set `orgdomid`='".intval($id)."', `orgcertid`='$CSRid'");
                if(is_array($_SESSION['_config']['altid']))
                        foreach($_SESSION['_config']['altid'] as $id)
-                               mysql_query("insert into `orgdomlink` set `orgdomid`='$id', `orgcertid`='$CSRid'");
+                               mysql_query("insert into `orgdomlink` set `orgdomid`='".intval($id)."', `orgcertid`='$CSRid'");
                waitForResult("orgdomaincerts", $CSRid,$oldid);
                $query = "select * from `orgdomaincerts` where `id`='$CSRid' and `crt_name` != ''";
                $res = mysql_query($query);
@@ -2029,7 +2048,7 @@ function buildSubjectFromSession() {
                                                `orgdomaincerts`,`org`
                                                where `orgdomaincerts`.`id`='$id' and
                                                `orgdomaincerts`.`orgid`=`org`.`orgid` and
-                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `org`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -2053,15 +2072,16 @@ function buildSubjectFromSession() {
                                        continue;
                                }
                                $query = "insert into `orgdomaincerts` set
-                                               `orgid`='".$row['orgid']."',
-                                               `CN`='".$row['CN']."',
-                                               `csr_name`='".$row['csr_name']."',
-                                               `created`='".$row['created']."',
+                                               `orgid`='".intval($row['orgid'])."',
+                                               `CN`='".mysql_real_escape_string($row['CN'])."',
+                                               `csr_name`='".mysql_real_escape_string($row['csr_name'])."',
+                                               `created`='".mysql_real_escape_string($row['created'])."',
                                                `modified`=NOW(),
-                                               `subject`='".$row['subject']."',
-                                               `type`='".$row['type']."',
-                                               `rootcert`='".$row['rootcert']."',
-                                               `description`='".$row['description']."'";
+                                               `subject`='".mysql_real_escape_string($row['subject'])."',
+                                               `type`='".intval($row['type'])."',
+                                               `rootcert`='".intval($row['rootcert'])."',
+                                               `description`='".mysql_real_escape_string($row['description'])."',
+                                               `md`='".HashAlgorithms::clean($row['md'])."'";
                                mysql_query($query);
                                $newid = mysql_insert_id();
                                //echo "NewID: $newid<br/>\n";
@@ -2071,7 +2091,7 @@ function buildSubjectFromSession() {
                                echo _("Renewing").": ".$row['CN']."<br>\n";
                                $res = mysql_query("select * from `orgdomlink` where `orgcertid`='".$row['id']."'");
                                while($r2 = mysql_fetch_assoc($res))
-                                       mysql_query("insert into `orgdomlink` set `orgdomid`='".$r2['id']."', `orgcertid`='$newid'");
+                                       mysql_query("insert into `orgdomlink` set `orgdomid`='".intval($r2['orgdomid'])."', `orgcertid`='$newid'");
                                waitForResult("orgdomaincerts", $newid,$oldid,0);
                                $query = "select * from `orgdomaincerts` where `id`='$newid' and `crt_name` != ''";
                                $res = mysql_query($query);
@@ -2080,7 +2100,8 @@ function buildSubjectFromSession() {
                                        printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.")." newid: $newid", "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
                                } else {
                                        $drow = mysql_fetch_assoc($res);
-                                       $cert = `/usr/bin/openssl x509 -in $drow[crt_name]`;
+                                       $crtname = escapeshellarg($drow['crt_name']);
+                                       $cert = shell_exec("/usr/bin/openssl x509 -in $crtname");
                                        echo "<pre>\n$cert\n</pre>\n";
                                }
                        }
@@ -2107,7 +2128,7 @@ function buildSubjectFromSession() {
                                                `orgdomaincerts`,`org`
                                                where `orgdomaincerts`.`id`='$id' and
                                                `orgdomaincerts`.`orgid`=`org`.`orgid` and
-                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `org`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -2142,7 +2163,7 @@ function buildSubjectFromSession() {
                                                `orgdomaincerts`,`org`
                                                where `orgdomaincerts`.`id`='$id' and
                                                `orgdomaincerts`.`orgid`=`org`.`orgid` and
-                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                                               `org`.`memid`='".intval($_SESSION['profile']['id'])."'";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) <= 0)
                                {
@@ -2228,7 +2249,7 @@ function buildSubjectFromSession() {
                                                `contact`='".$_SESSION['_config']['contact']."',
                                                `L`='".$_SESSION['_config']['L']."',
                                                `ST`='".$_SESSION['_config']['ST']."',
-                                               `C`='".$_SESSION['_config']['C']."',
+                                               `C`='".strtoupper($_SESSION['_config']['C'])."',
                                                `comments`='".$_SESSION['_config']['comments']."'");
                        showheader(_("My CAcert.org Account!"));
                        printf(_("'%s' has just been successfully added as an organisation to the database."), sanitizeHTML($_SESSION['_config']['O']));
@@ -2256,9 +2277,9 @@ function buildSubjectFromSession() {
                                                `contact`='".$_SESSION['_config']['contact']."',
                                                `L`='".$_SESSION['_config']['L']."',
                                                `ST`='".$_SESSION['_config']['ST']."',
-                                               `C`='".$_SESSION['_config']['C']."',
+                                               `C`='".strtoupper($_SESSION['_config']['C'])."',
                                                `comments`='".$_SESSION['_config']['comments']."'
-                                       where `id`='".$_SESSION['_config']['orgid']."'");
+                                       where `id`='".intval($_SESSION['_config']['orgid'])."'");
                        showheader(_("My CAcert.org Account!"));
                        printf(_("'%s' has just been successfully updated in the database."), sanitizeHTML($_SESSION['_config']['O']));
                        showfooter();
@@ -2438,11 +2459,11 @@ function buildSubjectFromSession() {
        {
                csrf_check('orgadmadd');
                if($_SESSION['profile']['orgadmin'] == 1)
-                       $masteracc = $_SESSION['_config'][masteracc] = intval($_REQUEST['masteracc']);
+                       $masteracc = $_SESSION['_config']['masteracc'] = intval($_REQUEST['masteracc']);
                else
-                       $masteracc = $_SESSION['_config'][masteracc] = 0;
+                       $masteracc = $_SESSION['_config']['masteracc'] = 0;
                $_REQUEST['email'] = $_SESSION['_config']['email'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['email'])));
-               $OU = $_SESSION['_config']['OU'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['OU'])));
+               $_SESSION['_config']['OU'] = stripslashes(trim($_REQUEST['OU']));
                $comments = $_SESSION['_config']['comments'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['comments'])));
                $res = mysql_query("select * from `users` where `email`='".$_REQUEST['email']."' and `deleted`=0");
                if(mysql_num_rows($res) <= 0)
@@ -2464,7 +2485,7 @@ function buildSubjectFromSession() {
                                                set `memid`='".intval($row['id'])."',
                                                        `orgid`='".intval($_SESSION['_config']['orgid'])."',
                                                        `masteracc`='$masteracc',
-                                                       `OU`='$OU',
+                                                       `OU`='".mysql_real_escape_string($_SESSION['_config']['OU'])."',
                                                        `comments`='$comments'");
                        }
                }
@@ -2473,7 +2494,7 @@ function buildSubjectFromSession() {
        if(($oldid == 34 || $id == 34) && $_SESSION['profile']['orgadmin'] != 1)
        {
                $orgid = intval($_SESSION['_config']['orgid']);
-               $res = mysql_query("select * from `org` where `orgid`='$orgid' and `memid`='".$_SESSION['profile']['id']."' and `masteracc`='1'");
+               $res = mysql_query("select * from `org` where `orgid`='$orgid' and `memid`='".intval($_SESSION['profile']['id'])."' and `masteracc`='1'");
                if(mysql_num_rows($res) <= 0)
                        $id = 32;
        }
@@ -2532,7 +2553,7 @@ function buildSubjectFromSession() {
                {
                        if($key == $lang)
                        {
-                               mysql_query("update `users` set `language`='$lang' where `id`='".$_SESSION['profile']['id']."'");
+                               mysql_query("update `users` set `language`='$lang' where `id`='".intval($_SESSION['profile']['id'])."'");
                                $_SESSION['profile']['language'] = $lang;
                                showheader(_("My CAcert.org Account!"));
                                echo _("Your language setting has been updated.");
@@ -2687,10 +2708,27 @@ function buildSubjectFromSession() {
                $oldid=0;
        }
 
-       if($oldid == 43 && $_REQUEST['action'] == "updatedob")
+       //check if ticket number was entered
+       if ( $id == 43 || $oldid == 43 || $id == 44 || $oldid == 44 ) {
+               if ($ticketno != "" ) {
+                       $ticketno = trim($_REQUEST['ticketno']);
+                       $ticketvalidation = valid_ticket_number($ticketno);
+               }
+
+               $_SESSION['ticketno'] = $ticketno;
+       }
+
+       if($oldid == 43 && $actionrequest == "updatedob" && $ticketvalidation == TRUE)
        {
                $id = 43;
                $oldid=0;
+               $userid = intval($_REQUEST['userid']);
+               if (!write_se_log($userid, $_SESSION['profile']['id'],'SE Name/DOB Change',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $fname = mysql_real_escape_string($_REQUEST['fname']);
                $mname = mysql_real_escape_string($_REQUEST['mname']);
                $lname = mysql_real_escape_string($_REQUEST['lname']);
@@ -2698,21 +2736,29 @@ function buildSubjectFromSession() {
                $day = intval($_REQUEST['day']);
                $month = intval($_REQUEST['month']);
                $year = intval($_REQUEST['year']);
-               $userid = intval($_REQUEST['userid']);
-               $query = "select `fname`,`mname`,`lname`,`suffix`,`dob` from `users` where `id`='$userid'";
-               $details = mysql_fetch_assoc(mysql_query($query));
-               $query = "insert into `adminlog` set `when`=NOW(),`old-lname`='${details['lname']}',`old-dob`='${details['dob']}',
-                               `new-lname`='$lname',`new-dob`='$year-$month-$day',`uid`='$userid',`adminid`='".$_SESSION['profile']['id']."'";
-               mysql_query($query);
                $query = "update `users` set `fname`='$fname',`mname`='$mname',`lname`='$lname',`suffix`='$suffix',`dob`='$year-$month-$day' where `id`='$userid'";
                mysql_query($query);
+       }elseif($oldid == 43 && $actionrequest == "updatedob" && $ticketvalidation == FALSE){
+               $id = 43;
+               $oldid=0;
+               $_SESSION['ticketmsg']='No action (name/dob change) taken. Ticket number is missing!';
        }
 
-       if($oldid == 43 && $_REQUEST['action'] == 'revokecert')
+       if($oldid == 43 && $actionrequest == 'revokecert' && $ticketvalidation == TRUE)
        {
                $userid = intval($_REQUEST['userid']);
+               if (!write_se_log($userid, $_SESSION['profile']['id'], 'SE Revoke all certificates',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                revoke_all_private_cert($userid);
                $id=43;
+       }elseif($oldid == 43 && $actionrequest == "revokecert" && $ticketvalidation == FALSE){
+               $id = 43;
+               $oldid=0;
+               $_SESSION['ticketmsg']='No certificates revokes. Ticket number is missing!';
        }
 
        if($oldid == 48 && $_REQUEST['domain'] == "")
@@ -2729,8 +2775,7 @@ function buildSubjectFromSession() {
 
        if($id == 44)
        {
-               if($_REQUEST['userid'] != "")
-                       $_REQUEST['userid'] = intval($_REQUEST['userid']);
+               $_REQUEST['userid'] = intval($_REQUEST['userid']);
                $row = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_REQUEST['userid'])."'"));
                if($row['email'] == "")
                        $id = 42;
@@ -2738,18 +2783,25 @@ function buildSubjectFromSession() {
                        $_REQUEST['email'] = $row['email'];
        }
 
-       if($oldid == 44)
+       if($oldid == 44 && $ticketvalidation == TRUE)
        {
                showheader(_("My CAcert.org Account!"));
                if(intval($_REQUEST['userid']) <= 0)
                {
                        echo _("No such user found.");
                } else {
+                       if (!write_se_log(intval($_REQUEST['userid']), $_SESSION['profile']['id'],'SE reset password',$ticketno)) {
+                               showheader(_("Something went wrong"));
+                               echo _("Writing to the admin log failed. Can't continue.");
+                               showfooter();
+                               exit;
+                       }
                        mysql_query("update `users` set `password`=sha1('".mysql_real_escape_string(stripslashes($_REQUEST['newpass']))."') where `id`='".intval($_REQUEST['userid'])."'");
                        $row = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_REQUEST['userid'])."'"));
                        printf(_("The password for %s has been updated successfully in the system."), sanitizeHTML($row['email']));
 
-
+                       $my_translation = L10n::get_translation();
+                       L10n::set_recipient_language(intval($_REQUEST['userid']));
                        $body  = sprintf(_("Hi %s,"),$row['fname'])."\n\n";
                        $body .= _("You are receiving this email because a CAcert administrator ".
                                        "has changed the password on your account.")."\n\n";
@@ -2758,18 +2810,24 @@ function buildSubjectFromSession() {
 
                        sendmail($row['email'], "[CAcert.org] "._("Password Update Notification"), $body,
                                                "support@cacert.org", "", "", "CAcert Support");
+                       L10n::set_translation($my_translation);
                }
 
                showfooter();
                exit;
+       }elseif($oldid == 44 && $ticketvalidation == FALSE){
+               $_SESSION['ticketmsg']='No password reset taken. Ticket number is missing!';
        }
 
+
        if($process != "" && $oldid == 45)
        {
                $CSR = clean_csr($CSR);
                $_SESSION['_config']['CSR'] = $CSR;
-               $_SESSION['_config']['subject'] = trim(`echo "$CSR"|/usr/bin/openssl req -text -noout|tr -d "\\0"|grep "Subject:"`);
-               $bits = explode(",", trim(`echo "$CSR"|/usr/bin/openssl req -text -noout|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               runCommand("/usr/bin/openssl req -text -noout|tr -d \"\\0\"|grep \"Subject:\"", $CSR, $CSRSubjects);
+               runCommand("/usr/bin/openssl req -text -noout|tr -d \"\\0\"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:", $CSR, $CSRAlts);
+               $_SESSION['_config']['subject'] = trim($CSRSubjects);
+               $bits = explode(",", trim($CSRAlts));
                foreach($bits as $val)
                {
                        $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
@@ -2793,8 +2851,11 @@ function buildSubjectFromSession() {
        if($process != "" && $oldid == 46)
        {
                $CSR = clean_csr($_SESSION['_config']['CSR']);
-               $_SESSION['_config']['subject'] = trim(`echo "$CSR"|/usr/bin/openssl req -text -noout|tr -d "\\0"|grep "Subject:"`);
-               $bits = explode(",", trim(`echo "$CSR"|/usr/bin/openssl req -text -noout|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               runCommand("/usr/bin/openssl req -text -noout|tr -d \"\\0\"|grep \"Subject:\"", $CSR, $CSRSubjects);
+               runCommand("/usr/bin/openssl req -text -noout|tr -d \"\\0\"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:", $CSR, $CSRAlts);
+
+               $_SESSION['_config']['subject'] = trim($CSRSubjects);
+               $bits = explode(",", trim($CSRAlts));
                foreach($bits as $val)
                {
                        $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
@@ -2830,10 +2891,10 @@ function buildSubjectFromSession() {
                $CSRid = mysql_insert_id();
 
                foreach($_SESSION['_config']['rowid'] as $dom)
-                       mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='$dom'");
+                       mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='".intval($dom)."'");
                if(is_array($_SESSION['_config']['altid']))
                foreach($_SESSION['_config']['altid'] as $dom)
-                       mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='$dom'");
+                       mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='".intval($dom)."'");
 
                $CSRname=generatecertpath("csr","server",$CSRid);
                $fp = fopen($CSRname, "w");
@@ -2856,150 +2917,260 @@ function buildSubjectFromSession() {
                }
        }
 
-       if($id == 43 && array_key_exists('tverify',$_REQUEST) && $_REQUEST['tverify'] > 0)
-       {
-               $memid = $_REQUEST['userid'] = intval($_REQUEST['tverify']);
-               $query = "select * from `users` where `id`='$memid'";
-               $row = mysql_fetch_assoc(mysql_query($query));
-               $ver = !$row['tverify'];
-               mysql_query("update `users` set `tverify`='$ver' where `id`='$memid'");
-       }
-
-       if($id == 43 && array_key_exists('assurer',$_REQUEST) && $_REQUEST['assurer'] > 0)
+       if($id == 43 && array_key_exists('assurer',$_REQUEST) && $_REQUEST['assurer'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admsetassuret');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['assurer']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change assurer status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['assurer'];
                mysql_query("update `users` set `assurer`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('assurer',$_REQUEST) && $_REQUEST['assurer'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['assurer']);
+               $_SESSION['ticketmsg']='No action (Change assurer status) taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('assurer_blocked',$_REQUEST) && $_REQUEST['assurer_blocked'] > 0)
+       if($id == 43 && array_key_exists('assurer_blocked',$_REQUEST) && $_REQUEST['assurer_blocked'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['assurer_blocked']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change assurer blocked status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['assurer_blocked'];
                mysql_query("update `users` set `assurer_blocked`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('assurer_blocked',$_REQUEST) && $_REQUEST['assurer_blocked'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['assurer_blocked']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('locked',$_REQUEST) && $_REQUEST['locked'] > 0)
+       if($id == 43 && array_key_exists('locked',$_REQUEST) && $_REQUEST['locked'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admactlock');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['locked']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change locked status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['locked'];
                mysql_query("update `users` set `locked`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('locked',$_REQUEST) && $_REQUEST['locked'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['locked']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] > 0)
+       if($id == 43 && array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admcodesign');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['codesign']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change codesign status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['codesign'];
                mysql_query("update `users` set `codesign`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['codesign']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('orgadmin',$_REQUEST) && $_REQUEST['orgadmin'] > 0)
+       if($id == 43 && array_key_exists('orgadmin',$_REQUEST) && $_REQUEST['orgadmin'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admorgadmin');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['orgadmin']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change org assuer status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['orgadmin'];
                mysql_query("update `users` set `orgadmin`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('orgadmin',$_REQUEST) && $_REQUEST['orgadmin'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['orgadmin']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('ttpadmin',$_REQUEST) && $_REQUEST['ttpadmin'] > 0)
+       if($id == 43 && array_key_exists('ttpadmin',$_REQUEST) && $_REQUEST['ttpadmin'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admttpadmin');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['ttpadmin']);
+               if(!write_se_log($memid, $_SESSION['profile']['id'],'SE Change ttp admin status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['ttpadmin'];
                mysql_query("update `users` set `ttpadmin`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('ttpadmin',$_REQUEST) && $_REQUEST['ttpadmin'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['ttpadmin']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('adadmin',$_REQUEST) && $_REQUEST['adadmin'] > 0)
+       if($id == 43 && array_key_exists('adadmin',$_REQUEST) && $_REQUEST['adadmin'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['adadmin']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change advertising admin status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = $row['adadmin'] + 1;
                if($ver > 2)
                        $ver = 0;
                mysql_query("update `users` set `adadmin`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('adadmin',$_REQUEST) && $_REQUEST['adadmin'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['adadmin']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('locadmin',$_REQUEST) && $_REQUEST['locadmin'] > 0)
+       if($id == 43 && array_key_exists('locadmin',$_REQUEST) && $_REQUEST['locadmin'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['locadmin']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change location admin status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['locadmin'];
                mysql_query("update `users` set `locadmin`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('locadmin',$_REQUEST) && $_REQUEST['locadmin'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['locadmin']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('admin',$_REQUEST) && $_REQUEST['admin'] > 0)
+       if($id == 43 && array_key_exists('admin',$_REQUEST) && $_REQUEST['admin'] > 0 && $ticketvalidation == TRUE)
        {
                csrf_check('admsetadmin');
                $memid = $_REQUEST['userid'] = intval($_REQUEST['admin']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change SE status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `users` where `id`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['admin'];
                mysql_query("update `users` set `admin`='$ver' where `id`='$memid'");
+       }elseif($id == 43 && array_key_exists('admin',$_REQUEST) && $_REQUEST['admin'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['admin']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('general',$_REQUEST) && $_REQUEST['general'] > 0)
+       if($id == 43 && array_key_exists('general',$_REQUEST) && $_REQUEST['general'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['general']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change general status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `alerts` where `memid`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['general'];
                mysql_query("update `alerts` set `general`='$ver' where `memid`='$memid'");
+       }elseif($id == 43 && array_key_exists('general',$_REQUEST) && $_REQUEST['general'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['general']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('country',$_REQUEST) && $_REQUEST['country'] > 0)
+       if($id == 43 && array_key_exists('country',$_REQUEST) && $_REQUEST['country'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['country']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change country status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `alerts` where `memid`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['country'];
                mysql_query("update `alerts` set `country`='$ver' where `memid`='$memid'");
+       }elseif($id == 43 && array_key_exists('country',$_REQUEST) && $_REQUEST['country'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['country']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('regional',$_REQUEST) && $_REQUEST['regional'] > 0)
+       if($id == 43 && array_key_exists('regional',$_REQUEST) && $_REQUEST['regional'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['regional']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change regional status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `alerts` where `memid`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['regional'];
                mysql_query("update `alerts` set `regional`='$ver' where `memid`='$memid'");
+       }elseif($id == 43 && array_key_exists('regional',$_REQUEST) && $_REQUEST['regional'] > 0 && $ticketvalidation == FALSE){
+               $_REQUEST['userid'] = intval($_REQUEST['regional']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
-       if($id == 43 && array_key_exists('radius',$_REQUEST) && $_REQUEST['radius'] > 0)
+       if($id == 43 && array_key_exists('radius',$_REQUEST) && $_REQUEST['radius'] > 0 && $ticketvalidation == TRUE)
        {
                $memid = $_REQUEST['userid'] = intval($_REQUEST['radius']);
+               if (!write_se_log($memid, $_SESSION['profile']['id'],'SE Change radius status',$ticketno)) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       showfooter();
+                       exit;
+               }
                $query = "select * from `alerts` where `memid`='$memid'";
                $row = mysql_fetch_assoc(mysql_query($query));
                $ver = !$row['radius'];
                mysql_query("update `alerts` set `radius`='$ver' where `memid`='$memid'");
+       }elseif($id == 43 && array_key_exists('radius',$_REQUEST) && $_REQUEST['radius'] > 0 && $ticketvalidation == false){
+               $_REQUEST['userid'] = intval($_REQUEST['radius']);
+               $_SESSION['ticketmsg']='No action taken. Ticket number is missing!';
        }
 
        if($id == 50)
        {
-               if(array_key_exists('userid',$_REQUEST) && $_REQUEST['userid'] != "")
+               if(array_key_exists('userid',$_REQUEST) && $_REQUEST['userid'] !== "") {
                        $_REQUEST['userid'] = intval($_REQUEST['userid']);
+               }
 
                $row = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_REQUEST['userid'])."'"));
-               if($row['email'] == "")
+               if($row['email'] == "") {
                        $id = 42;
-               else
+               } else {
                        $_REQUEST['email'] = $row['email'];
+               }
        }
 
        if($oldid == 50)
@@ -3014,151 +3185,69 @@ function buildSubjectFromSession() {
                if (trim($_REQUEST['arbitrationno'])==""){
                        showheader(_("My CAcert.org Account!"));
                        echo _("You did not enter an arbitration number entry.");
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
                        showfooter();
                        exit;
                }
                if ( 1 !== preg_match('/^[a-z]\d{8}\.\d+\.\d+$/i',trim($_REQUEST['arbitrationno'])) ) {
                        showheader(_("My CAcert.org Account!"));
                        printf(_("'%s' is not a valid arbitration number entry."), sanitizeHTML(trim($_REQUEST['arbitrationno'])));
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
                        showfooter();
                        exit;
                }
                if (check_email_exists(trim($_REQUEST['arbitrationno']).'@cacert.org')) {
                        showheader(_("My CAcert.org Account!"));
                        printf(_("The email address '%s' is already in a different account. Can't continue."), sanitizeHTML($_REQUEST['arbitrationno'].'@cacert.org'));
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
                        showfooter();
                        exit;
-                }
-               if (check_client_cert_running($_REQUEST['userid'],1) ||
-                       check_server_cert_running($_REQUEST['userid'],1) ||
-                       check_gpg_cert_running($_REQUEST['userid'],1)) {
+               }
+               if (check_client_cert_running(intval($_REQUEST['userid']),1) ||
+                       check_server_cert_running(intval($_REQUEST['userid']),1) ||
+                       check_gpg_cert_running(intval($_REQUEST['userid']),1)) {
                        showheader(_("My CAcert.org Account!"));
                        printf(_("The CCA retention time for at least one certificate is not over. Can't continue."));
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
                        showfooter();
                        exit;
                }
-               if (check_is_orgadmin($_REQUEST['userid'],1)) {
+               if (check_is_orgadmin(intval($_REQUEST['userid']),1)) {
                        showheader(_("My CAcert.org Account!"));
                        printf(_("The user is listed as Organisation Administrator. Can't continue."));
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
+                       showfooter();
+                       exit;
+               }
+               if (!write_se_log(intval($_REQUEST['userid']), $_SESSION['profile']['id'], 'SE Account delete', trim($_REQUEST['arbitrationno']))) {
+                       showheader(_("Something went wrong"));
+                       echo _("Writing to the admin log failed. Can't continue.");
+                       printf('<br/><a href="account.php?id=43&amp;userid=' . intval($_REQUEST['userid']) . '">' . _('Back to previous page.') .'</a>');
                        showfooter();
                        exit;
                }
-               account_delete($_REQUEST['userid'], trim($_REQUEST['arbitrationno']), $_SESSION['profile']['id']);
+               account_delete(intval($_REQUEST['userid']), trim($_REQUEST['arbitrationno']), $_SESSION['profile']['id']);
        }
 
-       if(($id == 51 || $id == 52 || $oldid == 52) && $_SESSION['profile']['tverify'] <= 0)
+       if(($id == 51 || $id == 52 || $oldid == 52))
        {
                showheader(_("My CAcert.org Account!"));
-               echo _("You don't have access to this area.");
+               echo _("You don't have access to this area.\nThe Tverify programme is terminated as of 16th November 2010" );
                showfooter();
                exit;
        }
 
-       if($oldid == 52)
-       {
-               $uid = intval($_REQUEST['uid']);
-               $query = "select * from `tverify` where `id`='$uid' and `modified`=0";
-               $rc = mysql_num_rows(mysql_query($query));
-               if($rc <= 0)
+       if($id == 59){
+               if (!($oldid == 43 && $_SESSION['profile']['admin'] == 1) &&
+                   !($oldid == 13 && intval($_REQUEST['userid']) == $_SESSION['profile']['id']))
                {
                        showheader(_("My CAcert.org Account!"));
-                       echo _("Unable to find a valid tverify request for this ID.");
+                       echo _("You do not have access to this page.");
                        showfooter();
                        exit;
                }
        }
 
-       if($oldid == 52)
-       {
-               $query = "select * from `tverify-vote` where `tverify`='$uid' and `memid`='".$_SESSION['profile']['id']."'";
-               $rc = mysql_num_rows(mysql_query($query));
-               if($rc > 0)
-               {
-                       showheader(_("My CAcert.org Account!"));
-                       echo _("You have already voted on this request.");
-                       showfooter();
-                       exit;
-               }
-       }
-
-       if($oldid == 52 && ($_REQUEST['agree'] != "" || $_REQUEST['disagree'] != ""))
-       {
-               $vote = -1;
-               if($_REQUEST['agree'] != "")
-                       $vote = 1;
-
-               $query = "insert into `tverify-vote` set
-                               `tverify`='$uid',
-                               `memid`='".$_SESSION['profile']['id']."',
-                               `when`=NOW(), `vote`='$vote',
-                               `comment`='".mysql_real_escape_string($_REQUEST['comment'])."'";
-               mysql_query($query);
-
-               $rc = mysql_num_rows(mysql_query("select * from `tverify-vote` where `tverify`='$uid' and `vote`='1'"));
-               if($rc >= 8)
-               {
-                       mysql_query("update `tverify` set `modified`=NOW() where `id`='$uid'");
-                       $tverify = mysql_fetch_assoc(mysql_query("select * from `tverify` where `id`='$uid'"));
-                       $memid = $tverify['memid'];
-                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='$memid'"));
-                       $tmp = mysql_fetch_assoc(mysql_query("select sum(`points`) as `points` from `notary` where `to`='$memid'"));
-
-                       $points = 0;
-                       if($tverify['URL'] != "" && $tverify['photoid'] != "")
-                               $points = 150 - intval($tmp['points']);
-                       if($tverify['URL'] != "" && $tverify['photoid'] == "")
-                               $points = 90 - intval($tmp['points']);
-                       if($tverify['URL'] == "" && $tverify['photoid'] == "")
-                               $points = 50 - intval($tmp['points']);
-
-                       if($points < 0)
-                               $points = 0;
-
-                       if($points > 0)
-                       {
-                               mysql_query("insert into `notary` set `from`='0', `to`='$memid', `points`='$points',
-                                               `method`='Thawte Points Transfer', `when`=NOW()");
-                               fix_assurer_flag($memid);
-                       }
-                       $totalpoints = intval($tmp['points']) + $points;
-
-                       $body  = _("Your request to have points transfered was successful. You were issued $points points as a result, and you now have $totalpoints in total")."\n\n"._("The following comments were made by reviewers")."\n\n";
-                       $res = mysql_query("select * from `tverify-vote` where `tverify`='$uid' and `vote`='1'");
-                       while($row = mysql_fetch_assoc($res))
-                               $body .= $row['comment']."\n";
-                       $body .= "\n";
-
-                       $body .= _("Best regards")."\n";
-                       $body .= _("CAcert Support Team");
-                       sendmail($user['email'], "[CAcert.org] Thawte Notary Points Transfer", $body, "website-form@cacert.org", "support@cacert.org", "", "CAcert Tverify");
-               }
-
-               $rc = mysql_num_rows(mysql_query("select * from `tverify-vote` where `tverify`='$uid' and `vote`='-1'"));
-               if($rc >= 4)
-               {
-                       mysql_query("update `tverify` set `modified`=NOW() where `id`='$uid'");
-                       $tverify = mysql_fetch_assoc(mysql_query("select * from `tverify` where `id`='$uid'"));
-                       $memid = $tverify['memid'];
-                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='$memid'"));
-
-                       $body  = _("Unfortunately your request for a points increase has been denied, below is the comments from people that reviewed your request as to why they rejected your application.")."\n\n";
-                       $res = mysql_query("select * from `tverify-vote` where `tverify`='$uid' and `vote`='-1'");
-                       while($row = mysql_fetch_assoc($res))
-                               $body .= $row['comment']."\n";
-                       $body .= "\n";
-
-                       $body .= _("You are welcome to try submitting another request at any time in the future, please make sure you take the reviewer comments into consideration or you risk having your application rejected again.")."\n\n";
-
-                       $body .= _("Best regards")."\n";
-                       $body .= _("CAcert Support Team");
-                       sendmail($user['email'], "[CAcert.org] Thawte Notary Points Transfer", $body, "website-form@cacert.org", "support@cacert.org", "", "CAcert Tverify");
-               }
-
-               showheader(_("My CAcert.org Account!"));
-               echo _("Your vote has been accepted.");
-               showfooter();
-               exit;
-       }
 
        if(intval($cert) > 0)
                $_SESSION['_config']['cert'] = intval($cert);
index a26757a..9ff794d 100644 (file)
@@ -22,6 +22,7 @@
        function showheader($title = "CAcert.org", $title2 = "")
        {
                global $id, $PHP_SELF;
+       $PHP_SELF = &$_SERVER['PHP_SELF'];
        $expand="";
        $tmpid = $id;
        if($PHP_SELF == "/wot.php")
 
        switch($tmpid)
        {
-               case 1:
-               case 2: $expand = " explode('emailacc');"; break;
-               case 3:
-               case 4:
-               case 5:
-               case 6: $expand = " explode('clicerts');"; break;
-               case 7:
-               case 8:
-               case 9: $expand = " explode('domains');"; break;
-               case 10:
-               case 11:
-               case 12:
-               case 15: $expand = " explode('servercert');"; break;
-               case 13:
-               case 14:
-               case 36:
-               case 41:
+               case 1:                                                 // Add email address
+               case 2: $expand = " explode('emailacc');"; break;       // View email addresses
+               case 3:                                                 // Add Client certificate
+               case 4:                                                 // Confirm Client Certificate Request
+               case 5:                                                 // View Client Certificates
+               case 6: $expand = " explode('clicerts');"; break;       // Client Certificate page
+               case 7:                                                 // Add new domain
+               case 8:                                                 // Confirm Domain page
+               case 9: $expand = " explode('domains');"; break;        // View Domains
+               case 10:                                                // Add Server Certifiacte
+               case 11:                                                // Confirm Server Certificate Rewust
+               case 12:                                                // View Server Cerificate
+               case 15: $expand = " explode('servercert');"; break;    // Server Certificate page
+               case 13:                                                // ViewEdit
+               case 14:                                                // Change password
+               case 36:                                                // My Alert settings
+               case 41:                                                // Language Settings
+               case 55:                                                // Trainings
+               case 59:                                                // Account History
                case 507:
-               case 508:
-               case 513: $expand = " explode('mydetails');"; break;
-               case 16:
-               case 17:
-               case 18:
-               case 19: $expand = " explode('clientorg');"; break;
-               case 20:
-               case 21:
-               case 22:
-               case 23: $expand = " explode('serverorg');"; break;
-               case 24:
-               case 25:
-               case 26:
-               case 27:
-               case 28:
-               case 29:
-               case 30:
+               case 508:                                               // My Listing
+               case 510:                                               // Old points calculation
+               case 515:                                               // New points calculation
+               case 513: $expand = " explode('mydetails');"; break;    // My Location
+               case 16:                                                // Add Org Client Cert
+               case 17:                                                // Confirm Org Client Certificate Request
+               case 18:                                                // View Org Client Certificate
+               case 19: $expand = " explode('clientorg');"; break;     // Org Cleint Cert page
+               case 20:                                                // Add Org Server Cert
+               case 21:                                                // Conform Org Server Cert Request
+               case 22:                                                // View Org Server Certs
+               case 23: $expand = " explode('serverorg');"; break;     // Org Server Certificate page
+               case 24:                                                // Add new Organisation
+               case 25:                                                // View Organisation List
+               case 26:                                                // View Organisation Domains
+               case 27:                                                // Edit Org Account
+               case 28:                                                // View Add Org Domain
+               case 29:                                                // Edit Org Domain
+               case 30:                                                // Delete Org Domain
                case 31:
-               case 32:
-               case 33:
-               case 34:
-               case 35: $expand = " explode('orgadmin');"; break;
+               case 32:                                                // View Org Admin
+               case 33:                                                // Add Org Admin
+               case 34:                                                // Delete Org Admin
+               case 60:                                                // View Organisation Account History
+               case 35: $expand = " explode('orgadmin');"; break;      // View Org Admin Organisation List
                case 42:
                case 43:
                case 44:
                case 50:
                case 54:
                case 53: $expand = " explode('sysadmin');"; break;
-               case 500:
+               case 500:                                               // CAcert Web of Trust
                case 501:
-               case 502:
-               case 503:
-               case 504:
-               case 505:
+               case 502:                                               // Become an Assurer
+               case 503:                                               // CAcert Web of Trust Roles
+               case 504:                                               // TTP
+               case 505:                                               // Assurer Some one
                case 506:
                case 509:
-               case 510:
                case 511:
-               case 512:
-               case 516:                                       // TTP form
-               case 517: $expand = " explode('WoT');"; break;  //Assurer check
+               case 512:                                               // Find Assurer
+               case 516:                                               // TTP form
+               case 517: $expand = " explode('WoT');"; break;          // Assurer check
                case 1000:
                case 1001:
-               case 1002:
+               case 1002:                                              // View GPG key
                case 1003:
                case 1004:
                case 1005:
                case 1008:
                case 1009:
                case 1010: $expand = " explode('gpg');"; break;
-               case 1500:
-               case 1501:
-               case 1502:
+               case 1500:                                              // Dipute
+               case 1501:                                              // Dispute Email Request
+               case 1502:                                              // ViewEdit
                case 1503:
                case 1504:
                case 1505:
 <title><?=$title?></title>
 <? if(array_key_exists('header',$_SESSION) && $_SESSION['_config']['header'] != "") { ?><?=$_SESSION['_config']['header']?><? } ?>
 <link rel="stylesheet" href="/styles/default.css" type="text/css" />
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script language="JavaScript" type="text/javascript">
 function explode(e) {
     if (document.getElementById(e).style.display == 'none') {
@@ -174,10 +178,8 @@ function hideall() {
     </div>
     <div class="relatedLinks">
       <h3 class="pointer" onclick="explode('mydetails')">+ <?=_("My Details")?></h3>
-      <ul class="menu" id="mydetails"><li><a href="account.php?id=13"><?=_("View/Edit")?></a></li><li><a href="account.php?id=14"><?=_("Change Password")?></a></li><li><a href="account.php?id=41"><?=_("Default Language")?></a></li><li><a href="wot.php?id=8"><?=_("My Listing")?></a></li><li><a href="wot.php?id=13"><?=_("My Location")?></a></li><li><a href="account.php?id=36"><?=_("My Alert Settings")?></a></li><li><a href="wot.php?id=10"><?=_("My Points")?></a></li><?
-       if($_SESSION['profile']['id'] == 1 || $_SESSION['profile']['id'] == 5897)
-               echo "<li><a href='sqldump.php'>SQL Dump</a></li>";
-       ?></ul>
+      <ul class="menu" id="mydetails"><li><a href="account.php?id=13"><?=_("View/Edit")?></a></li><li><a href="account.php?id=14"><?=_("Change Password")?></a></li><li><a href="account.php?id=41"><?=_("Default Language")?></a></li><li><a href="wot.php?id=8"><?=_("My Listing")?></a></li><li><a href="wot.php?id=13"><?=_("My Location")?></a></li><li><a href="account.php?id=36"><?=_("My Alert Settings")?></a></li><li><a href="account.php?id=55"><?=_("My Trainings")?></a></li><li><a href="wot.php?id=10"><?=_("My Points")?></a></li>
+     </ul>
     </div>
     <div class="relatedLinks">
       <h3 class="pointer" onclick="explode('emailacc')">+ <?=_("Email Accounts")?></h3>
@@ -270,7 +272,7 @@ function hideall() {
     <div class="story">
       <h3><?=$title2?></h3>
 <? if($_SESSION['_config']['errmsg'] != "") { ?>
-<p><font color="#ff0000" size="+2"><? echo $_SESSION['_config']['errmsg']; $_SESSION['_config']['errmsg'] = ""; ?> </font></p>
+<p class="error_fatal"><? echo $_SESSION['_config']['errmsg']; $_SESSION['_config']['errmsg'] = ""; ?></p>
 <? } ?>
 <?
        }
index be94549..83802ad 100644 (file)
@@ -17,6 +17,7 @@
 */
 
        require_once(dirname(__FILE__)."/lib/general.php");
+       require_once(dirname(__FILE__)."/notary.inc.php");
 
        session_name("cacert");
        session_start();
 //     if($_SESSION['profile']['id'] > 0)
 //             session_regenerate_id();
 
+       //cf. http://stackoverflow.com/a/14532168
+       if(!defined('ENT_HTML401'))     define('ENT_HTML401', 0);
+       if(!defined('ENT_XML1'))        define('ENT_XML1', 16);
+       if(!defined('ENT_XHTML'))       define('ENT_XHTML', 32);
+       if(!defined('ENT_HTML5'))       define('ENT_HTML5', (32|16));
+
        $pageLoadTime_Start = microtime(true);
 
        $junk = array(_("Face to Face Meeting"), _("Trusted Third Parties"), _("Thawte Points Transfer"), _("Administrative Increase"),
@@ -46,9 +53,7 @@
 
        if(array_key_exists('HTTP_HOST',$_SERVER) &&
                        $_SERVER['HTTP_HOST'] != $_SESSION['_config']['normalhostname'] &&
-                       $_SERVER['HTTP_HOST'] != $_SESSION['_config']['securehostname'] &&
-                       $_SERVER['HTTP_HOST'] != $_SESSION['_config']['tverify'] &&
-                       $_SERVER['HTTP_HOST'] != "stamp.cacert.org")
+                       $_SERVER['HTTP_HOST'] != $_SESSION['_config']['securehostname'])
        {
                if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
                        header("location: https://".$_SESSION['_config']['normalhostname']);
        }
 
        if(array_key_exists('HTTP_HOST',$_SERVER) &&
-                       ($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] ||
-                       $_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify']))
+                       ($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname']))
        {
                if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
                {
                }
                else
                {
-                       if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'])
-                       header("location: https://". $_SESSION['_config']['securehostname']);
-                       if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify'])
-                       header("location: https://".$_SESSION['_config']['tverify']);
+                       if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname']){
+                               header("location: https://". $_SESSION['_config']['securehostname']);
+                       }
                        exit;
+
                }
        }
 
        L10n::detect_language();
        L10n::init_gettext();
 
-        if(array_key_exists('profile',$_SESSION) && is_array($_SESSION['profile']) && array_key_exists('id',$_SESSION['profile']) && $_SESSION['profile']['id'] > 0)
+       if(array_key_exists('profile',$_SESSION) && is_array($_SESSION['profile']) && array_key_exists('id',$_SESSION['profile']) && $_SESSION['profile']['id'] > 0)
        {
-               $locked = mysql_fetch_assoc(mysql_query("select `locked` from `users` where `id`='".$_SESSION['profile']['id']."'"));
+               $locked = mysql_fetch_assoc(mysql_query("select `locked` from `users` where `id`='".intval($_SESSION['profile']['id'])."'"));
                if($locked['locked'] == 0)
                {
-                       $query = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
-                       $res = mysql_query($query);
-                       $row = mysql_fetch_assoc($res);
-                       $_SESSION['profile']['points'] = $row['total'];
+                       update_points_in_profile();
                } else {
                        $_SESSION['profile'] = "";
                        unset($_SESSION['profile']);
 
        function loadem($section = "index")
        {
-               if($section != "index" && $section != "account" && $section != "tverify")
+               if($section != "index" && $section != "account")
                {
                        $section = "index";
                }
 
-               if($section == "account")
+               if($section == "account"){
                        include_once($_SESSION['_config']['filepath']."/includes/account_stuff.php");
+               }
 
-               if($section == "index")
+               if($section == "index"){
                        include_once($_SESSION['_config']['filepath']."/includes/general_stuff.php");
-
-               if($section == "tverify")
-                       include_once($_SESSION['_config']['filepath']."/includes/tverify_stuff.php");
+               }
        }
 
        function includeit($id = "0", $section = "index")
        {
                $id = intval($id);
-               if($section != "index" && $section != "account" && $section != "wot" && $section != "help" && $section != "gpg" && $section != "disputes" && $section != "tverify" && $section != "advertising")
+               if($section != "index" && $section != "account" && $section != "wot" && $section != "help" && $section != "gpg" && $section != "disputes" && $section != "advertising")
                {
                        $section = "index";
                }
 
-               if($section == "tverify" && file_exists($_SESSION['_config']['filepath']."/tverify/index/$id.php"))
-                       include_once($_SESSION['_config']['filepath']."/tverify/index/$id.php");
-               else if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
+               if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
                        include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
+               }
                else {
                        $id = "0";
 
-                       if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
+                       if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
                                include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
-                       else {
+                       else {
 
                                $section = "index";
                                $id = "0";
 
-                               if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
+                               if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
                                        include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
-                               else
+                               } else {
                                        include_once($_SESSION['_config']['filepath']."/www/error404.php");
+                               }
                        }
                }
        }
                //echo "Points due to name matches: $points<br/>";
 
                $shellpwd = escapeshellarg($pwd);
-               $do = `grep $shellpwd /usr/share/dict/american-english`;
+               $do = shell_exec("grep -F -- $shellpwd /usr/share/dict/american-english");
                if($do)
                        $points--;
 
                }
        }
 
+       function isValidWildcard($name){
+               if(substr($name,0,2) == "*."){
+                       $name = substr($name, 2);
+               }
+               if(!preg_match('/^(\\.(?!-)[a-z0-9_-]*[a-z0-9])+$/i','.'.$name)){
+                       return false;
+               }
+               return strpos($name, "*") === false;
+       }
+
        function getcn()
        {
                unset($_SESSION['_config']['rows']);
                        $bits = explode(".", $CN);
                        $dom = "";
                        $cnok = 0;
+
+                       if(!isValidWildcard($CN)){
+                               $_SESSION['_config']['rejected'][] = $CN;
+                               continue;
+                       }
+
                        for($i = count($bits) - 1; $i >= 0; $i--)
                        {
                                if($dom)
                                        $dom = $bits[$i];
                                $_SESSION['_config']['row'] = "";
                                $dom = mysql_real_escape_string($dom);
-                               $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
+                               $query = "select * from domains where `memid`='".intval($_SESSION['profile']['id'])."' and `domain` = '$dom' and `deleted`=0 and `hash`=''";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) > 0)
                                {
                        else
                                continue;
 
+                       if(!isValidWildcard($alt)){
+                               $_SESSION['_config']['rejected'][] = $alt;
+                               continue;
+                       }
+
                        $bits = explode(".", $alt);
                        $dom = "";
                        $altok = 0;
                                        $dom = $bits[$i];
                                $_SESSION['_config']['altrow'] = "";
                                $dom = mysql_real_escape_string($dom);
-                               $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
+                               $query = "select * from domains where `memid`='".intval($_SESSION['profile']['id'])."' and `domain` = '$dom' and `deleted`=0 and `hash`=''";
                                $res = mysql_query($query);
                                if(mysql_num_rows($res) > 0)
                                {
                        $CN = $_SESSION['_config']["$cnc.CN"];
                        $bits = explode(".", $CN);
                        $dom = "";
+
+                        if(!isValidWildcard($CN)){
+                                $_SESSION['_config']['rejected'][] = $CN;
+                                continue;
+                        }
+
                        for($i = count($bits) - 1; $i >= 0; $i--)
                        {
                                if($dom)
                                $_SESSION['_config']['row'] = "";
                                $dom = mysql_real_escape_string($dom);
                                $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
-                                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                                `org`.`orgid`=`orginfo`.`id` and
                                                `orgdomains`.`orgid`=`orginfo`.`id` and
                                                `orgdomains`.`domain`='$dom'";
                        else
                                continue;
 
+                        if(!isValidWildcard($alt)){
+                                $_SESSION['_config']['rejected'][] = $alt;
+                                continue;
+                        }
+
                        $bits = explode(".", $alt);
                        $dom = "";
                        for($i = count($bits) - 1; $i >= 0; $i--)
                                $_SESSION['_config']['altrow'] = "";
                                $dom = mysql_real_escape_string($dom);
                                $query = "select * from `orginfo`,`orgdomains`,`org` where
-                                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
                                                `org`.`orgid`=`orginfo`.`id` and
                                                `orgdomains`.`orgid`=`orginfo`.`id` and
                                                `orgdomains`.`domain`='$dom'";
                                $dom = $bits[$i];
                        $dom = mysql_real_escape_string($dom);
                        $query = "select * from `org`,`orgdomains`,`orginfo`
-                                       where `org`.`memid`='".$_SESSION['profile']['id']."'
+                                       where `org`.`memid`='".intval($_SESSION['profile']['id'])."'
                                        and `orgdomains`.`orgid`=`org`.`orgid`
                                        and `orginfo`.`id`=`org`.`orgid`
                                        and `orgdomains`.`domain`='$dom'";
                if($id <= 0)
                        $id = $_SESSION['profile']['id'];
 
-               $query = "select sum(`points`) as `points` from `notary` where `to`='$id' group by `to`";
-               $row = mysql_fetch_assoc(mysql_query($query));
-               $points = $row['points'];
+               $points = get_received_total_points($id);
 
                $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
-               $query = "select * from `users` where `id`='".$_SESSION['profile']['id']."' and `dob` < '$dob'";
+               $query = "select * from `users` where `id`='".intval($_SESSION['profile']['id'])."' and `dob` < '$dob'";
                if(mysql_num_rows(mysql_query($query)) < 1)
                {
                        if($points >= 100)
                return(0);
        }
 
-       function hex2bin($data)
+       /**
+        * Decode UTF-8 byte sequences into HTML entities
+        *
+        * @see https://blog.benny-baumann.de/?p=332
+        */
+       function charset_decode_utf8_callback($match) {
+               $m = $match[0];
+
+               switch(strlen($m)) {
+               case 6:
+                       // decode six byte unicode characters
+                       return '&#'.((ord($m[0])-252)*1073741824+(ord($m[1])-200)*16777216+(ord($m[2])-200)*262144+(ord($m[3])-128)*4096+(ord($m[4])-128)*64+(ord($m[5])-128)).';';
+               case 5:
+                       // decode five byte unicode characters
+                       return '&#'.((ord($m[0])-248)*16777216+(ord($m[1])-200)*262144+(ord($m[2])-128)*4096+(ord($m[3])-128)*64+(ord($m[4])-128)).';';
+               case 4:
+                       // decode four byte unicode characters
+                       return '&#'.((ord($m[0])-240)*262144+(ord($m[1])-128)*4096+(ord($m[2])-128)*64+(ord($m[3])-128)).';';
+               case 3:
+                       // decode three byte unicode characters
+                       return '&#'.((ord($m[0])-224)*4096+(ord($m[1])-128)*64+(ord($m[2])-128)).';';
+               case 2:
+                       // decode two byte unicode characters
+                       return '&#'.((ord($m[0])-192)*64+(ord($m[1])-128)).';';
+               default:
+                       return $m;
+               }
+       }
+
+       /**
+        * Decode utf-8 strings
+        * @param string $string Encoded string
+        * @return string Decoded string
+        * @see https://blog.benny-baumann.de/?p=332
+        */
+       function charset_decode_utf8 ($string) {
+               // decode 2-6 byte unicode characters
+               $string = preg_replace_callback("/[\374-\375][\200-\277][\200-\277][\200-\277][\200-\277][\200-\277]|".
+                       "[\370-\373][\200-\277][\200-\277][\200-\277][\200-\277]|".
+                       "[\360-\367][\200-\277][\200-\277][\200-\277]|".
+                       "[\340-\357][\200-\277][\200-\277]|".
+                       "[\300-\337][\200-\277]/",
+                       'charset_decode_utf8_callback', $string);
+
+               // remove broken unicode
+               $string = preg_replace("/[\200-\237]|\240|[\241-\377]/",'?',$string);
+
+               return $string;
+       }
+
+       function gpg_hex2bin($data)
        {
                while(strstr($data, "\\x"))
                {
                        $after = substr($data, $pos + 4);
                        $data = $before.$char.$after;
                }
-               return(utf8_decode($data));
+
+               return htmlentities(charset_decode_utf8($data), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);
        }
 
        function signmail($to, $subject, $message, $from, $replyto = "")
                $fp = fopen($tmpfname, "w");
                fputs($fp, $message);
                fclose($fp);
-               $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
+               $to_esc = escapeshellarg($to);
+               $do = shell_exec("/usr/bin/gpg --homedir /home/gpg --clearsign \"$tmpfname\"|/usr/sbin/sendmail ".$to_esc);
                @unlink($tmpfname);
        }
 
                if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
                {
                        list($username,$domain)=explode('@',$email,2);
-                       $dom = escapeshellarg($domain);
-                       $line = trim(`dig +short MX $dom 2>&1`);
-#echo $email."-$dom-$line-\n";
-#echo `dig +short mx heise.de 2>&1`."-<br>\n";
-
-                       $list = explode("\n", $line);
-                       foreach($list as $row) {
-                               if(!strstr($row, " ")) {
-                                       continue;
+                       $mxhostrr = array();
+                       $mxweight = array();
+                       if( !getmxrr($domain, $mxhostrr, $mxweight) ) {
+                               $mxhostrr = array($domain);
+                               $mxweight = array(0);
+                       } else if ( empty($mxhostrr) ) {
+                               $mxhostrr = array($domain);
+                               $mxweight = array(0);
+                       }
+
+                       $mxhostprio = array();
+                       for($i = 0; $i < count($mxhostrr); $i++) {
+                               $mx_host = trim($mxhostrr[$i], '.');
+                               $mx_prio = $mxweight[$i];
+                               if(empty($mxhostprio[$mx_prio])) {
+                                       $mxhostprio[$mx_prio] = array();
+                               }
+                               $mxhostprio[$mx_prio][] = $mx_host;
+                       }
+
+                       array_walk($mxhostprio, function(&$mx) { shuffle($mx); } );
+                       ksort($mxhostprio);
+
+                       $mxhosts = array();
+                       foreach($mxhostprio as $mx_prio => $mxhostnames) {
+                               foreach($mxhostnames as $mx_host) {
+                                       $mxhosts[] = $mx_host;
                                }
-                               list($pri, $mxhosts[]) = explode(" ", trim($row), 2);
                        }
-                       $mxhosts[] = $domain;
-                       array_walk($mxhosts, function(&$mx) { $mx = trim($mx, '.'); } );
 
                        foreach($mxhosts as $key => $domain)
                        {
-                               $fp = @fsockopen($domain,25,$errno,$errstr,5);
+                               $fp_opt = array(
+                                       'ssl' => array(
+                                               'verify_peer'   => false,       // Opportunistic Encryption
+                                               )
+                                       );
+                               $fp_ctx = stream_context_create($fp_opt);
+                               $fp = @stream_socket_client("tcp://$domain:25",$errno,$errstr,5,STREAM_CLIENT_CONNECT,$fp_ctx);
                                if($fp)
                                {
+                                       stream_set_blocking($fp, true);
 
-                                       $line = fgets($fp, 4096);
-                                        while(substr($line, 0, 4) == "220-")
-                                               $line = fgets($fp, 4096);
-                                       if(substr($line, 0, 3) != "220")
+                                       $has_starttls = false;
+
+                                       do {
+                                               $line = fgets($fp, 4096);
+                                       } while(substr($line, 0, 4) == "220-");
+                                       if(substr($line, 0, 3) != "220") {
+                                               fclose($fp);
                                                continue;
-                                       fputs($fp, "HELO www.cacert.org\r\n");
-                                       $line = fgets($fp, 4096);
-                                       while(substr($line, 0, 3) == "220")
+                                       }
+
+                                       fputs($fp, "EHLO www.cacert.org\r\n");
+                                       do {
                                                $line = fgets($fp, 4096);
-                                       if(substr($line, 0, 3) != "250")
+                                               $has_starttls |= substr(trim($line),4) == "STARTTLS";
+                                       } while(substr($line, 0, 4) == "250-");
+                                       if(substr($line, 0, 3) != "250") {
+                                               fclose($fp);
                                                continue;
-                                       fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
-                                       $line = fgets($fp, 4096);
+                                       }
+
+                                       if($has_starttls) {
+                                               fputs($fp, "STARTTLS\r\n");
+                                               do {
+                                                       $line = fgets($fp, 4096);
+                                               } while(substr($line, 0, 4) == "220-");
+                                               if(substr($line, 0, 3) != "220") {
+                                                       fclose($fp);
+                                                       continue;
+                                               }
+
+                                               stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
+
+                                               fputs($fp, "EHLO www.cacert.org\r\n");
+                                               do {
+                                                       $line = fgets($fp, 4096);
+                                               } while(substr($line, 0, 4) == "250-");
+                                               if(substr($line, 0, 3) != "250") {
+                                                       fclose($fp);
+                                                       continue;
+                                               }
+                                       }
 
-                                       if(substr($line, 0, 3) != "250")
+                                       fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
+                                       do {
+                                               $line = fgets($fp, 4096);
+                                       } while(substr($line, 0, 4) == "250-");
+                                       if(substr($line, 0, 3) != "250") {
+                                               fclose($fp);
                                                continue;
+                                       }
+
                                        fputs($fp, "RCPT TO:<$email>\r\n");
-                                       $line = trim(fgets($fp, 4096));
+                                       do {
+                                               $line = fgets($fp, 4096);
+                                       } while(substr($line, 0, 4) == "250-");
+                                       if(substr($line, 0, 3) != "250") {
+                                               fclose($fp);
+                                               continue;
+                                       }
+
                                        fputs($fp, "QUIT\r\n");
                                        fclose($fp);
 
                                        $line = mysql_real_escape_string(trim(strip_tags($line)));
                                        $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
-                                       if(is_array($_SESSION['profile'])) $query.=", `uid`='".$_SESSION['profile']['id']."'";
+                                       if(isset($_SESSION['profile']) && is_array($_SESSION['profile']) && isset($_SESSION['profile']['id'])) $query.=", `uid`='".intval($_SESSION['profile']['id'])."'";
                                        mysql_query($query);
 
                                        if(substr($line, 0, 3) != "250")
                                }
                        }
                }
-               $query = "insert into `pinglog` set `when`=NOW(), `uid`='".$_SESSION['profile']['id']."',
+               $query = "insert into `pinglog` set `when`=NOW(), `uid`='".intval($_SESSION['profile']['id'])."',
                                `email`='$myemail', `result`='Failed to make a connection to the mail server'";
                mysql_query($query);
                return _("Failed to make a connection to the mail server");
                        $subject="";
                        if(mysql_num_rows($res) > 0)
                        {
-                               printf(_("Your certificate request is still queued and hasn't been processed yet. Please wait, and go to Certificates -> View to see it's status."));
+                               printf('<p>' . _("Your certificate request is still queued and hasn't been processed yet. Please wait, and go to Certificates -> View to see it's status." . '</p>'));
                                $subject="[CAcert.org] Certificate TIMEOUT";
                                $body = "A certificate has timed out!\n\n";
                        }
                        else
                        {
-                               printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.")." certid:$table:".intval($certid), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                               printf('<p>' . _("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.") . " certid:$table:".intval($certid) . '</p>', "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
                                $subject="[CAcert.org] Certificate FAILURE";
                                $body = "A certificate has failed: $table $certid $id $show\n\n";
                        }
 
                        $body .= _("Best regards")."\n"._("CAcert.org Support!");
 
-                       sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
+                       sendmail("sw-message@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
 
                        if($show) showfooter();
                        if($show) exit;
 
        function sanitizeHTML($input)
        {
-               return htmlentities(strip_tags($input), ENT_QUOTES);
+               return htmlentities(strip_tags($input), ENT_QUOTES | ENT_SUBSTITUTE, 'ISO-8859-1', false);
                //In case of problems, please use the following line again:
                //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
                //return htmlspecialchars(strip_tags($input));
                return $res;
        }
 
+       /**
+         * Returns the given ip address truncated to /16 (ipv4) or to /48 (ipv6)
+         */
+       function anonymizeIP($ip){
+               $bits = @inet_pton($ip);
+               if($bits === false) {
+                       return false;
+               }
 
-?>
+               if(strlen($bits) == 4) {
+                       $bits[2] = "\0";
+                       $bits[3] = "\0";
+                       $newIP = @inet_ntop($bits);
+                       if($newIP !== false) {
+                               $newIP .= "/16";
+                       }
+                       return $newIP;
+               } else if(strlen($bits) == 16) {
+                       for($i=6;$i<16;$i++){
+                               $bits[$i]="\0";
+                       }
+                       $newIP = @inet_ntop($bits);
+                       if($newIP !== false) {
+                               $newIP .= "/48";
+                       }
+                       return $newIP;
+               }
+               return false;
+       }
index 4c1bd30..19c3d2f 100644 (file)
@@ -38,7 +38,7 @@ google_color_text = "000000";
 google_color_border = "FFFFFF";
 //-->
 </script>
-<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script><? } else { 
+<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script><? } else {
 ?><h2><?=_("Free digital certificates!")?></h2><? } ?></div>
   </div>
   <div id="pageNav">
@@ -47,15 +47,15 @@ google_color_border = "FFFFFF";
       <? if(array_key_exists('mconn',$_SESSION) && $_SESSION['mconn']) { ?>
       <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=1"><?=_("Join")?></a>
       <? } ?>
-      <a href="/policy/CAcertCommunityAgreement.php"><?=_("Community Agreement")?></a>
+      <a href="/policy/CAcertCommunityAgreement.html"><?=_("Community Agreement")?></a>
       <a href="/index.php?id=3"><?=_("Root Certificate")?></a>
     </div>
     <? if(array_key_exists('mconn',$_SESSION) && $_SESSION['mconn']) { ?>
     <div class="relatedLinks">
       <h3 class="pointer"><?=_("My Account")?></h3>
-      <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=4"><?=_("Password Login")?></a> 
+      <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=4"><?=_("Password Login")?></a>
       <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=5"><?=_("Lost Password")?></a>
-      <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=4&amp;noauto=1"><?=_("Net Cafe Login")?></a> 
+      <a href="https://<?=$_SESSION['_config']['normalhostname']?>/index.php?id=4&amp;noauto=1"><?=_("Net Cafe Login")?></a>
       <a href="https://<?=$_SESSION['_config']['securehostname']?>/index.php?id=4"><?=_("Certificate Login")?></a>
     </div>
     <? } ?>
@@ -80,7 +80,7 @@ google_color_border = "FFFFFF";
     <div class="story">
 <? if($title2!="") echo "<h3>$title2</h3>"; ?>
 <? if($_SESSION['_config']['errmsg'] != "") { ?>
-<p><font color="#ff0000" size="+2"><? echo $_SESSION['_config']['errmsg']; $_SESSION['_config']['errmsg'] = ""; ?> </font></p>
+<p class="error_fatal"><? echo $_SESSION['_config']['errmsg']; $_SESSION['_config']['errmsg'] = ""; ?></p>
 <? } ?>
 <?
 
@@ -137,8 +137,8 @@ if(!function_exists("showfooter"))
         <a href="/policy/PrivacyPolicy.html"><?=_("Privacy Policy")?></a> |
         <a href="/index.php?id=51"><?=_("Mission Statement")?></a> | <a href="/index.php?id=11"><?=_("Contact Us")?></a> |
        &copy;2002-<?=date("Y")?> <?=_("by CAcert")?></div>
-</div>  
-</body>             
+</div>
+</body>
 </html><?
        }
 }
index 2713a81..270a569 100644 (file)
@@ -24,7 +24,7 @@ if (array_key_exists('HTTP_USER_AGENT',$_SERVER) && strstr($_SERVER['HTTP_USER_A
                        'manually created certificate requests instead.')?></p>
        </noscript>
 
-       <div id="noActiveX" style="color:red">
+       <div id="noActiveX" class="error_fatal">
                <p><?=_('Could not initialize ActiveX object required for certificate generation.')?></p>
                <p><?=_('You have to enable ActiveX for this to work. On Windows Vista, Windows 7 and '.
                        'later versions you have to add this website to the list of trusted sites '.
@@ -41,7 +41,7 @@ if (array_key_exists('HTTP_USER_AGENT',$_SERVER) && strstr($_SERVER['HTTP_USER_A
                </p>
        </div>
 
-       <form method="post" style="display:none" action="account.php"
+       <form method="post" style="display:none;" action="account.php"
                        id="CertReqForm">
                <input type="hidden" name="oldid" value="<?=intval($id)?>" />
                <input type="hidden" id="CSR" name="CSR" />
@@ -72,7 +72,7 @@ if (array_key_exists('HTTP_USER_AGENT',$_SERVER) && strstr($_SERVER['HTTP_USER_A
                                // the maximum is 2048, then only 1024, 1536 and 2048 bits may
                                // be specified as key size.
                                echo _('Step')?>: <span id="keySizeStep"></span></p>
-                       <p style="color:red"><?php
+                       <p class="error_fatal"><?php
                                printf(_('Please note that RSA key sizes smaller than %d bit '.
                                        'will not be accepted by CAcert.'),
                                        2048)?>
@@ -121,7 +121,7 @@ if (array_key_exists('HTTP_USER_AGENT',$_SERVER) && strstr($_SERVER['HTTP_USER_A
                        <input type="hidden" name="keytype" value="NS">
                        <?=_("Keysize:")?> <keygen name="SPKAC" challenge="<? $_SESSION['spkac_hash']=make_hash(); echo $_SESSION['spkac_hash']; ?>">
 
-                       <input type="submit" name="submit" value="<?=_("Create Certificate Request")?>">
+                       <input type="submit" name="submit" value="<?=_("Generate key pair within browser")?>">
                        <input type="hidden" name="oldid" value="<?=intval($id)?>">
                </form>
        </p>
index e311668..f9c1399 100644 (file)
 
 /**
  * Function to recalculate the cached Assurer status
- * 
+ *
  * @param int $userID
  *     if the user ID is not given the flag will be recalculated for all users
- * 
+ *
  * @return bool
  *     false if there was an error on fixing the flag. This does NOT return the
  *     new value of the flag
@@ -30,7 +30,7 @@
 function fix_assurer_flag($userID = NULL)
 {
        // Update Assurer-Flag on users table if 100 points and CATS passed.
-       // 
+       //
        // We may have some performance issues here if no userID is given
        // there are ~150k assurances and ~220k users currently
        // but the exists-clause on cats_passed should be a good filter
@@ -46,20 +46,21 @@ function fix_assurer_flag($userID = NULL)
                                WHERE `cp`.`variant_id` = `cv`.`id`
                                        AND `cv`.`type_id` = 1
                                        AND `cp`.`user_id` = `u`.`id`
-                       ) 
+                       )
                        AND (
-                               SELECT SUM(`points`) FROM `notary` AS `n`
-                               WHERE `n`.`to` = `u`.`id`
+                               SELECT SUM(`awarded`) FROM `notary` AS `n`
+                               WHERE `n`.`to` = `u`.`id` AND `n`.`method` != \'Administrative Increase\' AND `n`.`from` != `n`.`to`
                                        AND (`n`.`expire` > now()
-                                       OR `n`.`expire` IS NULL)
+                                            OR `n`.`expire` IS NULL)
+                                       AND `n`.`deleted` = 0
                        ) >= 100';
-       
+
        $query = mysql_query($sql);
        if (!$query) {
                return false;
        }
        // Challenge has been passed and non-expired points >= 100
-       
+
        // Reset flag if requirements are not met
        //
        // Also a bit performance critical but assurer flag is only set on
@@ -80,19 +81,70 @@ function fix_assurer_flag($userID = NULL)
                                                AND `cp`.`user_id` = `u`.`id`
                                )
                                OR (
-                                       SELECT SUM(`points`) FROM `notary` AS `n`
-                                       WHERE `n`.`to` = `u`.`id`
+                                       SELECT SUM(`awarded`) FROM `notary` AS `n`
+                                       WHERE `n`.`to` = `u`.`id` AND `n`.`method` != \'Administrative Increase\' AND `n`.`from` != `n`.`to`
                                                AND (
                                                        `n`.`expire` > now()
                                                        OR `n`.`expire` IS NULL
                                                )
+                                               AND `n`.`deleted` = 0
                                ) < 100
                        )';
-       
+
        $query = mysql_query($sql);
        if (!$query) {
                return false;
        }
-       
+
        return true;
-}
\ No newline at end of file
+}
+
+/**
+ * Supported hash algorithms for signing certificates
+ */
+class HashAlgorithms {
+       /**
+        * Default hash algorithm identifier for signing
+        * @var string
+        */
+       public static $default = 'sha256';
+
+       /**
+        * Get display strings for the supported hash algorithms
+        * @return array(string=>array('name'=>string, 'info'=>string))
+        *     - [$hash_identifier]['name'] = Name that should be displayed in UI
+        *     - [$hash_identifier]['info'] = Additional information that can help
+        *       with the selection of a suitable algorithm
+        */
+       public static function getInfo() {
+               return array(
+                               'sha256' => array(
+                                               'name' => 'SHA-256',
+                                               'info' => _('Currently recommended, because the other algorithms might break on some older versions of the GnuTLS library (older than 3.x) still shipped in Debian for example.'),
+                                       ),
+                               'sha384' => array(
+                                               'name' => 'SHA-384',
+                                               'info' => '',
+                                       ),
+                               'sha512' => array(
+                                               'name' => 'SHA-512',
+                                               'info' => _('Highest protection against hash collision attacks of the algorithms offered here.'),
+                                       ),
+                       );
+       }
+
+       /**
+        * Check if the input is a supported hash algorithm identifier otherwise
+        * return the identifier of the default hash algorithm
+        *
+        * @param string $hash_identifier
+        * @return string The cleaned identifier
+        */
+       public static function clean($hash_identifier) {
+               if (array_key_exists($hash_identifier, self::getInfo() )) {
+                       return $hash_identifier;
+               } else {
+                       return self::$default;
+               }
+       }
+}
index 8ad2ccf..dd4f3a5 100644 (file)
@@ -128,7 +128,7 @@ function checkWeakKeyText($text)
 
        if ($algorithm === "rsaEncryption")
        {
-               if (!preg_match('/^\s*RSA Public Key: \((\d+) bit\)$/m', $text, $keysize))
+               if (!preg_match('/^\s*Public-Key: \((\d+) bit\)$/m', $text, $keysize))
                {
                        return failWithId("checkWeakKeyText(): Couldn't parse the RSA ".
                                                "key size.\nData:\n$text");
@@ -173,7 +173,7 @@ function checkWeakKeyText($text)
                        $exponent = $exponent[1]; // exponent might be very big =>
                        //handle as string using bc*()
 
-                       if (bccomp($exponent, "3") === 0)
+                       if (bccomp($exponent, "65537") < 0)
                        {
                                return sprintf(_("The keys you use might be insecure. ".
                                                        "Although there is currently no known attack for ".
@@ -308,7 +308,7 @@ function checkDebianVulnerability($text, $keysize = 0)
                if ($algorithm !== "rsaEncryption") return false;
                        
                /* Extract public key size */
-               if (!preg_match('/^\s*RSA Public Key: \((\d+) bit\)$/m', $text,
+               if (!preg_match('/^\s*Public-Key: \((\d+) bit\)$/m', $text,
                $keysize))
                {
                        trigger_error("checkDebianVulnerability(): Couldn't parse the ".
@@ -338,7 +338,7 @@ function checkDebianVulnerability($text, $keysize = 0)
 
 
        /* Extract RSA modulus */
-       if (!preg_match('/^\s*Modulus \(\d+ bit\):\n'.
+       if (!preg_match('/^\s*Modulus:\n'.
                                '((?:\s*[0-9a-f][0-9a-f]:(?:\n)?)+[0-9a-f][0-9a-f])$/m',
        $text, $modulus))
        {
index 85b132d..5458788 100644 (file)
 
 /**
  * Checks if the user may log in and retrieve the user id
- * 
+ *
  * Usually called with $_SERVER['SSL_CLIENT_M_SERIAL'] and
  *     $_SERVER['SSL_CLIENT_I_DN_CN']
- * 
+ *
  * @param $serial string
  *     usually $_SERVER['SSL_CLIENT_M_SERIAL']
  * @param $issuer_cn string
@@ -32,9 +32,9 @@
 function get_user_id_from_cert($serial, $issuer_cn)
 {
        $query = "select `memid` from `emailcerts` where
-                       `serial`='".mysql_escape_string($serial)."' and
+                       `serial`='".mysql_real_escape_string($serial)."' and
                        `rootcert`= (select `id` from `root_certs` where
-                               `Cert_Text`='".mysql_escape_string($issuer_cn)."') and
+                               `Cert_Text`='".mysql_real_escape_string($issuer_cn)."') and
                        `revoked`=0 and disablelogin=0 and
                        UNIX_TIMESTAMP(`expire`) - UNIX_TIMESTAMP() > 0";
        $res = mysql_query($query);
@@ -43,7 +43,7 @@ function get_user_id_from_cert($serial, $issuer_cn)
                $row = mysql_fetch_assoc($res);
                return intval($row['memid']);
        }
-       
+
        return -1;
 }
 
@@ -71,7 +71,7 @@ function failWithId($errormessage) {
 
 /**
  * Runs a command on the shell and return it's exit code and output
- * 
+ *
  * @param string $command
  *             The command to run. Make sure that you escapeshellarg() any non-constant
  *             parts as this is executed on a shell!
@@ -85,7 +85,7 @@ function failWithId($errormessage) {
  * @param string|bool $errors
  *             The output the command wrote to STDERR (this is passed as reference),
  *             if true (default) the output will be written to the real STDERR
- * 
+ *
  * @return int|bool
  *             The exit code of the command, true if the execution of the command
  *             failed (true because then
@@ -93,38 +93,38 @@ function failWithId($errormessage) {
  */
 function runCommand($command, $input = "", &$output = null, &$errors = true) {
        $descriptorspec = array();
-       
+
        if ($input !== true) {
                $descriptorspec[0] = array("pipe", "r"); // STDIN for child
        }
-       
+
        if ($output !== true) {
                $descriptorspec[1] = array("pipe", "w"); // STDOUT for child
        }
-       
+
        if ($errors !== true) {
                $descriptorspec[2] = array("pipe", "w"); // STDERR for child
        }
-       
+
        $proc = proc_open($command, $descriptorspec, $pipes);
-       
+
        if (is_resource($proc))
        {
                if ($input !== true) {
                        fwrite($pipes[0], $input);
                        fclose($pipes[0]);
                }
-               
+
                if ($output !== true) {
                        $output = stream_get_contents($pipes[1]);
                }
-               
+
                if ($errors !== true) {
                        $errors = stream_get_contents($pipes[2]);
                }
-               
+
                return proc_close($proc);
-               
+
        } else {
                return true;
        }
@@ -145,19 +145,18 @@ function runCommand($command, $input = "", &$output = null, &$errors = true) {
                {
                        $Result |= 5;
                }
-               
-               $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
+
+               $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now() and `deleted` = 0');
                $row = mysql_fetch_assoc($query);
                if ($row['points'] < 100) {
                        $Result |= 3;
                }
-               
+
                $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
                $row = mysql_fetch_assoc($query);
                if ($row['assurer_blocked'] > 0) {
                        $Result |= 9;
                }
-               
+
                return $Result;
        }
-       
\ No newline at end of file
index 85b7aff..4859946 100644 (file)
 class L10n {
        /**
         * These are tranlations we currently support.
-        * 
+        *
         * If another translation is added, it doesn't suffice to have gettext set
         * up, you also need to add it here, because it acts as a white list.
-        * 
+        *
         * @var array("ISO-language code" => "native name of the language")
         */
        public static $translations = array(
@@ -53,15 +53,15 @@ class L10n {
                                "zh-cn" => "&#x4e2d;&#x6587;(&#x7b80;&#x4f53;)",
                                "zh-tw" => "&#x4e2d;&#x6587;(&#33274;&#28771;)",
                        );
-       
+
        /**
         * setlocale needs a language + region code for whatever reason so here's
         * the mapping from a translation code to locales with the region that
         * seemed the most common for this language
-        * 
+        *
         * You probably never need this. Use {@link set_translation()} to change the
         * language instead of manually calling setlocale().
-        * 
+        *
         * @var array(string => string)
         */
        private static $locales = array(
@@ -101,11 +101,11 @@ class L10n {
                                "zh-cn" => "zh_CN",
                                "zh-tw" => "zh_TW",
                        );
-       
+
        /**
         * Auto-detects the language that should be used and sets it. Only works for
         * HTTP, not in a command line script.
-        * 
+        *
         * Priority:
         * <ol>
         *      <li>explicit parameter "lang" passed in HTTP (e.g. via GET)</li>
@@ -128,10 +128,10 @@ class L10n {
                                return;
                        }
                }
-               
-               
+
+
                $languages = array();
-               
+
                // parse Accept-Language header
                if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
                        $bits = explode(",", strtolower(
@@ -144,29 +144,29 @@ class L10n {
                                        $c = floatval(substr($b[1], 2));
                                else
                                        $c = 1;
-                               
+
                                if ($c != 0)
                                {
                                        $languages[trim($b[0])] = $c;
                                }
                        }
                }
-               
+
                // check if there is an explicit language given as parameter
                if(array_key_exists("lang",$_REQUEST) && trim($_REQUEST["lang"]) != "")
                {
                        // higher priority than those values in the header
                        $languages[strtolower(trim($_REQUEST["lang"]))] = 2.0;
                }
-               
+
                arsort($languages, SORT_NUMERIC);
-               
+
                // this is used to be compatible with browsers like internet
                // explorer which only provide the language code including the
                // region not without. Also handles the fallback to English (qvalues
                // may only have three digits after the .)
                $fallbacks = array("en" => 0.0005);
-               
+
                foreach($languages as $lang => $qvalue)
                {
                        // ignore any non-conforming values (that's why we don't need to
@@ -179,7 +179,7 @@ class L10n {
                        }
                        $lang_prefix = $matches[1]; // usually two-letter language code
                        $fallbacks[$lang_prefix] = $qvalue;
-                       
+
                        $chosen_translation = "";
                        if ($lang === '*') {
                                // According to the standard '*' matches anything but any
@@ -202,7 +202,7 @@ class L10n {
                                        }
                                }
                        }
-                       
+
                        if ($chosen_translation !== "")
                        {
                                if (self::set_translation($chosen_translation)) {
@@ -210,7 +210,7 @@ class L10n {
                                }
                        }
                }
-               
+
                // No translation found yet => try the prefixes
                arsort($fallbacks, SORT_NUMERIC);
                foreach ($fallbacks as $lang => $qvalue) {
@@ -218,16 +218,47 @@ class L10n {
                                return;
                        }
                }
-               
+
                // should not get here, as the fallback of "en" is provided and that
                // should always work => log an error
                trigger_error("L10n::detect_language(): could not set language",
                        E_USER_WARNING);
        }
-       
+
+       /**
+        * Normalise the translation code (e.g. from the old codes to the new)
+        *
+        * @return string
+        *              a translation code or the empty string if it can't be normalised
+        */
+       public static function normalise_translation($translation_code) {
+               // check $translation_code against whitelist
+               if (array_key_exists($translation_code, self::$translations) ) {
+                       return $translation_code;
+               }
+
+               // maybe it's a locale as previously used in the system? e.g. en_AU
+               if (preg_match('/^([a-z][a-z])_([A-Z][A-Z])$/', $translation_code, $matches) !== 1) {
+                       return '';
+               }
+
+               $lang_code = $matches[1];
+               $region_code = strtolower($matches[2]);
+
+               if (array_key_exists("${lang_code}-${region_code}", self::$translations)) {
+                       return "${lang_code}-${region_code}";
+               }
+
+               if (array_key_exists($lang_code, self::$translations)) {
+                       return $lang_code;
+               }
+
+               return '';
+       }
+
        /**
         * Get the set translation
-        * 
+        *
         * @return string
         *              a translation code or the empty string if not set
         */
@@ -238,13 +269,13 @@ class L10n {
                        return "";
                }
        }
-       
+
        /**
         * Set the translation to use.
-        * 
+        *
         * @param string $translation_code
         *              the translation code as specified in the keys of {@link $translations}
-        * 
+        *
         * @return bool
         *              <ul>
         *              <li>true if the translation has been set successfully</li>
@@ -255,27 +286,11 @@ class L10n {
         *              </ul>
         */
        public static function set_translation($translation_code) {
-               // check $translation_code against whitelist
-               if ( !array_key_exists($translation_code, self::$translations) ) {
-                       // maybe it's a locale as previously used in the system? e.g. en_AU
-                       if ( preg_match('/^([a-z][a-z])_([A-Z][A-Z])$/', $translation_code,
-                                           $matches) !== 1 ) {
-                               return false;
-                       }
-                       
-                       $lang_code = $matches[1];
-                       $region_code = strtolower($matches[2]);
-                       
-                       if ( array_key_exists("${lang_code}-${region_code}",
-                                                 self::$translations) ) {
-                               $translation_code = "${lang_code}-${region_code}";
-                       } elseif ( array_key_exists($lang_code, self::$translations) ) {
-                               $translation_code = $lang_code;
-                       } else {
-                               return false;
-                       }
+               $translation_code = self::normalise_translation($translation_code);
+               if (empty($translation_code)) {
+                       return false;
                }
-               
+
                // map translation to locale
                if ( !array_key_exists($translation_code, self::$locales) ) {
                        // weird. maybe you added a translation but haven't added a
@@ -285,7 +300,7 @@ class L10n {
                        return false;
                }
                $locale = self::$locales[$translation_code];
-               
+
                // set up locale
                if ( !putenv("LANG=$locale") ) {
                        trigger_error("L10n::set_translation(): could not set the ".
@@ -297,42 +312,42 @@ class L10n {
                                "LC_ALL to $locale", E_USER_WARNING);
                        return false;
                }
-               
-               
+
+
                // only set if we're running in a server not in a script
                if (isset($_SESSION)) {
                        // save the setting
                        $_SESSION['_config']['language'] = $translation_code;
-                       
-                       
+
+
                        // Set up the recode settings needed e.g. in PDF creation
                        $_SESSION['_config']['recode'] = "html..latin-1";
-                       
+
                        if($translation_code === "zh-cn" || $translation_code === "zh-tw")
                        {
                                $_SESSION['_config']['recode'] = "html..gb2312";
-                               
+
                        } else if($translation_code === "pl" || $translation_code === "hu") {
                                $_SESSION['_config']['recode'] = "html..ISO-8859-2";
-                               
+
                        } else if($translation_code === "ja") {
                                $_SESSION['_config']['recode'] = "html..SHIFT-JIS";
-                               
+
                        } else if($translation_code === "ru") {
                                $_SESSION['_config']['recode'] = "html..ISO-8859-5";
-                               
+
                        } else if($translation_code == "lt") { // legacy, keep for reference
                                $_SESSION['_config']['recode'] = "html..ISO-8859-13";
-                               
+
                        }
                }
-               
+
                return true;
        }
-       
+
        /**
         * Sets up the text domain used by gettext
-        * 
+        *
         * @param string $domain
         *              the gettext domain that should be used, defaults to "messages"
         */
@@ -340,4 +355,21 @@ class L10n {
                bindtextdomain($domain, $_SESSION['_config']['filepath'].'/locale');
                textdomain($domain);
        }
-}
\ No newline at end of file
+
+       public static function set_recipient_language($accountid) {
+               //returns the language of a recipient to make sure that the language is correct
+               //use together with
+               $query = "select `language` from `users` where `id`='".intval($accountid)."'";
+               $res = mysql_query($query);
+               if (mysql_num_rows($res)>=0) {
+                       $row = mysql_fetch_assoc($res);
+                       if (NULL==$row['language'] || $row['language']=='') {
+                               self::set_translation('en');
+                       } else {
+                               self::set_translation($row['language']);
+                       }
+               } else {
+                       self::set_translation('en');
+               }
+       }
+}
index 4f9b8e8..cf36592 100644 (file)
@@ -19,6 +19,7 @@
        include_once("../includes/lib/general.php");
        require_once("../includes/lib/l10n.php");
        include_once("../includes/mysql.php");
+       require_once('../includes/notary.inc.php');
 
        if(!isset($_SESSION['profile']) || !is_array($_SESSION['profile'])) {
                $_SESSION['profile'] = array( 'id' => 0, 'loggedin' => 0 );
                        if($key == '_config' || $key == 'mconn' || 'csrf_' == substr($key, 0, 5))
                                continue;
                        if(is_int($key) || is_string($key))
-                               unset($_SESSION[$key]);
-                       unset($$key);
-                       //session_unregister($key);
+                               unset($_SESSION[$key]);
+                       unset($$key);
+                       //session_unregister($key);
                }
 
-               $_SESSION['profile'] = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='$uid'"));
+               $_SESSION['profile'] = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($uid)."'"));
                if($_SESSION['profile']['locked'] == 0)
                        $_SESSION['profile']['loggedin'] = 1;
                else
                        unset($_SESSION['profile']);
        }
-  
+
        if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] && ($_SESSION['profile']['id'] == 0 || $_SESSION['profile']['loggedin'] == 0))
        {
                $user_id = get_user_id_from_cert($_SERVER['SSL_CLIENT_M_SERIAL'],
                                if($key == '_config' || $key == 'mconn' || 'csrf_' == substr($key, 0, 5))
                                        continue;
                                if(is_int($key) || is_string($key))
-                                       unset($_SESSION[$key]);
-                               unset($$key);
-                               //session_unregister($key);
+                                       unset($_SESSION[$key]);
+                               unset($$key);
+                               //session_unregister($key);
                        }
 
                        $_SESSION['profile'] = mysql_fetch_assoc(mysql_query(
-                                       "select * from `users` where `id`='".$user_id."'"));
+                                       "select * from `users` where `id`='".intval($user_id)."'"));
                        if($_SESSION['profile']['locked'] == 0)
                                $_SESSION['profile']['loggedin'] = 1;
                        else
                        {
                                if($key == '_config' || $key == 'mconn' || 'csrf_' == substr($key, 0, 5))
                                        continue;
-                               unset($_SESSION[$key]);
-                               unset($$key);
-                               //session_unregister($key);
+                               unset($_SESSION[$key]);
+                               unset($$key);
+                               //session_unregister($key);
                        }
 
-                       $_SESSION['_config']['oldlocation'] = '';
-
-                       foreach($_GET as $key => $val)
-                       {
-                               if($_SESSION['_config']['oldlocation'])
-                                       $_SESSION['_config']['oldlocation'] .= "&";
-
-                               $key = str_replace(array("\n", "\r"), '', $key);
-                               $val = str_replace(array("\n", "\r"), '', $val);
-                               $_SESSION['_config']['oldlocation'] .= "$key=$val";
-                       }
-                       $_SESSION['_config']['oldlocation'] = substr($_SERVER['SCRIPT_NAME'], 1)."?".$_SESSION['_config']['oldlocation'];
-
-                       header("location: https://".$_SESSION['_config']['securehostname']."/index.php?id=4");
+                       $_SESSION['_config']['oldlocation'] = $_SERVER['REQUEST_URI'];
+                       header("Location: https://{$_SESSION['_config']['securehostname']}/index.php?id=4");
                        exit;
                }
        }
 
        if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] && ($_SESSION['profile']['id'] <= 0 || $_SESSION['profile']['loggedin'] == 0))
        {
-               header("location: https://".$_SESSION['_config']['normalhostname']);
+               header("Location: https://{$_SESSION['_config']['normalhostname']}");
                exit;
        }
 
        if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] && $_SESSION['profile']['id'] > 0 && $_SESSION['profile']['loggedin'] > 0)
        {
-               $query = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
-               $res = mysql_query($query);
-               $row = mysql_fetch_assoc($res);
-               $_SESSION['profile']['points'] = $row['total'];
+               update_points_in_profile();
 
                if($_SESSION['profile']['language'] == "")
                {
                        $query = "update `users` set `language`='".L10n::get_translation()."'
-                                                       where `id`='".$_SESSION['profile']['id']."'";
+                                                       where `id`='".intval($_SESSION['profile']['id'])."'";
                        mysql_query($query);
                } else {
                        L10n::set_translation($_SESSION['profile']['language']);
                $_SESSION['profile'] = "";
                foreach($_SESSION as $key => $value)
                {
-                       unset($_SESSION[$key]);
-                       unset($$key);
-                       //session_unregister($key);
+                       unset($_SESSION[$key]);
+                       unset($$key);
+                       //session_unregister($key);
                }
 
-               header("location: https://".$normalhost."/index.php");
+               header("Location: https://{$normalhost}/index.php");
                exit;
        }
 
        if($_SESSION['profile']['loggedin'] < 1)
        {
-               $_SESSION['_config']['oldlocation'] = '';
-
-               foreach($_REQUEST as $key => $val)
-               {
-                       if('' != $_SESSION['_config']['oldlocation'])
-                               $_SESSION['_config']['oldlocation'] .= "&";
+               $_SESSION['_config']['oldlocation'] = $_SERVER['REQUEST_URI'];
+               header("Location: https://{$_SERVER['HTTP_HOST']}/index.php?id=4");
+               exit;
+       }
 
-                       $key = str_replace(array("\n", "\r"), '', $key);
-                       $val = str_replace(array("\n", "\r"), '', $val);
-                       $_SESSION['_config']['oldlocation'] .= "$key=$val";
+       if (!isset($_SESSION['profile']['ccaagreement']) || !$_SESSION['profile']['ccaagreement']) {
+               $_SESSION['profile']['ccaagreement']=get_user_agreement_status($_SESSION['profile']['id'],'CCA');
+               if (!$_SESSION['profile']['ccaagreement']) {
+                       $_SESSION['_config']['oldlocation'] = $_SERVER['REQUEST_URI'];
+                       header("Location: https://{$_SERVER['HTTP_HOST']}/index.php?id=52");
+                       exit;
                }
-               $_SESSION['_config']['oldlocation'] = substr($_SERVER['SCRIPT_NAME'], 1)."?".$_SESSION['_config']['oldlocation'];
-               $hostname=$_SERVER['HTTP_HOST'];
-               $hostname = str_replace(array("\n", "\r"), '', $hostname);
-               header("location: https://".$hostname."/index.php?id=4");
-               exit;
        }
 ?>
index 10185fc..d246f8f 100644 (file)
@@ -24,7 +24,6 @@
        }
        $_SESSION['_config']['normalhostname'] = "www.cacert.org";
        $_SESSION['_config']['securehostname'] = "secure.cacert.org";
-       $_SESSION['_config']['tverify'] = "tverify.cacert.org";
 
        function sendmail($to, $subject, $message, $from, $replyto = "", $toname = "", $fromname = "", $errorsto = "returns@cacert.org", $extra="")
        {
index cb05d6b..a6c265c 100644 (file)
@@ -16,6 +16,9 @@
     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
 
+define('NULL_DATETIME', '0000-00-00 00:00:00');
+define('THAWTE_REVOCATION_DATETIME', '2010-11-16 00:00:00');
+
        function query_init ($query)
        {
                return mysql_query($query);
@@ -35,7 +38,7 @@
        function get_number_of_assurances ($userid)
        {
                $res = query_init ("SELECT count(*) AS `list` FROM `notary`
-                       WHERE `method` = 'Face to Face Meeting' AND `from`='".intval($userid)."' ");
+                       WHERE `method` = 'Face to Face Meeting' AND `from`='".intval($userid)."' and `deleted` = 0");
                $row = query_getnextrow($res);
 
                return intval($row['list']);
@@ -44,7 +47,7 @@
        function get_number_of_ttpassurances ($userid)
        {
                $res = query_init ("SELECT count(*) AS `list` FROM `notary`
-                       WHERE (`method`='Trusted Third Parties' or `method`='TTP-Assisted') AND `to`='".intval($userid)."' ");
+                       WHERE (`method`='Trusted Third Parties' or `method`='TTP-Assisted') AND `to`='".intval($userid)."' and `deleted` = 0");
                $row = query_getnextrow($res);
 
                return intval($row['list']);
@@ -53,7 +56,7 @@
        function get_number_of_assurees ($userid)
        {
                $res = query_init ("SELECT count(*) AS `list` FROM `notary`
-                       WHERE `method` = 'Face to Face Meeting' AND `to`='".intval($userid)."' ");
+                       WHERE `method` = 'Face to Face Meeting' AND `to`='".intval($userid)."' and `deleted` = 0");
                $row = query_getnextrow($res);
 
                return intval($row['list']);
@@ -62,7 +65,7 @@
     &nb