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
###############################
#
# Author:  Jesper Wallin
# Date:    2011-11-04
# Contact: [email protected]
#
#
# Usage:
#
# loadplugin GeoIP geoip.pm
#
# header MG_GEOIP_COUNTRY eval:check_geoip_country()
# priority MG_GEOIP_COUNTRY -1000
# add_header all Country _COUNTRY_
#
# header MG_FROM_CHINA X-Spam-Country =~ /CN/
# describe MG_FROM_CHINA Relayed through a IP located in China
# score MG_FROM_CHINA 0.1
#
# header MG_FROM_SCANDINAVIA X-Spam-Country =~ /(SE|NO|DK)/
# describe MG_FROM_SCANDINAVIA Relayed through a IP located in Scandinavia.
# score MG_FROM_SCANDINAVIA -0.1
#
#
package GeoIP;

use strict;
use warnings;

use Mail::SpamAssassin::Plugin;
use Geo::IP;
our @ISA = qw(Mail::SpamAssassin::Plugin);

sub new {
  my ($class, $mailsa) = @_;
  $class = ref($class) || $class;
  my $self = $class->SUPER::new($mailsa);
  bless($self, $class);
  $self->register_eval_rule("check_geoip_country");
  return $self;
}

sub check_geoip_country {
  my ( $self, $pms ) = @_;

  # get the last relay.
  $pms->{lasthop} = $pms->{relays_untrusted}->[0];

  # make sure we actually have a IP.
  if (defined($pms->{lasthop}) && defined($pms->{lasthop}->{ip}))
  {
    # add the ip to templates.
    $pms->set_tag('COUNTRY_IP', $pms->{lasthop}->{ip});

    # lookup the IP in  the GeoIP database.
    my $geo = Geo::IP->new(GEOIP_MEMORY_CACHE);
    my $country = $geo->country_code_by_addr($pms->{lasthop}->{ip});

    # add the country (if any) to templates.
    if (defined($country))
    {
      $pms->{msg}->put_metadata('X-Spam-Country', $country);
      $pms->set_tag('COUNTRY', $country);
    }
    else
    {
      $pms->{msg}->put_metadata('X-Spam-Country', 'Unknown');
      $pms->set_tag('COUNTRY', 'Unknown');
    }
  }

  # only add the template headers.
  return 0;
}

1;