894f2983028420fb67ac21faf7108a4e45a072ee
[cacert.git] / www / gpg.php
1 <? /*
2 LibreSSL - CAcert web application
3 Copyright (C) 2004-2008 CAcert Inc.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */ ?>
18 <?
19 require_once("../includes/loggedin.php");
20
21 $id = 0; if(array_key_exists('id',$_REQUEST)) $id=intval($_REQUEST['id']);
22 $oldid = $_REQUEST['oldid'] = array_key_exists('oldid',$_REQUEST) ? intval($_REQUEST['oldid']) : 0;
23
24 if($_SESSION['profile']['points'] < 50)
25 {
26 header("location: /account.php");
27 exit;
28 }
29
30 loadem("account");
31
32
33
34 $CSR=""; if(array_key_exists('CSR',$_REQUEST)) $CSR=stripslashes($_REQUEST['CSR']);
35
36
37 if($oldid == "0")
38 {
39 if(array_key_exists('process',$_REQUEST) && $_REQUEST['process'] != "" && $CSR == "")
40 {
41 $_SESSION['_config']['errmsg'] = _("You failed to paste a valid GPG/PGP key.");
42 $id = $oldid;
43 $oldid=0;
44 }
45 }
46
47 $keyid="";
48
49 if(0)
50 {
51 if($_SESSION["profile"]["id"] != 5897)
52 {
53 showheader(_("Welcome to CAcert.org"));
54 echo "The OpenPGP signing system is currently shutdown due to a maintenance. We hope to get it fixed within the next few hours. We are very sorry for the inconvenience.";
55
56 exit(0);
57 }
58 }
59
60
61 function verifyName($name)
62 {
63 if($name == "") return 0;
64 if($name == $_SESSION['profile']['fname']." ".$_SESSION['profile']['lname']) return 1;
65 if($name == $_SESSION['profile']['fname']." ".$_SESSION['profile']['mname']." ".$_SESSION['profile']['lname']) return 1;
66 if($name == $_SESSION['profile']['fname']." ".$_SESSION['profile']['lname']." ".$_SESSION['profile']['suffix']) return 1;
67 if($name == $_SESSION['profile']['fname']." ".$_SESSION['profile']['mname']." ".$_SESSION['profile']['lname']." ".$_SESSION['profile']['suffix']) return 1;
68 return 0;
69
70 }
71
72 function verifyEmail($email)
73 {
74 if($email == "") return 0;
75 if(mysql_num_rows(mysql_query("select * from `email` where `memid`='".$_SESSION['profile']['id']."' and `email`='".mysql_real_escape_string($email)."' and `deleted`=0 and `hash`=''")) > 0) return 1;
76 return 0;
77 }
78
79
80
81 $ToBeDeleted=array();
82 $state=0;
83 if($oldid == "0" && $CSR != "")
84 {
85 $debugkey = $gpgkey = clean_gpgcsr($CSR);
86 $debugpg = $gpg = trim(`echo "$gpgkey"|gpg --with-colons --homedir /tmp 2>&1`);
87 $lines = "";
88 $gpgarr = explode("\n", $gpg);
89 foreach($gpgarr as $line)
90 {
91 #echo "Line[]: $line <br/>\n";
92 if(substr($line, 0, 3) == "pub" || substr($line, 0, 3) == "uid")
93 {
94 if($lines != "")
95 $lines .= "\n";
96 $lines .= $line;
97 }
98 }
99 $gpg = $lines;
100 $expires = 0;
101 $nerr=0; $nok=0;
102 $multiple = 0;
103
104 $resulttable=_("The following UIDs were found in your key:")."<br/><table border='1'><tr><td>#</td><td>"._("Name")."</td><td>"._("Email")."</td><td>Result</td>";
105 $i=0;
106 $lastvalidemail="";
107 $npubs=0;
108 foreach(explode("\n", $gpg) as $line)
109 {
110 $bits = explode(":", $line);
111 $resulttable.="<tr><td>".++$i."</td>";
112 $name = $comment = "";
113 if($bits[0] == "pub")
114 {
115 $npubs++;
116 }
117 if($npubs>1)
118 {
119 showheader(_("Welcome to CAcert.org"));
120 echo "<font color='#ff0000'>"._("Please upload only one key at a time.")."</font>";
121 unset($_REQUEST['process']);
122 $id = $oldid;
123 unset($oldid);
124 exit();
125 }
126 if($bits[0] == "pub" && (!$keyid || !$when))
127 {
128 $keyid = $bits[4];
129 $when = $bits[5];
130 if($bits[6] != "")
131 $expires = 1;
132 }
133 $name="";
134 $comm="";
135 $mail="";
136 $uidformatwrong=0;
137
138 if(sizeof($bits)<10) $uidformatwrong=1;
139
140 if(preg_match("/\@.*\@/",$bits[9]))
141 {
142 showheader(_("Welcome to CAcert.org"));
143
144 echo "<font color='#ff0000'>"._("Multiple Email Adresses per UID are not allowed.")."</font>";
145 unset($_REQUEST['process']);
146 $id = $oldid;
147 unset($oldid);
148 exit();
149 }
150
151 // Name (Comment) <Email>
152 if(preg_match("/^([^\(\)\[@<>]+) \(([^\(\)@<>]*)\) <([\w=\/%.-]*\@[\w.-]*|[\w.-]*\![\w=\/%.-]*)>/",$bits[9],$matches))
153 {
154 $name=trim(hex2bin($matches[1]));
155 $nocomment=0;
156 $comm=trim(hex2bin($matches[2]));
157 $mail=trim(hex2bin($matches[3]));
158 }
159 // Name <EMail>
160 elseif(preg_match("/^([^\(\)\[@<>]+) <([\w=\/%.-]*\@[\w.-]*|[\w.-]*\![\w=\/%.-]*)>/",$bits[9],$matches))
161 {
162 $name=trim(hex2bin($matches[1]));
163 $nocomment=1;
164 $comm="";
165 $mail=trim(hex2bin($matches[2]));
166 }
167 // Unrecognized format
168 else
169 {
170 $nocomment=1;
171 $uidformatwrong=1;
172 }
173 $nameok=verifyName($name);
174 $emailok=verifyEmail($mail);
175
176
177 if($comm != "")
178 $comment[] = $comm;
179
180 $resulttable.="<td bgcolor='#".($nameok?"c0ffc0":"ffc0c0")."'>".sanitizeHTML($name)."</td>";
181 $resulttable.="<td bgcolor='#".($emailok?"c0ffc0":"ffc0c0")."'>".sanitizeHTML($mail)."</td>";
182
183 $uidok=0;
184 if($bits[1]=="r")
185 {
186 $rmessage=_("Error: UID is revoked");
187 }
188 elseif($uidformatwrong==1)
189 {
190 $rmessage=_("The format of the UID was not recognized. Please use 'Name (comment) &lt;email@domain>'");
191 }
192 elseif($mail=="" and $name=="")
193 {
194 $rmessage=_("Error: Both Name and Email address are empty");
195 }
196 elseif($emailok and $nameok)
197 {
198 $uidok=1;
199 $rmessage=_("Name and Email OK.");
200 }
201 elseif(!$emailok and !$nameok)
202 {
203 $rmessage=_("Name and Email both cannot be matched with your account.");
204 }
205 elseif($emailok and $name=="")
206 {
207 $uidok=1;
208 $rmessage=_("The email is OK. The name is empty.");
209 }
210 elseif($nameok and $mail=="")
211 {
212 $uidok=1;
213 $rmessage=_("The name is OK. The email is empty.");
214 }
215 elseif(!$emailok)
216 {
217 $rmessage=_("The email address has not been registered and verified in your account. Please add the email address to your account first.");
218 }
219 elseif(!$nameok)
220 {
221 $rmessage=_("The name in the UID does not match the name in your account. Please verify the name.");
222 }
223
224 else
225 {
226 $rmessage=_("Error");
227 }
228 if($uidok)
229 {
230 $nok++;
231 $resulttable.="<td>$rmessage</td>";
232 $lastvalidemail=$mail;
233 }
234 else
235 {
236 $nerr++;
237 //$ToBeDeleted[]=$i;
238 //echo "Adding UID $i\n";
239 $resulttable.="<td bgcolor='#ffc0c0'>$rmessage</td>";
240 }
241 $resulttable.="</tr>\n";
242
243 if($emailok) $multiple++;
244 }
245 $resulttable.="</table>";
246
247
248 if($nok==0)
249 {
250 showheader(_("Welcome to CAcert.org"));
251 echo $resulttable;
252
253 echo "<font color='#ff0000'>"._("No valid UIDs found on your key")."</font>";
254 unset($_REQUEST['process']);
255 $id = $oldid;
256 unset($oldid);
257 $do = `echo "$debugkey\n--\n$debugpg\n--" >> /www/tmp/gpg.debug`;
258 exit();
259 }
260 elseif($nerr)
261 {
262 $resulttable.=_("The unverified UIDs have been removed, the verified UIDs have been signed.");
263 }
264
265
266 }
267
268
269 if($oldid == "0" && $CSR != "")
270 {
271 $query = "insert into `gpg` set `memid`='".intval($_SESSION['profile']['id'])."',
272 `email`='".mysql_real_escape_string($lastvalidemail)."',
273 `level`='1',
274 `expires`='".mysql_real_escape_string($expires)."',
275 `multiple`='".mysql_real_escape_string($multiple)."',
276 `keyid`='".mysql_real_escape_string($keyid)."'";
277 mysql_query($query);
278 $id = mysql_insert_id();
279
280
281 $cwd = '/tmp/gpgspace'.$id;
282 mkdir($cwd,0755);
283
284 $fp = fopen("$cwd/gpg.csr", "w");
285 fputs($fp, clean_gpgcsr($CSR));
286 fclose($fp);
287
288
289 system("gpg --homedir $cwd --import $cwd/gpg.csr");
290
291
292 $debugpg = $gpg = trim(`gpg --homedir $cwd --with-colons --fixed-list-mode --list-keys $keyid 2>&1`);
293 $lines = "";
294 $gpgarr = explode("\n", $gpg);
295 foreach($gpgarr as $line)
296 {
297 //echo "Line[]: $line <br/>\n";
298 if(substr($line, 0, 4) == "uid:")
299 {
300 $name = $comment = "";
301 $bits = explode(":", $line);
302
303 $pos = strpos($bits[9], "(") - 1;
304 $nocomment = 0;
305 if($pos < 0)
306 {
307 $nocomment = 1;
308 $pos = strpos($bits[9], "<") - 1;
309 }
310 if($pos < 0)
311 {
312 $pos = strlen($bits[9]);
313 }
314
315 $name = trim(hex2bin(trim(substr($bits[9], 0, $pos))));
316 $nameok=verifyName($name);
317 if($nocomment == 0)
318 {
319 $pos += 2;
320 $pos2 = strpos($bits[9], ")");
321 $comm = trim(hex2bin(trim(substr($bits[9], $pos, $pos2 - $pos))));
322 if($comm != "")
323 $comment[] = $comm;
324 $pos = $pos2 + 3;
325 } else {
326 $pos = strpos($bits[9], "<") + 1;
327 }
328
329 $mail="";
330 if (preg_match("/<([\w.-]*\@[\w.-]*)>/", $bits[9],$match)) {
331 //echo "Found: ".$match[1];
332 $mail = trim(hex2bin($match[1]));
333 }
334 else
335 {
336 //echo "Not found!\n";
337 }
338
339 $emailok=verifyEmail($mail);
340
341 $uidid=$bits[7];
342
343 if($bits[1]=="r")
344 {
345 $ToBeDeleted[]=$uidid;
346 }
347 elseif($mail=="" and $name=="")
348 {
349 //echo "$uidid will be deleted\n";
350 $ToBeDeleted[]=$uidid;
351 }
352 elseif($emailok and $nameok)
353 {
354 }
355 elseif($emailok and $name=="")
356 {
357 }
358 elseif($nameok and $mail=="")
359 {
360 }
361 elseif(!$emailok and !$nameok)
362 {
363 //echo "$uidid will be deleted\n";
364 $ToBeDeleted[]=$uidid;
365 }
366 elseif(!$emailok)
367 {
368 //echo "$uidid will be deleted\n";
369 $ToBeDeleted[]=$uidid;
370 }
371 elseif(!$nameok)
372 {
373 //echo "$uidid will be deleted\n";
374 $ToBeDeleted[]=$uidid;
375 }
376
377 }
378 }
379
380
381
382
383 if(count($ToBeDeleted)>0)
384 {
385
386
387 $descriptorspec = array(
388 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
389 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
390 2 => array("pipe", "w") // stderr is a file to write to
391 );
392
393 $stderr = fopen('php://stderr', 'w');
394
395
396 //echo "Keyid: $keyid\n";
397
398 $process = proc_open("/usr/bin/gpg --homedir $cwd --no-tty --command-fd 0 --status-fd 1 --logger-fd 2 --edit-key $keyid", $descriptorspec, $pipes);
399
400 //echo "Process: $process\n";
401 //fputs($stderr,"Process: $process\n");
402
403 if (is_resource($process)) {
404 //echo("it is a resource\n");
405 // $pipes now looks like this:
406 // 0 => writeable handle connected to child stdin
407 // 1 => readable handle connected to child stdout
408 // Any error output will be appended to /tmp/error-output.txt
409 while (!feof($pipes[1]))
410 {
411 $buffer = fgets($pipes[1], 4096);
412 //echo $buffer;
413
414 if($buffer == "[GNUPG:] GET_BOOL keyedit.sign_all.okay\n")
415 {
416 fputs($pipes[0],"yes\n");
417 }
418 elseif($buffer == "[GNUPG:] GOT_IT\n")
419 {
420 }
421 elseif(ereg("^\[GNUPG:\] GET_BOOL keyedit\.remove\.uid\.okay\s*",$buffer))
422 {
423 fputs($pipes[0],"yes\n");
424 }
425 elseif(ereg("^\[GNUPG:\] GET_LINE keyedit\.prompt\s*",$buffer))
426 {
427 if(count($ToBeDeleted)>0)
428 {
429 $delthisuid=array_pop($ToBeDeleted);
430 //echo "Deleting an UID $delthisuid\n";
431 fputs($pipes[0],"uid ".$delthisuid."\n");
432 }
433 else
434 {
435 //echo "Saving\n";
436 fputs($pipes[0],$state?"save\n":"deluid\n");
437 $state++;
438 }
439 }
440 elseif($buffer == "[GNUPG:] GOOD_PASSPHRASE\n")
441 {
442 }
443 elseif(ereg("^\[GNUPG:\] KEYEXPIRED ",$buffer))
444 {
445 echo "Key expired!\n";
446 exit;
447 }
448 elseif($buffer == "")
449 {
450 //echo "Empty!\n";
451 }
452 else
453 {
454 echo "ERROR: UNKNOWN $buffer\n";
455 }
456
457
458 }
459 //echo "Fertig\n";
460 fclose($pipes[0]);
461
462 //echo stream_get_contents($pipes[1]);
463 fclose($pipes[1]);
464
465 // It is important that you close any pipes before calling
466 // proc_close in order to avoid a deadlock
467 $return_value = proc_close($process);
468
469 //echo "command returned $return_value\n";
470 }
471 else
472 {
473 echo "Keine ressource!\n";
474 }
475
476
477 }
478
479
480 $csrname=generatecertpath("csr","gpg",$id);
481 $do=`gpg --homedir $cwd --batch --export-options export-minimal --export $keyid >$csrname`;
482
483 mysql_query("update `gpg` set `csr`='$csrname' where `id`='$id'");
484 waitForResult('gpg', $id);
485
486 showheader(_("Welcome to CAcert.org"));
487 echo $resulttable;
488 $query = "select * from `gpg` where `id`='$id' and `crt`!=''";
489 $res = mysql_query($query);
490 if(mysql_num_rows($res) <= 0)
491 {
492 echo _("Your certificate request has failed to be processed correctly, please try submitting it again.")."<br>\n";
493 echo _("If this is a re-occuring problem, please send a copy of the key you are trying to signed to support@cacert.org. Thank you.");
494 } else {
495 echo "<pre>";
496 readfile(generatecertpath("crt","gpg",$id));
497 echo "</pre>";
498 }
499
500 showfooter();
501 exit;
502 }
503
504 $id = intval($id);
505
506 showheader(_("Welcome to CAcert.org"));
507 includeit($id, "gpg");
508 showfooter();
509 ?>