Linux

Postfix: Mail-Relay mit SMTP-Auth via Submission/TLS für ausgehende Mails

0

Ein Server soll als Relayhost (oder in der Windowswelt auch Smarthost gennant) dienen. Wer keine feste IP Adresse mit passenden DNS Reverse Eintrag hat wird schlechte Chancen haben das ein richtig konfigurierter Mailserver die Mails annehmen wird. Die Lösung ist die Mails an einen anderen Relayhost oder Mailserver zu schicken und dieser stellt dann die Mails zu. Manchmal bieten die Provider selbst Relayhosts an in vielen Fällen bleibt nichts anderes übrig als das ganze über ein Postfach zu versenden. Einige Provider bieten das Anliefern von Mails nur noch über Submission (TCP/587) und TLS verschlüsselt an. Ist mir persönlich auch lieber …

Beispielszenario

Provider: example.net

Mailaccount: user1@example.net Password: example%1

Mailserver: mail.example.net

Submission (TCP/587) und TLS sind notwendig.

 Lösung

“/etc/postfix/main.cf” ergänzen mit:

relayhost = mail.example.net:submission
smtp_use_tls=yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/smtp_auth
smtp_sasl_security_options = noanonymous, noplaintext
smtp_sasl_tls_security_options = noanonymous

/etc/postfix/smtp_auth (Map-Datei, muss initialisiert werden!!!)

mail.example.net:submission               user1@example.net:example%1

Folgende Kommandos sind noch auszuführen:

postmap /etc/postfix/smtp_auth

durchführen um die Datei zu mappen.

/etc/init.d/postfix restart

durchführen um die Änderungen zu aktivieren.

socat: Pfiffiges Tool zum Mappen von IPv6 auf IPv4 Adressen

0

Wer gerade vor dem Problem steht alle Dienste auf seinen Linux Maschinen IPv4/IPv6 Dualstack fähig zu machen, der ist froh wenn er so ein Tool wie socat findet.

Es sind zwar die meisten Linux Dienste bereits Dualstack fähig aber es gibt vereinzelt noch Dienste wo keine regelmäßige bis keine Pflege der Software stattfindet.

socat ist quasi ein IPv6 -> IPv4 Relay. Das Paket ist im Packet Repository von Debian / Ubuntu verfügbar.

Beschreibung von socat aus der README des Pakets:

socat is a relay for bidirectional data transfer between two independent data
channels. Each of these data channels may be a file, pipe, device (serial line
etc. or a pseudo terminal), a socket (UNIX, IP4, IP6 - raw, UDP, TCP), an
SSL socket, proxy CONNECT connection, a file descriptor (stdin etc.), the GNU
line editor (readline), a program, or a combination of two of these.
These modes include generation of "listening" sockets, named pipes, and pseudo
terminals.

socat can be used, e.g., as TCP port forwarder (one-shot or daemon), as an
external socksifier, for attacking weak firewalls, as a shell interface to UNIX
sockets, IP6 relay, for redirecting TCP oriented programs to a serial line, to
logically connect serial lines on different computers, or to establish a
relatively secure environment (su and chroot) for running client or server
shell scripts with network connections.

Many options are available to refine socats behaviour:
terminal parameters, open() options, file permissions, file and process owners,
basic socket options like bind address, advanced socket options like IP source
routing, linger, TTL, TOS (type of service), or TCP performance tuning.

More capabilities, like daemon mode with forking, client address check,
"tail -f" mode, some stream data processing (line terminator conversion),
choosing sockets, pipes, or ptys for interprocess communication, debug and
trace options, logging to syslog, stderr or file, and last but not least
precise error messages make it a versatile tool for many different purposes.

In fact, many of these features already exist in specialized tools; but until
now, there does not seem to exists another tool that provides such a generic,
flexible, simple and almost comprehensive (UNIX) byte stream connector.

Das Tool kann noch wesentlich mehr, Infos findet man auf der Webseite des Programmierers http://www.dest-unreach.org/socat/.

Ich habe das für meinen alten SKS Keyserver verwendet, der noch kein IPv6 beherrscht. Ich lasse das ganze in einzelnen Screens laufen.

screen -dmS socat1 socat TCP6-LISTEN:11370,ipv6only=1,reuseaddr,fork TCP4:1.2.3.4:11370
screen -dmS socat2 socat TCP6-LISTEN:11371,ipv6only=1,reuseaddr,fork TCP4:1.2.3.4:11371
screen -dmS socat3 socat TCP6-LISTEN:80,ipv6only=1,reuseaddr,fork TCP4:1.2.3.4:11371

Damit das ganze auch noch einen Neustart überlebt kann man es noch in die /etc/rc.local vor dem “exit 0″ einfügen.

Python Version von getadsmtp.pl

0

Übersetzung des AD Mailadressen Sammelskripts von Perl nach Python.

Download

#!/usr/bin/python

# getadsmtp.py
# Version 1.0
# The script is an translation from the orginal perl script getadsmtp.pl

# This script will pull all users' SMTP addresses from your Active Directory
# (including primary and secondary email addresses) and list them in the
# format "user@example.com OK" which Postfix uses with relay_recipient_maps.
# Be sure to double-check the path to python above.

# This requires python-ldap to be installed.  To install python-ldap on debian based systems,
# at a shell type "apt-get install python-ldap" or "sudo apt-get install python-ldap"

import os, sys, ldap

# Enter the path/file for the output
valid_addresses = "/etc/postfix/example_recipients"

# Enter the FQDN of your Active Directory domain controllers below
dc1="dc01.example.com"
dc2="dc02.example.com"

# Enter the LDAP container for your userbase.
# The syntax is CN=Users,dc=example,dc=com
# This can be found by installing the Windows 2000 Support Tools
# then running ADSI Edit.
# In ADSI Edit, expand the "Domain NC [domaincontroller1.example.com]" &
# you will see, for example, DC=example,DC=com (this is your base).
# The Users Container will be specified in the right pane as
# CN=Users depending on your schema (this is your container).
# You can double-check this by clicking "Properties" of your user
# folder in ADSI Edit and examining the "Path" value, such as:
# LDAP://domaincontroller1.example.com/CN=Users,DC=example,DC=com
# which would be hqbase="cn=Users,dc=example,dc=com"
# Note:  You can also use just hqbase="dc=example,dc=com"
hqbase="cn=Users,dc=example,dc=com"

# Enter the username & password for a valid user in your Active Directory
# with username in the form cn=username,cn=Users,dc=example,dc=com
# Make sure the user's password does not expire.  Note that this user
# does not require any special privileges.
# You can double-check this by clicking "Properties" of your user in
# ADSI Edit and examining the "Path" value, such as:
# LDAP://domaincontroller1.example.com/CN=user,CN=Users,DC=example,DC=com
# which would be $user="cn=user,cn=Users,dc=example,dc=com"
# Note: You can also use the UPN login: "user@example.com"
user="cn=user,cn=Users,dc=example,dc=com"
passwd="password"

try:
  l = ldap.initialize("ldap://%s" %(dc1))
  l.set_option(ldap.OPT_REFERRALS, 0)
  l.protocol_version = 3
  l.simple_bind_s(user, passwd)

except ldap.LDAPError, e:
  try:
    l = ldap.initialize("ldap://%s" %(dc2))
    l.set_option(ldap.OPT_REFERRALS, 0)
    l.protocol_version = 3
    l.simple_bind_s(user, passwd)

  except ldap.LDAPError, e:
    print "Error connecting to specified domain controllers\n"
    sys.exit()

# Play around with this to grab objects such as Contacts, Public Folders, etc.
# A minimal filter for just users with email would be:
# filter = "(&(sAMAccountName=*)(mail=*))"
filter = "(& (mailnickname=*) (| (&(objectCategory=person)(objectClass=user)(!(homeMDB=*))(!(msExchHomeServerName=*)))(&(objectCategory=person)(objectClass=user)(|(homeMDB=*)(msExchHomeServerName=*)))(&(objectCategory=person)(objectClass=contact))(objectCategory=group)(objectCategory=publicFolder)(objectClass=msExchDynamicDistributionList) ))"

attrs = ["proxyAddresses"]
scope = ldap.SCOPE_SUBTREE

r = l.search(hqbase, scope, filter, attrs)
type,a = l.result(r)
result_set = []

for x in a:
  name,attrs = x
  if hasattr(attrs, 'has_key') and attrs.has_key('proxyAddresses'):
    proxyAddresses = attrs['proxyAddresses']
    for y in proxyAddresses:
      result_set.append("%s OK" %(y.replace("smtp:","").replace("SMTP:","")))

# Add additional restrictions, users, etc. to the output file below.
#result_set.append("user@example.com OK")
#result_set.append("user1@example.com 550 User unknown.")
#result_set.append("bad.example.com 550 User does not exist.")

#######################################################################
# Build file ...
output = file(valid_addresses,'w')

for line in result_set:
  output.write("%s\n" %(line))

output.close()

Layer 3 VPN mit OpenSSH

0

OpenSSH ist in der Lage über Tun-Interfaces ein Layer 3 VPN herzustellen. Dies ist eine sehr einfache Variante, besonders schön ist das man SSH auch in vielen Fällen über einen Proxy verwenden kann.

Szenario

Aufbau:

  • Firewall (intern: 10.10.0.254, extern: 55.66.77.88, macht PAT über externes Interface)
  • SSHVPN VM ist eine VMware Maschine auf meinem VMware Server (intern: 10.10.0.122, tun0: 10.255.255.1, macht PAT über internes Interface)
  • Mein PC (Ubuntu 10.10 Maschine mit NX intern: 10.10.0.80)
  • Mein Netbook in dem Beispiel irgendwo im Internet mit UMTS Stick (Ubuntu 10.10 Netbook Edition)
  • Auf der Firewall ist ein NAT Portforwarding für TCP Port 22 auf 10.10.0.122 eingerichtet

Der Client

Falls noch kein Schlüsselpaar für root existiert muss eines angelegt werden.

toor@sshvpn-vm:~$ sudo ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/root/.ssh/id_rsa.
Your public key has been saved in /home/root/.ssh/id_rsa.pub.
The key fingerprint is:
05:d2:94:2e:16:fd:96:29:5c:6d:13:b5:55:8f:ce:31 root@sshvpn-vm
The key's randomart image is:
+--[ RSA 2048]----+
|      .+o. ..o. +|
|      ..+.. +  +.|
|       + o.+ .E .|
|      o +.=  o o |
|     . .So    o  |
|                 |
|                 |
|                 |
|                 |
+-----------------+
toor@sshvpn-vm:~$

Am einfachsten ist es ohne Passwort. Meine Empfehlung: Unbedingt mit Passwort machen, ist sicherer ;-) Den Namen unverändert lassen, auch den Speicherort. id_rsa wird im .ssh Verzeichnis beim Verbindungsaufbau vom ssh Client automatisch verwendet sofern vorhanden.

Anpassen der /etc/network/interfaces Datei

Folgenden Absatz an das Ende der Datei anfügen.

iface tun0 inet static
      pre-up ssh -S /var/run/sshvpn-tun-ctrl -M -f -w 0:0 55.66.77.88 true
      pre-up sleep 5
      address 10.255.255.2
      pointopoint 10.255.255.1
      netmask 255.255.255.252
      up route add -net 10.10.0.0 netmask 255.255.255.0 gw 10.255.255.1 tun0
      post-down ssh -S /var/run/sshvpn-tun-ctrl -O exit 55.66.77.88

Der Server

Anpassen der /etc/ssh/sshd_config Datei

Hinzufügen / Anpassen folgender Optionen

PermitTunnel point-to-point
PermitRootLogin forced-commands-only

PermitRootLogin existiert bei Ubuntu Systemen (steht auf Yes) schon bei anderen Distris kann das anders sein. Falls die PermitRootLogin existiert die orginale einfach auskommentieren.

Anpassen der /root/.ssh/authorized_keys Datei

tunnel="0",command="/sbin/ifdown tun0;/sbin/ifup tun0" ssh-rsa AAAA.... root@sshvpn-vm

Ab ssh-rsa muss alles ersetzt werden durch den Inhalt aus dem generierten öffentlichen Schüssel vom Client. (/root/.ssh/id_rsa.pub)

Anpassen der /etc/network/interfaces Datei

Folgenden Absatz an das Ende der Datei anfügen.

iface tun0 inet static
      address 10.255.255.1
      netmask 255.255.255.252
      pointopoint 10.255.255.2

IP Forwarding auf dem Server aktivieren

$ sysctl -w net.ipv4.ip_forward=1

Für eine dauerhaftes IP Forwarding muss mann noch die /etc/sysctl.conf anpassen.

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf

NAT aktivieren

Ich habe auf meinem SSHVPN Server NAT aktiviert damit ich ohne Routing arbeiten kann, das ist einfacher.

Folgendes Script in /etc/init.d anlegen.

iptables.nat.sshvpn:

/sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Aktivieren für Systemstart:

$  update-rc.d iptables.nat.sshvpn defaults

Test des VPN Tunnels

Auf dem Client kann der Tunnel mit folgendem Kommando gestartet werden.

$ sudo ifup tun0

Der SSH Client baut dann die Verbindung zum Server auf und richtet das Tunnelinterface ein.

Ein einfacher Ping zeigt das es funktioniert hat.

$  ping 10.10.0.80
PING 10.10.0.80 (10.10.0.80) 56(84) bytes of data.
64 bytes from 10.10.0.80: icmp_req=1 ttl=64 time=99.57 ms
64 bytes from 10.10.0.800: icmp_req=2 ttl=64 time=90.238 ms
64 bytes from 10.10.0.80: icmp_req=3 ttl=64 time=90.217 ms
64 bytes from 10.10.0.80: icmp_req=4 ttl=64 time=90.181 ms

Viel Spaß mit euren eigenen SSH VPNs ;-)

Automatische Proxy Zuweisung über WPAD/PAC

0

In meiner Testumgebung verwende ich verschiedene Domains die nicht über einen Proxy gehen sollen. Da die manuelle Pflege an meinen Maschinen mir zu umständlich erscheint habe ich mich für den Proxy PAC (Proxy Auto Configuration) weg entschieden. Normalerweise wäre es ja ganz einfach, einfach bei jeder Domain als TLD .local verwenden und als Filter in der  Proxykonfiguration *.local ausschließen. Leider habe ich aber auch .com, usw. im Einsatz und ein Filter auf *.com wäre denkbar unpraktisch ;-) Die Lösung: PAC-File zentral auf meinem Server und bekanntgabe via WPAD.

PAC-File (wpad.dat)

function FindProxyForURL(url, host) {

   var proxy_yes = "PROXY proxy.lanbugs.local:3128";
   var proxy_wlan_yes = "PROXY proxy-wlan.lanbugs.local:3128";
   var proxy_no = "DIRECT";
   var proxy_failback = "PROXY proxy.lanbugs.local:3128; DIRECT";

   // Muss ins Internet direkt
   if (shExpMatch(url,"www.lanbugs.de/*")) {return proxy_yes;}
   if (shExpMatch(url,"www.thoma.cc/*")) {return proxy_yes;}

   // Interne Webseiten
   if (shExpMatch(url,"*.lanbugs.local/*")) {return proxy_no;}
   if (shExpMatch(url, "*.lanbugs.de/*")) {return proxy_no;}
   if (shExpMatch(url, "*.thoma.cc/*")) {return proxy_no;}

   // Homenet
   if (isInNet(host, "10.10.4.0", "255.255.255.0")) {
      return proxy_yes;
   }

   // WLAN
   if (isInNet(host, "10.10.5.0", "255.255.255.0")) {
      return proxy_wlan_yes;
   }

   // Server
   if (isInNet(host, "10.10.4.200", "255.255.255.255"){
     return proxy_no;
   }

   return proxy_failback;
}

Meine PAC Konfiguration mancht folgendes:

  • www.lanbugs.de wird weiterhin zum Proxy gesendet alles andere wird direkt über den internen DNS auf interne Webserver umgeleitet
  • www.thoma.cc wird weiterhin zum Proxy gesendet alles andere wird direkt über den internen DNS aus interne Webserver umgeleitet
  • *.lanbugs.local wird komplett vom Proxy ausgeschlossen
  • Mein Homenet wird komplett über den Proxy proxy.lanbugs.local abgewickelt
  • Mein WLAN Netz wird komplett über den Proxy proxy-wlan.lanbugs.local abgewickelt
  • Für den Server 10.10.4.200 geht nicht über den Proxy
  • Für alle anderen wird versucht über den Proxy zu gehen funktioniert das nicht versucht der Browser es direkt

WPAD Konfiguration

WPAD lässt sich über DNS, DHCP und als manuelles File verteilen, leider unterstützen nicht alle Browser alle Wege.

WPAD Kompatibilitätsliste

Browser DNS DHCP Manuelles File
Internet Explorer 6.0 (SP1) und höher JA JA JA
Firefox 1.5.x JA NEIN JA
Firefox 2.5.x JA NEIN JA
Opera NEIN NEIN JA
NetScape JA NEIN JA
Safari ? ? JA

Vorbereiten des Webservers für WPAD/PAC File

Mein Server läuft mit Ubuntu 8.04 LTS. Bei den Ubuntu / Debian Versionen liegt die MIME Type Konfiguration unter /etc/apache2/mods-enabled.

/etc/apache2/mods-enabled/mime.conf

AddType application/x-ns-proxy-autoconfig .dat
AddType application/x-ns-proxy-autoconfig .pac

Desweiteren sollte die Dateiendung noch in /etc/mime.types bekannt gegeben werden.

application/x-ns-proxy-autoconfig dat
application/x-ns-proxy-autoconfig pac

Das PAC File liegt im root-Verzeichnis des Webservers /var/www als proxy.pac und wpad.dat. Alternativ habe ich noch einen Vorschlag gelesen nur die proxy.pac anzulegen und die Datei via redirect unter wpad.dat erreichbar zu machen. Geschmackssache ….

WPAD via DNS

WPAD via DNS geht über verschiedene Wege. Entweder über einen A/CNAME Record oder über einen TXT/SRV Eintrag. Es kann nicht schaden alle möglichkeiten anzulegen. Per DHCP wird in meinem Netz die Domain lanbugs.local als Primäres DNS Suffix mitgegeben, folglich muss ein Eintrag für wpad.lanbugs.local angelegt werden.

Auszug aus der Zone lanbugs.local:

...
wpad           IN A                       10.10.4.200
wpad.tcp       IN SRV       0 0 80        10.10.4.200
               IN TXT                     "service: wpad:http://wpad.lanbugs.local/wpad.dat"
...

WPAD via DHCP

Der DHCP Server muss mit der Option 252 erweitert werden. In dieser Option wird die URL der wpad.dat eingefügt.

option wpad code 252 = text;

subnet 10.10.4.0 netmask 255.255.255.0 {
…
option wpad “http://wpad.lanbugs.local/wpad.dat ”;
…
}

subnet 10.10.5.0 netmask 255.255.255.0 {
…
option wpad “http://wpad.lanbugs.local/wpad.dat ”;
…
}

WPAD via Manuelles File

Falls alles nicht funktionieren  sollte lässt sich das File auch manuell Eintragen.

Firefox:

Extras -> Einstellungen -> Erweitert -> Netzwerk -> Verbindung (Einstellungen) -> Automatische Proxy-Konfigurations-URL: http://wpad.lanbugs.local/proxy.pac

Internet Explorer:

Extras -> Internet Optionen -> Verindungen -> LAN-Einstellungen (Einstellungen) -> (x) Automatisches Konfigurationsskript verwenden: http://wpad.lanbugs.local/proxy.pac

Chrome:

Nutzt die Einstellungen vom Internet Explorer

Opera:

Einstellungen -> Netzwerk -> Proxyserver -> (x) Automatische Proxykonfiguration verwenden (Skript): http://wpad.lanbugs.local/proxy.pac

Finale

Damit die automatische Zuweisung klappt sollte der Browser auch so eingestellt sein das er eine WPAD Konfiguration zulässt.

Firefox:

Extras -> Einstellungen -> Erweitert -> Netzwerk -> Verbindung (Einstellungen) -> (x) Die Proxy-Einstellungen für dieses Netzwerk automatisch erkennen

Internet Explorer:

Extras -> Internet Optionen -> Verindungen -> LAN-Einstellungen (Einstellungen) -> (x) Automatische Suche der Einstellungen

Chrome:

Nutzt die Einstellugen vom Internet Explorer

Opera:

Hier scheint nur der manuelle Weg zu bleiben

Postfix als Frontend für einen Microsoft Exchange Server

1

Für einen Kunden habe ich einen Postfix eingerichtet als Frontend Server für seine Exchange Infrastruktur. Die Mailadressen werden automatisch aus dem Active Directory ausgelesen und in einem Hash-File gespeichert. Vorteil ist das der Postfix so nur gültige Mailaliases zulässt. Der Frontend macht auch noch weitere Überprüfungen. (postgrey, policy-weight, etc.)

Folgendes Script wird für das Auslesen der Aliase aus dem AD verwendet:

#!/usr/bin/perl -T -w

# Version 1.02

# This script will pull all users' SMTP addresses from your Active Directory
# (including primary and secondary email addresses) and list them in the
# format "user@example.com OK" which Postfix uses with relay_recipient_maps.
# Be sure to double-check the path to perl above.

# This requires Net::LDAP to be installed.  To install Net::LDAP, at a shell
# type "perl -MCPAN -e shell" and then "install Net::LDAP"

use Net::LDAP;
use Net::LDAP::Control::Paged;
use Net::LDAP::Constant ( "LDAP_CONTROL_PAGED" );

# Enter the path/file for the output
$VALID = "/etc/postfix/example_recipients";

# Enter the FQDN of your Active Directory domain controllers below
$dc1="domaincontroller1.example.com";
$dc2="domaincontroller2.example.com";

# Enter the LDAP container for your userbase.
# The syntax is CN=Users,dc=example,dc=com
# This can be found by installing the Windows 2000 Support Tools
# then running ADSI Edit.
# In ADSI Edit, expand the "Domain NC [domaincontroller1.example.com]" &
# you will see, for example, DC=example,DC=com (this is your base).
# The Users Container will be specified in the right pane as
# CN=Users depending on your schema (this is your container).
# You can double-check this by clicking "Properties" of your user
# folder in ADSI Edit and examining the "Path" value, such as:
# LDAP://domaincontroller1.example.com/CN=Users,DC=example,DC=com
# which would be $hqbase="cn=Users,dc=example,dc=com"
# Note:  You can also use just $hqbase="dc=example,dc=com"
$hqbase="cn=Users,dc=example,dc=com";

# Enter the username & password for a valid user in your Active Directory
# with username in the form cn=username,cn=Users,dc=example,dc=com
# Make sure the user's password does not expire.  Note that this user
# does not require any special privileges.
# You can double-check this by clicking "Properties" of your user in
# ADSI Edit and examining the "Path" value, such as:
# LDAP://domaincontroller1.example.com/CN=user,CN=Users,DC=example,DC=com
# which would be $user="cn=user,cn=Users,dc=example,dc=com"
# Note: You can also use the UPN login: "user\@example.com"
$user="cn=user,cn=Users,dc=example,dc=com";
$passwd="password";

# Connecting to Active Directory domain controllers
$noldapserver=0;
$ldap = Net::LDAP->new($dc1) or
   $noldapserver=1;
if ($noldapserver == 1)  {
   $ldap = Net::LDAP->new($dc2) or
      die "Error connecting to specified domain controllers $@ \n";
}

$mesg = $ldap->bind ( dn => $user,
                     password =>$passwd);
if ( $mesg->code()) {
    die ("error:", $mesg->code(),"\n","error name: ",$mesg->error_name(),
        "\n", "error text: ",$mesg->error_text(),"\n");
}

# How many LDAP query results to grab for each paged round
# Set to under 1000 for Active Directory
$page = Net::LDAP::Control::Paged->new( size => 990 );

@args = ( base     => $hqbase,
# Play around with this to grab objects such as Contacts, Public Folders, etc.
# A minimal filter for just users with email would be:
# filter => "(&(sAMAccountName=*)(mail=*))"
         filter => "(& (mailnickname=*) (| (&(objectCategory=person)
                    (objectClass=user)(!(homeMDB=*))(!(msExchHomeServerName=*)))
                    (&(objectCategory=person)(objectClass=user)(|(homeMDB=*)
                    (msExchHomeServerName=*)))(&(objectCategory=person)(objectClass=contact))
                    (objectCategory=group)(objectCategory=publicFolder)(objectClass=msExchDynamicDistributionList) ))",
          control  => [ $page ],
          attrs  => "proxyAddresses",
);

my $cookie;
while(1) {
  # Perform search
  my $mesg = $ldap->search( @args );

# Filtering results for proxyAddresses attributes
  foreach my $entry ( $mesg->entries ) {
    my $name = $entry->get_value( "cn" );
    # LDAP Attributes are multi-valued, so we have to print each one.
    foreach my $mail ( $entry->get_value( "proxyAddresses" ) ) {
     # Test if the Line starts with one of the following lines:
     # proxyAddresses: [smtp|SMTP]:
     # and also discard this starting string, so that $mail is only the
     # address without any other characters...
     if ( $mail =~ s/^(smtp|SMTP)://gs ) {
       push(@valid, $mail." OK\n");
     }
    }
  }

  # Only continue on LDAP_SUCCESS
  $mesg->code and last;

  # Get cookie from paged control
  my($resp)  = $mesg->control( LDAP_CONTROL_PAGED ) or last;
  $cookie    = $resp->cookie or last;

  # Set cookie in paged control
  $page->cookie($cookie);
}

if ($cookie) {
  # We had an abnormal exit, so let the server know we do not want any more
  $page->cookie($cookie);
  $page->size(0);
  $ldap->search( @args );
  # Also would be a good idea to die unhappily and inform OP at this point
     die("LDAP query unsuccessful");
}
# Only write the file once the query is successful
open VALID, ">$VALID" or die "CANNOT OPEN $VALID $!";
print VALID @valid;
# Add additional restrictions, users, etc. to the output file below.
#print VALID "user\@example.com OK\n";
#print VALID "user1\@example.com 550 User unknown.\n";
#print VALID "bad.example.com 550 User does not exist.\n";

close VALID;

Quelle: http://www-personal.umich.edu/~malth/gaptuning/postfix/

Ich habe das Perlscript in /etc/postfix abgelegt. Rechte sollten auch 700 sein. Diese 6 Parameter müssen geändert werden.

$VALID = "/etc/postfix/exchange_recipients";

$dc1="dc01.lanbugs.intra";
$dc2="dc02.lanbugs.intra";

$hqbase="cn=Users,dc=lanbugs,dc=intra";

$user="cn=sys-read-aliases-mailfront,cn=Users,dc=lanbugs,dc=intra";
$passwd="geheim123";

Das Script wird als Cronjob jede Stunde ausgeführt. Hierzu muss nur ein File mit dem Namen run_read_aliases_from_exchange.sh mit den Rechten 700 im Verzeichnis /etc/cron.hourly angelegt werden. (Debian/Ubuntu)

run_read_aliases_from_exchange.sh:

#!/bin/sh

cd /etc/postfix ; ./getadsmtp.pl && postmap exchange_recipients

In der /etc/postfix/main.cf kann dann das neue Hash-File als relay_recipient_map verwendet werden.

main.cf:

...
relay_recipient_maps = hash:/etc/postfix/exchange_recipients
relay_domains = lanbugs.de
transport_maps = hash:/etc/postfix/transport
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 10.1.1.20/32
...

relay_domains erlaubt allgemein die Domain lanbugs.de. mynetworks wurde noch um die IP-Adresse des Exchange Servers erweitert damit dieser E-Mails zur Außenwelt senden kann. Die transport_maps sorgen dafür dass alle Mails an lanbugs.de an den Exchange Server weiter transportiert werden.

/etc/postfix/transport: (nach dem Anlegen postmap /etc/postfix/transport nicht vergessen!!!!)

langbugs.de      smtp:[10.1.1.20]:25

10.1.1.20 ist der interne Exchange Server.

Viel Spaß mit dem Postfix Frontend ;-)

Forwarding für bestimmte DNS Zonen in Bind9

0

In diesem Szenario hat der Kunde in der DMZ 2 DNS Server (Forwarding zum Provider) stehen. Diese DNS Server sind die „Inernet“ DNS Server. Im internen Netz betreibt der Kunde mehrere Active Directory instanzen. Der Kunde möchte das seine internen DNS Zonen innerhalb der DMZ auflösbar sind. Dies kann man über Zonenweiterleitung in Bind realisieren.

zone "ad01.local" IN {
	type forward;
	forwarders {10.0.0.1; 10.0.0.2;};
};

zone "ad02.local" IN {
	type forward;
	forwarders {10.0.0.3; 10.0.0.4;};
};

zone "msexch.local" IN {
	type forward;
	forwarders {10.0.0.5; 10.0.0.6;};
};

eth Inferfacenummerierung ändern

0

für Ubuntu / Debian

In bestimmten Fällen will man die Nummerierung der eth Interfaces ändern. Wenn z.B. eine virtuelle Maschine geklont wird und eine neue MAC-Adresse für das Ethernet Interface generiert wird dann würde das Interface eth1 lauten.

Die Zuordnung der Interfaces wird über UDEV realisiert in der Datei /etc/udev/rules.d/70-persistent-net.rules

Nach Änderung der MAC Adresse:

# This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

# PCI device 0x1022:0x2000 (pcnet32)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:0c:29:15:a5:b6", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

# PCI device 0x1022:0x2000 (pcnet32)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:0c:29:15:a5:b7", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

00:0c:29:15:a5:b7 soll wieder eth0 werden 00:0c:29:15:a5:b6 gibt es nicht mehr und kann gelöscht werden.

Nach Änderung:

# This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

# PCI device 0x1022:0x2000 (pcnet32)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:0c:29:15:a5:b7", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

Neue SSH Hostkeys generieren

0

für Debian / Ubuntu

Falls man eine VMware Maschine kopiert benötigt man neue SSH Keys. Folgende Zeilen generieren neue Keys.

sudo rm /etc/ssh/ssh_host_key
sudo rm /etc/ssh/ssh_host_key.pub
sudo rm /etc/ssh/ssh_host_rsa_key
sudo rm /etc/ssh/ssh_host_rsa_key.pub
sudo rm /etc/ssh/ssh_host_dsa_key
sudo rm /etc/ssh/ssh_host_dsa_key.pub
sudo /usr/bin/ssh-keygen -t rsa1 -f /etc/ssh/ssh_host_key -N ""
sudo /usr/bin/ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N ""
sudo /usr/bin/ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N ""

WPA Enterprise mit EAP PEAP

0

Howto für Ubuntu und Debian

Für dieses Howto wird freeradius mit openssl Support benötigt.

Eine Anleitung für freeradius+openssl ist hier zu finden: Freeradius mit EAP Support

Die Pakete wie in der Anleitung beschrieben installieren.

Die unten aufgeführten Konfigurationsteile sind Ergänzungen oder Änderungen der Default Config.

openssl installieren
apt-get install openssl
RootCA anlegen

In das Verzeichnis /etc/freeradius/certs wechseln

cd /etc/freeradius/certs

openssl liefert ein einfaches Script um eine CA anzulegen.

/usr/lib/ssl/misc/CA.pl -newca
CA certificate filename (or enter to create)

Mit [Enter] bestätigen.

Making CA certificate ...
Generating a 1024 bit RSA private key
...............................................++++++
..........++++++
writing new private key to './demoCA/private/cakey.pem'

Ein Passwort definieren und eingeben.

Enter PEM pass phrase:
Verifying – Enter PEM pass phrase:

-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----

Country Name (2 letter code) [AU]:DE
State or Province Name (full name) [Some-State]:Bayern
Locality Name (eg, city) []:München
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Test
Organizational Unit Name (eg, section) []:Testabteilung
Common Name (eg, YOUR name) []:rootca
Email Address []:rootca@example.org

Please enter the following 'extra' attributes
to be sent with your certificate request

2 mal mit [Enter] bestätigen.

A challenge password []:
An optional company name []:

Using configuration from /usr/lib/ssl/openssl.cnf
Enter pass phrase for ./demoCA/private/cakey.pem:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:
            b7:bc:7f:60:3c:98:84:b2
        Validity
            Not Before: Jul 31 07:33:47 2009 GMT
            Not After : Jul 30 07:33:47 2012 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            organizationName          = Test
            organizationalUnitName    = Testabteilung
            commonName                = rootca
            emailAddress              = rootca@example.org
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                5C:85:A3:1C:70:8E:E3:60:62:C9:5A:60:83:A2:D5:3C:EA:64:C7:C9
            X509v3 Authority Key Identifier:
                keyid:5C:85:A3:1C:70:8E:E3:60:62:C9:5A:60:83:A2:D5:3C:EA:64:C7:C9
                DirName:/C=DE/ST=Bayern/O=Test/OU=Testabteilung/CN=rootca/emailAddress=rootca@example.org
                serial:B7:BC:7F:60:3C:98:84:B2

            X509v3 Basic Constraints:
                CA:TRUE
Certificate is to be certified until Jul 30 07:33:47 2012 GMT (1095 days)

Write out database with 1 new entries
Data Base Updated
Server Zertifikat erzeugen
openssl req -new -nodes -keyout server_key.pem -out server_req.pem -days 730 -config /etc/ssl/openssl.cnf
Generating a 1024 bit RSA private key
...++++++
..............................................................................++++++
writing new private key to 'server_key.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----

Country Name (2 letter code) [AU]:DE
State or Province Name (full name) [Some-State]:Bayern
Locality Name (eg, city) []:München
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Test
Organizational Unit Name (eg, section) []:Testabteilung
Common Name (eg, YOUR name) []:server
Email Address []:server@example.org

Please enter the following 'extra' attributes
to be sent with your certificate request

A challenge password []:
An optional company name []:

Server Zertifikat mit der rootCA signieren
openssl ca -config /etc/ssl/openssl.cnf -policy policy_anything -out server_cert.pem -infiles ./server_req.pem
Using configuration from /etc/ssl/openssl.cnf

Passwort der CA eingeben:

Enter pass phrase for ./demoCA/private/cakey.pem:

Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:
            b7:bc:7f:60:3c:98:84:b3
        Validity
            Not Before: Jul 31 08:10:11 2009 GMT
            Not After : Jul 31 08:10:11 2010 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            localityName              = M\C3\BCnchen
            organizationName          = Test
            organizationalUnitName    = Testabteilung
            commonName                = server
            emailAddress              = server@example.org
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                D7:95:A8:C4:D7:70:BE:4C:D4:52:B1:E6:B5:A6:CD:37:B2:4A:6B:AE
            X509v3 Authority Key Identifier:
                keyid:5C:85:A3:1C:70:8E:E3:60:62:C9:5A:60:83:A2:D5:3C:EA:64:C7:C9

Certificate is to be certified until Jul 31 08:10:11 2010 GMT (365 days)

Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y

Write out database with 1 new entries
Data Base Updated
Server Zertifikat zusammenbauen
cat server_key.pem server_cert.pem > server.pem
radiusd.conf
mschap {
 authtype = MS-CHAP
 use_mppe = yes
 require_encryption = yes
 require_strong = yes
clients.conf

In clients.conf muss für den Accesspoint ein „Shared Secret“ festgelegt werden. 192.168.0.10 ist die IP des Accesspoints.

client 192.168.0.10 {
        # This is the shared secret between the Authenticator (the
        # access point) and the Authentication Server (RADIUS).
        secret          = 123password456
        shortname       = accesspoint
    }
users

Einen neuen User anlegen. Am Ende der users Datei einen neuen Benutzer hinzufügen. ACHTUNG in mehreren Howtos wird der Syntax User-Password == „password“ noch verwendet. Dieser Syntax ist für freeradius Version 2.x obsolet. Der neue Syntax lautet Cleartext-Password := „password“.

"mobil-user"     Cleartext-Password := "password123"
eap.conf
eap {
 default_eap_type = peap
  tls {
   CA_file = ${cadir}/demoCA/cacert.pem
  }
}
sites-enabled/default
authorize {
 mschap
 # unix
}

authenticate {
 Auth-Type MS-CHAP {
  mschap
 }
 # unix
}

accounting {
 # unix
}
freeradius testen
freeradius -X

Wenn alles ohne Fehler durchläuft sollte da folgendes erscheinen

Listening on authentication address * port 1812
Listening on accounting address * port 1813
Listening on proxy address * port 1814
Ready to process requests.
Daemon starten
[Strg-C]
/etc/init.d/freeradius start
Accesspoint einstellen -Allgemein-
  • Radiusserver + Radiusport + Shared Secret eingeben
  • Modus: WPA2-Enterprise
Client anbinden -Allgemein-
  • CAcert.pem zu den vertrauten Zertifizierungsstellen hinzufügen
  • Mode WPA2-Enterprise
  • EAP PEAP auswählen
Fertig!
nach oben