# Log and analyze data with rrdtool


Introduction

We are going to log, every five seconds, the RTT values obtained from doing a ping to two different IP addresses.


Create the database

If we do not obtain a value in 10 seconds that value is lost.
The expected values are between 20.000 and 80.000 milliseconds.
We log data every 1 sample.
We store 120960 samples (one week).
Each sample is taken every 5 seconds.

12 samples x 5 seconds/sample = 60 seconds = 1 minute
12 samples x 60m x 24h x 7d = 120960 samples

# rrdtool create rtt.rrd \
> -s 5 \
> DS:google:GAUGE:10:20.000:80.000 \
> DS:yahoo:GAUGE:10:20.000:80.000 \
> RRA:AVERAGE:0.5:1:120960 \
> RRA:MIN:0.5:1:120960 \
> RRA:MAX:0.5:1:120960

Obtain the RTT values

# cat rtt.sh
#!/bin/bash

google_ip="$1"
 yahoo_ip="$2"

google_rtt=`ping -c 1 -W 1 $google_ip | grep rtt | tr '/' ' ' | awk '{print $7}'`
 yahoo_rtt=`ping -c 1 -W 1 $yahoo_ip  | grep rtt | tr '/' ' ' | awk '{print $7}'`

echo "N:$google_rtt:$yahoo_rtt"
rrdtool update rtt.rrd N:$google_rtt:$yahoo_rtt
# watch -n 5 ./rtt.sh 216.239.32.10 68.180.131.16

Check stored values

# rrdtool fetch rtt.rrd AVERAGE | grep -v nan

Analyze the graph

# cat make_graph.sh
#!/bin/bash

rtt_rrd="rtt.rrd"
rtt_png="rtt.png"
last=`rrdtool last rtt.rrd`
date=`date`
width="6000"
height="300"

rrdtool graph $rtt_png \
--start end-1hour --end $last \
--title "Round-Trip Time (RTT)" \
--vertical-label "Milliseconds" \
--width $width \
--height $height \
--x-grid SECOND:5:SECOND:30:SECOND:60:0:%T%n%D \
--color BACK#222222 \
--color FONT#aaaaaa \
--color CANVAS#222222 \
--color GRID#444444 \
--color MGRID#666666 \
--color AXIS#888888 \
--color ARROW#888888 \
--font-render-mode normal \
--pango-markup \
--graph-render-mode normal \
--slope-mode \
--imgformat PNG \
--watermark "$date - hacktracking.blogspot.com" \
DEF:vgoogle=$rtt_rrd:google:AVERAGE \
DEF:vyahoo=$rtt_rrd:yahoo:AVERAGE \
COMMENT:" \\n" \
COMMENT:" \\n" \
LINE:vgoogle\#ff0000:'<b>GOOGLE</b>' \
GPRINT:vgoogle:MIN:"<small>min = </small>%3.3lf <small>ms</small>" \
GPRINT:vgoogle:MAX:"<small>max = </small>%3.3lf <small>ms</small>" \
GPRINT:vgoogle:AVERAGE:"<small>avg = </small>%3.3lf <small>ms</small>" \
GPRINT:vgoogle:LAST:"<small>last = </small>%3.3lf <small>ms</small>" \
COMMENT:" \\n" \
COMMENT:" \\n" \
LINE:vyahoo\#00ff00:'<b>YAHOO</b> ' \
GPRINT:vyahoo:MIN:"<small>min = </small>%5.3lf <small>ms</small>" \
GPRINT:vyahoo:MAX:"<small>max = </small>%3.3lf <small>ms</small>" \
GPRINT:vyahoo:AVERAGE:"<small>avg = </small>%3.3lf <small>ms</small>" \
GPRINT:vyahoo:LAST:"<small>last = </small>%3.3lf <small>ms</small>" \
COMMENT:" \\n" \
COMMENT:" \\n"
# ./make_graph.sh && eog rtt.png

References

# man rrdtool rrdcreate rrdupdate rrdfetch rrdlast rrdgraph

# Wired 802.1x with EAP/TLS


Authentication server (Freeradius)

# apt-get install freeradius openssl
# mkdir /etc/ssl/CA
# mkdir /etc/ssl/newcerts
# echo '01' > /etc/ssl/CA/serial
# touch /etc/ssl/CA/index.txt
# cat /etc/ssl/openssl.cnf
...
[ CA_default ]

dir             = /etc/ssl
database        = $dir/CA/index.txt
certificate     = $dir/certs/cacert.pem
serial          = $dir/CA/serial
private_key     = $dir/private/cakey.pem
...
# cd /etc/ssl/CA
# openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650
Generating a 1024 bit RSA private key
.................++++++
.........++++++
writing new private key to 'cakey.pem'
Enter PEM pass phrase:MY_SECRET
Verifying - Enter PEM pass phrase:MY_SECRET
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:ES
State or Province Name (full name) [Some-State]:CAT
Locality Name (eg, city) []:BCN
Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyCA
Organizational Unit Name (eg, section) []:AAA
Common Name (e.g. server FQDN or YOUR name) []:ca.lab.net
Email Address []:root@lab.net
# mv cakey.pem /etc/ssl/private/.
# mv cacert.pem /etc/ssl/certs/.
# cat >> /etc/ssl/CA/xpextensions << eof
> [xpclient_ext]
> extendedKeyUsage=1.3.6.1.5.5.7.3.2
>
> [xpserver_ext]
> extendedKeyUsage=1.3.6.1.5.5.7.3.1
> eof
# openssl req -new -nodes -keyout freeradiuskey.pem -out freeradius.csr -days 3650
Generating a 1024 bit RSA private key
......++++++
..................++++++
writing new private key to 'freeradiuskey.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:ES
State or Province Name (full name) [Some-State]:CAT
Locality Name (eg, city) []:BCN
Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyCA
Organizational Unit Name (eg, section) []:AAA
Common Name (e.g. server FQDN or YOUR name) []:freeradius.lab.net
Email Address []:root@lab.net

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
# openssl ca -in freeradius.csr -config /etc/ssl/openssl.cnf
Using configuration from /etc/ssl/openssl.cnf
Enter pass phrase for /etc/ssl/private/cakey.pem:MY_SECRET
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jan 15 18:28:48 2013 GMT
            Not After : Jan 15 18:28:48 2014 GMT
        Subject:
            countryName               = ES
            stateOrProvinceName       = CAT
            organizationName          = MyCA
            organizationalUnitName    = AAA
            commonName                = freeradius.lab.net
            emailAddress              = root@lab.net
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                78:3A:A1:E4:7E:69:FC:71:CD:45:22:AF:52:C0:4A:D8:E1:1F:99:20
            X509v3 Authority Key Identifier:
                keyid:14:75:4E:1F:6B:E3:FD:5A:88:77:71:93:60:32:81:6C:D5:AD:10:C4

Certificate is to be certified until Jan 15 18:28:48 2014 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1 (0x1)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=ES, ST=CAT, L=BCN, O=MyCA, OU=AAA, CN=ca.lab.net/emailAddress=root@lab.net
        Validity
            Not Before: Jan 15 18:28:48 2013 GMT
            Not After : Jan 15 18:28:48 2014 GMT
        Subject: C=ES, ST=CAT, O=MyCA, OU=AAA, CN=freeradius.lab.net/emailAddress=root@lab.net
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:d1:7a:a6:74:ce:cd:b1:96:1b:5b:f1:21:8b:45:
                    fe:52:a0:c4:ac:84:8a:ad:05:65:97:5e:fd:af:bb:
                    7d:1d:e9:9a:91:8d:46:48:16:83:88:90:da:03:b3:
                    5d:32:e2:e4:e3:2f:73:18:41:26:73:26:f3:32:03:
                    c0:02:a5:be:04:9e:36:40:99:cc:1b:52:03:4d:8a:
                    2a:9c:9f:65:10:56:0c:09:a9:26:fb:6e:09:78:e1:
                    00:28:b1:c6:b0:97:e3:87:78:ea:fe:89:24:8a:86:
                    5d:44:8f:70:bf:43:a4:a2:d0:23:b9:f7:ee:ae:48:
                    d1:fb:98:1e:61:d8:6c:87:cb
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                78:3A:A1:E4:7E:69:FC:71:CD:45:22:AF:52:C0:4A:D8:E1:1F:99:20
            X509v3 Authority Key Identifier:
                keyid:14:75:4E:1F:6B:E3:FD:5A:88:77:71:93:60:32:81:6C:D5:AD:10:C4

    Signature Algorithm: sha1WithRSAEncryption
         b9:41:6b:0e:57:88:a2:aa:a6:d1:5d:55:f0:1c:48:3f:c8:4f:
         97:09:65:1a:f7:08:45:f0:e4:10:e6:32:67:14:2f:6e:4f:b0:
         a0:21:56:96:32:90:5b:4c:78:01:40:05:92:4a:d3:2c:c2:11:
         77:a8:0d:3b:49:cb:2f:e4:22:99:44:0d:2a:0d:1e:6a:d1:3d:
         2e:72:19:46:9d:0e:3c:a3:3e:bf:a6:1e:2f:5c:f0:71:8a:b7:
         09:11:97:e1:0d:0e:29:5d:30:aa:87:e9:9d:37:86:13:c6:bd:
         8b:05:d5:c1:ec:c1:31:f8:79:a2:c2:16:92:c2:13:bd:aa:a6:
         89:37
-----BEGIN CERTIFICATE-----
MIIC2zCCAkSgAwIBAgIBATANBgkqhkiG9w0BAQUFADB4MQswCQYDVQQGEwJFUzEM
MAoGA1UECAwDQ0FUMQwwCgYDVQQHDANCQ04xDTALBgNVBAoMBE15Q0ExDDAKBgNV
BAsMA0FBQTETMBEGA1UEAwwKY2EubGFiLm5ldDEbMBkGCSqGSIb3DQEJARYMcm9v
dEBsYWIubmV0MB4XDTEzMDExNTE4Mjg0OFoXDTE0MDExNTE4Mjg0OFowcjELMAkG
A1UEBhMCRVMxDDAKBgNVBAgMA0NBVDENMAsGA1UECgwETXlDQTEMMAoGA1UECwwD
QUFBMRswGQYDVQQDDBJmcmVlcmFkaXVzLmxhYi5uZXQxGzAZBgkqhkiG9w0BCQEW
DHJvb3RAbGFiLm5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0XqmdM7N
sZYbW/Ehi0X+UqDErISKrQVll179r7t9HemakY1GSBaDiJDaA7NdMuLk4y9zGEEm
cybzMgPAAqW+BJ42QJnMG1IDTYoqnJ9lEFYMCakm+24JeOEAKLHGsJfjh3jq/okk
ioZdRI9wv0OkotAjuffurkjR+5geYdhsh8sCAwEAAaN7MHkwCQYDVR0TBAIwADAs
BglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYD
VR0OBBYEFHg6oeR+afxxzUUir1LAStjhH5kgMB8GA1UdIwQYMBaAFBR1Th9r4/1a
iHdxk2AygWzVrRDEMA0GCSqGSIb3DQEBBQUAA4GBALlBaw5XiKKqptFdVfAcSD/I
T5cJZRr3CEXw5BDmMmcUL25PsKAhVpYykFtMeAFABZJK0yzCEXeoDTtJyy/kIplE
DSoNHmrRPS5yGUadDjyjPr+mHi9c8HGKtwkRl+ENDildMKqH6Z03hhPGvYsF1cHs
wTH4eaLCFpLCE72qpok3
-----END CERTIFICATE-----
Data Base Updated
# cp /etc/ssl/newcerts/01.pem freeradius.pem
# cat freeradiuskey.pem > freeradiuskeycert.pem
# grep -A 100 BEGIN freeradius.pem >> freeradiuskeycert.pem
# openssl req -new -nodes -keyout wxpkey.pem -out wxp.csr -days 3650
Generating a 1024 bit RSA private key
.........................++++++
...++++++
writing new private key to 'wxpkey.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:ES
State or Province Name (full name) [Some-State]:CAT
Locality Name (eg, city) []:BCN
Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyCA
Organizational Unit Name (eg, section) []:AAA
Common Name (e.g. server FQDN or YOUR name) []:wxp.lab.net
Email Address []:root@lab.net

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
# openssl ca -in wxp.csr -config /etc/ssl/openssl.cnf -extensions xpclient_ext -extfile /etc/ssl/CA/xpextensions
Using configuration from /etc/ssl/openssl.cnf
Enter pass phrase for /etc/ssl/private/cakey.pem:MY_SECRET
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 2 (0x2)
        Validity
            Not Before: Jan 15 18:34:05 2013 GMT
            Not After : Jan 15 18:34:05 2014 GMT
        Subject:
            countryName               = ES
            stateOrProvinceName       = CAT
            organizationName          = MyCA
            organizationalUnitName    = AAA
            commonName                = wxp.lab.net
            emailAddress              = root@lab.net
        X509v3 extensions:
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
Certificate is to be certified until Jan 15 18:34:05 2014 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 2 (0x2)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=ES, ST=CAT, L=BCN, O=MyCA, OU=AAA, CN=ca.lab.net/emailAddress=root@lab.net
        Validity
            Not Before: Jan 15 18:34:05 2013 GMT
            Not After : Jan 15 18:34:05 2014 GMT
        Subject: C=ES, ST=CAT, O=MyCA, OU=AAA, CN=wxp.lab.net/emailAddress=root@lab.net
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:c3:b9:f0:f7:09:c4:89:85:30:b4:e8:83:99:39:
                    c3:19:49:c6:b5:9e:df:28:88:6a:4c:f9:7f:9d:45:
                    92:a3:e3:22:18:9a:3b:ff:49:20:f9:63:97:59:d8:
                    b4:49:73:ea:0e:76:e0:62:d2:6b:25:35:fa:14:c3:
                    31:26:7d:33:db:7f:42:5d:ad:a6:48:11:32:a7:e0:
                    0b:9b:77:45:4d:cb:68:66:28:30:48:fd:43:8b:d7:
                    d3:c3:36:a6:bd:9a:83:76:2f:34:65:a5:aa:53:97:
                    e8:fc:e8:83:74:6e:a7:84:74:8c:0b:36:b6:f3:9a:
                    d5:d8:6d:39:ba:e2:2b:27:a5
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
    Signature Algorithm: sha1WithRSAEncryption
         25:3b:75:12:2b:d0:9f:bd:02:e3:9b:8f:b3:04:ee:82:80:60:
         08:0c:1e:60:19:e0:3b:10:5d:0f:6c:4e:50:29:1a:50:0f:1d:
         3c:a5:a1:af:ce:73:42:c7:d7:81:b8:68:3a:40:c6:88:4e:cd:
         fa:b8:f4:65:34:44:6b:6a:85:6e:8a:5e:34:19:4f:3a:5f:45:
         8b:4f:ac:35:5d:26:55:bf:eb:4c:b7:fa:83:25:cd:62:78:07:
         4c:48:3d:e1:51:5d:21:26:33:9f:05:8b:fc:8a:99:6b:cf:70:
         ce:23:ae:f4:04:d8:aa:20:f7:11:02:c0:3f:dc:b1:24:f2:1b:
         0d:f5
-----BEGIN CERTIFICATE-----
MIICcDCCAdmgAwIBAgIBAjANBgkqhkiG9w0BAQUFADB4MQswCQYDVQQGEwJFUzEM
MAoGA1UECAwDQ0FUMQwwCgYDVQQHDANCQ04xDTALBgNVBAoMBE15Q0ExDDAKBgNV
BAsMA0FBQTETMBEGA1UEAwwKY2EubGFiLm5ldDEbMBkGCSqGSIb3DQEJARYMcm9v
dEBsYWIubmV0MB4XDTEzMDExNTE4MzQwNVoXDTE0MDExNTE4MzQwNVowazELMAkG
A1UEBhMCRVMxDDAKBgNVBAgMA0NBVDENMAsGA1UECgwETXlDQTEMMAoGA1UECwwD
QUFBMRQwEgYDVQQDDAt3eHAubGFiLm5ldDEbMBkGCSqGSIb3DQEJARYMcm9vdEBs
YWIubmV0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDufD3CcSJhTC06IOZ
OcMZSca1nt8oiGpM+X+dRZKj4yIYmjv/SSD5Y5dZ2LRJc+oOduBi0mslNfoUwzEm
fTPbf0JdraZIETKn4Aubd0VNy2hmKDBI/UOL19PDNqa9moN2LzRlpapTl+j86IN0
bqeEdIwLNrbzmtXYbTm64isnpQIDAQABoxcwFTATBgNVHSUEDDAKBggrBgEFBQcD
AjANBgkqhkiG9w0BAQUFAAOBgQAlO3USK9CfvQLjm4+zBO6CgGAIDB5gGeA7EF0P
bE5QKRpQDx08paGvznNCx9eBuGg6QMaITs36uPRlNERraoVuil40GU86X0WLT6w1
XSZVv+tMt/qDJc1ieAdMSD3hUV0hJjOfBYv8iplrz3DOI670BNiqIPcRAsA/3LEk
8hsN9Q==
-----END CERTIFICATE-----
Data Base Updated 
# cp /etc/ssl/newcerts/02.pem wxp.pem
# openssl pkcs12 -export -in wxp.pem -inkey wxpkey.pem -certfile /etc/ssl/certs/cacert.pem -name "Wired-dot1x" -out wxp.p12
Enter Export Password:MY_EXPORT
Verifying - Enter Export Password:MY_EXPORT
# cp /etc/ssl/certs/cacert.pem /etc/freeradius/certs/.
# cp /etc/ssl/CA/freeradiuskeycert.pem /etc/freeradius/certs/.
# cp /etc/freeradius/eap.conf /etc/freeradius/eap.conf.orig
# cat /etc/freeradius/eap.conf
        eap {
                default_eap_type = tls
                timer_expire     = 60
                ignore_unknown_eap_types = no
                cisco_accounting_username_bug = no
                max_sessions = 4096
                md5 {
                }
                leap {
                }
                gtc {
                        auth_type = PAP
                }
                tls {
                        certdir = ${confdir}/certs
                        cadir = ${confdir}/certs
                        private_key_file = ${certdir}/freeradiuskeycert.pem
                        certificate_file = ${certdir}/freeradiuskeycert.pem
                        CA_file = ${cadir}/cacert.pem
                        dh_file = ${certdir}/dh
                        random_file = /dev/urandom
                        fragment_size = 1024
                        include_length = yes
                        CA_path = ${cadir}
                        cipher_list = "DEFAULT"
                        make_cert_command = "${certdir}/bootstrap"
                        cache {
                              enable = no
                              max_entries = 255
                        }
                        verify {
                        }
                }
                ttls {
                        default_eap_type = md5
                        copy_request_to_tunnel = no
                        use_tunneled_reply = no
                        virtual_server = "inner-tunnel"
                }
                peap {
                        default_eap_type = mschapv2
                        copy_request_to_tunnel = no
                        use_tunneled_reply = no
                        virtual_server = "inner-tunnel"
                }
                mschapv2 {
                }
        }
# /etc/init.d/freeradius stop
# freeradius -X


Authenticator/NAS (Cisco Catalyst 2960)

Switch(config)# aaa new-model
Switch(config)# radius server freeradius
Switch(config-radius-server)# address ipv4 192.168.0.100 auth-port 1812 acct-port 1813
Switch(config-radius-server)# key MYSECRET
Switch(config)# aaa authentication dot1x default group radius
Switch(config)# aaa authorization network default group radius
Switch(config)# aaa accounting dot1x default start-stop group radius
Switch(config)# radius-server vsa send accounting
Switch(config)# radius-server vsa send authentication
Switch(config)# interface FastEthernet0/10
Switch(config-if)# switchport mode access
Switch(config-if)# authentication event fail retry 0 action authorize vlan 30
Switch(config-if)# authentication event no-response action authorize vlan 20
Switch(config-if)# authentication port-control auto
Switch(config-if)# mab eap
Switch(config-if)# dot1x pae authenticator
Switch(config-if)# dot1x timeout tx-period 1
Switch(config-if)# spanning-tree portfast
Switch# !debug dot1x


Supplicant (Windows XP)

Copy cacert.pem and wxp.p12 to the windows xp client.
Rename cacert.pem to cacert.der.

C:\> net start "Wired Autoconfig"
C:\> mmc
File > Add/Remove Snap-in... > Add > Certificates > Add > Computer account > Next > Finish > Close > OK
- Certifcates (Local Computer) > Personal > Certificates > All Tasks > Import... > wxp.p12 > key (MY_EXPORT)
- Certifcates (Local Computer) > Trusted Root Certification Authorities > Certificates > All Tasks > Import... > cacert.der
C:\> netsh lan export profile folder=C:\
C:\> type nic.xml
<?xml version="1.0"?>
<LANProfile xmlns="http://www.microsoft.com/networking/LAN/profile/v1">
        <MSM>
                <security>
                        <OneXEnforced>false</OneXEnforced>
                        <OneXEnabled>true</OneXEnabled>
                        <OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
                                <cacheUserData>false</cacheUserData>
                                <authMode>machineOrUser</authMode>
                                <EAPConfig><EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig"><EapMethod><Type xmlns="http://www.microsoft.com/provisioning/EapCommon">13</Type><VendorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorId><VendorType xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorType><AuthorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</AuthorId></EapMethod><ConfigBlob>020000002A0000001D0000001400000037689DD23A688A3C5CFF726F9407DC30F999752F000001000000</ConfigBlob></EapHostConfig></EAPConfig>
                        </OneX>
                </security>
        </MSM>
</LANProfile>
Change 'machineOrUser' for 'machine'.
C:\> netsh lan add profile filename=nic.xml
NIC > Properties > Authentication
- Enable IEEE 802.1x authentication for this network
-- EAP type: Smart Card or other Certificate
-- Settings
--- Use a certificate on this computer > Use simple certificate selection
--- Validate server certificate
--- Trusted Root Certification Authorities > ca.lab.net


References

http://en.wikipedia.org/wiki/IEEE_802.1X
http://www.cisco.com/en/US/docs/solutions/Enterprise/Security/TrustSec_1.99/Dot1X_Deployment/Dot1x_Dep_Guide.html

# Wired 802.1x with MD5


Authentication server (Freeradius)

# apt-get install freeradius
# cat /etc/freeradius/clients.conf
client c2960_switch {
        ipaddr = 192.168.0.200
        secret = MYSECRET
}
# cat /etc/freeradius/users
"user1" Cleartext-Password := "PASSWORD1"
        Filter-Id = "user1_acl.in"

"user2" Cleartext-Password := "PASSWORD2"
        Tunnel-Type = VLAN,
        Tunnel-Medium-Type = IEEE-802,
        Tunnel-Private-Group-Id = 10

"000f1f8ce650" Cleartext-Password := "000f1f8ce650" # Supplicant's MAC address
        Tunnel-Type = VLAN,
        Tunnel-Medium-Type = IEEE-802,
        Tunnel-Private-Group-Id = 11
# cat /etc/freeradius/radiusd.conf
prefix = /usr
exec_prefix = /usr
sysconfdir = /etc
localstatedir = /var
sbindir = ${exec_prefix}/sbin
logdir = /var/log/freeradius
raddbdir = /etc/freeradius
radacctdir = ${logdir}/radacct
name = freeradius
confdir = ${raddbdir}
run_dir = ${localstatedir}/run/${name}
db_dir = ${raddbdir}
libdir = /usr/lib/freeradius
pidfile = ${run_dir}/${name}.pid
user = freerad
group = freerad
max_request_time = 30
cleanup_delay = 5
max_requests = 1024
listen {
        type = auth
        ipaddr = *
        port = 0
}
listen {
        ipaddr = *
        port = 0
        type = acct
}
hostname_lookups = no
allow_core_dumps = no
regular_expressions     = yes
extended_expressions    = yes
log {
        destination = files
        file = ${logdir}/radius.log
        syslog_facility = daemon
        stripped_names = no
        auth = no
        auth_badpass = no
        auth_goodpass = no
}
checkrad = ${sbindir}/checkrad
security {
        max_attributes = 200
        reject_delay = 1
        status_server = yes
}
proxy_requests  = yes
$INCLUDE proxy.conf
$INCLUDE clients.conf
thread pool {
        start_servers = 5
        max_servers = 32
        min_spare_servers = 3
        max_spare_servers = 10
        max_requests_per_server = 0
}
modules {
        $INCLUDE ${confdir}/modules/
        $INCLUDE eap.conf
}
instantiate {
        exec
        expr
        expiration
        logintime
}
$INCLUDE policy.conf
$INCLUDE sites-enabled/
# mkdir /var/log/freeradius/radacct
# chown freerad:freerad /var/log/freeradius/radacct
# cat /etc/freeradius/sites-enabled/default
authorize {
        preprocess
        chap
        mschap
        digest
        suffix
        eap {
                ok = return
        }
        files
        expiration
        logintime
        pap
}
authenticate {
        Auth-Type PAP {
                pap
        }
        Auth-Type CHAP {
                chap
        }
        Auth-Type MS-CHAP {
                mschap
        }
        digest
        unix
        eap
}
preacct {
        preprocess
        acct_unique
        suffix
        files
}
accounting {
        detail
        unix
        radutmp
        exec
        attr_filter.accounting_response
}
session {
        radutmp
}
post-auth {
        exec
        Post-Auth-Type REJECT {
                attr_filter.access_reject
        }
}
pre-proxy {
}
post-proxy {
        eap
}

# /etc/init.d/freeradius stop
# freeradius -X


Authenticator/NAS (Cisco Catalyst 2960)

Switch(config)# aaa new-model
Switch(config)# radius server freeradius
Switch(config-radius-server)# address ipv4 192.168.0.100 auth-port 1812 acct-port 1813
Switch(config-radius-server)# key MYSECRET
Switch(config)# aaa authentication dot1x default group radius
Switch(config)# aaa authorization network default group radius
Switch(config)# aaa accounting dot1x default start-stop group radius
Switch(config)# radius-server vsa send accounting
Switch(config)# radius-server vsa send authentication
Switch(config)# interface FastEthernet0/10
Switch(config-if)# switchport mode access
Switch(config-if)# authentication event fail retry 0 action authorize vlan 30
Switch(config-if)# authentication event no-response action authorize vlan 20
Switch(config-if)# authentication port-control auto
Switch(config-if)# mab eap
Switch(config-if)# dot1x pae authenticator
Switch(config-if)# dot1x timeout tx-period 1
Switch(config-if)# spanning-tree portfast
Switch(config)# ip access-list extended user1_acl
Switch(config-ext-nacl)#  permit icmp any host 192.168.0.100
Switch# test aaa group radius user1 PASSWORD1 legacy
Switch# !debug dot1x


Supplicant (Windows XP)

C:\> net start "Wired Autoconfig"
NIC > Properties > Authentication
- Enable IEEE 802.1x authentication for this network
- EAP type: MD5-Challenge


References

http://en.wikipedia.org/wiki/IEEE_802.1X
http://www.cisco.com/en/US/docs/solutions/Enterprise/Security/TrustSec_1.99/Dot1X_Deployment/Dot1x_Dep_Guide.html

# ashell: Proxy chaining hooking connect()


Introduction

Anonymous shell (ashell) is a tool to tunnel your connections through HTTP/Socks4/Socks5 proxies.
Supports TCP, authentication and chaining different proxy types.
It works by hooking the connect() function using LD_PRELOAD environment variable.

http://sourceforge.net/projects/ashell/


Building and using the tool

# apt-get install libssl-dev
# wget http://downloads.sourceforge.net/project/ashell/ashell-0.3.tar.bz2
# tar xvjf ashell-0.3.tar.bz2
# cd ashell-0.3
# cat README
# cp ashell/ashell.c .
# cat > Makefile << "EOF"
> HEADERS = http.h socks.h strlib.h
> OBJECTS = http.o socks.o strlib.o ashell.o
> CFLAGS = -Wall
> LFLAGS = -ldl -shared -nostartfiles -fpic
>
> default: ashell.so
>
> %.o: %.c $(HEADERS)
> #gcc -o $@ -c $<
>
> ashell.so: $(OBJECTS)
> #gcc -o $@ $(CFLAGS) $(LFLAGS) $(OBJECTS)
>
> clean:
> #rm -rf $(OBJECTS)
> EOF
# sed -i 's/#/\t/' Makefile
# make
# curl -w "\nTime total=%{time_total}\n" whatismyip.akamai.com
1.2.3.4
Time total=0,058
# export P_DEBUG=0 # P_DEBUG=1 turns on debugging
# export LD_PRELOAD=./ashell.so
# export APROXY=S:89.28.65.46:1080+S:86.127.123.141:18060
# curl -w "\nTime total=%{time_total}\n" whatismyip.akamai.com
86.127.123.141
Time total=3,323


Socks5 open proxy list

http://spys.ru/en/socks-proxy-list/


# LD_PRELOAD hooking


# grep -m 1 localtime /usr/include/time.h
extern struct tm *localtime (__const time_t *__timer) __THROW;
# cat newdate.c
#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <dlfcn.h>

struct tm *(*orig_localtime)(const time_t *timep);

struct tm *localtime(const time_t *timep){
        time_t t=946684860;
        return orig_localtime(&t);
}

void _init(void){
        orig_localtime=dlsym(RTLD_NEXT,"localtime");
}
# gcc -Wall -fPIC -o newdate.o -c newdate.c
# ld -shared -o newdate.so newdate.o -ldl
# date
Thu Jan 10 13:35:30 CET 2013
# LD_PRELOAD=./newdate.so date
Sat Jan  1 01:01:00 CET 2000

# Hat-Check problem


Introduction

A couple of days ago we did the santa secret ('amigo invisible').
We wrote each name in a small paper and put them in a box.
Each participant had to take one small paper from the box.
We repeated the draw five times before to obtain a name different than our own.

What is the probability that each one obtain a different name?

The response has a limit in 1/e (Euler's number) and exists a similar probability game (the hat-check problem).

I found the hat-check problem after write a C program and observe that the result is similar beyond five friends/hats.


C program

# cat hat_game.c
#include <stdio.h>
#include <stdlib.h>

unsigned int *hats;
unsigned int favorable;
unsigned int possible;
unsigned int max;

void init(){
        unsigned int i;
        favorable=0;
        possible=1;
        hats=(unsigned int *)malloc(max*sizeof(unsigned int));
        for(i=0;i<max;i++){
                possible*=i+1;
        }
}

void end(){
        float probability;
        free(hats);
        printf("\n");
        printf("favorable   = %u\n",favorable);
        printf("possible    = %u\n",possible);
        probability=(float)favorable/possible;
        printf("probability = favorable/possible = %.10f\n\n",probability);
}

int exists(unsigned int num,unsigned top){
        unsigned int i;
        for(i=0;i<top;i++){
                if(hats[i]==num){return 1;}
        }
        return 0;
}

void print_result(){
        unsigned int i;
        printf("======> ");
        for(i=0;i<max;i++){
                printf("%u ",hats[i]);
        }
        printf("\n");
}

int hat_game(int min){
        unsigned int i,j;
        for(i=min;i<min+1;i++){
                for(j=0;j<max;j++){
                        if((i!=j)&&(exists(j,i)==0)){
                                hats[i]=j;
                                if(i==max-1){
                                        //print_result(max);
                                        favorable++;
                                        return 0;
                                }else{
                                        hat_game(i+1);
                                }
                        }
                }
        }
}

int main(int argc, char *argv[]){
        max=atoi(argv[1]);
        init();
        hat_game(0);
        end();
        return 0;
}
# gcc -O3 -march=native -o hat_game hat_game.c
# ./hat_game 10

favorable   = 1334961
possible    = 3628800
probability = favorable/possible = 0.3678794503

References

http://www.proofwiki.org/wiki/Hat-Check_Problem
http://en.wikipedia.org/wiki/Derangement

# Memory layout of C programs and stack frames


C program layout

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Code segment]
[Data segment]
[BSS  segment]
[Heap        ]
[Stack       ]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Code/Text segment

- Contains executable instructions.
- Read-only memory.
- Shared (only a single copy needs to be in memory).


Data segment

- Contains initialized global or static variables.
- Read-write memory.


BSS segment

- Contains uninitialized global or static variables.
- Read-write memory.


Heap

- Read-write memory.
- Grows to higher memory addresses.
- Managed by malloc, realloc and free functions.


Stack

- LIFO structure.
- Read-write memory.
- Grows to lower memory addresses.
- Contains stack frames (one for each pushed function):

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Local variables   ]
[Old Base Pointer  ]
[Return address    ]
[Function arguments]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Data and BSS example

# cat c-layout.c
#include <stdio.h>

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252       8    1316     524 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      12    1320     528 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      16    1324     52c c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i=10;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     256      12    1324     52c c-layout

# Redistribution, summarization, default routing and troubleshooting


Configuring Route Maps with the route-map Command

The general rules for route maps are:

- Each route-map command must have an explicitly configured name. All commands that use the same name are part of the same route map.
- Each route-map command has an action (permit or deny).
- Each route-map command in the same route map has a unique sequence number, allowing deletion and insertion of single route-map commands.
- The route-map processes routes taken from the current routing table (redistribution).
- The route-map is processed sequentially based on the sequence numbers.
- Once a particular route is matched by the route map, it is not processed beyond that matching route-map command (redistribution).
- Once matched, if the route-map has a permit parameter, the route is redistributed (redistribution).
- Once matched, if the route-map has a deny parameter, the route is not redistributed (redistribution).

Key points about route map logic when used for redistribution:

- route-map commands with the permit option either cause a route to be redistributed or leave the route to be examined by the next route-map clause.
- route-map commands with the deny option either filter the route or leave the route to be examined by the next route-map clause.
- A permit match in the ACL either causes a redistribution (route-map permit) or filtered (route-map deny).
- The route-map command includes an implied deny all clause at the end. To configure a permit all, use a route-map permit, but without a match command.


Route Map match Commands for Route Redistribution

- match interface _interface-type_ _interface-number_: Looks at outgoing interface of routes.
- match ip address _access-list_ | _prefix-list_: Examines route prefix and prefix length.
- match ip next-hop _access-list_: Examines route's next-hop address.
- match ip route-source _access-list_: Matches advertising router's IP address.
- match metric _metric-value_ _deviation_: Matches route's metric exactly or a range of metrics.
- match route-type _internal_ | _external_ _type-1_ | _type-2_ | _level-1_ | _level-2_: Matches route type.
- match tag _tag-value_: Tag must have been set earlier.


Route Map set Commands for Route Redistribution

- set level _level1_ | _level-2_ | _level-1-2_ | _stub-area_ | _backbone_: Defines database into which the route is redistributed.
- set metric _metric-value_: Sets the route's metric for OSPF, RIP and IS-IS.
- set metric _bandwidth_ _delay_ _reliability_ _loading_ _mtu_: Sets the IGRP/EIGRP metric values.
- set metric-type _internal_ | _external_ | _type-1_ | _type-2_: Sets type of route for IS-IS and OSPF.
- set tag _tag-value_: Sets the unitless tag value in the route.


IP Prefix Lists

Provide mechanisms to match two components of an IP route:

- The route prefix (the subnet number)
- The prefix length (the subnet mask)

Prefix list logic can be summarized into a two-step comparison process for each route:

- The route's prefix must be within the range of addresses implied by the prefix-list command's network/length parameters.
- The route's prefix length must match the range of prefixes implied by the prefix-list command.

LE and GE parameters and the implied range:

- Neither: conf-length = route-length
- Only le: conf-length <= route-length <= le-value
- Only ge: ge-value <= route-length <= 32
- Both ge and le: ge-value <= route-length <= le-value


Administrative Distance

- Connected: 0
- Static: 1
- EIGRP summary route: 5
- EBGP: 20
- EIGRP (internal): 90
- IGRP: 100
- OSPF: 110
- IS-IS: 115
- RIP: 120
- EIGRP (external): 170
- iBGP: 200
- Unreachable: 255

The defaults can be changed by using the distance command:

- distance _distance_ (RIP)
- distance eigrp _internal-distance_ _external-distance_
- distance ospf _intra-area-distance_ _inter-area-distance_ _external-distance_


Mechanics of the redistribute Command

The redistribute command identifies the routing source from which routes are taken and the router command identifies the routing process into which the routes are advertised.


Redistribution Using Default Settings

router eigrp 1
 redistribute ospf 1 metric 1544 5 255 1 1500
 redistribute rip metric 1544 5 255 1 1500
 no auto-summary
router ospf 1
 redistribute eigrp 1 subnets
 redistribute rip subnets
router rip
 version 2
 redistribute eigrp 1 metric 2
 redistribute ospf 1 metric 3
 no auto-summary

Logic to choose which routes to redistribute from a particular IGP protocol:

1. Take all routes in the routing table that were learned by that routing protocol.
2. Take all connected subnets matched by that routing protocol's network commands.


Setting Metrics, Metric Types, and Tags

Three mechanisms for setting the metrics of redistributed routes:

1. Call a route map from the redistribute command (set metric) -> different metrics for different routes.
2. Use the metric option on the redistribute command -> same metric for all routes of routing protocol.
3. Use the default-metric command under the router command -> same metric for all redistributed routes.


Redistributing a Subset of Routes Using a Route Map

router eigrp 1
 redistribute ospf 1 route-map ospf-into-eigrp
 default-metric 1544 5 1 1 1
 no auto-summary
router ospf 1
 redistribute eigrp 1 subnets route-map eigrp-into-ospf
ip access-list standard A-14-3-x-x
 permit 14.3.0.0 0.0.255.255
ip access-list standard A-15-1-1-5
 permit 15.1.1.5
ip access-list standard A-6-6-6-6
 permit 6.6.6.6
ip prefix-list e-into-o seq 5 permit 14.2.0.0/16 ge 23 le 24
route-map ospf-into-eigrp permit 10
 match ip next-hop A-15-1-1-5
 set tag 5
route-map ospf-into-eigrp permit 15
 match ip route-source A-6-6-6-6
 match route-type external type-1
 set tag 6
route-map eigrp-into-ospf permit 10
 match ip address prefix-list e-into-o
 set metric 300
route-map eigrp-into-ospf permit 18
 match ip address A-14-3-x-x
 set tag 99


Route Summarization

Features:

- The advertised summary is assigned the same metric as the currently lowest-metric component subnet.
- The router does not advertise the component subnets.
- The router does not advertise the summary when its routing tables does not have any of the component subnets.
- The summarizing router creates a local route to the summary, with destination null0, to prevent routing loops.
- Summary routes reduces the size of routing tables and topology databases, improving convergence.
- Summary routes decrease the amount of specific information in routing tables, causing suboptimal routing.


EIGRP Route Summarization

Under an interface:

ip summary-address eigrp _as-number_ _network-address_ _subnet-mask_ _admin-distance_

If any of the component routes are in that router's table, EIGRP advertises the summary route out that interface.
The EIGRP AD for summary routes defaults to 5.


OSPF Route Summarization

OPSF allows route summarization only as routes are injected into an area, either by an:

- ABR (IA routes): area _area-id_ range _ip-address-mask_ _advertise_|_not-advertise_ cost _cost_
- ASBR (external routes): summary-address _ip-address-mask_ _not-advertise_ tag _tag_

The area range command specifies an area in which the component subnets reside, with the summary being advertised into all other areas.


Default Routes

Four methods for learning default routes:

- Static route to 0.0.0.0 with the redistribute static command (RIP, EIGRP).
- The default-information originate (RIP, OSPF). The always keyword means a default is sourced regardless of whether a default route is in the routing table. A static route to 0.0.0.0/0 does not cause RIP to inject a default.
- The ip default-network command (RIP, EIGRP). The classfull network must be in the local routing table.
- Using summary routes (EIGRP).


Useful troubleshooting commands in diagnosing Layer 3

- show ip protocols
- show interface _interface_
- show ip interface _interface_
- show ip nat translations
- show ip access-list
- show ip interface brief
- show dampening
- show logging
- show policy-map
- show route-map
- show standby
- show vrrp
- show track
- show ip route _prefix_
- debug ip routing (useful to detect a routing loop)
- debug ipv6 routing