Debian Codegraph @

check_email_delivery/src/check_smtp_send_epn

raw
1 #!/usr/bin/perl
2 use strict;
3 use POSIX qw(strftime);
4 my $VERSION = '0.7.3';
5 my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <[email protected]>';
6 my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
7 my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
8
9 # look for required modules
10 exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Net::SMTP/);
11
12 BEGIN {
13 if( grep { /^--hires$/ } @ARGV ) {
14 eval "use Time::HiRes qw(time);";
15 warn "Time::HiRes not installed\n" if $@;
16 }
17 }
18
19 Getopt::Long::Configure("bundling");
20 my $verbose = 0;
21 my $help = "";
22 my $help_usage = "";
23 my $show_version = "";
24 my $smtp_server = "";
25 my $default_smtp_port = "25";
26 my $default_smtp_ssl_port = "465";
27 my $default_smtp_tls_port = "587";
28 my $smtp_port = "";
29 my @mailto = ();
30 my $mailfrom = "";
31 my @header = ();
32 my $body = "";
33 my $stdin = "";
34 my $template = "";
35 my $expect_response = "250";
36 my $warntime = 15;
37 my $criticaltime = 30;
38 my $timeout = 60;
39 my $tls = 0;
40 my $ssl = 0;
41 my $auth_method = undef;
42 my $username = "";
43 my $password = "";
44 my $time_hires = "";
45 my $mx_lookup = 0;
46 my $ok;
47 $ok = Getopt::Long::GetOptions(
48 "V|version"=>\$show_version,
49 "v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
50 "w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
51 # smtp settings
52 "H|hostname=s"=>\$smtp_server,"p|port=i"=>\$smtp_port,
53 "mailto=s"=>\@mailto, "mailfrom=s",\$mailfrom,
54 "header=s"=>\@header, "body=s"=>\$body, "stdin"=>\$stdin,
55 "template!"=>\$template,
56 # SSL/TLS/auth options
57 "tls!"=>\$tls, "ssl!"=>\$ssl, "auth=s"=>\$auth_method,
58 "U|username=s"=>\$username,"P|password=s"=>\$password,
59 # Server response
60 "E|expect-response=s"=>\$expect_response,
61 # Time
62 "hires"=>\$time_hires,
63 );
64
65 if( $show_version ) {
66 print "$VERSION\n";
67 if( $verbose ) {
68 print "Default warning threshold: $warntime seconds\n";
69 print "Default critical threshold: $criticaltime seconds\n";
70 print "Default timeout: $timeout seconds\n";
71 }
72 exit $status{UNKNOWN};
73 }
74
75 if( $help ) {
76 exec "perldoc", $0 or print "Try `perldoc $0`\n";
77 exit $status{UNKNOWN};
78 }
79
80 if( $smtp_server eq "" && scalar(@mailto) == 1 ) {
81 # no SMTP server specified but one mailto address given means we can look up the MX record
82 $mx_lookup = 1;
83 }
84
85 my @required_module = ();
86 push @required_module, 'Net::SMTP::SSL' if $ssl;
87 push @required_module, ('MIME::Base64','Authen::SASL') if $ssl && $username;
88 push @required_module, 'Net::SMTP::TLS' if $tls;
89 push @required_module, 'Net::SMTP_auth' if $auth_method and not $tls; # whereas if auth_method and tls we use TLS_auth, which is included in this script!
90 push @required_module, 'Text::Template' if $template;
91 push @required_module, 'Net::DNS' if $mx_lookup;
92 push @required_module, 'Email::Address' if $mx_lookup;
93 exit $status{UNKNOWN} unless load_modules(@required_module);
94
95
96 # split up @mailto if commas were used instead of multiple options
97 @mailto = split(/,/,join(',',@mailto));
98
99 if( $help_usage ||
100 (
101 ($smtp_server eq "" && !$mx_lookup) || scalar(@mailto)==0 || $mailfrom eq ""
102 )
103 ) {
104 print "Usage: $0 [-H host [-p port]] --mailto recipient\@your.net [--mailto recipient2\@your.net ...] --mailfrom sender\@your.net --body 'some text' [-w <seconds>] [-c <seconds>]\n";
105 exit $status{UNKNOWN};
106 }
107
108 # initialize
109 my $report = new PluginReport;
110 my $time_start = time;
111 my $actual_response = undef;
112 my @warning = ();
113 my @critical = ();
114
115 my $smtp_debug = 0;
116 $smtp_debug = 1 if $verbose >= 3;
117
118 # default date and message id headers
119 push @header, default_date_header() unless find_header("Date",@header);
120 push @header, default_messageid_header() unless find_header("Message-ID",@header);
121
122 # look up MX server if necessary
123 if( $mx_lookup ) {
124 my $addr = Email::Address->new( undef, $mailto[0] );
125 my $mx_domain = $addr->host;
126 print "MX lookup " . $mx_domain . "\n" if $verbose > 1;
127 my $res = Net::DNS::Resolver->new;
128 my @mx = Net::DNS::mx($res, $mx_domain);
129 if( @mx ) {
130 # use the first server
131 foreach my $rr (@mx) {
132 print "pref : " . $rr->preference . " exchange: " . $rr->exchange . "\n" if $verbose > 2;
133 }
134 $smtp_server = $mx[0]->exchange;
135 print "smtp server: $smtp_server\n" if $verbose;
136 }
137 else {
138 print "SMTP SEND CRITICAL - Cannot find MX records for $mx_domain\n";
139 exit $status{CRITICAL};
140 }
141 }
142
143 # connect to SMTP server
144 # create the smtp handle using Net::SMTP, Net::SMTP::SSL, Net::SMTP::TLS, or an authentication variant
145 my $smtp;
146 eval {
147 if( $tls and $auth_method ) {
148 $smtp_port = $default_smtp_tls_port unless $smtp_port;
149 $smtp = TLS_auth->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password, Auth_Method=>$auth_method);
150 if( $smtp ) {
151 my $message = oneline($smtp->message());
152 die "cannot connect with TLS/$auth_method: $message" if $smtp->code() =~ m/53\d/;
153 }
154 }
155 elsif( $tls ) {
156 $smtp_port = $default_smtp_tls_port unless $smtp_port;
157 $smtp = Net::SMTP::TLS->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password);
158 if( $smtp ) {
159 my $message = oneline($smtp->message());
160 die "cannot connect with TLS: $message" if $smtp->code() =~ m/53\d/;
161 }
162 }
163 elsif( $ssl ) {
164 $smtp_port = $default_smtp_ssl_port unless $smtp_port;
165 $smtp = Net::SMTP::SSL->new($smtp_server, Port => $smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
166 if( $smtp && $username ) {
167 $smtp->auth($username, $password);
168 my $message = oneline($smtp->message());
169 die "cannot connect with SSL/password: $message" if $smtp->code() =~ m/53\d/;
170 }
171 }
172 elsif( $auth_method ) {
173 $smtp_port = $default_smtp_port unless $smtp_port;
174 $smtp = Net::SMTP_auth->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
175 if( $smtp ) {
176 $smtp->auth($auth_method, $username, $password);
177 my $message = oneline($smtp->message());
178 die "cannot connect with SSL/$auth_method: $message" if $smtp->code() =~ m/53\d/;
179 }
180 }
181 else {
182 $smtp_port = $default_smtp_port unless $smtp_port;
183 $smtp = Net::SMTP->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
184 if( $smtp && $username ) {
185 $smtp->auth($username, $password);
186 my $message = oneline($smtp->message());
187 die "cannot connect with password: $message" if $smtp->code() =~ m/53\d/;
188 }
189 }
190 };
191 if( $@ ) {
192 $@ =~ s/\n/ /g; # the error message can be multiline but we want our output to be just one line
193 print "SMTP SEND CRITICAL - $@\n";
194 exit $status{CRITICAL};
195 }
196 unless( $smtp ) {
197 print "SMTP SEND CRITICAL - Could not connect to $smtp_server port $smtp_port\n";
198 exit $status{CRITICAL};
199 }
200 my $time_connected = time;
201
202 # add the monitored server's banner to the report
203 if( $tls ) {
204 $report->{banner} = "";
205 }
206 elsif( $ssl ) {
207 $report->{banner} = $smtp->banner || "";
208 chomp $report->{banner};
209 }
210 else {
211 $report->{banner} = $smtp->banner || "";
212 chomp $report->{banner};
213 }
214
215
216 # send email
217 if( $stdin ) {
218 $body = "";
219 while(<STDIN>) {
220 $body .= $_;
221 }
222 }
223
224 # if user wants to use template substitutions, this is the place to process body and headers
225 if( $template ) {
226 foreach my $item (@header,$body) {
227 my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$item,PACKAGE=>'SmtpMessageTemplate');
228 $item = $t->fill_in(PREPEND=>q{package SmtpMessageTemplate;});
229 # print "item: $item\n";
230 }
231 }
232
233
234 $smtp->mail($mailfrom);
235 foreach( @mailto ) {
236 # the two SMTP modules have different error reporting mechanisms:
237 if( $tls ) {
238 # Net::SMTP::TLS croaks when the recipient is rejected
239 eval {
240 $smtp->to($_);
241 };
242 if( $@ ) {
243 print "SMTP SEND CRITICAL - Could not send to $_\n";
244 print "Reason: $@\n" if $verbose;
245 exit $status{CRITICAL};
246 }
247 }
248 else {
249 # Net::SMTP returns false when the recipient is rejected
250 my $to_returned = $smtp->to($_);
251 if( !$to_returned ) {
252 print "SMTP SEND CRITICAL - Could not send to $_\n";
253 print "Reason: Recipient rejected or authentication failed\n" if $verbose;
254 exit $status{CRITICAL};
255 }
256 }
257 }
258
259 # Net::SMTP::TLS doesn't implement code() so we need to wrap calls in eval to get our error messages
260
261 # start data transfer (expect response 354)
262 $smtp->data();
263
264 # send data
265 $smtp->datasend("To: ".join(", ",@mailto)."\n");
266 $smtp->datasend("From: $mailfrom\n");
267 foreach( @header ) {
268 $smtp->datasend("$_\n");
269 }
270 $smtp->datasend("\n");
271 $smtp->datasend($body);
272 $smtp->datasend("\n");
273
274 eval {
275 # end data transfer (expect response 250)
276 $smtp->dataend();
277 };
278 if( $@ ) {
279 $actual_response = $tls ? get_tls_error($@) : $smtp->code();
280 }
281 else {
282 $actual_response = $tls ? "250" : $smtp->code(); # no error means we got 250
283 }
284
285 eval {
286 # disconnect from SMTP server (expect response 221)
287 $smtp->quit();
288 };
289 if( $@ ) {
290 push @warning, "Error while disconnecting from $smtp_server";
291 }
292
293 # calculate elapsed time and issue warnings
294 my $time_end = time;
295 my $elapsedtime = $time_end - $time_start;
296 $report->{seconds} = $elapsedtime;
297
298 push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
299 push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
300 push @critical, "response was $actual_response but expected $expect_response" if ( $actual_response ne $expect_response );
301
302 # print report and exit with known status
303 my $perf_data = "elapsed=".$report->{seconds}."s;$warntime;$criticaltime"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
304 my $short_report = $report->text(qw/seconds/) . " | $perf_data";
305 my $long_report = join("", map { "$_: $report->{$_}\n" } qw/banner/ );
306 if( scalar @critical ) {
307 my $crit_alerts = join(", ", @critical);
308 print "SMTP SEND CRITICAL - $crit_alerts; $short_report\n";
309 print $long_report if $verbose;
310 exit $status{CRITICAL};
311 }
312 if( scalar @warning ) {
313 my $warn_alerts = join(", ", @warning);
314 print "SMTP SEND WARNING - $warn_alerts; $short_report\n";
315 print $long_report if $verbose;
316 exit $status{WARNING};
317 }
318 print "SMTP SEND OK - $short_report\n";
319 print $long_report if $verbose;
320 exit $status{OK};
321
322
323 # utility to load required modules. exits if unable to load one or more of the modules.
324 sub load_modules {
325 my @missing_modules = ();
326 foreach( @_ ) {
327 eval "require $_";
328 push @missing_modules, $_ if $@;
329 }
330 if( @missing_modules ) {
331 print "Missing perl modules: @missing_modules\n";
332 return 0;
333 }
334 return 1;
335 }
336
337 # utility to extract error codes out of Net::SMTP::TLS croak messages
338 sub get_tls_error {
339 my ($errormsg) = @_;
340 $errormsg =~ m/: (\d+) (.+)/;
341 my $code = $1;
342 return $code;
343 }
344
345 # looks for a specific header in a list of headers; returns true if found
346 sub find_header {
347 my ($name, @list) = @_;
348 return scalar grep { m/^$name: /i } @list;
349 }
350
351 # RFC 2822 date header
352 sub default_date_header {
353 return strftime "Date: %a, %e %b %Y %H:%M:%S %z (%Z)", gmtime;
354 }
355
356 # RFC 2822 message id header
357 sub default_messageid_header {
358 my $random = randomstring(16,qw/0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z/);
359 my $hostname = `hostname`;
360 chomp $hostname;
361 return "Message-ID: <".time.".".$random.".checksmtpsend@".$hostname.">";
362 }
363
364 # returns a random string of specified length using characters from specified set
365 sub randomstring {
366 my ($length,@set) = @_;
367 my $size = scalar @set;
368 my $string = "";
369 while($length--) {
370 $string .= $set[int(rand($size))];
371 }
372 return $string;
373 }
374
375 # replaces all newlines in the input string with spaces
376 sub oneline {
377 my ($input) = @_;
378 $input =~ s/[\r\n]+/ /g;
379 return $input;
380 }
381
382 # NAME
383 # PluginReport
384 # SYNOPSIS
385 # $report = new PluginReport;
386 # $report->{label1} = "value1";
387 # $report->{label2} = "value2";
388 # print $report->text(qw/label1 label2/);
389 package PluginReport;
390
391 sub new {
392 my ($proto,%p) = @_;
393 my $class = ref($proto) || $proto;
394 my $self = bless {}, $class;
395 $self->{$_} = $p{$_} foreach keys %p;
396 return $self;
397 }
398
399 sub text {
400 my ($self,@labels) = @_;
401 my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
402 my $text = join(", ", @report);
403 return $text;
404 }
405
406 package SmtpMessageTemplate;
407
408 sub trim {
409 my ($text) = @_;
410 $text =~ s/^\s*//;
411 $text =~ s/\s*$//;
412 return $text;
413 }
414
415 # NAME
416 # TLS_auth
417 # SYNOPSYS
418 #
419 # Based on contribution by Brad Guillory
420 package TLS_auth;
421 #use Net::SMTP::TLS;
422 our @ISA = qw(Net::SMTP::TLS);
423 use Carp;
424 sub new {
425 my ($proto,$server,%p) = @_;
426 my $class = ref($proto) || $proto;
427 #my $self = bless {}, $class;
428 no strict 'refs';
429 no warnings 'once';
430 *Net::SMTP::TLS::login = *TLS_auth::login; # override parent's login with ours so when it's called in the constructor, our overriden version will be used
431 my $self = Net::SMTP::TLS->new($server,%p);
432 return $self;
433 }
434
435
436 sub login {
437 my ($self) = @_;
438 my $type = $self->{features}->{AUTH};
439 if(not $type){
440 die "Server did not return AUTH in capabilities\n"; # croak
441 }
442 # print "Feature: $type\nAuth Method: $self->{Auth_Method}\n";
443 if($type =~ /CRAM\-MD5/ and $self->{Auth_Method} =~ /CRAM\-MD5/i){
444 $self->auth_MD5();
445 }elsif($type =~ /LOGIN/ and $self->{Auth_Method} =~ /LOGIN/i){
446 $self->auth_LOGIN();
447 }elsif($type =~ /PLAIN/ and $self->{Auth_Method} =~ /PLAIN/i){
448 #print "Calling auth_PLAIN\n";
449 $self->auth_PLAIN();
450 }else{
451 die "Unsupported Authentication mechanism: $self->{Auth_Method}\n"; # croak
452 }
453 }
454
455
456 package main;
457 1;
458