]> the.earth.li Git - autodns.git/blob - autodns.pl
cscvs to tla changeset 5
[autodns.git] / autodns.pl
1 #!/usr/bin/perl -Tw
2 # autodns 0.0.7
3 # Copyright 1999-2004 Project Purple. Written by Jonathan McDowell
4 # See ACKNOWLEDGEMENTS file for full details of contributors.
5 # http://www.earth.li/projectpurple/progs/autodns.html
6 # Released under the GPL.
7 #
8 # $Id: autodns.pl,v 1.5 2005/03/21 15:11:01 noodles Exp $
9 #
10
11 use strict;
12 use Fcntl qw(:flock);
13 use File::Temp qw(tempfile);
14 use IPC::Open3;
15 use MIME::Parser;
16
17 $ENV{'PATH'}="/usr/local/bin:/usr/bin:/bin:/usr/sbin";
18
19 my ($from, $subject, $gpguser, $gpggood, $usersfile, $lockfile, $priv);
20 my ($user, $server, $inprocess, $delcount, $addcount, $reload_command);
21 my ($domain, @MAIL, @GPGERROR, @COMMANDS, %zones);
22 my ($me, $ccreply, $conffile, $domainlistroot, @cfgfiles, $VERSION);
23
24 $VERSION="0.0.7";
25
26 #
27 # Local configuration here (until it gets moved to a config file).
28 #
29 # These are sort of suitable for a Debian setup.
30 #
31
32 # Who I should reply as.
33 $me="autodns\@earth.li";
34
35 # Who replies should be CCed to.
36 $ccreply="noodles\@earth.li";
37
38 # Where to look for zones we're already hosting.
39 @cfgfiles=("/etc/bind/named.conf",
40         "/etc/bind/named.secondary.conf");
41
42 # The file we should add/delete domains from.
43 $conffile="/etc/bind/named.secondary.conf";
44
45 # The file that contains details of the authorized users.
46 $usersfile="/etc/bind/autodns.users";
47
48 # Base file name to for list of users domains.
49 $domainlistroot="/etc/bind/domains.";
50
51 # The lockfile we use to ensure we have exclusive access to the
52 # $domainlistroot$user files and $conffile.
53 $lockfile="/etc/bind/autodns.lck";
54
55 # The command to reload the nameserver domains list.
56 $reload_command="sudo ndc reconfig 2>&1";
57
58 ###
59 ### There should be no need to edit anything below (unless you're not
60 ### using BIND). This statement might even be true now - let me know if not.
61 ###
62
63 #
64 # Try to figure out what zones we currently know about by parsing config
65 # files. Sets the item in %zones to 1 for each zone it finds.
66 #
67 # Call with the name of a config file to read:
68 #
69 # &getzones("/etc/named.conf");
70 #
71 sub getzones {
72         my ($namedfile) = @_;
73
74         open (NAMEDCONF, "< $namedfile") or
75                 &fatalerror("Can't open $namedfile");
76
77         while (<NAMEDCONF>) {
78                 if (/^\s*zone\s*"([^"]+)"/) {
79                         $zones{$1}=1;
80                 }
81         }
82
83         close NAMEDCONF;
84 }
85
86 #
87 # Check that a domain is only made up of valid characters.
88 #
89 # These are: a-z, 0-9, - or .
90 #
91 sub valid_domain {
92         my $domain = shift;
93         $domain = lc $domain;
94         if ($domain =~ /^(?:[a-z0-9-]+\.)+[a-z]{2,4}$/) {
95                 return 1;
96         } elsif ($domain =~ /^(?:[0-9\/-]+\.)+in-addr.arpa$/) {
97                 return 1;
98         } else {
99                 return 0;
100         }
101 }
102
103 #
104 # Deal with a fatal error by printing an error message, closing the pipe to
105 # sendmail and exiting.
106 #
107 # fatalerror("I'm melting!");
108 #
109 sub fatalerror {
110         my $message = shift;
111
112         print REPLY $message;
113         close(REPLY);
114
115         flock(LOCKFILE, LOCK_UN);
116         close(LOCKFILE);
117         unlink($lockfile);
118
119 #       die $message;
120         exit;
121 }
122
123 #
124 # Get user details from usersfile based on a PGP ID.
125 #
126 # A users entry looks like:
127 #
128 # <username>:<keyid>:<priviledge level>:<master server ip>
129 #
130 # Priviledge level is not currently used.
131 #
132 # ($user, $priv, $server) = &getuserinfo("5B430367");
133 #
134 sub getuserinfo {
135         my $gpguser = shift;
136         my ($user, $priviledge, $server);
137
138         open (CONFIGFILE, "< $usersfile") or
139                 &fatalerror("Couldn't open user configuration file.");
140
141         foreach (<CONFIGFILE>) {
142                 if (/^([^#.]+):$gpguser:(\d+):(.+)$/) {
143                         $user=$1;
144                         $priviledge=$2;
145                         $server=$3;
146                         chomp $user;
147                         chomp $priviledge;
148                         chomp $server;
149         
150                         if ($user !~ /^.+$/) {
151                                 close(CONFIGFILE);
152                                 &fatalerror("Error in user configuration file: Can't get username.\n");
153                         }
154
155                         if ($server !~ /^(\d{1,3}\.){3}\d{1,3}$/) {
156                                 $server =~ s/\d\.]//g;
157                                 close(CONFIGFILE); 
158                                 &fatalerror("Error in user configuration file: Invalid primary server IP address ($server)\n");
159                                 exit;
160                         } 
161                 }
162         } 
163         close(CONFIGFILE);
164
165         if ($user =~ /^$/) {
166                 &fatalerror("User not found.\n");
167         }
168
169         return ($user, $priviledge, $server);
170 }
171
172 $delcount=$addcount=$inprocess=0;
173
174 # Read in the mail from stdin.
175 @MAIL=<>;
176
177 $subject = "Reply from AutoDNS";
178 # Now lets try to find out who it's from.
179 foreach (@MAIL) {
180         if (/^$/) { last; }
181         if (/^From: (.*)/i) { $from=$1; chomp $from;}
182         if (/^Subject:\s+(re:)?(.*)$/i) { $subject="Re: ".$2 if ($2);}
183 }
184
185 if ((! defined($from)) || $from =~ /^$/ ) {
186         die "Couldn't find a from address.";
187 } elsif ($from =~ /mailer-daemon@/i) {
188         die "From address is mailer-daemon, ignoring.";
189 }
190
191 if (! defined($subject)) { $subject="Reply from AutoDNS"; };
192
193 # We've got a from address. Start a reply.
194
195 open(REPLY, "|sendmail -t -oem -oi") or die "Couldn't spawn sendmail";
196
197 print REPLY "From: $me\n";
198 print REPLY "To: $from\n";
199 #
200 # Check to see if our CC address is the same as the from address and if so
201 # don't CC.
202 #
203 if ($from ne $ccreply) {
204         print REPLY "Cc: $ccreply\n";
205 }
206 print REPLY <<EOF;
207 Subject: $subject
208
209 AutoDNS $VERSION
210 Copyright 1999-2004 Project Purple. Written by Jonathan McDowell.
211 Released under the GPL.
212
213 EOF
214
215 #
216 # Throw the mail at MIME::Parser and see if it accepts it.
217 #
218 my $parser = new MIME::Parser;
219 $parser->output_to_core(1); # No temporary files
220 my $entity = $parser->parse_data(\@MAIL);
221
222 #
223 # Make sure locale is set to C so we get messages in English as we expect.
224 #
225 $ENV{'LC_ALL'}="C";
226
227 if ($entity->parts) {
228         # MIME
229
230         my ($got_sig, $got_text) = (0, 0);
231         my ($sig_name,$sig_fh,$text_name,$text_fh);
232         ($sig_fh, $sig_name) = tempfile();
233         ($text_fh, $text_name) = tempfile();
234
235         foreach my $subent ($entity->parts) {
236                 if ($subent->effective_type eq "text/plain") {
237                         @COMMANDS = split /\n/,$subent->bodyhandle->as_string;
238
239                         my $str = $subent->as_string;
240                         $str =~ s/=\n$//;
241                         $str =~ s/\n/\r\n/g;
242                         print $text_fh $str;
243                         close($text_fh);
244                         $got_text++;
245                 } elsif ($subent->effective_type eq
246                                 "application/pgp-signature") {
247                         print $sig_fh $subent->as_string;
248                         close($sig_fh);
249                         $got_sig++;
250                 }
251         }
252
253         if ($got_sig && $got_text) {
254                 open3(\*GPGIN, \*GPGOUT, \*GPGERR, "gpg --batch --verify ".
255                         $sig_name." ".$text_name);
256
257                 close GPGIN;
258
259                 @GPGERROR=<GPGERR>;
260                 my @GPGOUTPUT=<GPGOUT>;
261                 close GPGERR;
262                 close GPGOUT;
263
264                 unlink($text_name);
265                 unlink($sig_name);
266         }
267 } else {
268         # Clear text.
269
270         open3(\*GPGIN, \*GPGOUT, \*GPGERR, "gpg --batch");
271
272         # Feed it the mail.
273         print GPGIN @MAIL;
274         close GPGIN;
275
276         # And grab what it has to say.
277         @GPGERROR=<GPGERR>;
278         @COMMANDS=<GPGOUT>;
279         close GPGERR;
280         close GPGOUT;
281 }
282
283 # Check who it's from and if the signature was a good one.
284 $gpggood=1;
285 foreach (@GPGERROR) {
286         chomp;
287         if (/Signature made.* (.*)$/) {
288                 $gpguser=$1; 
289         } elsif (/error/) {
290                 $gpggood = 0;
291                 print REPLY "Some errors ocurred\n";
292         } elsif (/BAD signature/) {
293                 $gpggood = 0;
294                 print REPLY "BAD signature!\n";
295         } elsif (/public key not found/) {
296                 $gpggood = 0;
297                 print REPLY "Public Key not found\n";
298         }
299 }
300
301 # If we have an empty user it probably wasn't signed.
302 if (! $gpguser) {
303         print REPLY "Message appears not to be GPG signed.\n";
304         close REPLY;
305         exit;
306 }
307
308 # Check the signature we got was ok.
309 if ($gpggood) {
310         print REPLY "Good GPG signature found. ($gpguser)\n";
311 } else {
312         print REPLY "Bad GPG signature!\n";
313         close REPLY;
314         exit;
315 }
316
317 # Now let's check if we know this person.
318 ($user, $priv, $server) = &getuserinfo($gpguser);
319
320 if (! defined($user) || ! $user) {
321         print REPLY "Unknown user.\n";
322         close REPLY;
323         exit;
324 }
325
326 print REPLY "Got user '$user'\n";
327
328 # Right. We know this is a valid user. Get a lock to ensure we have exclusive
329 # access to the configs from here on in.
330 open (LOCKFILE,">$lockfile") ||
331          &fatalerror("Couldn't open lock file\n");
332 &fatalerror("Couldn't get lock\n") unless(flock(LOCKFILE,LOCK_EX));
333
334 # Ok, now we should figure out what domains we already know about.
335 foreach my $cfgfile (@cfgfiles) {
336         getzones($cfgfile);
337 }
338
339 foreach (@COMMANDS) {
340         # Remove trailing CRs and leading/trailing whitespace
341         chomp;
342         s/\r//;
343         s/^\s*//;
344         s/\s*$//;
345
346         if ($inprocess) {
347                 print REPLY ">>>$_\n";
348         }
349
350         if (/^$/) {
351                 #
352                 # Empty line, so ignore it.
353                 # 
354         } elsif (/^END$/) {
355                 $inprocess=0;
356         } elsif (/^BEGIN$/) {
357                 $inprocess=1;
358         } elsif ($inprocess && /^ADD\s+(.*)$/) {
359                 $domain = $1;
360
361                 # Convert domain to lower case.
362                 $domain =~ tr/[A-Z]/[a-z]/;
363                 if (! valid_domain($domain)) {
364                         $domain =~ s/[-a-z0-9.]//g;
365                         print REPLY "Invalid character(s) in domain name: $domain\n";
366                 } elsif (defined($zones{$domain}) && $zones{$domain}) {
367                         print REPLY "We already secondary $domain\n";
368                 } else {
369                         print REPLY "Adding domain $domain\n";
370                         $zones{$domain}=1;
371
372                         my $df = $domain;
373                         $df =~ tr,/,:,;
374
375                         open (DOMAINSFILE, ">>$conffile");
376                         print DOMAINSFILE "
377 ### Domain added for '$user'
378
379 zone \"$domain\" {
380         type slave;
381         masters { $server; };
382         file \"secondary/$user/$df\";
383         allow-transfer { none; };
384         allow-query { any; };
385 };\n";
386                         close DOMAINSFILE;
387
388                         open (DOMAINLIST, ">>$domainlistroot$user") or
389                                 &fatalerror("Couldn't open file.\n");
390                         print DOMAINLIST "$domain\n";
391                         close DOMAINLIST;
392                         $addcount++;
393                 }
394         } elsif ($inprocess && /^DEL\s(.*)$/) {
395                 $domain = $1;
396
397                 # Convert domain to lower case.
398                 $domain =~ tr/[A-Z]/[a-z]/;
399                 if (!valid_domain($domain)) {
400                         $domain =~ s/[-a-z0-9.]//g;
401                         print REPLY "Invalid character(s) in domain name: $domain\n";
402                 } elsif (!defined($zones{$domain}) || !$zones{$domain}) {
403                                 print REPLY "$domain does not exist!\n";
404                 } else {
405                         print REPLY "Deleting domain $domain\n";
406                         my (@newcfg,$found);
407
408                         open (DOMAINLIST, "<$domainlistroot$user") or
409                                 &fatalerror("Couldn't open file $domainlistroot$user for reading: $!.\n");
410                         my @cfg = <DOMAINLIST>;
411                         close(DOMAINLIST);
412                         @newcfg = grep { ! /^$domain$/ } @cfg;
413                         if (scalar @cfg == scalar @newcfg) {
414                                 print REPLY "Didn't find $domain in $domainlistroot$user!\n";
415                                 print REPLY "You are only allowed to delete your own domains that exist.\n";
416                                 next;
417                         }
418
419                         open (DOMAINLIST, ">$domainlistroot$user") or 
420                                 &fatalerror("Couldn't open file $domainlistroot$user for writing: $!.\n");
421                         print DOMAINLIST @newcfg;
422                         close DOMAINLIST;
423
424                         $found=0;
425                         @newcfg=();
426                         open (DOMAINSFILE, "<$conffile") or
427                                 &fatalerror("Couldn't open file $conffile for reading: $!\n");
428                         {
429                         local $/ = ''; # eat whole paragraphs
430                         while (<DOMAINSFILE>) {
431                                 unless (/^\s*zone\s+"$domain"/) {
432                                         push @newcfg, $_;
433                                 } else {
434                                         $found=1;
435                                         if ($newcfg[-1] =~ /^###/) {
436                                                 # remove comment and \n
437                                                 pop @newcfg;
438                                         }
439                                 }
440                         }
441                         } # end of paragraph eating
442
443                         if (!$found) {
444                                 print REPLY "Didn't find $domain in $conffile!\n";
445                                 next;
446                         }
447
448                         open (DOMAINSFILE, ">$conffile") or
449                                 &fatalerror("Couldn't open $conffile for writing: $!\n");
450                         print DOMAINSFILE @newcfg;
451                         close DOMAINSFILE;
452                         $delcount++;
453                         $zones{$domain} = 0;
454                 }
455         } elsif ($inprocess && /^LIST$/) {
456                 print REPLY "Listing domains for user $user\n";
457                 print REPLY "------\n";
458                 if (open (DOMAINLIST, "<$domainlistroot$user")) {
459                         my $count = 0;
460                         while (<DOMAINLIST>) {
461                                 $count++;
462                                 print REPLY;
463                         }
464                         close (DOMAINLIST);
465                         print REPLY "------\n";
466                         print REPLY "Total of $count domains.\n";
467                 } else {
468                         print REPLY "Couldn't open $domainlistroot$user: $!\n";
469                 }
470         } elsif ($inprocess && /^HELP$/) {
471                 print REPLY "In order to use the service, you will need to send GPG signed\n";
472                 print REPLY "messages.\n\n";
473                 print REPLY "The format of the text in these messages is important, as they represent\n";
474                 print REPLY "commands to autodns. Commands are formatted one per line, and enclosed\n";
475                 print REPLY "by \"BEGIN\" and \"END\" commands (without the quotes).\n";
476                 print REPLY "Current valid commands are:\n";
477                 print REPLY "BEGIN - begin processing.\n";
478                 print REPLY "END - end processing.\n";
479                 print REPLY "HELP - display this message.\n";
480                 print REPLY "LIST - show all the zones currently held by you.\n";
481                 print REPLY "ADD <domain> - adds the domain <domain> for processing.\n";
482                 print REPLY "DEL <domain> - removes the domain <domain> if you own it.\n";
483         } elsif ($inprocess) {
484                 print REPLY "Unknown command!\n";
485         }
486 }
487 flock(LOCKFILE, LOCK_UN);
488 close(LOCKFILE);
489 unlink($lockfile);
490
491 print REPLY "Added $addcount domains.\n" if $addcount;
492 print REPLY "Removed $delcount domains.\n" if $delcount;
493 if ($addcount || $delcount) {
494         print REPLY "Reloading nameserver config.\n";
495         print REPLY `$reload_command`;
496 }
497 close REPLY;
498
499 exit 0;