tor.cgi: Check for valid relay address.
[people/teissler/ipfire-2.x.git] / html / cgi-bin / tor.cgi
1 #!/usr/bin/perl
2 ###############################################################################
3 # #
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2013 IPFire Team <info@ipfire.org> #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 use strict;
23 use Locale::Country;
24
25 # enable only the following on debugging purpose
26 use warnings;
27 use CGI::Carp 'fatalsToBrowser';
28
29 require '/var/ipfire/general-functions.pl';
30 require "${General::swroot}/lang.pl";
31 require "${General::swroot}/header.pl";
32
33 #workaround to suppress a warning when a variable is used only once
34 my @dummy = ( ${Header::colouryellow} );
35 undef (@dummy);
36
37 my @bandwidth_limits = (
38 1000 * 1024, # 1G
39 500 * 1024,
40 200 * 1024,
41 100 * 1024, # 100M
42 64 * 1024,
43 50 * 1024,
44 25 * 1024,
45 20 * 1024,
46 16 * 1024,
47 10 * 1024,
48 8 * 1024,
49 4 * 1024,
50 2 * 1024,
51 1024, # 1M
52 512,
53 256,
54 160
55 );
56 my @accounting_periods = ('daily', 'weekly', 'monthly');
57
58 my $TOR_CONTROL_PORT = 9051;
59
60 our %netsettings = ();
61 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
62
63 our %settings = ();
64
65 $settings{'TOR_ENABLED'} = 'off';
66 $settings{'TOR_SOCKS_PORT'} = 9050;
67 $settings{'TOR_EXIT_COUNTRY'} = '';
68 $settings{'TOR_USE_EXIT_NODES'} = '';
69 $settings{'TOR_ALLOWED_SUBNETS'} = "$netsettings{'GREEN_NETADDRESS'}\/$netsettings{'GREEN_NETMASK'}";
70 if (&Header::blue_used()) {
71 $settings{'TOR_ALLOWED_SUBNETS'} .= ",$netsettings{'BLUE_NETADDRESS'}\/$netsettings{'BLUE_NETMASK'}";
72 }
73
74 $settings{'TOR_RELAY_ENABLED'} = 'off';
75 $settings{'TOR_RELAY_MODE'} = 'exit';
76 $settings{'TOR_RELAY_ADDRESS'} = '';
77 $settings{'TOR_RELAY_PORT'} = 9001;
78 $settings{'TOR_RELAY_NICKNAME'} = '';
79 $settings{'TOR_RELAY_CONTACT_INFO'} = '';
80 $settings{'TOR_RELAY_NOADVERTISE'} = 'off';
81 $settings{'TOR_RELAY_BANDWIDTH_RATE'} = 0;
82 $settings{'TOR_RELAY_BANDWIDTH_BURST'} = 0;
83 $settings{'TOR_RELAY_ACCOUNTING_LIMIT'} = 0;
84 $settings{'TOR_RELAY_ACCOUNTING_PERIOD'} = 'daily';
85
86 $settings{'ACTION'} = '';
87
88 my $errormessage = '';
89 my $warnmessage = '';
90
91 &Header::showhttpheaders();
92
93 # Get GUI values.
94 &Header::getcgihash(\%settings);
95
96 # Create tor command connection.
97 our $torctrl = &TorConnect();
98
99 # Toggle enable/disable field.
100 if ($settings{'ACTION'} eq $Lang::tr{'save'}) {
101 if ($settings{'TOR_RELAY_NICKNAME'} !~ /^[a-zA-Z0-9]+$/) {
102 $errormessage = "$Lang::tr{'tor errmsg invalid relay name'}: $settings{'TOR_RELAY_NICKNAME'}";
103 }
104
105 if (!&General::validport($settings{'TOR_SOCKS_PORT'})) {
106 $errormessage = "$Lang::tr{'tor errmsg invalid socks port'}: $settings{'TOR_SOCKS_PORT'}";
107 }
108
109 if (!&General::validport($settings{'TOR_RELAY_PORT'})) {
110 $errormessage = "$Lang::tr{'tor errmsg invalid relay port'}: $settings{'TOR_RELAY_PORT'}";
111 }
112
113 if ($settings{'TOR_RELAY_ADDRESS'} ne '') {
114 if ((!&General::validfqdn($settings{'TOR_RELAY_ADDRESS'})) && (!&General::validip($settings{'TOR_RELAY_ADDRESS'}))) {
115 $errormessage = "$Lang::tr{'tor errmsg invalid relay address'}: $settings{'TOR_RELAY_ADDRESS'}";
116 }
117 }
118
119 my @temp = split(/[\n,]/,$settings{'TOR_ALLOWED_SUBNETS'});
120 $settings{'TOR_ALLOWED_SUBNETS'} = "";
121 foreach (@temp) {
122 s/^\s+//g; s/\s+$//g;
123 if ($_) {
124 unless (&General::validipandmask($_)) {
125 $errormessage = "$Lang::tr{'tor errmsg invalid ip or mask'}: $_";
126 }
127 $settings{'TOR_ALLOWED_SUBNETS'} .= $_.",";
128 }
129 }
130
131 @temp = split(/[\n,]/,$settings{'TOR_USE_EXIT_NODES'});
132 $settings{'TOR_USE_EXIT_NODES'} = "";
133 foreach (@temp) {
134 s/^\s+//g; s/\s+$//g;
135 if ($_) {
136 $settings{'TOR_USE_EXIT_NODES'} .= $_.",";
137 }
138 }
139
140 # Burst bandwidth must be less or equal to bandwidth rate.
141 if ($settings{'TOR_RELAY_BANDWIDTH_RATE'} == 0) {
142 $settings{'TOR_RELAY_BANDWIDTH_BURST'} = 0;
143
144 } elsif ($settings{'TOR_RELAY_BANDWIDTH_BURST'} < $settings{'TOR_RELAY_BANDWIDTH_RATE'}) {
145 $settings{'TOR_RELAY_BANDWIDTH_BURST'} = $settings{'TOR_RELAY_BANDWIDTH_RATE'};
146 }
147
148 if ($errormessage eq '') {
149 # Write configuration settings to file.
150 &General::writehash("${General::swroot}/tor/settings", \%settings);
151
152 # Update configuration files.
153 &BuildConfiguration();
154 }
155 } else {
156 # Load settings from file.
157 &General::readhash("${General::swroot}/tor/settings", \%settings);
158 }
159
160 &showMainBox();
161
162 # Close Tor control connection.
163 &TorClose($torctrl);
164
165 # Functions
166
167 sub showMainBox() {
168 my %checked = ();
169 my %selected = ();
170
171 $checked{'TOR_ENABLED'}{'on'} = '';
172 $checked{'TOR_ENABLED'}{'off'} = '';
173 $checked{'TOR_ENABLED'}{$settings{'TOR_ENABLED'}} = 'checked';
174
175 $checked{'TOR_RELAY_ENABLED'}{'on'} = '';
176 $checked{'TOR_RELAY_ENABLED'}{'off'} = '';
177 $checked{'TOR_RELAY_ENABLED'}{$settings{'TOR_RELAY_ENABLED'}} = 'checked';
178
179 &Header::openpage($Lang::tr{'tor configuration'}, 1, '');
180 &Header::openbigbox('100%', 'left', '', $errormessage);
181
182 if ($errormessage) {
183 &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
184 print "<font class='base'>$errormessage&nbsp;</font>\n";
185 &Header::closebox();
186 }
187
188 print "<form method='post' action='$ENV{'SCRIPT_NAME'}'>\n";
189
190 &Header::openbox('100%', 'left', $Lang::tr{'tor configuration'});
191
192 print <<END;
193 <table width='100%'>
194 <tr>
195 <td colspan='4' class='base'><b>$Lang::tr{'tor common settings'}</b></td>
196 </tr>
197 <tr>
198 <td width='25%' class='base'>$Lang::tr{'tor enabled'}:</td>
199 <td width='30%'><input type='checkbox' name='TOR_ENABLED' $checked{'TOR_ENABLED'}{'on'} /></td>
200 <td width='25%' class='base'>$Lang::tr{'tor socks port'}:</td>
201 <td width='20%'><input type='text' name='TOR_SOCKS_PORT' value='$settings{'TOR_SOCKS_PORT'}' size='5' /></td>
202 </tr>
203 <tr>
204 <td width='25%' class='base'>$Lang::tr{'tor relay enabled'}:</td>
205 <td width='30%'><input type='checkbox' name='TOR_RELAY_ENABLED' $checked{'TOR_RELAY_ENABLED'}{'on'} /></td>
206 <td width='25%' class='base'></td>
207 <td width='20%'></td>
208 </tr>
209 </table>
210 END
211
212 if ($settings{'TOR_ENABLED'} eq 'on') {
213 my @temp = split(",", $settings{'TOR_ALLOWED_SUBNETS'});
214 $settings{'TOR_ALLOWED_SUBNETS'} = join("\n", @temp);
215
216 @temp = split(",", $settings{'TOR_USE_EXIT_NODES'});
217 $settings{'TOR_USE_EXIT_NODES'} = join("\n", @temp);
218
219 print <<END;
220 <br>
221 <hr size='1'>
222 <br>
223
224 <table width='100%'>
225 <tr>
226 <td colspan='4' class='base'><b>$Lang::tr{'tor acls'}</b></td>
227 </tr>
228 <tr>
229 <td colspan='2' class='base' width='55%'>
230 $Lang::tr{'tor allowed subnets'}:
231 </td>
232 <td colspan='2' width='45%'></td>
233 </tr>
234 <tr>
235 <td colspan='2' class='base' width='55%'>
236 <textarea name='TOR_ALLOWED_SUBNETS' cols='32' rows='3' wrap='off'>$settings{'TOR_ALLOWED_SUBNETS'}</textarea>
237 </td>
238 <td colspan='2' width='45%'></td>
239 </tr>
240 </table>
241
242 <br>
243 <hr size='1'>
244 <br>
245
246 <table width='100%'>
247 <tr>
248 <td colspan='4' class='base'><b>$Lang::tr{'tor exit nodes'}</b></td>
249 </tr>
250 <tr>
251 <td colspan='2' class='base' width='55%'></td>
252 <td colspan='2' class='base' width='45%'>$Lang::tr{'tor use exit nodes'}:</td>
253 </tr>
254 <tr>
255 <td width='50%' colspan='2'>
256 <select name='TOR_EXIT_COUNTRY'>
257 <option value=''>- $Lang::tr{'tor exit country any'} -</option>
258 END
259
260 my @country_names = Locale::Country::all_country_names();
261 foreach my $country_name (sort @country_names) {
262 my $country_code = Locale::Country::country2code($country_name);
263 $country_code = uc($country_code);
264 print "<option value='$country_code'>$country_name ($country_code)</option>\n";
265 }
266
267 print <<END;
268 </select>
269 </td>
270 <td width='50%' colspan='2'>
271 <textarea name='TOR_USE_EXIT_NODES' cols='32' rows='3' wrap='off'>$settings{'TOR_USE_EXIT_NODES'}</textarea>
272 </td>
273 </tr>
274 </table>
275 <br><br>
276 END
277 }
278
279 &Header::closebox();
280
281 if ($settings{'TOR_RELAY_ENABLED'} eq 'on') {
282 $checked{'TOR_RELAY_NOADVERTISE'}{'on'} = '';
283 $checked{'TOR_RELAY_NOADVERTISE'}{'off'} = '';
284 $checked{'TOR_RELAY_NOADVERTISE'}{$settings{'TOR_RELAY_NOADVERTISE'}} = 'checked';
285
286 $selected{'TOR_RELAY_MODE'}{'bridge'} = '';
287 $selected{'TOR_RELAY_MODE'}{'exit'} = '';
288 $selected{'TOR_RELAY_MODE'}{'private-bridge'} = '';
289 $selected{'TOR_RELAY_MODE'}{'relay'} = '';
290 $selected{'TOR_RELAY_MODE'}{$settings{'TOR_RELAY_MODE'}} = 'selected';
291
292 $selected{'TOR_RELAY_BANDWIDTH_RATE'}{'0'} = '';
293 foreach (@bandwidth_limits) {
294 $selected{'TOR_RELAY_BANDWIDTH_RATE'}{$_} = '';
295 }
296 $selected{'TOR_RELAY_BANDWIDTH_RATE'}{$settings{'TOR_RELAY_BANDWIDTH_RATE'}} = 'selected';
297
298 $selected{'TOR_RELAY_BANDWIDTH_BURST'}{'0'} = '';
299 foreach (@bandwidth_limits) {
300 $selected{'TOR_RELAY_BANDWIDTH_BURST'}{$_} = '';
301 }
302 $selected{'TOR_RELAY_BANDWIDTH_BURST'}{$settings{'TOR_RELAY_BANDWIDTH_BURST'}} = 'selected';
303
304 foreach (@accounting_periods) {
305 $selected{'TOR_RELAY_ACCOUNTING_PERIOD'}{$_} = '';
306 }
307 $selected{'TOR_RELAY_ACCOUNTING_PERIOD'}{$settings{'TOR_RELAY_ACCOUNTING_PERIOD'}} = 'selected';
308
309 &Header::openbox('100%', 'left', $Lang::tr{'tor relay configuration'});
310
311 print <<END;
312 <table width='100%'>
313 <tr>
314 <td width='25%' class='base'>$Lang::tr{'tor relay mode'}:</td>
315 <td width='30%'>
316 <select name='TOR_RELAY_MODE'>
317 <option value='exit' $selected{'TOR_RELAY_MODE'}{'exit'}>$Lang::tr{'tor relay mode exit'}</option>
318 <option value='relay' $selected{'TOR_RELAY_MODE'}{'relay'}>$Lang::tr{'tor relay mode relay'}</option>
319 <option value='bridge' $selected{'TOR_RELAY_MODE'}{'bridge'}>$Lang::tr{'tor relay mode bridge'}</option>
320 <option value='private-bridge' $selected{'TOR_RELAY_MODE'}{'private-bridge'}>$Lang::tr{'tor relay mode private bridge'}</option>
321 </select>
322 </td>
323 <td width='25%' class='base'>$Lang::tr{'tor relay port'}:</td>
324 <td width='20%'>
325 <input type='text' name='TOR_RELAY_PORT' value='$settings{'TOR_RELAY_PORT'}' size='5' />
326 </td>
327 </tr>
328 <tr>
329 <td width='25%' class='base'>$Lang::tr{'tor relay address'}:&nbsp;<img src='/blob.gif' alt='*' /></td>
330 <td width='30%'>
331 <input type='text' name='TOR_RELAY_ADDRESS' value='$settings{'TOR_RELAY_ADDRESS'}' />
332 </td>
333 <td width='25%' class='base'>$Lang::tr{'tor do not advertise relay'}:</td>
334 <td width='20%'>
335 <input type='checkbox' name='TOR_RELAY_NOADVERTISE' $checked{'TOR_RELAY_NOADVERTISE'}{'on'} />
336 </td>
337 </tr>
338 <tr>
339 <td width='25%' class='base'>$Lang::tr{'tor relay nickname'}:&nbsp;<img src='/blob.gif' alt='*' /></td>
340 <td width='30%'>
341 <input type='text' name='TOR_RELAY_NICKNAME' value='$settings{'TOR_RELAY_NICKNAME'}' />
342 </td>
343 <td colspan='2'></td>
344 </tr>
345 <tr>
346 <td width='25%' class='base'>$Lang::tr{'tor contact info'}:&nbsp;<img src='/blob.gif' alt='*' /></td>
347 <td width='75%' colspan='3'>
348 <input type='text' name='TOR_RELAY_CONTACT_INFO' value='$settings{'TOR_RELAY_CONTACT_INFO'}' size='60' />
349 </td>
350 </tr>
351 </table>
352
353 <hr size='1'>
354
355 <table width='100%'>
356 <tr>
357 <td colspan='4' class='base'><b>$Lang::tr{'tor bandwidth settings'}</b></td>
358 </tr>
359 <tr>
360 <td width='25%' class='base'>$Lang::tr{'tor bandwidth rate'}:</td>
361 <td width='30%' class='base'>
362 <select name='TOR_RELAY_BANDWIDTH_RATE'>
363 END
364
365 foreach (@bandwidth_limits) {
366 if ($_ >= 1024) {
367 print "<option value='$_' $selected{'TOR_RELAY_BANDWIDTH_RATE'}{$_}>". $_ / 1024 ." MBit/s</option>\n";
368 } else {
369 print "<option value='$_' $selected{'TOR_RELAY_BANDWIDTH_RATE'}{$_}>$_ kBit/s</option>\n";
370 }
371 }
372
373 print <<END;
374 <option value='0' $selected{'TOR_RELAY_BANDWIDTH_RATE'}{'0'}>$Lang::tr{'tor bandwidth unlimited'}</option>
375 </select>
376 </td>
377 <td width='25%' class='base'>$Lang::tr{'tor accounting limit'}:</td>
378 <td width='20%'>
379 <input type='text' name='TOR_RELAY_ACCOUNTING_LIMIT' value='$settings{'TOR_RELAY_ACCOUNTING_LIMIT'}' size='12' />
380 </td>
381 </tr>
382 <tr>
383 <td width='25%' class='base'>$Lang::tr{'tor bandwidth burst'}:</td>
384 <td width='20%' class='base'>
385 <select name='TOR_RELAY_BANDWIDTH_BURST'>
386 END
387
388 foreach (@bandwidth_limits) {
389 if ($_ >= 1024) {
390 print "<option value='$_' $selected{'TOR_RELAY_BANDWIDTH_BURST'}{$_}>". $_ / 1024 ." MBit/s</option>\n";
391 } else {
392 print "<option value='$_' $selected{'TOR_RELAY_BANDWIDTH_BURST'}{$_}>$_ kBit/s</option>\n";
393 }
394 }
395 print <<END;
396 <option value='0' $selected{'TOR_RELAY_BANDWIDTH_BURST'}{'0'}>$Lang::tr{'tor bandwidth unlimited'}</option>
397 </select>
398 </td>
399 <td width='25%' class='base'>$Lang::tr{'tor accounting period'}:</td>
400 <td width='20%'>
401 <select name='TOR_RELAY_ACCOUNTING_PERIOD'>
402 END
403
404 foreach (@accounting_periods) {
405 print "<option value='$_' $selected{'TOR_RELAY_ACCOUNTING_PERIOD'}{$_}>$Lang::tr{'tor accounting period '.$_}</option>";
406 }
407
408 print <<END;
409 </select>
410 </td>
411 </tr>
412 </table>
413 END
414
415 &Header::closebox();
416 }
417
418 print <<END;
419 <table width='100%'>
420 <tr>
421 <td>
422 <img src='/blob.gif' align='top' alt='*' />&nbsp;<font class='base'>$Lang::tr{'this field may be blank'}</font>
423 </td>
424 <td align='right'>&nbsp;</td>
425 </tr>
426 </table>
427
428 <hr>
429
430 <table width='100%'>
431 <tr>
432 <td>&nbsp;</td>
433 <td align='center'><input type='submit' name='ACTION' value='$Lang::tr{'save'}' /></td>
434 <td>&nbsp;</td>
435 </tr>
436 </table>
437 END
438
439 # If we have a control connection, show the stats.
440 if ($torctrl) {
441 &Header::openbox('100%', 'left', $Lang::tr{'tor stats'});
442
443 my @traffic = &TorTrafficStats($torctrl);
444
445 if (@traffic) {
446 print <<END;
447 <table width='100%'>
448 END
449
450 if ($settings{'TOR_RELAY_ENABLED'} eq 'on') {
451 my $fingerprint = &TorRelayFingerprint($torctrl);
452 if ($fingerprint) {
453 print <<END;
454 <tr>
455 <td width='40%' class='base'>$Lang::tr{'tor relay fingerprint'}:</td>
456 <td width='60%'>
457 <a href='https://atlas.torproject.org/#details/$fingerprint' target='_blank'>$fingerprint</a>
458 </td>
459 </tr>
460 END
461 }
462 }
463
464 my $address = TorGetInfo($torctrl, "address");
465 if ($address) {
466 print <<END;
467 <tr>
468 <td width='40%' class='base'>$Lang::tr{'tor relay external address'}:</td>
469 <td width='60%'>$address</td>
470 </tr>
471 END
472 }
473
474 print <<END;
475 <tr>
476 <td width='40%'>$Lang::tr{'tor traffic read written'}:</td>
477 END
478 print "<td width='60%'>" . &FormatBytes($traffic[0]) ."/". &FormatBytes($traffic[1]) . "</td>";
479 print <<END;
480 </tr>
481 </table>
482 END
483 }
484
485 my $accounting = &TorAccountingStats($torctrl);
486 if ($accounting) {
487 print <<END;
488 <table width='100%'>
489 <tr>
490 <td colspan='2' class='base'><b>$Lang::tr{'tor accounting'}</b></td>
491 </tr>
492 END
493
494 if ($accounting->{'hibernating'} eq "hard") {
495 print <<END;
496 <tr>
497 <td class='base' colspan='2' bgcolor="$Header::colourred" align='center'>
498 <font color='white'>$Lang::tr{'tor traffic limit hard'}</font>
499 </td>
500 </tr>
501 END
502 } elsif ($accounting->{'hibernating'} eq "soft") {
503 print <<END;
504 <tr>
505 <td class='base' colspan='2' bgcolor="$Header::colourorange" align='center'>
506 <font color='white'>$Lang::tr{'tor traffic limit soft'}</font>
507 </td>
508 </tr>
509 END
510 }
511
512 print <<END;
513 <tr>
514 <td width='40%' class='base'>$Lang::tr{'tor accounting interval'}</td>
515 <td width='60%'>
516 $accounting->{'interval-start'} - $accounting->{'interval-end'}
517 </td>
518 </tr>
519 <tr>
520 <td width='40%' class='base'>$Lang::tr{'tor accounting bytes'}</td>
521 <td width='60%'>
522 END
523
524 print &FormatBytes($accounting->{'bytes_read'}) . "/" . &FormatBytes($accounting->{'bytes_written'});
525 print " (" . &FormatBytes($accounting->{'bytes-left_read'}) . "/" . &FormatBytes($accounting->{'bytes-left_written'});
526 print " $Lang::tr{'tor accounting bytes left'})";
527
528 print <<END;
529 </td>
530 </tr>
531 </table>
532 END
533 }
534
535 my @nodes = &TorORConnStatus($torctrl);
536 if (@nodes) {
537 my $nodes_length = scalar @nodes;
538 print <<END;
539 <table width='100%'>
540 <tr>
541 <td width='40%' class='base'><b>$Lang::tr{'tor connected relays'}</b></td>
542 <td width='60%' colspan='2'>($nodes_length)</td>
543 </tr>
544 END
545
546 foreach my $node (@nodes) {
547 print <<END;
548 <tr>
549 <td width='40%'>
550 <a href='https://atlas.torproject.org/#details/$node->{'fingerprint'}' target='_blank'>
551 $node->{'name'}
552 </a>
553 </td>
554 <td width='30%'>
555 END
556
557 if (exists($node->{'country_code'})) {
558 print "<a href='country.cgi#$node->{'country_code'}'><img src='/images/flags/$node->{'country_code'}.png' border='0' align='absmiddle' alt='$node->{'country_code'}'></a>";
559 }
560
561 print <<END;
562 <a href='ipinfo.cgi?ip=$node->{'address'}'>$node->{'address'}</a>:$node->{'port'}
563 </td>
564 <td width='30%' align='right'>
565 ~$node->{'bandwidth_string'}
566 </td>
567 </tr>
568 END
569 }
570 print "</table>";
571 }
572
573 &Header::closebox();
574 }
575
576 print "</form>\n";
577
578 &Header::closebigbox();
579 &Header::closepage();
580 }
581
582 sub BuildConfiguration() {
583 my %settings = ();
584 &General::readhash("${General::swroot}/tor/settings", \%settings);
585
586 my $torrc = "${General::swroot}/tor/torrc";
587
588 open(FILE, ">$torrc");
589
590 # Global settings.
591 print FILE "ControlPort $TOR_CONTROL_PORT\n";
592
593 if ($settings{'TOR_ENABLED'} eq 'on') {
594 my $strict_nodes = 0;
595
596 print FILE "SocksPort 0.0.0.0:$settings{'TOR_SOCKS_PORT'}\n";
597
598 my @subnets = split(",", $settings{'TOR_ALLOWED_SUBNETS'});
599 foreach (@subnets) {
600 print FILE "SocksPolicy accept $_\n" if (&General::validipandmask($_));
601 }
602 print FILE "SocksPolicy reject *\n" if (@subnets);
603
604 if ($settings{'TOR_EXIT_COUNTRY'} ne '') {
605 $strict_nodes = 1;
606
607 print FILE "ExitNodes {$settings{'TOR_EXIT_COUNTRY'}}\n";
608 }
609
610 if ($settings{'TOR_USE_EXIT_NODES'} ne '') {
611 $strict_nodes = 1;
612
613 my @nodes = split(",", $settings{'TOR_USE_EXIT_NODES'});
614 foreach (@nodes) {
615 print FILE "ExitNode $_\n";
616 }
617 }
618
619 if ($strict_nodes > 0) {
620 print FILE "StrictNodes 1\n";
621 }
622 }
623
624 if ($settings{'TOR_RELAY_ENABLED'} eq 'on') {
625 # Reject access to private networks.
626 print FILE "ExitPolicyRejectPrivate 1\n";
627
628 print FILE "ORPort $settings{'TOR_RELAY_PORT'}";
629 if ($settings{'TOR_RELAY_NOADVERTISE'} eq 'on') {
630 print FILE " NoAdvertise";
631 }
632 print FILE "\n";
633
634 if ($settings{'TOR_RELAY_ADDRESS'} ne '') {
635 print FILE "Address $settings{'TOR_RELAY_ADDRESS'}\n";
636 }
637
638 if ($settings{'TOR_RELAY_NICKNAME'} ne '') {
639 print FILE "Nickname $settings{'TOR_RELAY_NICKNAME'}\n";
640 }
641
642 if ($settings{'TOR_RELAY_CONTACT_INFO'} ne '') {
643 print FILE "ContactInfo $settings{'TOR_RELAY_CONTACT_INFO'}\n";
644 }
645
646 # Limit to bridge mode.
647 my $is_bridge = 0;
648
649 if ($settings{'TOR_RELAY_MODE'} eq 'bridge') {
650 $is_bridge++;
651
652 # Private bridge.
653 } elsif ($settings{'TOR_RELAY_MODE'} eq 'private-bridge') {
654 $is_bridge++;
655
656 print FILE "PublishServerDescriptor 0\n";
657
658 # Exit node.
659 } elsif ($settings{'TOR_RELAY_MODE'} eq 'exit') {
660 print FILE "ExitPolicy accept *:*\n";
661
662 # Relay only.
663 } elsif ($settings{'TOR_RELAY_MODE'} eq 'relay') {
664 print FILE "ExitPolicy reject *:*\n";
665 }
666
667 if ($is_bridge > 0) {
668 print FILE "BridgeRelay 1\n";
669 print FILE "Exitpolicy reject *:*\n";
670 }
671
672 if ($settings{'TOR_RELAY_BANDWIDTH_RATE'} > 0) {
673 print FILE "RelayBandwidthRate ";
674 print FILE $settings{'TOR_RELAY_BANDWIDTH_RATE'} / 8;
675 print FILE " KB\n";
676
677 if ($settings{'TOR_RELAY_BANDWIDTH_BURST'} > 0) {
678 print FILE "RelayBandwidthBurst ";
679 print FILE $settings{'TOR_RELAY_BANDWIDTH_BURST'} / 8;
680 print FILE " KB\n";
681 }
682 }
683
684 if ($settings{'TOR_RELAY_ACCOUNTING_LIMIT'} > 0) {
685 print FILE "AccountingMax ".$settings{'TOR_RELAY_ACCOUNTING_LIMIT'}." MB\n";
686
687 if ($settings{'TOR_RELAY_ACCOUNTING_PERIOD'} eq 'daily') {
688 print FILE "AccountingStart day 00:00\n";
689 } elsif ($settings{'TOR_RELAY_ACCOUNTING_PERIOD'} eq 'weekly') {
690 print FILE "AccountingStart week 1 00:00\n";
691 } elsif ($settings{'TOR_RELAY_ACCOUNTING_PERIOD'} eq 'monthly') {
692 print FILE "AccountingStart month 1 00:00\n";
693 }
694 }
695 }
696
697 close(FILE);
698
699 # Restart the service.
700 if (($settings{'TOR_ENABLED'} eq 'on') || ($settings{'TOR_RELAY_ENABLED'} eq 'on')) {
701 system("/usr/local/bin/torctrl restart &>/dev/null");
702 } else {
703 system("/usr/local/bin/torctrl stop &>/dev/null");
704 }
705 }
706
707 sub TorConnect() {
708 my $socket = new IO::Socket::INET(
709 Proto => 'tcp', PeerAddr => '127.0.0.1', PeerPort => $TOR_CONTROL_PORT,
710 ) or return;
711
712 $socket->autoflush(1);
713
714 # Authenticate.
715 &TorSendCommand($socket, "AUTHENTICATE");
716
717 return $socket;
718 }
719
720 sub TorSendCommand() {
721 my ($socket, $cmd) = @_;
722
723 # Replace line ending with \r\n.
724 chomp $cmd;
725 $cmd .= "\r\n";
726
727 $socket->send($cmd);
728
729 my @output = ();
730 while (my $line = <$socket>) {
731 # Skip empty lines.
732 if ($line =~ /^.\r\n$/) {
733 next;
734 }
735
736 # Command has been successfully executed.
737 if ($line =~ /250 OK/) {
738 last;
739
740 # Error.
741 } elsif ($line =~ /^5\d+/) {
742 last;
743
744 } else {
745 # Remove line endings.
746 $line =~ s/\r\n$//;
747
748 push(@output, $line);
749 }
750 }
751
752 return @output;
753 }
754
755 sub TorSendCommandOneLine() {
756 my ($tor, $cmd) = @_;
757
758 my @output = &TorSendCommand($tor, $cmd);
759 return $output[0];
760 }
761
762 sub TorGetInfo() {
763 my ($tor, $cmd) = @_;
764
765 my $output = &TorSendCommandOneLine($tor, "GETINFO ".$cmd);
766
767 my ($key, $value) = split("=", $output);
768 return $value;
769 }
770
771 sub TorClose() {
772 my $socket = shift;
773
774 if ($socket) {
775 $socket->shutdown(2);
776 }
777 }
778
779 sub TorTrafficStats() {
780 my $tor = shift;
781
782 my $output_read = &TorGetInfo($tor, "traffic/read");
783 my $output_written = &TorGetInfo($tor, "traffic/written");
784
785 return ($output_read, $output_written);
786 }
787
788 sub TorRelayFingerprint() {
789 my $tor = shift;
790
791 return &TorGetInfo($tor, "fingerprint");
792 }
793
794 sub TorORConnStatus() {
795 my $tor = shift;
796 my @nodes = ();
797
798 my @output = &TorSendCommand($tor, "GETINFO orconn-status");
799 foreach (@output) {
800 $_ =~ s/^250[\+-]orconn-status=//;
801 next if ($_ eq "");
802 last if ($_ eq ".");
803 next unless ($_ =~ /^\$/);
804
805 my @line = split(" ", $_);
806 my @node = split(/[=~]/, $line[0]);
807
808 my $node = &TorNodeDescription($tor, $node[0]);
809 if ($node) {
810 push(@nodes, $node);
811 }
812 }
813
814 # Sort by names.
815 @nodes = sort { $a->{'name'} cmp $b->{'name'} } @nodes;
816
817 return @nodes;
818 }
819
820 sub TorNodeDescription() {
821 my ($tor, $fingerprint) = @_;
822 $fingerprint =~ s/\$//;
823
824 my $node = {
825 fingerprint => $fingerprint,
826 exit_node => 0,
827 };
828
829 my @output = &TorSendCommand($tor, "GETINFO ns/id/$node->{'fingerprint'}");
830
831 foreach (@output) {
832 # Router
833 if ($_ =~ /^r (\w+) (.*) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (\d+)/) {
834 $node->{'name'} = $1;
835 $node->{'address'} = $3;
836 $node->{'port'} = $4;
837
838 my $country_code = &TorGetInfo($tor, "ip-to-country/$node->{'address'}");
839 $node->{'country_code'} = $country_code;
840
841 # Flags
842 } elsif ($_ =~ /^s (.*)$/) {
843 $node->{'flags'} = split(" ", $1);
844
845 foreach my $flag ($node->{'flags'}) {
846 if ($flag eq "Exit") {
847 $node->{'exit_node'}++;
848 }
849 }
850
851 # Bandwidth
852 } elsif ($_ =~ /^w Bandwidth=(\d+)/) {
853 $node->{'bandwidth'} = $1 * 8;
854 $node->{'bandwidth_string'} = &FormatBitsPerSecond($node->{'bandwidth'});
855 }
856 }
857
858 if (exists($node->{'name'})) {
859 return $node;
860 }
861 }
862
863 sub TorAccountingStats() {
864 my $tor = shift;
865 my $ret = {};
866
867 my $enabled = &TorGetInfo($tor, "accounting/enabled");
868 if ($enabled ne '1') {
869 return;
870 }
871
872 my @cmds = ("hibernating", "interval-start", "interval-end");
873 foreach (@cmds) {
874 $ret->{$_} = &TorGetInfo($tor, "accounting/$_");
875 }
876
877 my @cmds = ("bytes", "bytes-left");
878 foreach (@cmds) {
879 my $output = &TorGetInfo($tor, "accounting/$_");
880 my @bytes = split(" ", $output);
881
882 $ret->{$_."_read"} = $bytes[0];
883 $ret->{$_."_written"} = $bytes[1];
884 }
885
886 return $ret;
887 }
888
889 sub FormatBytes() {
890 my $bytes = shift;
891
892 my @units = ("B", "KB", "MB", "GB", "TB");
893 my $units_index = 0;
894
895 while (($units_index <= $#units) && ($bytes >= 1024)) {
896 $units_index++;
897 $bytes /= 1024;
898 }
899
900 return sprintf("%.2f %s", $bytes, $units[$units_index]);
901 }
902
903 sub FormatBitsPerSecond() {
904 my $bits = shift;
905
906 my @units = ("Bit/s", "KBit/s", "MBit/s", "GBit/s", "TBit/s");
907 my $units_index = 0;
908
909 while (($units_index <= $#units) && ($bits >= 1024)) {
910 $units_index++;
911 $bits /= 1024;
912 }
913
914 return sprintf("%.2f %s", $bits, $units[$units_index]);
915 }