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