четвъртък, 24 април 2014 г.

test available ssl ciphers

testciphers.sh
#!/usr/bin/env bash

# OpenSSL requires the port number.
SERVER=$1 #host:port
DELAY=1
ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')

echo Obtaining cipher list from $(openssl version).

for cipher in ${ciphers[@]}
do
echo -n Testing $cipher...
result=$(echo -n | openssl s_client -cipher "$cipher" -connect $SERVER 2>&1)
if [[ "$result" =~ "Cipher is ${cipher}" ]] ; then
  echo YES
else
  if [[ "$result" =~ ":error:" ]] ; then
    error=$(echo -n $result | cut -d':' -f6)
    echo NO \($error\)
  else
    echo UNKNOWN RESPONSE
    echo $result
  fi
fi
sleep $DELAY
done

python SNMP v3 trap catcher

 Needs lots of work to be called finished but works this way too.


snmptrapcatcher.py

from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
import time
from datetime import datetime

datecheck=str(datetime.now().strftime("%d%m%y"))
logfile=str(datetime.now().strftime("SNMP-%d-%m-%y.log"))
tolog=open(logfile, 'a')
# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4
config.addSocketTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpTransport().openServerMode(('0.0.0.0', 161))
)

# SNMPv3/USM setup

# user: usr-md5-none, auth: MD5, priv NONE
config.addV3User(
    snmpEngine, 'snmpuser',
    config.usmHMACMD5AuthProtocol, 'snmppassword!'
)

# Callback function for receiving notifications
def cbFun(snmpEngine,
          stateReference,
          contextEngineId, contextName,
          varBinds,
          cbCtx):
    global datecheck
    global logfile
    global tolog
    if str(datetime.now().strftime("%d%m%y")) != datecheck:
            logfile=str(datetime.now().strftime("SNMP-%d-%m-%y.log"))
            tolog=open(logfile, 'a')
       tolog.write(datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    tolog.write('\n')
    #tolog.write('Notification received, ContextEngineId "%s", ContextName "%s"' % (
    #    contextEngineId.prettyPrint(), contextName.prettyPrint()
    #    )
    #)
    for name, val in varBinds:
        tolog.write('%s = %s\n' % (name.prettyPrint(), val.prettyPrint()))
    tolog.flush()


# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmpEngine, cbFun)

snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish

# Run I/O dispatcher which would receive queries and send confirmations
try:
    snmpEngine.transportDispatcher.runDispatcher()
except:
    snmpEngine.transportDispatcher.closeDispatcher()
    raise

indexing vms on separate vmware ESXi servers

When there is no Enterprise license for ESXi there is usually more than one separate servers and if no proper documentation is kept you can easily forget where is your vm (on which hypervisor).

Here is a handy little python script that will show all vms on a list of hosts.
It uses pysphere for esx communication and yaml for config file. Also some commented parts that give more info if you uncomment.

getvms.py
#!/usr/bin/python

import yaml
from pysphere import *

def listvms(server,hv):
    vmlist = server.get_registered_vms()
    for i in vmlist:
        vm1 = server.get_vm_by_path(i)
        print ("%s -") % hv ,
        print vm1.get_properties()['name']



f = open('config.yaml')
config = yaml.load(f)
f.close()
hvlist = ['host1', 'host2', 'host3']
for hvserver in hvlist:
    server = VIServer()
    server.connect(hvserver, config["user"], config["pass"])
    #print "Connection established to host %s" % hvserver,
    #print server.get_server_type(), server.get_api_version()




    #vm1 = server.get_vm_by_path("[datastore1] cvs/cvs.vmx")
    """
    for i in vm1.get_properties():
        print i,
        print vm1.get_property(i)
    """

    listvms(server,hvserver)

    server.disconnect()


config.yaml
user: root
pass: passwordforuser

сряда, 23 април 2014 г.

Apache + LDAP + SSL + Proxy frontend for proprietary web application that offers no authentication.

 Lets say we have a web application that we can't/don't want to tamper with and offers no authentication. It runs on port 8000. Offers no ssl.

Do block port 8000 on all interfaces except for 127.0.0.1.
iptables -A INPUT -p tcp -d !127.0.0.1 --dport 8000 -j DROP

Use the following configuration for apache.

Listen 80
Listen 443
LDAPVerifyServerCert off
LDAPTrustedMode SSL
LDAPTrustedGlobalCert CERT_BASE64 /etc/httpd/cert1.pem
LDAPTrustedGlobalCert KEY_BASE64 /etc/httpd/key1.pem
NameVirtualHost *:443
<VirtualHost *:443>
         ProxyRequests Off
         ProxyPreserveHost On
         ProxyPass / http://127.0.0.1:8000/
         ProxyPassReverse / http://127.0.0.1:8000/
         SSLEngine on
         SSLCertificateFile /etc/httpd/webssl.cer
         SSLCertificateKeyFile /etc/httpd/webssl.key
        <Location />
                Order deny,allow
                Allow from all
                AuthLDAPBindDN "CN=LDAP Query,CN=Users,DC=dc1,DC=example,DC=net"
                AuthLDAPBindPassword "LDAP PASSWORD FOR BIND USER"
                # search user
                AuthLDAPURL "ldap://dc1.example.net:636/CN=Users,DC=dc1,DC=example,DC=net?sAMAccountName?sub?(objectClass=*)" SSL
                AuthType Basic
                AuthName "Password Required"
                Require valid-user
                AuthBasicProvider ldap
        </Location>
</VirtualHost>
# Separate virtual host running on port 80 to rewrite http to https because the application return urls with http
<VirtualHost *:80>
         RewriteEngine On
         RewriteCond %{HTTPS} off
         RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

Windows Events to Syslog

 To have all logs transfered in the same way on linux dominating network here is a great tool:  
https://code.google.com/p/eventlog-to-syslog/

Also accepts filtering using XPath expressions.

RTFM: https://eventlog-to-syslog.googlecode.com/files/Readme_4.5.0.pdf

Regex web testers and tutorials/books

Inspired by regexbuddy. Works pretty fine and is web so can be used if you are away of your usual workplace and preffered software

Here is a handy guide: http://www.regular-expressions.info/quickstart.html

Still work in progress but since i like the author here is a "Learn the hard way" book on regex: http://regex.learncodethehardway.org/book/

openssl Commands

Source:  https://www.sslshopper.com/article-most-common-openssl-commands.html

 Again copy/pasta to have it near when needed:

General OpenSSL Commands

These commands allow you to generate CSRs, Certificates, Private Keys and do other miscellaneous tasks.
  • Generate a new private key and Certificate Signing Request
    openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key
  • Generate a self-signed certificate (see How to Create and Install an Apache Self Signed Certificate for more info)
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt
  • Generate a certificate signing request (CSR) for an existing private key
    openssl req -out CSR.csr -key privateKey.key -new
  • Generate a certificate signing request based on an existing certificate
    openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key
  • Remove a passphrase from a private key
    openssl rsa -in privateKey.pem -out newPrivateKey.pem

Checking Using OpenSSL

If you need to check the information within a Certificate, CSR or Private Key, use these commands. You can also check CSRs and check certificates using our online tools.
  • Check a Certificate Signing Request (CSR)
    openssl req -text -noout -verify -in CSR.csr
  • Check a private key
    openssl rsa -in privateKey.key -check
  • Check a certificate
    openssl x509 -in certificate.crt -text -noout
  • Check a PKCS#12 file (.pfx or .p12)
    openssl pkcs12 -info -in keyStore.p12

Debugging Using OpenSSL

If you are receiving an error that the private doesn't match the certificate or that a certificate that you installed to a site is not trusted, try one of these commands. If you are trying to verify that an SSL certificate is installed correctly, be sure to check out the SSL Checker.
  • Check an MD5 hash of the public key to ensure that it matches with what is in a CSR or private key
    openssl x509 -noout -modulus -in certificate.crt | openssl md5
    openssl rsa -noout -modulus -in privateKey.key | openssl md5
    openssl req -noout -modulus -in CSR.csr | openssl md5
  • Check an SSL connection. All the certificates (including Intermediates) should be displayed
    openssl s_client -connect www.paypal.com:443

Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file and use it with Tomcat or IIS. Use our SSL Converter to convert certificates without messing with OpenSSL.
  • Convert a DER file (.crt .cer .der) to PEM
    openssl x509 -inform der -in certificate.cer -out certificate.pem
  • Convert a PEM file to DER
    openssl x509 -outform der -in certificate.pem -out certificate.der
  • Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
    openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
    You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
  • Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt

Java Keystore commands

Source:  http://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

 

I will copy/pasta the part that i use so I will have it handy here.

 

Java Keytool Commands for Creating and Importing

These commands allow you to generate a new Java Keytool keystore file, create a CSR, and import certificates. Any root or intermediate certificates will need to be imported before importing the primary certificate for your domain.
  • Generate a Java keystore and key pair keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
  • Generate a certificate signing request (CSR) for an existing Java keystore keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr
  • Import a root or intermediate CA certificate to an existing Java keystore keytool -import -trustcacerts -alias root -file Thawte.crt -keystore keystore.jks
  • Import a signed primary certificate to an existing Java keystore keytool -import -trustcacerts -alias mydomain -file mydomain.crt -keystore keystore.jks
  • Generate a keystore and self-signed certificate (see How to Create a Self Signed Certificate using Java Keytool for more info) keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048

Java Keytool Commands for Checking

If you need to check the information within a certificate, or Java keystore, use these commands.
  • Check a stand-alone certificate keytool -printcert -v -file mydomain.crt
  • Check which certificates are in a Java keystore keytool -list -v -keystore keystore.jks
  • Check a particular keystore entry using an alias keytool -list -v -keystore keystore.jks -alias mydomain

Other Java Keytool Commands

  • Delete a certificate from a Java Keytool keystore keytool -delete -alias mydomain -keystore keystore.jks
  • Change a Java keystore password keytool -storepasswd -new new_storepass -keystore keystore.jks
  • Export a certificate from a keystore keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
  • List Trusted CA Certs keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts
  • Import New CA into Trusted Certs keytool -import -trustcacerts -file /path/to/ca/ca.pem -alias CA_ALIAS -keystore $JAVA_HOME/jre/lib/security/cacerts

вторник, 22 април 2014 г.

openssl verify

Make a folder to contain your public certificates:

#mkdir certs
#cd certs

Get public cert for the server you want to check:
#openssl s_client -showcerts -connect server:port

Copy from the "-----BEGIN CERTIFICATE-----" to the "-----END CERTIFICATE-----" , and save it in a file ending in .pem

Get issuer (CA) root certificate ("Certification Authority Root Certificate")
should be provided by your issuer or if you are your own CA you should know how to get this. Place it in the same directory as the certificate of your server (the one you are testing).

 Rehash the certificates. This is basically creating a link files to your .pem files. Names are based on the certificate content so openssl command will be able to operate on the files.

#for file in *.pem; do ln -s $file `openssl x509 -hash -noout -in $file`.0; done

Verify the certificate:

#openssl s_client -CApath . -connect server:port

Output should be similar to:
..
..
..
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : DES-CBC3-SHA
    Session-ID: 53563D55F85CD643713643B7163A8C25113B114703C975DEA1C57D659FFBF96E
    Session-ID-ctx:
    Master-Key: 7288C083E0723BC61C4C21DC91908E34BD5C65695064E4E114FF4ED763ECA1D489794B9911E69021B8A8083A9CAB18EE
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1398160725
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
..
..

If you see Verify return code: 0 (ok) you are good!