Cisco/Python: Backup der Konfiguration bei write Event auf externen Server

Diverse Cisco Geräte können bei einem write Event die Konfiguration an einen anderen Server z.B. über HTTP pushen.

Cisco Config:

archive
 path http://1.2.3.4/cisco_config/put/$h-$t
 write-memory

Apache /etc/httpd/conf.d/zzz_cisco_backup.conf:

WSGIDaemonProcess cisco_backup user=apache group=apache threads=10
WSGIPythonPath /opt/cisco_backup/web_root
WSGIScriptAlias /cisco_backup /opt/cisco_backup/web_root/cisco_backup.wsgi

<Directory /opt/cisco_backup/web_root>
WSGIProcessGroup cisco_backup
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Order deny,allow
Allow from all

<Files cisco_backup.py>
Require all granted
</Files>
<Files cisco_backup.wsgi>
Require all granted
</Files>

</Directory>

cisco_backup.wsgi File:

import sys

sys.path.append("/opt/cisco_backup/web_root")

from cisco_backup import app as application

cisco_backup.py File:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route("/put/<cfg>", methods=['PUT'])
def get_config(cfg):
   with open('/opt/cisco_config/incoming_configs/%s' % cfg, "wb") as f:
      f.write(request.data)
   return "ok"

if __name__ == "__main__":
    app.run()

Viel Spaß 😉

Python: Snippet – E-Mail versenden, alternative zu Mailer

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText


def postmaster(mfrom, mto, msubject, message, smtphost):

    msg = MIMEText(message.encode("utf-8"))
    msg['Subject'] = msubject
    msg['From'] = mfrom
    msg['To'] = mto

    s = smtplib.SMTP(smtphost)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()

 

Python: Snippet: SSH shell on Cisco devices

Mit dem Snippet können Kommandos auf einer Cisco Shell via SSH ausgeführt werden.

#!/usr/bin/env python

import paramiko
import sys


def send_string_and_wait_for_string(command, wait_string, should_print):
    shell.send(command)
  
    receive_buffer = ""

    while not wait_string in receive_buffer:
        receive_buffer += shell.recv(1024)

    if should_print:
        print receive_buffer

    return receive_buffer

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("10.62.62.10", username="testuser", password="testpasswd", look_for_keys=False, allow_agent=False)

shell = client.invoke_shell()
send_string_and_wait_for_string("", "#", False)
send_string_and_wait_for_string("terminal length 0\n", "#", False)
output=send_string_and_wait_for_string("show logging\n", "#", False)
print output
client.close()

Mehr Infos / Quelle: http://blog.timmattison.com/archives/2014/06/25/automating-cisco-switch-interactions/

NGINX Reverse Proxy für Exchange 2016

Folgende Pakete müssen auf einem Ubuntu 16.04 LTS installiert werden:

apt install nginx nginx-extras

Die Konfiguration wird abgelegt unter /etc/nginx/conf.d/exchange.conf

Folgende Dinge müssen angepasst werden:

  • DNS Name unter dem OWA etc. erreichbar sein soll z.B. mail.example.org
  • Autodiscover DNS Name z.B. autodiscover.example.org
  • Interner Exchange Server z.B. exchange-server.example.internal
server {
    listen 80;
    server_name mail.example.org autodiscover.example.org;
    return 301 https://$host$request_uri;
}

server {
    tcp_nodelay on;
    listen 443;
    ssl                     on;
    ssl_certificate /etc/ssl/certs/star.example.org.pem;
    ssl_certificate_key /etc/ssl/private/star.example.org.key;

    ssl_session_timeout     5m;
    server_name mail.example.org;

    location / {
            return 301 https://mail.example.org/owa;
    }

    proxy_http_version      1.1;
    proxy_read_timeout      360;
    proxy_pass_header       Date;
    proxy_pass_header       Server;
    proxy_pass_header       Authorization;
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_pass_request_headers on;
    more_set_input_headers 'Authorization: $http_authorization';
    proxy_set_header Accept-Encoding "";
    more_set_headers -s 401 'WWW-Authenticate: Basic realm="exchange-server.example.internal"';
    # proxy_request_buffering off;
    proxy_buffering off;
    proxy_set_header Connection "Keep-Alive";

    location ~* ^/owa { proxy_pass https://exchange-server.example.internal; }
    location ~* ^/Microsoft-Server-ActiveSync { proxy_pass https://exchange-server.example.internal; }
    location ~* ^/ecp { proxy_pass https://exchange-server.example.internal; }
    location ~* ^/rpc { proxy_pass https://exchange-server.example.internal; }
    location ~* ^/autodiscover { proxy_pass https://exchange-server.example.internal; }
    location ~* ^/oab { proxy_pass https://exchange-server.example.internal; }

    error_log /var/log/nginx/exchange-rproxy-ssl-error.log;
    access_log /var/log/nginx/exchange-rproxy-ssl-access.log;
}

Ob alles einwandfrei Funktioniert lässt sich über einen Webservice von Microsoft testen:

https://testconnectivity.microsoft.com/

 

Quellen:

Viel Spaß 😉

Check_MK: Problem mit Apache HTTP Proxy – SELinux blockt Reverse Proxy Verbindung zur Check_MK Instanz

Habe gerade auf ein frisch installiertes CentOS 7.4 Check_MK 1.4.0p19 installiert. Nach dem Start einer OMD Instanz kommt nur die Fehlermeldung:

OMD: Site Not Started

You need to start this site in order to access the web interface.

Im Apache Log ist folgendes zu sehen:

[Mon Dec 04 08:50:48.097245 2017] [proxy_http:error] [pid 20887] [client x.x.x.x:31372] AH01114: HTTP: failed to make connection to backend: 127.0.0.1, referer: http://server.example.net/extern/
[Mon Dec 04 08:50:56.943253 2017] [proxy:error] [pid 20883] (13)Permission denied: AH00957: HTTP: attempt to connect to 127.0.0.1:5000 (127.0.0.1) failed
[Mon Dec 04 08:50:56.943276 2017] [proxy:error] [pid 20883] AH00959: ap_proxy_connect_backend disabling worker for (127.0.0.1) for 0s
[Mon Dec 04 08:50:56.943280 2017] [proxy_http:error] [pid 20883] [client x.x.x.x:31408] AH01114: HTTP: failed to make connection to backend: 127.0.0.1

netstat – tulpen zeigt aber das das Backend läuft:

# netstat -tulpen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name    
...
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      997        71127      21004/httpd         
...

Ein Blick in das Audit Log verrät das SELinux zuschägt:

#tail -f /var/log/audit/audit.log
...
type=AVC msg=audit(1512377448.096:3647): avc:  denied  { name_connect } for  pid=20887 comm="httpd" dest=5000 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:commplex_main_port_t:s0 tclass=tcp_socket
type=SYSCALL msg=audit(1512377448.096:3647): arch=c000003e syscall=42 success=no exit=-13 a0=a a1=559b02b25650 a2=10 a3=7fffb621631c items=0 ppid=20882 pid=20887 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="httpd" exe="/usr/sbin/httpd" subj=system_u:system_r:httpd_t:s0 key=(null)
type=AVC msg=audit(1512377508.204:3689): avc:  denied  { name_connect } for  pid=21020 comm="httpd" dest=5000 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:commplex_main_port_t:s0 tclass=tcp_socket
type=SYSCALL msg=audit(1512377508.204:3689): arch=c000003e syscall=42 success=no exit=-13 a0=a a1=559b02b25650 a2=10 a3=7fffb621633c items=0 ppid=20882 pid=21020 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="httpd" exe="/usr/sbin/httpd" subj=system_u:system_r:httpd_t:s0 key=(null)
...

Das Problem kann temporär zum testen wie folgt gelöst werden:

/usr/sbin/setsebool httpd_can_network_connect 1

um die Änderung permanent zu übernehmen:

/usr/sbin/setsebool -P httpd_can_network_connect 1

 

Python: Snippet/Experiment – Syslog Server mit globalen und Host Filtern

Der Code ist nicht fertig und war mal ein Labor Versuch. Es lassen sich globale und Host Filter setzen wo diese zutreffen werden die Logs in ein extra File geschrieben.

Config file:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Config definition


class CFG:

    def __init__(self):

        # Path for logfiles
        self.syslogpath = "/home/mthoma/_dev/syslog/log/"

        # Listner Port
        self.port = 3702

        # Listner address
        self.host = "0.0.0.0"

        # Global Filter
        self.global_filter = {
            "filter": [
                ".*FOOBAR.*",
                ".*COFFEE.*"
            ]
        }

        # Host Filter
        self.host_filter = {
            "10.201.11.33": {
                "filter": [
                    ".*MACFLAP.*",
                    ".*BUBU.*",
                ]
            },
        }

Syslog Server:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Load config class
from config import CFG

# Load common classes
import re
import logging
import SocketServer
import socket
import os

# Load configuration file
C = CFG()

formatter = logging.Formatter('%(message)s')

def setup_logger(name, log_file, level=logging.INFO):
    handler = logging.FileHandler(log_file)
    handler.setFormatter(formatter)
    
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)
    
    return logger


class SyslogUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = bytes.decode(self.request[0].strip())
        sockets = self.request[1]

        ip = str(self.client_address[0])
        
    # Try to resolve reverse record via DNS
        try:
            name, alias, addresslist = socket.gethostbyaddr(ip)
        except:
            name = ip
        
    # Set path
        path = C.syslogpath+name+"/"
        
    # Create path if not exist
        try:
            os.stat(path)
        except:
            os.mkdir(path)
        
        logger = setup_logger('normal_log', path+"log")
        logger.info(str(data))
        
        logger_sp = setup_logger('special_log', path+"spec")
        
        if ip in C.host_filter:
            filters = options['filter'] + C.global_filter['filter']
            filter_join = "|".join(filters)
            
            if re.match(r"%s" % filter_join, str(data)):
                logger_sp.info(str(data))
        else:
            filters = C.global_filter['filter']
            filter_join = "|".join(filters)
            
            if re.match(r"%s" % filter_join, str(data)):
                logger_sp.info(str(data))
                
        
        
        print "%s : " % self.client_address[0], str(data)

        logging.info(str(data))



if __name__ == "__main__":

    try:
        server = SocketServer.UDPServer((C.host,C.port), SyslogUDPHandler)
        server.serve_forever(poll_interval=0.5)

    except (IOError, SystemExit):
        raise

    except KeyboardInterrupt:
        print "Crtl+C Pressed. Shutting down."

 

Python: Snippet Multiprocessing mit Ergebnis

Beispiel für Parallelisierung von Jobs mit Ergebnis welche als Liste zurückgegeben werden.

#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-

import os
from multiprocessing import Pool


def worker(job):
    x, y = job
    result = x ** y
    return os.getpid(), result
  
if __name__ == '__main__':
    jobs = [(1, 2), (3, 4), (5, 6), (11, 12), (13, 14), (15, 16), (21, 22), (23, 24), (25, 26)]
    
    result_buffer = []
  
    pool = Pool(processes=5)
    
    for job in jobs:
        result_buffer.append(pool.apply_async(worker, args=(job,)))
    
    pool.close()
    pool.join()
  
    results = [r.get() for r in result_buffer]

    print results
  
    for pid, result in results:
        print "working pid was: %s" % pid
        print "result is: %s" % result
        print "---"

Beispiel Ergebnis:

$python mp_with_result.py

[(7992, 1), (7992, 81), (7992, 15625), (7992, 3138428376721L), (7992, 3937376385699289L), (7992, 6568408355712890625L), (7992, 122694327386105632949003612841L), (7992, 480250763996501976790165756943041L), (7992, 2220446049250313080847263336181640625L)]
working pid was: 7992
result is: 1
---
working pid was: 7992
result is: 81
---
working pid was: 7992
result is: 15625
---
working pid was: 7992
result is: 3138428376721
---
working pid was: 7992
result is: 3937376385699289
---
working pid was: 7992
result is: 6568408355712890625
---
working pid was: 7992
result is: 122694327386105632949003612841
---
working pid was: 7992
result is: 480250763996501976790165756943041
---
working pid was: 7992
result is: 2220446049250313080847263336181640625
---

 

Python: Experiment/Snippet – Komprimieren und löschen von Logfiles nach X Tagen

Ein Ansatz für Logverzeichnisse im Format /log/<yyyy>/<mm>/<dd>/<div. logsfiles>

#!/usr/bin/env python

import gzip
import shutil
import os
import datetime
import time

#############################################
# Config
#############################################

# Path of Logfiles
# Structure is /opt/log/<YYYY>/<MM>/<DD>/
gpath='/opt/log/'

# hold logs for x days
hold_time=180



#############################################

def get_immediate_subdirectories(a_dir):
    return [name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))]

def delete_files(f):
    # delete file if older than hold time
    nowx = time.time()

    for file in os.listdir(f):    
        if os.stat(f+file).st_mtime < nowx - hold_time * 86400:
            f_path = f+file
            print "delete %s " % f_path
            os.remove(f_path)
            
    try:
        os.rmdir(f)
    except:
        pass
            
    
    
def compress_files(lpath):
    # Compress files
    print "Working on: " + lpath
    obj = os.listdir(lpath)
    for f in obj:
        if os.path.isfile(lpath+f) and ".gz" not in f:
            with open(lpath+f,'rb') as f_in:
                with gzip.open(lpath+f+".gz",'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
                    os.remove(lpath+f)
            
#compress everything which ist older than now

now = datetime.datetime.now()
years = get_immediate_subdirectories(gpath)

for year in years:

    # delete empty directories
    if not os.listdir(gpath+year):
        os.rmdir(gpath+year)
    else:

        months = get_immediate_subdirectories(gpath+year)
    
        for month in months:

            # delete empty directories
            if not os.listdir(gpath+year+"/"+month):
                os.rmdir(gpath+year+"/"+month)

            else:
                days = get_immediate_subdirectories(gpath+year+"/"+month)
                        
                # Remove current day from compressing & cleaning
                if month == str(now.month) and year == str(now.year):

                    if len(str(now.day)):
                        now_day = "0%s" % now.day
                    else:
                        now_day = str(now.day)

                    days.remove(now_day)
        
                for day in days:
                    # delete empty directories
                    if not os.listdir(gpath+year+"/"+month+"/"+day+"/"):
                        os.rmdir(gpath+year+"/"+month+"/"+day+"/")
                    else:
                        # compress all files in folder
                        compress_files(gpath+year+"/"+month+"/"+day+"/")
                        
                        # delete old files
                        delete_files(gpath+year+"/"+month+"/"+day+"/")

 

Python: Snippet – Kaputten UTF-8 String reparieren

Ich habe aus der Datenbank einen String zurückbekommen der UTF-8 war aber falsch kodiert zurückgegeben wurde. So wurde aus Geschäftsstelle -> Gesch├ñftsstelle

Folgendes Snippet kann einen kaputten UTF-8 String neu auf UTF-8 kodieren:

name_kaputt = 'Gesch\xc3\xa4ftsstelle'

name = ''.join(chr(ord(c)) for c in name_kaputt).decode("utf-8")

print name_kaputt
print name

Ergebnis:

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> name_kaputt = 'Gesch\xc3\xa4ftsstelle'
>>> name = ''.join(chr(ord(c)) for c in name_kaputt).decode("utf-8")
>>> print name_kaputt
Geschäftsstelle
>>> print name
Geschäftsstelle

 

 

Python: Snippet – Datum / Zeitstempel älter als X Tage z.B. 90 Tage

Mit dem Typ datetime lässt sich direkt rechnen was das ganze sehr bequem macht.

Beispiel:

import datetime

old_time = datetime.datetime(2016, 4, 11, 10, 57, 23)
today = datetime.datetime.today()

age = today - old_time

if age.days > 90:
    print "Older than 90 days"
else:
    print "Not older than 90 days"

Beispiel Datei Alter:

import datetime
import os

file_mod_time = datetime.datetime.fromtimestamp(os.path.getmtime('foobar.txt'))
today = datetime.datetime.today()

age = today - file_mod_time

if age.days > 90:
    print "File older than 90 days"
else:
    print "File not older than 90 days"

 

Check_MK: Automation via Web Service

Wenn man Dinge automatisieren möchte kann man das über die Webservices von Check_MK machen. Dazu gibt es einen schönen Artikel von Check_MK selbst: https://mathias-kettner.de/checkmk_multisite_automation.html

Leider ist es aus der URL nicht leicht rauszufinden welche Variablen man mitgeben muss um z.B. einen Service zu Ack’en. Es gibt aber einen Trick um das einfach herauszufinden.

In den Global Settings unter User Interface -> Debug mode aktivieren.

Danach gewünschte Aktion ausführen und sich die Debug Ausgabe ansehen:

Hier sind jetzt alle Variablen aufgelistet die bei dem Request übergeben werden.

Viel Spaß beim automatisieren 😉

Einfacher Random String Generator in Python

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

N = Anzahl der Stellen

z.B. Uppercase + Digits mit 16 Stellen:

OMD[dev1]:~$ python
Python 2.7.13 (default, Jul 24 2017, 12:14:45) 
[GCC 6.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information. 
>>> import string
>>> import random
>>> ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(16))
'J8J3D3UMASJ33B1M'

Quelle/Mehr: https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python

Subnetze und IP Adressen extrahieren aus SPF Records (z.B. Office365 oder Google Apps for Business)

Wenn man bei Office365 oder Google Apps for Business einen eigenen Mailserver (Postfix) vorschalten möchte beim versenden/empfangen muss man die Mailserver von Microsoft/Google Whitelisten in den mynetworks bei Postfix.

Das Script löst alle SPF Record includes auf und generiert CIDR Maps die sich in Postfix einbinden lassen.

Beispiel:

max@dev1:~$ python get_subnets_of_spf_record_mynetwoks.py
Working on job office365
Working on job google

Es werden 2 Files erzeugt:

max@dev1:~$ cat /etc/postfix/networks/google 
64.18.0.0/20 OK
64.233.160.0/19 OK
66.102.0.0/20 OK
66.249.80.0/20 OK
72.14.192.0/18 OK
74.125.0.0/16 OK
108.177.8.0/21 OK
173.194.0.0/16 OK
207.126.144.0/20 OK
209.85.128.0/17 OK
216.58.192.0/19 OK
216.239.32.0/19 OK
[2001:4860:4000::]/36 OK
[2404:6800:4000::]/36 OK
[2607:f8b0:4000::]/36 OK
[2800:3f0:4000::]/36 OK
[2a00:1450:4000::]/36 OK
[2c0f:fb50:4000::]/36 OK
172.217.0.0/19 OK
108.177.96.0/19 OK
max@dev1:~/test$ cat /etc/postfix/networks/office365
207.46.101.128/26 OK
207.46.100.0/24 OK
207.46.163.0/24 OK
65.55.169.0/24 OK
157.56.110.0/23 OK
157.55.234.0/24 OK
213.199.154.0/24 OK
213.199.180.0/24 OK
157.56.112.0/24 OK
207.46.51.64/26 OK
157.55.158.0/23 OK
64.4.22.64/26 OK
40.92.0.0/14 OK
40.107.0.0/17 OK
40.107.128.0/17 OK
134.170.140.0/24 OK
[2a01:111:f400::]/48 OK
23.103.128.0/19 OK
23.103.198.0/23 OK
65.55.88.0/24 OK
104.47.0.0/17 OK
23.103.200.0/21 OK
23.103.208.0/21 OK
23.103.191.0/24 OK
216.32.180.0/23 OK
94.245.120.64/26 OK
[2001:489a:2202::]/48 OK

In Posftix werden sie in der main.cf eingebunden:

# ----------------------------------------------------------------------
# My Networks
# ----------------------------------------------------------------------
mynetworks =
        cidr:/etc/postfix/networks/local
        cidr:/etc/postfix/networks/other
        cidr:/etc/postfix/networks/google
        cidr:/etc/postfix/networks/office365

Da sich zwischendurch die Records auch mal ändern können empfiehlt es sich einen Cronjob dafür einzurichten. Ich habe eine Variante mit diff die nur patcht wenn das Resultat nicht null ist.

Das Script lässt sich auch noch für andere Dienste / etc. anpassen:

lookup_spf = {
# Google Apps for Business
"google": {
          "domain": "google.com",
          "file"  : "/etc/postfix/networks/google",
          },

# Office365
"office365": {
          "domain": "spf.protection.outlook.com",
          "file"  : "/etc/postfix/networks/office365",
          },

# Example
"example": {
          "domain": "example.com",
          "file"  : "/etc/postfix/networks/example",
          },

}

Sourcecode:

#!/usr/bin/env python

#
# get_subnets_of_spf_record_mynetwoks.py
# Resolve all known ip addresses from spf record and generate cidr map for postfix
#
# Version 1.0
# Written by Maximilian Thoma (http://www.lanbugs.de)
#
# The generated files can be used in postfix config with for example mynetworks = cidr:/etc/postfix/<generated_file>
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation;
# either version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, 
# MA 02110, USA
#

#
# Requirements:
# dnspython module  -> pip install dnspython
#

import dns.resolver
from dns.exception import DNSException
import re
import sys

# Look for DNS Record at:
#
# "jobname": {
#            "domain": "domainname",
#            "file": "output_file",
#            }
#

# 

lookup_spf = {
# Google Apps for Business
"google": {
          "domain": "google.com",
          "file"  : "/etc/postfix/networks/google",
          },

# Office365
"office365": {
          "domain": "spf.protection.outlook.com",
          "file"  : "/etc/postfix/networks/office365",
          },
}

############################################################################################

def getspf(record, filehandler):
    # Init Resolver
    myResolver = dns.resolver.Resolver()

    try:
        # Try to lookup TXT record
        myAnswer = myResolver.query(record,"TXT")

    except DNSException:
        sys.stderr.write("Failed to query record, SPF broken.")
        return

    results = []

    for rdata in myAnswer:
        # Get string out of records
        for txt_string in rdata.strings:
            # Append to SPF Records buffer if "spf" in string
            if "spf" in txt_string:
                results.append(txt_string)

    # If results >=1
    if len(results) >= 1:
        # Work on records
        for spf in results:
            # Split parts
            parts = spf.split(" ")
            # Check parts
            for part in parts:

                s_include = re.match(r"^include:(?P<domain>.*)$", part)
                s_ip4 = re.match(r"^ip4:(?P<ip4>.*)$", part)
                s_ip6 = re.match(r"^ip6:(?P<ip6>.*)$", part)

                # If in part "include" found, next round
                if s_include:
                    getspf(s_include.group('domain'), filehandler)
                # elif ip4 found
                elif s_ip4:
                    filehandler.write(s_ip4.group('ip4') + " OK\n")
                # elif ip6 found
                elif s_ip6:
                    filehandler.write("[" + s_ip6.group('ip6').replace("/","]/") + " OK\n")
                # else no valid record
                else:
                    pass
    # no results 
    else:
        sys.stderr.write("No results")
        pass

def main():
    # Working on jobs
    for jobname, config in lookup_spf.iteritems():

        print "Working on job %s" % jobname

        # open file
        filehandler = open(config['file'], 'w')
        # start query spf records
        getspf(config['domain'], filehandler)
        # close file
        filehandler.close()


#getspf(lookup_spf)

if __name__ == "__main__":
    main()

 

Postfix Mails aus der Queue von bestimmten Absendern löschen

Mit diesen Kommandos lassen sich aus der Postfix Queue Mails löschen die dort wegen Zustellungsproblemen liegengeblieben sind. Besonders wenn man einen Kunden drauf hat mit Malware Infektion und man die Reste aus der Queue beseitigen möchte.

Für die komplette Domain:

postqueue -p | tail -n +2 | awk 'BEGIN { RS = "" } /@example\.com/ { print $1 }' | tr -d '*!' | postsuper -d -

Für einen einzelnen Absender:

postqueue -p | tail -n +2 | awk 'BEGIN { RS = "" } /mail@example\.com/ { print $1 }' | tr -d '*!' | postsuper -d -

 

HP Server Tools für Debian/Ubuntu

HP stellt für verschiedene Linux Distributionen seine eigenen Tools bereit. Unteranderem System Health Application and Command line Utilities, iLO Online Configuration Utilities und die Insight Management Agents.

HP SDR (Software Delivery Repository): http://downloads.linux.hpe.com/SDR/index.html

Repository für Debian 8 (jessie) hinzufügen

/etc/apt/sources.list.d/HP-mcp.list anlegen

deb http://downloads.linux.hpe.com/SDR/repo/mcp jessie/current non-free

Alternativ Repository für Ubuntu 16.04 LTS hinzufügen

/etc/apt/sources.list.d/HP-mcp.list anlegen

deb http://downloads.linux.hpe.com/SDR/repo/mcp xenial/current non-free

Repository PGP Keys importieren (curl wird benötigt)

curl http://downloads.linux.hpe.com/SDR/hpPublicKey1024.pub | apt-key add -
curl http://downloads.linux.hpe.com/SDR/hpPublicKey2048.pub | apt-key add -
curl http://downloads.linux.hpe.com/SDR/hpPublicKey2048_key1.pub | apt-key add -
curl http://downloads.linux.hpe.com/SDR/hpePublicKey2048_key1.pub | apt-key add -

Paketquellen updaten

apt update

Pakete installieren (hp-health, hponcfg, hp-snmp-agents)

apt install hp-health hponcfg hp-snmp-agents

HP-Health (hpasmcli)

Das Kommando für die Health Tools ist hpasmcli.

root@rzm-srv01e13:~# hpasmcli
HPE management CLI for Linux (v2.0)
Copyright 2015 Hewlett Packard Enterprise Development LP.

--------------------------------------------------------------------------
NOTE: Some hpasmcli commands may not be supported on all Proliant servers.
      Type 'help' to get a list of all top level commands.
--------------------------------------------------------------------------
hpasmcli> 

Beispiele

show server

hpasmcli> show server
System        : ProLiant DL360 G7
Serial No.    : XXXXXXXXXX      
ROM version   : P68 08/16/2015
UEFI Support  : No
iLo present   : Yes
Embedded NICs : 4
  NIC1 MAC: d8:9d:67:aa:aa:aa
  NIC2 MAC: d8:9d:67:bb:bb:bb
  NIC3 MAC: d8:9d:67:cc:cc:cc
  NIC4 MAC: d8:9d:67:dd:dd:dd

Processor: 0
  Name         : Intel(R) Xeon(R) CPU E5640 @ 2.67GHz            
  Stepping     : 2
  Speed        : 2667 MHz
  Bus          : 133 MHz
  Core         : 4
  Thread       : 8
  Socket       : 1
  Level1 Cache : 128 KBytes
  Level2 Cache : 1024 KBytes
  Level3 Cache : 12288 KBytes
  Status       : Ok

Processor: 1
  Name         : Intel(R) Xeon(R) CPU E5640 @ 2.67GHz            
  Stepping     : 2
  Speed        : 2667 MHz
  Bus          : 133 MHz
  Core         : 4
  Thread       : 8
  Socket       : 2
  Level1 Cache : 128 KBytes
  Level2 Cache : 1024 KBytes
  Level3 Cache : 12288 KBytes
  Status       : Ok

Processor total  : 2

Memory installed : 49152 MBytes
ECC supported    : Yes

show temp

hpasmcli>  show temp         
Sensor   Location              Temp       Threshold
------   --------              ----       ---------
#1        AMBIENT              22C/71F    42C/107F 
#2        PROCESSOR_ZONE       40C/104F   82C/179F 
#3        PROCESSOR_ZONE       40C/104F   82C/179F 
#4        MEMORY_BD            35C/95F    87C/188F 
#5        MEMORY_BD            38C/100F   78C/172F 
#6        MEMORY_BD            35C/95F    87C/188F 
#7        MEMORY_BD            36C/96F    78C/172F 
#8        MEMORY_BD            38C/100F   87C/188F 
#9        MEMORY_BD            37C/98F    78C/172F 
#10       MEMORY_BD            37C/98F    87C/188F 
#11       MEMORY_BD            37C/98F    78C/172F 
#12       POWER_SUPPLY_BAY     39C/102F   59C/138F 
#13       POWER_SUPPLY_BAY     50C/122F   73C/163F 
#14       MEMORY_BD            32C/89F    72C/161F 
#15       PROCESSOR_ZONE       35C/95F    73C/163F 
#16       PROCESSOR_ZONE       34C/93F    64C/147F 
#17       MEMORY_BD            35C/95F    63C/145F 
#18       PROCESSOR_ZONE       43C/109F   69C/156F 
#19       SYSTEM_BD            39C/102F   69C/156F 
#20       SYSTEM_BD            43C/109F   71C/159F 
#21       SYSTEM_BD            50C/122F   65C/149F 
#22       SYSTEM_BD            52C/125F   71C/159F 
#23       SYSTEM_BD            45C/113F   69C/156F 
#24       SYSTEM_BD            50C/122F   69C/156F 
#25       SYSTEM_BD            39C/102F   63C/145F 
#26       SYSTEM_BD            49C/120F   66C/150F 
#27       SCSI_BACKPLANE_ZONE  50C/122F   60C/140F 
#28       SYSTEM_BD            72C/161F   110C/230F

show fan

hpasmcli>  show fan 
Fan  Location        Present Speed  of max  Redundant  Partner  Hot-pluggable
---  --------        ------- -----  ------  ---------  -------  -------------
#1   SYSTEM          Yes     NORMAL  29%     Yes        0        No            
#2   SYSTEM          Yes     NORMAL  29%     Yes        0        No            
#3   SYSTEM          Yes     NORMAL  29%     Yes        0        No            
#4   SYSTEM          Yes     NORMAL  29%     Yes        0        No            

show powersupply

hpasmcli> show powersupply
Power supply #1
  Present  : Yes
  Redundant: No
  Condition: Ok
  Hotplug  : Supported
  Power    : 110 Watts
Power supply #2
  Present  : Yes
  Redundant: No
  Condition: FAILED
  Hotplug  : Supported

Kommandos lassen sich auch ohne die interaktive hpasmcli ausführen.

root@rzm-srv01e13:~# hpasmcli -s "show fan; show powersupply"

Fan  Location        Present Speed  of max  Redundant  Partner  Hot-pluggable
---  --------        ------- -----  ------  ---------  -------  -------------
#1   SYSTEM          Yes     NORMAL  30%     Yes        0        No            
#2   SYSTEM          Yes     NORMAL  30%     Yes        0        No            
#3   SYSTEM          Yes     NORMAL  30%     Yes        0        No            
#4   SYSTEM          Yes     NORMAL  30%     Yes        0        No            


Power supply #1
  Present  : Yes
  Redundant: No
  Condition: Ok
  Hotplug  : Supported
  Power    : 115 Watts
Power supply #2
  Present  : Yes
  Redundant: No
  Condition: FAILED
  Hotplug  : Supported

hponcfg (Online iLO Configuration Utility)

Über hponcfg lässt sich das iLO ohne Systemneustart konfigurieren.

root@rzm-srv01e13:~# hponcfg 
HP Lights-Out Online Configuration utility
Version 4.6.0 Date 09/28/2015 (c) Hewlett-Packard Company, 2015
Firmware Revision = 1.87 Device type = iLO 3 Driver name = hpilo

USAGE:
  hponcfg  -?
  hponcfg  -h
  hponcfg  -m minFw
  hponcfg  -r [-m minFw ]
  hponcfg  [-a] -w filename [-m minFw]
  hponcfg  -g [-m minFw]
  hponcfg  -f filename [-l filename] [-s namevaluepair] [-v] [-m minFw]
  hponcfg  -i [-l filename] [-s namevaluepair] [-v] [-m minFw]

  -h,  --help           Display this message
  -?                    Display this message
  -r,  --reset          Reset the Management Processor to factory defaults
  -b,  --reboot         Reboot Management Processor without changing any setting
  -f,  --file           Get/Set Management Processor configuration from "filename" 
  -i,  --input          Get/Set Management Processor configuration from the XML input 
                        received through the standard input stream.
  -w,  --writeconfig    Write the Management Processor configuration to "filename"
  -a,  --all            Capture complete Management Processor configuration to the file.
                        This should be used along with '-w' option
  -l,  --log            Log replies to "filename"
  -v,  --xmlverbose     Display all the responses from Management Processor
  -s,  --substitute     Substitute variables present in input config file
                        with values specified in "namevaluepairs"
  -g,  --get_hostinfo   Get the Host information
  -m,  --minfwlevel     Minimum firmware level

hp-snmp-agents (SNMP Erweiterungen für HP Sensoren)

HP liefert ein Konfigurationstool mit das Menügeführt einen durch das Grundsetup durchführt.

/sbin/hpsnmpconfig

Ich habe nur die Read/Write und ReadOnly Community geändert und alles andere auf Default lassen.

Anschließend habe ich noch Korrekturen durchgeführt in der /etc/snmp/snmpd.conf

# Anpassung der Communitys
# Schreiben nur von Loopback aus
rwcommunity supergeheim 127.0.0.1
# Lesezugriff fuer Monitoring
rocommunity public 10.10.10.200

# Listener angepasst das er nur auf der Management NW Karte erreichbar ist
agentAddress  udp:10.10.10.1:161

Restart des SNMP Daemons nicht vergessen:

service snmpd restart

 

 

Check_MK: Agent Monitoring via SSH

Falls eine unverschlüsselte Abfrage des Check_MK Agemten nicht in Frage kommt ist es möglich den Agenten über SSH abzurufen.

SSH Key erzeugen in der OMD Umgebung

OMD[dev1]:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/omd/sites/dev1/.ssh/id_rsa): 
Created directory '/omd/sites/dev1/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /omd/sites/dev1/.ssh/id_rsa.
Your public key has been saved in /omd/sites/dev1/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:1Gxpgs9G9f4nK5uIvhe1iKU8xII1UzxFGZ7aApkYsNI dev1@cmkdev.m.local
The key's randomart image is:
+---[RSA 2048]----+
|  ...  o.o=o     |
| . . o++o=.+     |
|. E .o=++.O .    |
| .  . .*o*...    |
|       +S+.o..   |
|       .=.o ..   |
|         . .  o .|
|         ..... + |
|       .+o. oo.  |
+----[SHA256]-----+

Auf Zielsystem User anlegen, per sudo auf den Agenten berechtigen und SSH Publickey anlegen

User monitoring anlegen

root@target:~# adduser monitoring
Lege Benutzer »monitoring« an ...
Lege neue Gruppe »monitoring« (1003) an ...
Lege neuen Benutzer »monitoring« (1002) mit Gruppe »monitoring« an ...
Erstelle Home-Verzeichnis »/home/monitoring« ...
Kopiere Dateien aus »/etc/skel« ...
Geben Sie ein neues UNIX-Passwort ein: 
Geben Sie das neue UNIX-Passwort erneut ein: 
passwd: password updated successfully
Changing the user information for monitoring
Enter the new value, or press ENTER for the default
  Full Name []: Monitoring
  Room Number []: 
  Work Phone []: 
  Home Phone []: 
  Other []: 
Sind diese Informationen korrekt? [J/n] j

/etc/sudoers File anpassen

monitoring     ALL = NOPASSWD: /usr/bin/check_mk_agent

/home/monitoring/.ssh/authorized_keys anlegen

command="sudo /usr/bin/check_mk_agent" ssh-rsa AAAAB3NzaC..................GOXzCLX dev1@cmkdev.m.local

Rechte anpassen

chmod 640 /home/monitoring/.ssh/
chmod 600 /home/monitoring/.ssh/authorized_keys

xinetd Port 6556 abschalten

/etc/xinetd.d/check_mk anpassen

disable = yes

Anschließend „service xinetd restart“

Check_MK bekannt machen das Agent per SSH abgefragt werden muss

In WATO muss hierfür eine Regel angelegt werden.

Zu finden unter: Host & Service Parameters -> Datasource Programs -> Individual program call instead of agent access

Command line to execute:

ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no monitoring@$HOSTADDRESS$

Speichern und Regeln deployen, danach kann man mit WATO die Services suchen, etc.

Viel Spaß 😉

 

Weak SSH/SSL protocols and ciphers & hardening

Sammlung aller SSH/SSL relevanten und meist genutzten Dienste und deren optimale SSH/SSL Konfiguration.

Apache / Nginx

apache 2.4.18 | modern profile | OpenSSL 1.0.1e

Oldest compatible clients: Firefox 27, Chrome 30, IE 11 on Windows 7, Edge, Opera 17, Safari 9, Android 5.0, and Java 8

<VirtualHost *:443>
    ...
    SSLEngine on
    SSLCertificateFile      /path/to/signed_certificate_followed_by_intermediate_certs
    SSLCertificateKeyFile   /path/to/private/key

    # Uncomment the following directive when using client certificate authentication
    #SSLCACertificateFile    /path/to/ca_certs_for_client_authentication


    # HSTS (mod_headers is required) (15768000 seconds = 6 months)
    Header always set Strict-Transport-Security "max-age=15768000"
    ...
</VirtualHost>

# modern configuration, tweak to your needs
SSLProtocol             all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite          ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256
SSLHonorCipherOrder     on
SSLCompression          off
SSLSessionTickets       off

# OCSP Stapling, only in httpd 2.3.3 and later
SSLUseStapling          on
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off
SSLStaplingCache        shmcb:/var/run/ocsp(128000)

nginx 1.10.1 | modern profile | OpenSSL 1.0.1e

Oldest compatible clients: Firefox 27, Chrome 30, IE 11 on Windows 7, Edge, Opera 17, Safari 9, Android 5.0, and Java 8

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # certs sent to the client in SERVER HELLO are concatenated in ssl_certificate
    ssl_certificate /path/to/signed_cert_plus_intermediates;
    ssl_certificate_key /path/to/private_key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;


    # modern configuration. tweak to your needs.
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    # HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
    add_header Strict-Transport-Security max-age=15768000;

    # OCSP Stapling ---
    # fetch OCSP records from URL in ssl_certificate and cache them
    ssl_stapling on;
    ssl_stapling_verify on;

    ## verify chain of trust of OCSP response using Root CA and Intermediate certs
    ssl_trusted_certificate /path/to/root_CA_cert_plus_intermediates;

    resolver <IP DNS resolver>;

    ....
}

Quelle: https://mozilla.github.io/server-side-tls/ssl-config-generator/

SSL Webserver Test

Qualys hat eine tolle SSL Analyse Webseite, Link: https://www.ssllabs.com/ssltest/

Beispiel google.de:

Es zeigt einen schnellen Überblick plus sehr detailierte Informationen was nicht passt oder was man verbessern kann.

Alternative check with nmap

max@cmkdevel:~$ nmap --script ssl-cert,ssl-enum-ciphers -p 443 www.google.de            

Starting Nmap 7.01 ( https://nmap.org ) at 2017-08-01 09:08 CEST
Nmap scan report for www.google.de (172.217.17.35)
Host is up (0.031s latency).
Other addresses for www.google.de (not scanned): 2a00:1450:400e:804::2003
rDNS record for 172.217.17.35: ams16s29-in-f3.1e100.net
PORT    STATE SERVICE
443/tcp open  https
| ssl-cert: Subject: commonName=www.google.de/organizationName=Google Inc/stateOrProvinceName=California/countryName=US
| Issuer: commonName=Google Internet Authority G2/organizationName=Google Inc/countryName=US
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2017-07-19T11:48:30
| Not valid after:  2017-10-11T11:31:00
| MD5:   f21e dd1d 579f 5ea3 1b3d 2e79 873d 616c
|_SHA-1: f2af ac3f fb43 20be 9f6a b0fc 9356 808a f677 86fc
| ssl-enum-ciphers: 
|   TLSv1.0: 
|     ciphers: 
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|     compressors: 
|       NULL
|     cipher preference: server
|   TLSv1.1: 
|     ciphers: 
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|     compressors: 
|       NULL
|     cipher preference: server
|   TLSv1.2: 
|     ciphers: 
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|     compressors: 
|       NULL
|     cipher preference: server
|_  least strength: C

Nmap done: 1 IP address (1 host up) scanned in 3.31 seconds

Postfix

/etc/postfix/main.cf

smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3
smtpd_tls_mandatory_ciphers=high

tls_high_cipherlist=EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH:+CAMELLIA256:+AES256:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:CAMELLIA256-SHA:AES256-SHA:CAMELLIA128-SHA:AES128-SHA

smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CBC3-SHA, KRB5-DES, CBC3-SHA

smtpd_tls_dh1024_param_file=/etc/ssl/dh2048.pem

smtp_tls_mandatory_protocols = !SSLv2, !SSLv3
smtp_tls_protocols = !SSLv2, !SSLv3

lmtp_tls_mandatory_protocols = !SSLv2, !SSLv3
lmtp_tls_protocols = !SSLv2, !SSLv3

smtp_tls_security_level = may
smtp_tls_loglevel = 1

smtpd_tls_auth_only = yes

Generate new Diffie Hellman Keys

openssl dhparam -out /etc/ssl/dh2048.pem 2048

Restart Postfix

service postfix restart

Mehr: http://www.postfix.org/TLS_README.html

Check Postfix SSL Configuration

Test mit openssl s_client

openssl s_client -starttls smtp -connect mailserver.example.org:25

Alternative mit nmap

nmap --script ssl-cert,ssl-enum-ciphers -p 993,995,25,587 -Pn mailserver.example.org

Dovecot

/etc/dovecot/conf.d/10-ssl.conf

ssl_cipher_list = EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH+aRSA+RC4:EECDH:EDH+aRSA:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4
#only for dovecot >=2.2.6, enforce the server cipher preference
ssl_prefer_server_ciphers = yes
#disable SSLv2 and SSLv3
ssl_protocols = !SSLv2 !SSLv3

Restart dovecot

service dovecot restart

Überprüfen mit openssl s_connect

openssl s_client -connect mailserver.example.org:993
openssl s_client -connect mailserver.example.org:995

Alternative mit nmap

nmap --script ssl-cert,ssl-enum-ciphers -p 993,995 -Pn mailserver.example.org

SSH

/etc/ssh/sshd_config

# Remove dsa hostkeys
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key

KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes256-ctr
Macs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256

AuthenticationMethods publickey
LogLevel VERBOSE
Subsystem sftp  /usr/lib/ssh/sftp-server -f AUTHPRIV -l INFO
PermitRootLogin No
UsePrivilegeSeparation sandbox

Achtung ! DSA SSH Keys werden danach nicht mehr funktionieren.

Quelle: https://github.com/mozilla/wikimo_content/blob/master/Security/Guidelines/OpenSSH.mediawiki#Modern_OpenSSH_67

Restart SSH

service ssh restart

OpenVPN

/etc/openvpn/openvpn.conf

tls-version-min 1.2
tls-cipher TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384
cipher AES-256-CBC
auth SHA512
reneg-sec 60

Quelle: https://community.openvpn.net/openvpn/wiki/Hardening / https://gist.github.com/pwnsdx/8fc14ee1e9f561a0a5b8