December 16, 2017

The Kerberos Protocol

Key Concepts

"Kerberos uses symmetric-key cryptography to authenticate users to network services" [1]

"The Authentication Server maintain a database of principals and their secret keys." [2]

"The secret key is derived from a password. ==> Opens for password guessing attacks" [2]

"Basing trust on host addresses." [2]

RFC 4120 "The Kerberos Network Authentication Service (V5)" obsoletes RFC 1510

Overview



Client Authentication

"3.1. The Authentication Service (AS) Exchange" [2]

Message direction Message type Section
1. Client to Kerberos KRB_AS_REQ 5.4.1
2. Kerberos to client KRB_AS_REP 5.4.2
  KRB_ERROR 5.9.1

KRB_AS_REQ: cname, realm, from, till, nonce, address, ...  **cleartext message**
    cname, client's principal.
    realm
    from and till, the expiration time
    nonce, Number used only ones
    address, client's network address
   
KRB_AS_REP: {K.c,tgs, realm, from, till, nonce, ...}K.c {T.c,tgs}K.tgs
    {...}K.c encrypted with the Client Secret Key
    K.c,tgs Client/TGS Session Key
    realm
    from and till, the expiration time
    same nonce as in request

    {...}K.tgs encrypted with TGS Secret Key
    T.c,tgs Client-to-TGS (Ticket-Granting Service) Ticket which includes:
        Client principal
        Client network address
        Client/TGS Session Key

Authentication "This is acceptable because nobody but the principal whose identity was given in the request will be able to use the reply." [2]

Client Service Authorization

"3.3. The Ticket-Granting Service (TGS) Exchange" [2]

Message direction Message type Section
1. Client to Kerberos KRB_TGS_REQ 5.4.1
2. Kerberos to client KRB_TGS_REP 5.4.2
  KRB_ERROR 5.9.1

KRB_TGS_REQ: {authenticator, ...}K.c,tgs {T.c,tgs}K.tgs, address, from, till, nonce
    {...}K.c,tgs encrypted with Client/TGS Session Key
    Authenticator (which is composed of the client principal and timestamp)
   
    {T.c,tgs}K.tgs from KRB_AS_REP
   
    address, Service network address
    from and till, the expiration time
    nonce, Number used only ones

KRB_TGS_REP: {K.c,s, address, from, till, nonce, ...}K.c,tgs {T.c,s}K.s
    {...}K.c,tgs encrypted with Client/TGS Session Key
    K.c,s, Client/Service Session Key
    address, Service network address
    from and till, the expiration time
    same nonce as in request

    {...}K.s encrypted with the Service Secret Key.
    T.c,s Client-to-Service-Ticket which includes:
        Client principal
        Client network address
        Validity period
        Client/Server Session Key

Client Service Request

"3.2. The Client/Server Authentication Exchange" [2]

Message direction Message type Section
1. Client to Application KRB_AP_REQ 5.5.1
2. Application server to client KRB_AP_REP 5.5.2
  KRB_ERROR 5.9.1

KRB_AP_REQ: {authenticator, ts, ...}K.c,s {T.c,s}K.s
    {...}K.c,s encrypted with K.c,s Client/Service Session Key
    authenticator, new Authenticator which includes client principal and timestamp
    ts, timestamp
   
    {T.c,s}K.s from KRB_TGS_REP

KRB_AP_REP [Optional]: {ts}K.c,s
    {...}K.c,s encrypted with Client/Service Session Key
    ts, timestamp

keytabs (Key Tables)

Used for service that typical runs as system service and hence have no login. Here keytabs contains K.s.

Reference

[1] Red Hat System-Level Authentication Guide Chapter 11. Using Kerberos
[2] RFC 4120
[3] Kerberos (protocol) - Wikiwand

December 8, 2017

Install and Configure Postfix


# yum install postfix mutt

# service postfix start

# adduser student

# su - student

$ mutt

1. Press m to create a new message.
2. In To write student@server1.example.com
3. In Subject write something
4. In Body write something. The default editor is vi, so:
    4.1 enter i for insert
    4.2 now write
    4.3 when finished writing, press ESC
    4.4 to save, press :wq
5. Now send, press y.

Print mail queue

# postqueue -p
Mail queue is empty

Flush mail queue
# postqueue -f

less /var/log/maillog

# netstat -tulpn | grep 25
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      17389/master       

# grep inet_interfaces /etc/postfix/main.cf 
# The inet_interfaces parameter specifies the network interface
#inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost
inet_interfaces = localhost
# the address list specified with the inet_interfaces parameter.
# receives mail on (see the inet_interfaces parameter).
# to $mydestination, $inet_interfaces or $proxy_interfaces.
# - destinations that match $inet_interfaces or $proxy_interfaces,
# unknown@[$inet_interfaces] or unknown@[$proxy_interfaces] is returned
    

# vi /etc/postfix/main.cf 
...
inet_interfaces = all
...

# service postfix restart

# netstat -tulpn | grep 25
tcp        0      0 0.0.0.0:25                  0.0.0.0:*                   LISTEN      17558/master   

--------------------
Step 1: Install Packages
--------------------
# yum install sendmail sendmail-cf dovecot m4

--------------------
Step 2: Configure sendmail to receive external mails
--------------------

Edit /etc/mail/sendmail.mc

2.1 Comment out sendmail to listen to all network adresses. To comment out in sendmail, put 
'dnl' at the beginning of the line.

dnl DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl

2.2 We will use our local hostname as mail domain, so change 'localhost.localdomain' to your 
hostname, mine is server1.example.com.

LOCAL_DOMAIN(`localhost.localdomain')dnl

--------------------
Step 3. Recompile Sendmail using m4
--------------------

# m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf

--------------------
Step 4: Configure Dovecot to fetch emails
--------------------

4.1 Edit /etc/dovecot/dovecot.conf

#Protocols we want to be serving.
protocols = pop3

# A comma separated list of IPs or hosts where to listen in for connections.
listen = *, ::

4.2 Edit /etc/dovecot/conf.d/10-auth.conf

disable_plaintext_auth = no

#!include auth-system.conf.ext
!include auth-passwdfile.conf.ext

4.3 Add User

# echo "$USER:{PLAIN}password:$UID:$GROUPS::$HOME" > /etc/dovecot/users

Example:
magkar:{PLAIN}password:500:500::/home/magkar

Here I use an existing account on mail server, if you need to create a new user, use command 
useradd to create a new user and passwd to set password:

# useradd student1
# passwd student1

4.4 Last step. Verify installation by running 'dovecot -n'
# dovecot -n
# 2.0.9: /etc/dovecot/dovecot.conf
# OS: Linux 2.6.32-358.14.1.el6.x86_64 x86_64 Red Hat Enterprise Linux Server release 6.4 (Santiago) 
disable_plaintext_auth = no
mbox_write_locks = fcntl
passdb {
  args = scheme=CRYPT username_format=%u /etc/dovecot/users
  driver = passwd-file
}
protocols = pop3
ssl_cert = </etc/pki/dovecot/certs/dovecot.pem
ssl_key = </etc/pki/dovecot/private/dovecot.pem
userdb {
  args = username_format=%u /etc/dovecot/users
  driver = passwd-file
}

--------------------
Step 5: Restart sendmail and dovecot service
--------------------

# service dovecot restart
# service sendmail restart

If this is a fresh installation, either of the services are started, so stopping them will fail. 
Verify this by restarting the services again.

--------------------
Step 6: Testing the installation
--------------------

Thunderbird

email: magkar@server1.example.com

POP3 
Host: server1.example.com
Port: 110
No SSL
username: magkar
password: password
Send password cleartext

SMTP
Host: server1.example.com
Port: 25
NO AUTHENTICATION

Add static dns to /etc/hosts
server1.example.com    192.168.1.10 


--------------------
Reference
--------------------

http://wiki2.dovecot.org/BasicConfiguration
http://wiki2.dovecot.org/FindMailLocation
http://www.telnetport25.com/2012/02/configuring-e-mail-notifications-in-nagios-core/

SELinux


------------
What is SELinux Boolean?
------------
"Booleans allow parts of SELinux policy to be changed at runtime, without any knowledge of 
SELinux policy writing. This allows changes, such as allowing services access to NFS volumes, 
without reloading or recompiling SELinux policy." 
[https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/
Security-Enhanced_Linux/sect-Security-Enhanced_Linux-Working_with_SELinux-Booleans.html]

------------
Install semanage
------------

# yum install policycoreutils-python

------------
Working with SELinux boolean
------------

Previously you could get all SELinux Boolean with

# getsebool -a

But with RHEL 6, there is a better way, that also returns a comment for each boolean

# semanage boolean -l

To permently change a SELinux boolean

# setsebool -P httpd_can_network_connect on

------------
Reference 
------------
http://wiki.centos.org/TipsAndTricks/SelinuxBooleans

SELinux te policy file
http://oss.tresys.com/repos/refpolicy/archive/strict/domains/program/unused/nrpe.te

============
SELinux Process
============

# ps auxZ | grep nrpe
unconfined_u:system_r:nrpe_t:s0 nrpe 1234 0.0 0.0 41320 1340 ? Ss Jan13 0:14 /usr/sbin/nrpe -c /etc/nagios/nrpe.cfg -d

============
SELinux Files
============
# chcon -v --type=httpd_sys_content_t /html/index.html
context of /html/index.html changed to user_u:object_r:httpd_sys_content_t

Test

Make persistent

# semanage fcontext -a -t httpd_sys_content_t "/html(/.*)?" 


# touch /.autorelabel
# reboot 

============
SELinux Ports
============
5.4. Allowing Access to a Port

We may want a service such as Apache to be allowed to bind and listen for incoming 
connections on a non-standard port. By default, the SELinux policy will only allow 
services access to recognized ports associated with those services. If we wanted to 
allow Apache to listen on tcp port 81, we can add a rule to allow that using the 'semanage' command:

# semanage port -a -t http_port_t -p tcp 81 

A full list of ports that services are permitted access by SELinux can be obtained with:

# semanage port -l 

op5


------------------
Download OP5
------------------

op5-monitor-6.2.0.1-20131024.tar.gz

[http://www.op5.com/download-op5-monitor/]

------------------
Query RPM Package
------------------

Det finns två rpm i denna tar boll

# ll *nrpe*
-rw-rw-r--. 1 500 500 23068 Oct 24 10:17 nrpe-2.13.3-op5.1.x86_64.rpm
-rw-rw-r--. 1 500 500 11992 Oct 24 10:17 nrpe-client-2.13.3-op5.1.x86_64.rpm

Filer som RPM innehåller

# rpm -qpl nrpe-2.13.3-op5.1.x86_64.rpm
warning: nrpe-2.13.3-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
/etc/init.d/nrpe
/etc/nrpe.conf
/etc/nrpe.d
/etc/nrpe.d/op5_commands.cfg
/usr/sbin/nrpe

RPM Dependency/Requires [-R,--requires]

# rpm -qpR nrpe-2.13.3-op5.1.x86_64.rpm 
warning: nrpe-2.13.3-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
/bin/sh  
/bin/sh  
config(nrpe) = 2.13.3-op5.1
libc.so.6()(64bit)  
libc.so.6(GLIBC_2.2.5)(64bit)  
libc.so.6(GLIBC_2.3)(64bit)  
libc.so.6(GLIBC_2.3.4)(64bit)  
libc.so.6(GLIBC_2.4)(64bit)  
libcrypto.so.10()(64bit)  
libnsl.so.1()(64bit)  
libssl.so.10()(64bit)  
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(FileDigests) <= 4.6.0-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rpmlib(VersionedDependencies) <= 3.0.3-1
rtld(GNU_HASH)  
rpmlib(PayloadIsXz) <= 5.2-1

RPM installation scripts

# rpm -qp --scripts nrpe-2.13.3-op5.1.x86_64.rpm
warning: nrpe-2.13.3-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
postinstall scriptlet (using /bin/sh):
/sbin/chkconfig --add nrpe || :
/sbin/service nrpe stop || :
/sbin/service nrpe start || :

# Move command definitions to 'include_dir' if upgrading
if [ $1 -eq 2 ]; then
   grep -q '^command\[' /etc/nrpe.conf || :
   if [ $? -eq 0 ]; then
          echo "" >> /etc/nrpe.d/op5_commands.cfg
          echo "# Imported from /etc/nrpe.cfg" >> /etc/nrpe.d/op5_commands.cfg
          grep '^command\[' /etc/nrpe.conf >> /etc/nrpe.d/op5_commands.cfg || :
          sed '/^[\#]\?[ tab]\?command\[\[*/d' -i /etc/nrpe.conf || :
          echo "" >> /etc/nrpe.conf
          echo "# NOTE!" >> /etc/nrpe.conf
          echo "# Command definitions have meed moved to 'include_dir'." >> /etc/nrpe.conf
          echo "# Any commands defined in this file will be moved by future upgrades." >> /etc/nrpe.conf
          echo "" >> /etc/nrpe.conf
   fi

   grep -q '^include_dir' /etc/nrpe.conf || :
   if [ $? -ne 0 ]; then
          echo "# In order to make remote config with conf_nrpe work, you need to" >> /etc/nrpe.conf
          echo "# create the following directory. It needs to be read/writeable by" >> /etc/nrpe.conf
          echo "# nrpe_user specified above. " >> /etc/nrpe.conf
          echo "# All command definitions should be placed in the 'include_dir'" >> /etc/nrpe.conf
          echo "# NOTE: files in 'include_dir' must have a '.cfg' suffix." >> /etc/nrpe.conf
          echo "include_dir=/etc/nrpe.d" >> /etc/nrpe.conf
   fi
fi


------------------
NRPE RPM Installation
------------------
# rpm -ipvh nrpe-2.13.3-op5.1.x86_64.rpm
warning: nrpe-2.13.3-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
Preparing...                ########################################### [100%]
   1:nrpe                   ########################################### [100%]
nrpe doesn't seem to be running.
Starting nrpe in daemon mode ... done

Check process 

# ps auxZ | grep nrpe
unconfined_u:system_r:nrpe_t:s0 nobody 1271 0.0 0.0 39364 1364 ? Ss 13:27 0:00 /usr/sbin/nrpe -c /etc/nrpe.conf -d
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 1274 0.0 0.0 103244 832 pts/0 S+ 13:27 0:00 grep nrpe

------------------
NRPE RPM Configuration
------------------

# vi /etc/nrpe.conf
...
allowed_hosts=127.0.0.1,192.168.122.93
...

Restart NRPE to let configuration changes take effect

# service nrpe restart

------------------
Test NRPE Installation
------------------

From server 

# /usr/lib64/nagios/plugins/check_nrpe -H 192.168.122.12
NRPE v2.13

------------------
Plugin RPM Installation
------------------

# cat /etc/nrpe.d/op5_commands.cfg 
################################################################################
#
# op5-nrpe command configuration file
#

# COMMAND DEFINITIONS
# Syntax:
# command[<command_name>]=<command_line>
#
command[users]=/opt/plugins/check_users -w 5 -c 10
...

# ll *plugins*
-rw-rw-r--. 1 500 500 417248 Oct 24 10:17 plugins-community-2.8.5-op5.1.x86_64.rpm
-rw-rw-r--. 1 500 500  47920 Oct 24 10:17 plugins-metadata-2.8.7-op5.1.x86_64.rpm
-rw-rw-r--. 1 500 500 594020 Oct 24 10:17 plugins-nagios-2.6.5.1-op5.1.x86_64.rpm
-rw-rw-r--. 1 500 500  94088 Oct 24 10:17 plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm
-rw-rw-r--. 1 500 500   3160 Oct 24 10:17 plugins-op5-3.0.0-op5.1.el6.x86_64.rpm

# rpm -qpl plugins-community-2.8.5-op5.1.x86_64.rpm | grep check_users
warning: plugins-community-2.8.5-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY

# rpm -qpl plugins-nagios-2.6.5.1-op5.1.x86_64.rpm | grep check_users
warning: plugins-nagios-2.6.5.1-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY

# rpm -qpl plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm | grep check_users
warning: plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
/opt/plugins/check_users

# rpm -qpl plugins-op5-3.0.0-op5.1.el6.x86_64.rpm | grep check_users
warning: plugins-op5-3.0.0-op5.1.el6.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY





# rpm -ipvh plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm
warning: plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
error: Failed dependencies:
 perl(Exporter) is needed by plugins-nagios-local-2.6.5.1-op5.1.x86_64


# rpm -qpR plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm
warning: plugins-nagios-local-2.6.5.1-op5.1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID f6e3ade7: NOKEY
/bin/sh  
libc.so.6()(64bit)  
libc.so.6(GLIBC_2.2.5)(64bit)  
libc.so.6(GLIBC_2.3)(64bit)  
libc.so.6(GLIBC_2.3.4)(64bit)  
libc.so.6(GLIBC_2.4)(64bit)  
libc.so.6(GLIBC_2.8)(64bit)  
libdl.so.2()(64bit)  
libm.so.6()(64bit)  
libm.so.6(GLIBC_2.2.5)(64bit)  
libpthread.so.0()(64bit)  
libpthread.so.0(GLIBC_2.2.5)(64bit)  
perl(Exporter)  
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(FileDigests) <= 4.6.0-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rtld(GNU_HASH)  
rpmlib(PayloadIsXz) <= 5.2-1

Måste installera perl

# rpm -q --provides perl | grep Exporter
perl(Exporter) = 5.63
perl(Exporter::Heavy)  


-----------------------
Troubleshooting
-----------------------

# less /var/log/messages
...
nrpe[2703]: Error: Could not complete SSL handshake. 1
...

Från server enbart testa NRPE kommunikationen, genom att anropa NRPE utan kommando

# /usr/lib64/nagios/plugins/check_nrpe -H 192.168.122.12
NRPE v2.13

------------------
Plugin SELinux Problems
------------------

plugins does not seem to work with SELinux

On client set SELinux to Permissive

# setenforce 0

Double check that audit deamon is installed and running

# service auditd status
auditd (pid  983) is running...

sealert:

yum install setroubleshoot-server


semanage:
audit2allow:

yum install policycoreutils-python

check_log


-------------------
Introduction
-------------------

In mine previous blogs I have discussed how to setup the 

- Server [http://magnus-k-karlsson.blogspot.se/2014/01/install-nagios-core-35-on-rhel-6-from.html]
- Client/Agent [http://magnus-k-karlsson.blogspot.se/2014/01/install-nagios-agent-nrpe-on-rhel-6.html]

In this blog I will show you how to install and configure the check_log plugin. 

A good documentation overview site is https://www.nagios-plugins.org/doc/man/index.html.

-------------------
check_log
-------------------

#! /bin/sh
#
# Log file pattern detector plugin for Nagios
# Written by Ethan Galstad (nagios@nagios.org)
# Last Modified: 07-31-1999
#
# Usage: ./check_log <log_file> <old_log_file> <pattern>
#
# Description:
#
# This plugin will scan a log file (specified by the <log_file> option)
# for a specific pattern (specified by the <pattern> option).  Successive
# calls to the plugin script will only report *new* pattern matches in the
# log file, since an copy of the log file from the previous run is saved
# to <old_log_file>.
#
# Output:
#
# On the first run of the plugin, it will return an OK state with a message
# of "Log check data initialized".  On successive runs, it will return an OK
# state if *no* pattern matches have been found in the *difference* between the
# log file and the older copy of the log file.  If the plugin detects any 
# pattern matches in the log diff, it will return a CRITICAL state and print
# out a message is the following format: "(x) last_match", where "x" is the
# total number of pattern matches found in the file and "last_match" is the
# last entry in the log file which matches the pattern.
#
# Notes:
#
# If you use this plugin make sure to keep the following in mind:
#
#    1.  The "max_attempts" value for the service should be 1, as this
#        will prevent Nagios from retrying the service check (the
#        next time the check is run it will not produce the same results).
#
#    2.  The "notify_recovery" value for the service should be 0, so that
#        Nagios does not notify you of "recoveries" for the check.  Since
#        pattern matches in the log file will only be reported once and not
#        the next time, there will always be "recoveries" for the service, even
#        though recoveries really don't apply to this type of check.
#
#    3.  You *must* supply a different <old_file_log> for each service that
#        you define to use this plugin script - even if the different services
#        check the same <log_file> for pattern matches.  This is necessary
#        because of the way the script operates.
#
# Examples:
#
# Check for login failures in the syslog...
#
#   check_log /var/log/messages ./check_log.badlogins.old "LOGIN FAILURE"
#
# Check for port scan alerts generated by Psionic's PortSentry software...
#
#   check_log /var/log/message ./check_log.portscan.old "attackalert"
#

-------------------
Agent/Client Configuration check_log for JBoss EAP 6 Standalone
-------------------

The standard log file for JBoss EAP 6 running in standalone mode is

# ll /var/log/jbossas/standalone/server.log

First let pay attention to the third prerequisites for check_log and create a new "old" log file for check_log.

# touch /var/log/jbossas/standalone/server.log.check_log

# chmod 640 /var/log/jbossas/standalone/*

In the NRPE configuration file we see that there is a configuration directory for NRPE

# cat /etc/nagios/nrpe.cfg
...
# INCLUDE CONFIG DIRECTORY
# This directive allows you to include definitions from config files (with a
# .cfg extension) in one or more directories (with recursion).

include_dir=/etc/nrpe.d/

And there we will put our command for the check_log plugin.

# vi /etc/nrpe.d/check_jboss_log.cfg
command[check_jboss_log]=/usr/lib64/nagios/plugins/check_log -F /var/log/jbossas/standalone/server.log \
-O /var/log/jbossas/standalone/server.log.check_log -q "WARN"

Finally restart the nrpe deamon to make the new configuration take effect.

# service nrpe restart



http://mgrepl.fedorapeople.org/Blog/nagios.html

-------------------
Server Configuration
-------------------

# vi /etc/nagios/conf.d/virtual1.example.com.cfg

Block Cipher (Encryption) Cheat Sheet

Block Cipher
INPUT: a plaintext block and a key
OUTPUT: a ciphertext block of same length

  • A block cipher can be inverted (decrypted) with the key
  • Even if you know the plaintext and ciphertext it should be hard to recover the key
Bad, do not use Good, do use
DES AES
3DES Also OK, if AES is not available:
your own algorithm CAST (in PGP)
  Twofish, Blowfish

SSL/TLS Attacks

Padding oracles in CBC mode Compression

  • Vaudenay 2002
  • Boneh/Brumley 2003
  • BEAST 2011
  • Lucky13 2013
  • POODLE 2014
  • Lucky Microseconds 2015

RSA PKCS1-1.5

  • Bleichenbacher 1998
  • Jager 2015
  • DROWN 2016

MD5 & SHA1

  • CA forgery attack 2008
  • SLOTH 2016

Compression

  • CRIME 2012
  • BREACH 2013

Renegotiation

  • Marsh Ray Attack 2009
  • Renegotiation DoS 2011
  • 3Shake 2014

Export-grade ciphers

  • FREAK 2014
  • LogJam and WeakDH 2015
  • Sweet32 2016

Other

  • RC4 2013
  • Nonce reuse 2016

December 7, 2017

Crypto Key Length

keylength.com

Crypt Libraries

Library Website Written in
Libgcrypt gnupg.org/related_software/libgcrypt/ C
GnuTLS gnutls.org C
cryptlib cryptlib.com C
Botan botan.randombit.net C++
Crypto++® Library 5.6.5 cryptopp.com C++
Microsoft CryptoAPI
OpenSSL openssl.org C, assembly
Network Security Services, NSS developer.mozilla.org/en-US/docs/NSS C, assembly
NaCl nacl.cr.yp.to
Bouncy Castle bouncycastle.org Java and C#
libtomcrypt libtom.net C

Crypto Attacks Side-Channel Attacks

  • Timing Leaks - attacks based on measuring how much time various computations takes. For example algorithm known and start to guess key, if return fast the first bytes wrong if reply takes, you know that the first bytes are correct.
    • Mitigation: Constant time implementation
  • Error Oracles - return error leaks information, e.g. encoding typical error, etc. See also Bleichenbacher's attack on PKCS#1 and DROWN attack against SSLv2.
    • Mitigation: Ensure error does leak sensitive information, such as timing, interruptions, etc.
  • Software Bugs - all software contains bugs.
    • Mitigation: Patch or use more failsafe crypto
  • Optimizations - too clever solutions, can sometime be too clever
    • Mitigation: Do not try to outsmart yourself. Do not optimize if the outcome is marginal.

Comparing Elliptic-Curve Cryptography (ECC) and RSA

Reference: https://www.researchgate.net/publication/255970113_A_Survey_of_the_Elliptic_Curve_Integrated_Encryption_Scheme

Use standard curves only.

  • Curve25519
  • Curve448

Diffie–Hellman key exchange (DH)

"Diffie–Hellman key exchange (DH)[nb 1] is a method of securely exchanging cryptographic keys" [1]

"Although Diffie–Hellman key agreement itself is a non-authenticated key-agreement protocol, it provides the basis for a variety of authenticated protocols, and is used to provide forward secrecy in Transport Layer Security's ephemeral modes (referred to as EDH or DHE depending on the cipher suite)." [1]

"Ephemeral key exchanges are based on Diffie-Hellman and use per-session, temporary keys during the initial SSL/TLS handshake. They provide Perfect Forward Secrecy, PFS, which means a compromise of the server's long term signing key does not compromise the confidentiality of past session (see following rule). When the server uses an ephemeral key, the server will sign the temporary key with its long term key (the long term key is the customary key available in its certificate)." [2]

For Apache httpd do the following. First generate DH-parameters to get unique prime numbers. The size should be same as the key length in your server certificate.


# openssl dhparam 2048 -out dhparam2048.pem

Then configure Apache httpd to use them.


SSLOpenSSLConfCmd DHParameters <path to dhparam2048.pem>

Problem with DH: DH relies on that is hard to calculate discrete logarithm [3], this was used in the Logjam attack [4].

Reference:
[1] https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
[2] https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet 
[3] https://en.wikipedia.org/wiki/Discrete_logarithm
[4] https://en.wikipedia.org/wiki/Logjam_(computer_security)

December 6, 2017

Asymmetric Encryption with RSA and OAEP (Optimal Asymmetric Encryption Padding)

The preferred padding with RSA cipher algorithm is OAEP (Optimal Asymmetric Encryption Padding).

Java Example:

First generate public and private RSA keys with some length, here we use 2048 bits.


KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();

Then we we encrypt our plaintext


byte[] plaintext = "Secret goes here".getBytes(StandardCharsets.UTF_8);

// While using asymmetric ciphers, use ECB as the mode of operation, 
// which essentially is a hack behind-the-scenes, meaning ignore this value.
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] ciphertext = cipher.doFinal(plaintext);

Then we can print our ciphertext with Base64 encoding


String encoded = new String(Base64.getEncoder().encode(ciphertext), StandardCharsets.UTF_8);
System.out.println("Encrypted : " + encoded);

And finally decrypt it


// While using asymmetric ciphers, use ECB as the mode of operation, 
// which essentially is a hack behind-the-scenes, meaning ignore this value.
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plaintext = cipher.doFinal(ciphertext); 

System.out.println("Decrypted : " + new String(plaintext, StandardCharsets.UTF_8));

Asymetric RSA Trapdoor Permutation

The RSA algorithm works the following

  • Public Key: a large number n and exponent e
  • Private Key: primes p and q such that n = p * q.

The RSA trapdoor permutation: x -> xe mod n = y

So the strength in RSA is built around practical difficulty of factoring large integers.

Reference: https://en.wikipedia.org/wiki/RSA_Factoring_Challenge

See also https://www.theinquirer.net/inquirer/news/3019326/roca-rsa-encryption-key-flaw-puts-millions-of-devices-at-risk.

Symmetric Authenticated Encryption (AE) or Authenticated Encryption with Associated Data (AEAD)

You can do more in Symmetric Encryption (Cipher) and that is Symmetric Authenticated Encryption (AE) or Authenticated Encryption with Associated Data (AEAD) which simultaneously provides confidentiality, integrity, and authenticity assurances on the data. And this can be done in three ways

  • Encrypt-and-MAC (as in SSH originally)
  • MAC-then-Encrypt (as in TLSv1.0, v1.1, v1.2)
  • Encrypt-then-MAC (as in IPSec and TLSv1.3)

The recommended way is Encrypt-then-MAC, because if the package is malicious, you first want to do MAC validation and then encrypt, not the other way around. What if ciphertext contains evil code?

Belows shows a sequence diagram of the Encrypt-then-MAC, not that the key below is symmetric. Which means this signature does NOT offer non-repudiation as in with asymmetric keys.

Recommended AEAD are: AES-GSM and AES-CCM.

Reference: https://en.wikipedia.org/wiki/Authenticated_encryption#Encrypt-then-MAC_(EtM)

Block Cipher - Encrypt More Than 1 Block

If you are going to encrypt (cipher) more than one block, you need a mode of operation for that.

For example the preferred cipher AES (Advanced Encryption Standard) uses


Key sizes  128, 192 or 256 bits
Block sizes  128 bits

Electronic CodeBook, ECB

Cipher Block Chaining, CBC with random IVs

Counter, CTR with unique nonces (Number only used ONCE)

Counter with CBC-MAC, CCM

Galois/Counter Mode, GCM

Hash Functions Cheat Sheet

In previous blog I wrote about Deterministic Random Bit Generator, DRBG that makes arbitrary output from a short fixed length seed.

And the inverse of that is Hash Function

INPUT: arbitrarily long data
OUTPUT: short fixed length digest (e.g. 256 bit)

Hash functions are used for

Digest Signatures
Sign( Hash( message, salt ) )

Hash Key Derivation Function, HKDF
HKDF( randomness )

Password Based Hashing and Key Derivation Funtion, PBKDF
PBKDF( password, salt, iteration count )

Challenge Response Protocol
Hash( key, challenge )

Deterministic Random Bit Generator, DRBG
Hash( key, nonce, 1 ) || Hash( key, nonce, 2 ) || ...

Message Authentication Code, MAC
Hash( key, message )

Bad, do not use Good, do use
MD4, MD5 BLAKE2
SHA-1 (shattered.io) SHA-3
CRC SHA-2 (224, 256, 384, 512)
your own algorithm  

RNG/DRBG/PRNG Cheat Sheet

  • RNG (Random Number Generator) produces random bits
    • non-deterministic
    • uses external analog source
  • DRBG (Deterministic Random Bit Generator) produces pseudorandom bits
    • deterministic
    • from a seed (taken from RNG)
  • PRNG (Pseudo-Random Number Generator) produces pseudorandom bits
    • non-deterministic
    • from a seeds from an RNG to maintain entropy pool
    • produces output bits using a DRBG
Analog Source + seed --> RNG --> 010..10 --> PRNG (DRBG is a component of PRNG) --> 0101011100..01 

Deterministic Random Bit Generator, DRBG
INPUT: short fixed-length seed (e.g. 256 bit)
OUTPUT: arbitrarily long

Bad, do not use Good, do use
rand(3) /dev/urandom
random(3) Linux getrandom()
PHP rand() Java SecureRandom
your own algorithm Node.js crypto.randomBytes
&nbrp; WINAPI BCryptGenRandom
&nbrp; openssl rand

How to Test Randomness (Entropy)

You can use ent http://www.fourmilab.ch/random/. On Ubuntu you can install via


$ sudo apt-get install ent

$ man ent
ent(1)                                                                                                              ent(1)

NAME
       ent - pseudorandom number sequence test

SYNOPSIS
       ent [options] [file]

DESCRIPTION
       ENT Logo

       ent performs a variety of tests on the stream of bytes in file (or standard input if no file is specified) and pro‐
       duces output on standard output; for example:

       Entropy = 7.980627 bits per character.

       Optimum compression would reduce the size
       of this 51768 character file by 0 percent.

       Chi square distribution for 51768 samples is 1542.26, and randomly
       would exceed this value 0.01 percent of the times.

       Arithmetic mean value of data bytes is 125.93 (127.5 = random).
       Monte Carlo value for Pi is 3.169834647 (error 0.90 percent).
       Serial correlation coefficient is 0.004249 (totally uncorrelated = 0.0).

       The values calculated are as follows:
...

And to test it


$ dd if=/dev/urandom bs=128 count=1 > 128bits

$ ent 128bits 
Entropy = 6.576057 bits per byte.

Optimum compression would reduce the size
of this 128 byte file by 17 percent.

Chi square distribution for 128 samples is 244.00, and randomly
would exceed this value 67.89 percent of the times.

Arithmetic mean value of data bytes is 132.7656 (127.5 = random).
Monte Carlo value for Pi is 3.238095238 (error 3.07 percent).
Serial correlation coefficient is 0.124230 (totally uncorrelated = 0.0).

Random in Linux

  • Syscall available since kernel 3.17
  • Only blocks at initialization if insufficient entropy

$ man 2 getrandom
GETRANDOM(2)                                     Linux Programmer's Manual                                    GETRANDOM(2)

NAME
       getrandom - obtain a series of random bytes

SYNOPSIS
       #include <linux/random.h>

       int getrandom(void *buf, size_t buflen, unsigned int flags);
...

Source Linux kernel random.c

Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) in Linux and Java

Introduction

What is random? Example is the below bits randomly generated?


0100 1101 1101 0011

The probability for that is 1/2^16.

And to measure the uncertainty we introduce the notion entropy. And in Linux you can get the current entropy by:


$ cat /proc/sys/kernel/random/entropy_avail 
942

And in Linux there are two way to get random data


/dev/urandom (non-blocking)
/dev/random  (blocking)

So to get 128 bits from /dev/urandom you can do


$ dd if=/dev/urandom bs=128 count=1 2> /dev/null | od -t x1 -An
 fa 17 5c ae d2 6a 3f 82 8b 42 41 d9 72 bb 64 a1
 86 62 bc 04 65 e6 df 45 ce cb 24 fe 97 8f 14 25
 43 a2 0f 8a 43 07 b0 e4 b8 97 7f fe 24 32 b0 26
 6f 4e 12 d3 9b bc b4 40 e8 74 9e 03 6d cc 2f 02
 6f 54 dc 98 6a c8 fa 12 6c ed de 0e cd 89 16 d6
 2b b7 14 07 a9 c4 75 21 8e 79 04 48 c2 a9 7e b2
 1e a5 43 41 63 5a 82 01 ae 19 87 d2 06 d1 49 be
 5f ab 0d 0e 75 15 f1 50 b6 ba f6 40 c3 5e 0f 30

So the randomness in the Linux Kernel can be illustrated as


Entropy Sources:
 - Keyboard                                |--> Blocking entropy pool     --> /dev/random (blocking)
 - Interrupts   --> Primary Entropy Pool --|
 - Disk                                    |--> Non-blocking entropy pool --> /dev/urandom (non-blocking)
 - Mouse

Java

In Java things are more simple, always use java.security.SecureRandom.


// blocking random
SecureRandom nonBlockingSecureRandom = new SecureRandom();
System.out.println("Provider : " + nonBlockingSecureRandom.getProvider());
System.out.println("Algorithm : " + nonBlockingSecureRandom.getAlgorithm());
byte[] nonBlockingRandomBytes = new byte[20];
// SecureRandom randomizer should always be self-seeded
nonBlockingSecureRandom.nextBytes(nonBlockingRandomBytes);
System.out.println("Bytes : " + Arrays.toString(nonBlockingRandomBytes)
);

// blocking random
SecureRandom blockingSecureRandom = SecureRandom.getInstanceStrong();
System.out.println("Provider : " + blockingSecureRandom.getProvider());
System.out.println("Algorithm : " + blockingSecureRandom.getAlgorithm());
byte[] blockingRandomBytes = new byte[20];
// SecureRandom randomizer should always be self-seeded
blockingSecureRandom.nextBytes(blockingRandomBytes);
System.out.println("Bytes : " + Arrays.toString(blockingRandomBytes));

And produces when run on Linux.


Provider : SUN version 1.8
Algorithm : NativePRNG
Bytes : [114, -84, -57, -60, 76, -75, 49, -122, -12, 108, -3, 126, -29, -9, 81, 117, -108, -27, -14, 13]
Provider : SUN version 1.8
Algorithm : NativePRNGBlocking
Bytes : [55, 90, -125, 46, 18, 29, 51, 54, 10, 90, -57, 68, 30, -56, 32, -99, 43, 98, -113, -46]

You can also configure the default behaviour for SecureRandom in


$JAVA_HOME/lib/security/java.security
...
#
# Sun Provider SecureRandom seed source.
#
# Select the primary source of seed data for the "SHA1PRNG" and
# "NativePRNG" SecureRandom implementations in the "Sun" provider.
# (Other SecureRandom implementations might also use this property.)
#
# On Unix-like systems (for example, Solaris/Linux/MacOS), the
# "NativePRNG" and "SHA1PRNG" implementations obtains seed data from
# special device files such as file:/dev/random.
#
# On Windows systems, specifying the URLs "file:/dev/random" or
# "file:/dev/urandom" will enable the native Microsoft CryptoAPI seeding
# mechanism for SHA1PRNG.
#
# By default, an attempt is made to use the entropy gathering device
# specified by the "securerandom.source" Security property.  If an
# exception occurs while accessing the specified URL:
#
#     SHA1PRNG:
#         the traditional system/thread activity algorithm will be used.
#
#     NativePRNG:
#         a default value of /dev/random will be used.  If neither
#         are available, the implementation will be disabled.
#         "file" is the only currently supported protocol type.
#
# The entropy gathering device can also be specified with the System
# property "java.security.egd". For example:
#
#   % java -Djava.security.egd=file:/dev/random MainClass
#
# Specifying this System property will override the
# "securerandom.source" Security property.
#
# In addition, if "file:/dev/random" or "file:/dev/urandom" is
# specified, the "NativePRNG" implementation will be more preferred than
# SHA1PRNG in the Sun provider.
#
securerandom.source=file:/dev/random

#
# A list of known strong SecureRandom implementations.
#
# To help guide applications in selecting a suitable strong
# java.security.SecureRandom implementation, Java distributions should
# indicate a list of known strong implementations using the property.
#
# This is a comma-separated list of algorithm and/or algorithm:provider
# entries.
#
securerandom.strongAlgorithms=NativePRNGBlocking:SUN
...

December 4, 2017

Ubuntu 16.04 Disk Usage Analyzer

To be able to scan your entire file system you need to start the Disk Usage Analyzer with sudo.


$ sudo baobab

December 3, 2017

Getting Started with Python on Ubuntu 16.04

Prerequisite

Ubuntu 16.04


$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.3 LTS
Release: 16.04
Codename: xenial

Interactive Mode


$ python
Python 2.7.12 (default, Nov 20 2017, 18:23:56) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1
2

IDE - IDLE


$ sudo apt-get install idle

$ idle

File -> New File 
File -> Save as... -> hello.py

#!/usr/bin/env python3

name = input("Name: ")
print ("Hello " + name)

Reference

The Python Tutorial - https://docs.python.org/3/tutorial/