-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_dns.pl
executable file
·417 lines (376 loc) · 9.96 KB
/
socket_dns.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/perl -w
#
# socket_dns.pl v1.0 (JD Trout)
#
# This script should do the following:
#
# 1. Check to see if the specified port is up on the specified servers.
#
# 2. Make sure DNS reflects the sockets that are up.
# 2a. Run a safety check to make sure not to remove all DNS entries.
#
# 3. Email administrator on all major errors.
# 3a. Need to remove email address from code.
#
use Net::DNS;
use IO::Socket;
use strict;
# Fix output
$| = 1;
my %files;
my %config;
$files{'config'} = "/etc/socket_dns.conf";
my $debug = 0;
my $shutdown = 0;
my $daemon = 0;
#Command line args
foreach(@ARGV) {
if(/^\-d$/) { $daemon = 1; }
if(/^\-v$/) { $debug = 1; }
if(/^\-s$/) { $shutdown = 1; }
if(/^\-shutdown$/) { $shutdown = 1; }
}
##############
# Sub routines
##############
# Get Config
sub get_config {
#Read in Config
open(CONFIG, $files{'config'}) or die ("Can't open config file!");
my @listlines = <CONFIG>;
close(CONFIG);
my @clean;
foreach(@listlines) {
# Put a newline before and after every brace
#s/([{}]/\n\1\n/g;
# Blank line
if(/^[\n\t\ ]+$/) { next; }
# Pure Comments
if(/^[\n\t\ ]#.*/) { next; }
# Remove comments
s/#.*//;
# Remove Leading / trailing space
s/^[\ \t]+//;
s/[\ \t]+$//;
#Advanced chomp
s/\n+$//;
my @lines = split(/\n/, $_);
foreach(@lines) {
# Blank lines
if(/^[\n\t\ ]+$/) { next; }
if(/^$/) { next; }
s/\n+$//;
push(@clean, "$_\n");
}
}
my $section = 0;
# Hash Pointer
my $p_hash;
my $depth = 0;
foreach(@clean) {
chomp;
if($section) {
if(/\}/) { $depth -= 1; }
if($depth) {
# Parse out a name = value
/^\s*([\w\-\._]+)\s*=\s*"?(.+?)"?\s*$/ && do {
$p_hash->{$1} = $2;
}
}
if(/\{/) { $depth += 1; }
unless($depth) {
$section = 0;
}
}
else {
# Find sections
if(/^\[(.*)\]$/) {
my $sectioni_name;
my $section_name = $_ = $1;
if(/files/) {
$section = 1;
$depth = 0;
$p_hash = \%files;
}
elsif(/global/) {
$section = 1;
$depth = 0;
$p_hash = \%config;
}
}
}
}
# End foreach(@clean)
if($files{'output'}) {
my $output;
$output = $files{'output'} . $output;
}
return 1;
}
# Socket Check
sub socket_check {
my $ip = shift;
my $port = shift;
my $proto = $config{'query_proto'};
my $sock = new IO::Socket::INET (PeerAddr => $ip,
PeerPort => $port,
Proto => $proto);
if ($sock) { # Socket is good.
close $sock;
&write_log("Socket for $ip is active.");
print "Socket for $ip is active. \n" if $debug;
return 1;
}
else {
&write_log ("Socket for $ip is down.");
print "Socket for $ip is down. \n";
return 0;
}
}
# DNS check
sub dns_check {
#Defining necessary variables
my $ip = shift;
my $res = new Net::DNS::Resolver;
my @ips;
#Query the name server for the hostname.
if (my $query = $res->query($config{'query_hostname'})) {
foreach $_ ($query->answer) {
next unless $_->type eq "A";
my $address = $_->address;
push(@ips, $address);
}
#Match IP
my @match = grep(/$ip/i, @ips);
if ($match[0] eq $ip) {
return 1;
}
else {
&write_log ("$ip is no longer in DNS.");
print "$ip is no longer in DNS. \n" if $debug;
return 0;
}
}
else {
&write_log ("$ip is no longer in DNS, or socket_dns.pl can no longer query DNS.");
print "$ip is no longer in DNS, or socket_dns.pl can no longer query DNS. \n" if $debug;
return 0;
}
}
# Add DNS Record
sub dns_add {
#Defining necessary variables
my $ip = shift;
my $res = new Net::DNS::Resolver;
my $update = new Net::DNS::Update($config{'dns_zone'});
my $key_name = "$config{'dns_key_name'}";
my $key = "$config{'dns_key'}";
my $tsig = Net::DNS::RR->new("$key_name TSIG $key");
$tsig->fudge(60);
# Write update to log
&write_log("Adding host $config{'query_hostname'} with IP $ip to DNS");
#Add the A record
$update->push(update => rr_add("$config{'query_hostname'} 180 A $ip"));
$update->sign_tsig($tsig);
$res->nameservers($config{'dns_servers'});
my $ans = $res->send($update);
# Check to make sure record was added.
if (defined $ans) {
if ($ans->header->rcode eq "NOERROR") {
&write_log("Added $ip successfully to DNS.");
}
else {
print "Return code:", $ans->header->rcode if $debug;
&write_log( "Failed to add $ip to DNS. Please run again in debug.");
&email("Failed to add $ip to DNS. \n Return code: '$ans->header->rcode'");
}
}
else {
&write_log("Error: '$res->errorstring'");
&write_log("Failed to add $ip to DNS.");
&email("Failed to add $ip to DNS. \n
Error: $res->errorstring \n");
print "Error $res->errorstring \n when trying to DNS record for IP $ip \n" if $debug;
}
}
#Remove DNS
sub dns_del {
#Defining necessary variables
my $ip = shift;
my $res = new Net::DNS::Resolver;
my $update = new Net::DNS::Update($config{'dns_zone'});
my $key_name = $config{'dns_key_name'};
my $key = $config{'dns_key'};
my $tsig = Net::DNS::RR->new("$key_name TSIG $key");
$tsig->fudge(60);
# Write update to log
&write_log("Removing host $config{'query_hostname'} with IP $ip from DNS");
print "Removing host $config{'query_hostname'} from zone $config{'dns_zone'}, with IP $ip from DNS. \n";
#Remove the A record
$update->push(update => rr_del("$config{'query_hostname'} A $ip" ));
$update->sign_tsig($tsig);
$res->nameservers($config{'dns_servers'});
my $ans = $res->send($update);
# Check to make sure record was added.
if (defined $ans) {
if ($ans->header->rcode eq "NOERROR") {
&write_log("$ip removed successfully from DNS.");
print "$ip removed successfully from DNS.\n" if $debug;
}
else {
print "Return code:",$ans->header->rcode if $debug;
&write_log( "Failed to remove $ip From DNS.");
&email("Failed to remove $ip from DNS. \n Return code: '$ans->header->rcode'");
print "Failed to remove IP $ip.\n Return Code:", $ans->header->rcode, "\n" if $debug;
}
}
else {
&write_log("Error: '$res->errorstring'");
&write_log("Failed to remove $ip from DNS.");
&email("Failed to remove $ip from DNS. \n Error: '$res->errorstring' \n");
}
}
#DNS Safety
sub dns_safety_check {
my @query_host_ip = split(/\ /, $config{'query_host_ip'});
my $dns_count;
foreach(@query_host_ip) {
if (&dns_check($_) == 1) {
$dns_count++;
}
else {
&write_log("DNS Safety shows that $_ does not exists in DNS.");
print "DNS Safety shows that $_ does not exists in DNS. \n" if $debug;
}
}
print "DNS Count is $dns_count \n" if $debug;
if ($dns_count >= 2) {
return 1;
}
else {
return 0;
}
}
#Logging
sub write_log {
my $message = shift;
open(LOG, ">>$files{'log'}");
print LOG &format_time(time) . ": $message\n";
close(LOG);
}
#Format time
sub format_time {
my($sec, $min, $hour, $mday, $mon) = localtime($_[0]);
my($fmt_mon) = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[$mon];
return(sprintf("%s %d %.2d:%.2d:%.2d", $fmt_mon, $mday, $hour, $min, $sec));
}
# Email critical Errors
sub email {
my $body = shift;
my $subject = "[loni-sys] SSH IP Mgmt issue!";
#Send email
system("echo \"$body\" | mailx -s \"$subject\" sysadm\@loni.ucla.edu");
}
# Shutdown the daemon
sub shutdown_daemon {
open(PID, $files{'pid'});
my $pid = <PID>;
close(PID);
chomp $pid;
if($pid) {
print "Killing process $pid\n";
&write_log("Killing process $pid\n");
sleep(1);
system("kill $pid");
}
else {
&write_log("No process found \n");
print "No process found\n";
}
exit;
}
sub execute {
# Interval (in seconds) to perform check.
my $interval = shift;
while(1) {
&function();
sleep($interval);
}
}
sub function {
my $ports = $config{'query_ports'};
my @query_host_ip = split(/\ /, $config{'query_host_ip'});
foreach(@query_host_ip) {
my $sock = &socket_check($_, $ports);
print "my sock return is $sock \n" if $debug;
my $query = &dns_check($_);
print "my DNS return is $query \n" if $debug;
unless ($sock > 0) {
&write_log ("Socket check for $_ failed! Trying again in 20 seconds.");
print "Socket check for $_ failed! Trying again in 20 seconds. \n" if $debug;
sleep 20;
$sock = &socket_check($_, $ports);
}
if ($query > $sock) {
&write_log ("Running DNS Safety check.");
print "Running DNS Safety check. \n" if $debug;
my $dns_safety = &dns_safety_check();
print "DNS Safety return is $dns_safety \n" if $debug;
while($dns_safety) {
&write_log ("Socket is down but DNS exists. Removing DNS for $_.");
print "Socket is down but DNS exists. Removing DNS for $_. \n" if $debug;
&dns_del($_);
last;
}
}
elsif ($sock > $query) {
&write_log ("Socket is up but DNS does not exists. Adding DNS for $_.");
print "Socket is up but DNS does not exists. Adding DNS for $_. \n" if $debug;
&dns_add($_);
}
}
}
##########
# Program exe
##########
&get_config();
if($shutdown) {
&shutdown_daemon();
exit;
}
if($daemon) {
my $interval = $config{'query_interval'};
FORK: {
if(my $pid = fork) {
&write_log("Starting socket_dns.pl ($pid)");
print "Starting socket_dns.pl ($pid)" if $debug;
exit;
}
elsif (defined $pid) {
&write_log("Child started ($$)");
open(PIDFILE, ">" . $files{'pid'} ) || do
{
&write_log("Cannot write to $files{'pid'}, exiting");
print "Cannot write to $files{'pid'}, exiting" if $debug;
exit;
};
print PIDFILE "$$";
close(PIDFILE);
&execute($interval);
&write_log("Execute loop closed, process ending");
print "Execute loop closed, process ending" if $debug;
}
elsif ($! =~ /No more process/) {
sleep 5;
redo FORK;
}
else {
die 'Cannot fork: $!\n';
}
}
}
else {
my $interval = $config{'query_interval'};
&execute($interval);
exit;
}