Friday, April 25, 2008

802.11 MAC frame

Frame format=Mac header + framebody(variable length)+FCS(32bit CRC)
Mac header=Frame Control(2)+Duration/ID(2)+Addr1(6)+Addr2(6)+Addr3(6)+Seq control(2)+Addr4(6)+Qos Control(2)
FrameControl=Protocol version +Type+SubType+ToDS+FromDS+MoreFrag+Retry+PwrMgt+MoreData+ProtectedFrame+Order
Based on type and SubType value of Frame Control, all 802.11 frames can be classified as
1. Management frame (Type=00)
(Re)Association request (Re)Association Response
Probe Request Probe Response Action
Beacon, ATIM, Diassociation, (De)authentication
mac header=frame control+duration + addr1+SA+BSSID+squence control
framebody=0-2312 bytes
fcs=4 bytes
* Beacon frame format

2. Control Frame (Type=01)
RTS,CTS,ACK,PS-Poll
Block Ack REquest, Block Ack
CF-End, CF-End+CF-ACk
RTS Mac header: Frame Control+Duration +RA+TA+FCS
CTS Mac header: Frame Control+Duration+RA+FCS

3. Data Frame(Type=10)
Data, Data+CF-Ack, Data+CF-Poll
Qos Data, Qos Data+CF-Ack
Mac header=full mac header
framebody=0-23424 data bytes
FCS
.....

Friday, April 11, 2008

How to generate root certificates for WAP

1. Setup environment
export PASSWD=123456
export SSL_DIR=demoCA
export OPENSSL_CONF=openssl.cnf

2. openssl.cnf content
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#

# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
RANDFILE = $ENV::HOME/.rnd

# Extra OBJECT IDENTIFIER info:
#oid_file = $ENV::HOME/.oid
oid_section = new_oids

# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)

[ new_oids ]

# We can add new OIDs in here for use by 'ca' and 'req'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6

####################################################################
[ ca ]
default_ca = CA_default # The default ca section

####################################################################
[ CA_default ]

dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
#crl_dir = $dir/crl # Where the issued crl are kept
crl_dir = $dir/ca # Where the issued crl are kept
database = $dir/index.txt # database index file.
#unique_subject = no # Set to 'no' to allow creation of
# several ctificates with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.

certificate = $dir/ca/CAcert.pem # The CA certificate
#certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/ca/CRL.pem # The current CRL
private_key = $dir/ca/CAkey.pem # The private key
#private_key = $dir/private/cakey.pem# The private key
RANDFILE = $dir/private/.rand # private random number file

x509_extensions = usr_cert # The extentions to add to the cert

# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions = crl_ext

default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sha1 # which md to use.
preserve = no # keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match

# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = optional
localityName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional

####################################################################
[ req ]
default_bits = 1024
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
#attributes = req_attributes
#x509_extensions = v3_ca # The extentions to add to the self signed cert

# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret

# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString.
# utf8only: only UTF8Strings.
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
# so use this option with caution!
string_mask = nombstr

# req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
countryName_min = 2
countryName_max = 2

stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = CA

localityName = Locality Name (eg, city)
localityName_default = Sunnyvale

0.organizationName = Organization Name (eg, company)
0.organizationName_default = Fortinet Inc

# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd

organizationalUnitName = Organizational Unit Name (eg, section)
#organizationalUnitName_default =

commonName = Common Name (eg, YOUR name)
commonName_max = 64

emailAddress = Email Address
emailAddress_max = 64

# SET-ex3 = SET extension number 3

[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20

unstructuredName = An optional company name

[ usr_cert ]

# These extensions are added when 'ca' signs a request.

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]


# Extensions for a typical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer:always

# This is what PKIX recommends but some broken software chokes on critical
# extensions.
#basicConstraints = critical,CA:true
# So we do this instead.
basicConstraints = CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign

# Some might want this also
# nsCertType = sslCA, emailCA

# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy

# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF

[ crl_ext ]

# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.

# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always,issuer:always

[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer:always

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

[server_eku]
extendedKeyUsage = serverAuth

[client_eku]
extendedKeyUsage = clientAuth, emailProtection, codeSigning

[clientemail_eku]
extendedKeyUsage = emailProtection

3. usages
gencert.sh --ca "WAP CA"
This will generate root authority certificate
gencert.sh --server EAP_server
This will generate server certificate signed by root CA
gencert.sh --client EAP_client
This will generate client certificate signed by root CA

Friday, April 4, 2008

Hostapd 802.1X authentication

1. Overview

When EAP is invoked by an 802.1X enabled NAS (Network Access Server) device such as an 802.11 a/b/g Wireless Access Point, modern EAP methods can provide a secure authentication mechanism and negotiate a secure PMK (Pair-wise Master Key) between the client and NAS. The PMK can then be used for the wireless encryption session which uses TKIP or AES encryption.

2. 802.1X basic components
  • Supplicant -- A software client running on wireless client/station
  • Authenticator --- Access point. In som case, access point can also act as authentication server as well.
  • Authentication server-- a authentication database, usually a radius server, or microsoft IAS
EAP(extensible authentication protocol) is support on freeradius
  • EAP-MD5 (Message Digest) Challenge is an EAP authentication type that provides base-level EAP support. EAP-MD-5 is typically not recommended for wireless LAN implementations because it may allow the user's password to be derived. It provides for only one way authentication - there is no mutual authentication of wireless client and the network. And very importantly it does not provide a means to derive dynamic, per session wired equivalent privacy (WEP) keys.
  • EAP-TLS (Transport Layer Security) provides for certificate-based and mutual authentication of the client and the network. It relies on client-side and server-side certificates to perform authentication and can be used to dynamically generate user-based and session-based WEP keys to secure subsequent communications between the WLAN client and the access point. One drawback of EAP-TLS is that certificates must be managed on both the client and server side. For a large WLAN installation, this could be a very cumbersome task.
  • EAP-TTLS (Tunneled Transport Layer Security) was developed by Funk Software and Certicom, as an extension of EAP-TLS. This security method provides for certificate-based, mutual authentication of the client and network through an encrypted channel (or "tunnel"), as well as a means to derive dynamic, per-user, per-session WEP keys. Unlike EAP-TLS, EAP-TTLS requires only server-side certificates.
  • EAP-FAST (Flexible Authentication via Secure Tunneling) was developed by Cisco. Instead of using a certificate, mutual authentication is achieved by means of a PAC (Protected Access Credential) which can be managed dynamically by the authentication server. The PAC can be provisioned (distributed one time) to the client either manually or automatically. Manual provisioning is delivery to the client via disk or a secured network distribution method. Automatic provisioning is an in-band, over the air, distribution.
  • LEAP (Lightweight Extensible Authentication Protocol), is an EAP authentication type used primarily in Cisco Aironet WLANs. It encrypts data transmissions using dynamically generated WEP keys, and supports mutual authentication. Heretofore proprietary, Cisco has licensed LEAP to a variety of other manufacturers through their Cisco Compatible Extensions program.
  • PEAP (Protected Extensible Authentication Protocol) provides a method to transport securely authentication data, including legacy password-based protocols, via 802.11 wireless networks. PEAP accomplishes this by using tunneling between PEAP clients and an authentication server. Like the competing standard Tunneled Transport Layer Security (TTLS), PEAP authenticates wireless LAN clients using only server-side certificates, thus simplifying the implementation and administration of a secure wireless LAN. Microsoft, Cisco and RSA Security developed PEAP.
A review of the above discussions and table will usually provide the following conclusions:
  • MD5 is not typically used as it only does a one-way authentication, and perhaps even more importantly does not support automatic distribution and rotation of WEP keys so does nothing to relieve the administrative burden of manual WEP key maintenance.
  • TLS, while very secure, requires client certificates to be installed on each wireless workstation. Maintenance of a PKI infrastructure requires additional administrative expertise and time in addition to that of maintaining the WLAN itself.
  • TTLS addresses the certificate issue by tunneling TLS, and thus eliminating the need for a certificate on the client side. Making this an often preferred option. TTLS is primarily promoted by Funk and there is a charge for supplicant and authentication server software.
  • LEAP has the longest history, and while previously Cisco proprietary (works with Cisco wireless adapters only), Cisco has licensed LEAP to a variety of other manufacturers through their Cisco Compatible Extensions program. A strong password policy should be enforced when LEAP is used for authentication.
  • EAP-FAST is now available for enterprises that cannot enforce a strong password policy and do not want to deploy certificates for authentication.
  • The more recent PEAP works similar to EAP-TTLS in that it does not require a certificate on the client side. PEAP is backed by Cisco and Microsoft and is available at no additional cost from Microsoft. If desired to transition from LEAP to PEAP, Cisco's ACS authentication server will run both.
  • PEAPv0/EAP-MSCHAPv2
  • PEAPv1/EAP-GTC
Note:Note: The PEAP standard was created by Microsoft, Cisco, and RSA after EAP-TTLS had already come on the market. Even with its late start, Microsoft’s and Cisco’s size allowed them to quickly overtake EAP-TTLS in the market. Microsoft and Cisco parted ways when Microsoft only supported the PEAPv0 standard while Cisco supported both PEAPv0 and PEAPv1. PEAPv0 and PEAPv1 both refer to the outer authentication method and is the mechanism that creates the secure TLS tunnel to protect subsequent authentication transactions while EAP-MSCHAPv2, EAP-GTC, and EAP-SIM refer to the inner authentication method which facilitates user or device authentication. From Cisco’s perspective, PEAPv0 supports inner EAP methods EAP-MSCHAPv2 and EAP-SIM while PEAPv1 supports inner EAP methods EAP-GTC and EAP-SIM. Since Microsoft only supports PEAPv0 and doesn’t support PEAPv1, Microsoft simply calls PEAPv0 PEAP without the v0 or v1 designator. Another difference between Microsoft and Cisco is that Microsoft only supports PEAPv0/EAP-MSCHAPv2 mode but not PEAPv0/EAP-SIM mode. However, Microsoft supports another form of PEAPv0 (which Microsoft calls PEAP-EAP-TLS) that Cisco and other third-party server and client software don’t support. PEAP-EAP-TLS does require a client-side digital certificate located on the client’s hard drive or a more secure smartcard. PEAP-EAP-TLS is very similar in operation to the original EAP-TLS but provides slightly more protection due to the fact that portions of the client certificate that are unencrypted in EAP-TLS are encrypted in PEAP-EAP-TLS. Since few third-party clients and servers support PEAP-EAP-TLS, users should probably avoid it unless they only intend to use Microsoft desktop clients and servers. Ultimately, PEAPv0/EAP-MSCHAPv2 is the only form of PEAP that most people will ever know. PEAP is so successful in the market place that even Funk Software, the inventor and backer of EAP-TTLS, had no choice but to support PEAP in their server and client software for wireless networks.

Thursday, April 3, 2008

how to create CA root certificates

1. Run /usr/share/ssl/misc/CA or CA.pl -newca
it will creates demoCA/ directory
cacert.pem certs crl index.txt newcerts private serial

where cacert.pem=public key of new root authority
private/cakey.pem=private key of new root authority

crl = certificate revokeation List(CRL)

2. To generate a certificate request
/usr/share/ssl/misc/CA.pl -newreq
This will generate a newreq.pem
Make sure common name is different than that of root authority

3. Sign newreq.pem certificate request

CA.pl -sign
it will generate a newcert.pem in current directory





CA certificate filename (or enter to create)

Making CA certificate ...
Generating a 1024 bit RSA private key
......................................................++++++
.....++++++
writing new private key to './demoCA/private/./cakey.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:US
State or Province Name (full name) [Berkshire]:CA
Locality Name (eg, city) [Newbury]:Sunnyvale
Organization Name (eg, company) [My Company Ltd]:Fortinet Inc
Organizational Unit Name (eg, section) []:R&D
Common Name (eg, your name or your server's hostname) []:Wende Li
Email Address []:wli@fortinet.com

==========================
Note: this will creae a demoCA directory under current working directory and all the certificates and keys related files are in this directory.

The alternative command to create a Root Certificaion Authority is:
openssl req -new -x509 -keyout newreq.pem -out newreq.pem -days 365 -config openssl.conf
or CA.pl -newcert
This will generate a self-signed certificate (for Certificate Authority). The result file is newreq.rem.
This file needs to be split into two parts: cacert.pem and private/cakey.pem. WE can change the root certificates expire days beyond 365. This is the command to do that,
opensll req -new -x509 -keyout private/cakey.pem -out cacert.pem -days 3650

Now, you have a root Certificate Authority. Make sure this self signed root certificate is used to sign other certificates. Other people need to trust your self-signed root CA certificate, and therefore download it and register with browser.


You have to type the passphrase each time you want to sign another certificate with it.

2. Strip the certificates from all its text to keeyp only --CERTIFICATES-- section
openssl x509 -in cacert.pem -out cacert.crt
or openssl x509 -in newreq.pem -out cacert.crt

Install the CA root certificate as trusted Root Certificate
http://mysite.com/ssl/cacert.crt


3. Generate ans sign a certificate request
CA.pl -newreq or
openssl req -new -keyout newreq.pem -out newreq.pem -config openssl.cnf -days 365
To sign it, use
CA.pl -sign, or
openssl ca -policy policy_anything -out newcert.pem -infiles newreq.pem -config openssl.cnf
Those files have to be in demoCA/ directorty

cd demoCA
cacert.pem certs/ crl/ index.txt newcerts/ private/ serial
  • cacert.pem--the public key for new Certificate Authority is contained in cacert.perm, and the private key is in private/cakey.pem
  • To use CA's authority to sign SSL certs, you will need to make a new cert that a web server can use
=========================================
openssl help
openssl -help #first level help

openssl:Error: '--help' is an invalid command.

Standard commands
asn1parse ca ciphers crl crl2pkcs7
dgst dh dhparam dsa dsaparam
enc engine errstr gendh gendsa
genrsa nseq ocsp passwd pkcs12
pkcs7 pkcs8 rand req rsa
rsautl s_client s_server s_time sess_id
smime speed spkac verify version
x509

Message Digest commands (see the `dgst' command for more details)
md2 md4 md5 rmd160 sha
sha1

Cipher commands (see the `enc' command for more details)
aes-128-cbc aes-128-ecb aes-192-cbc aes-192-ecb aes-256-cbc
aes-256-ecb base64 bf bf-cbc bf-cfb
bf-ecb bf-ofb cast cast-cbc cast5-cbc
cast5-cfb cast5-ecb cast5-ofb des des-cbc
des-cfb des-ecb des-ede des-ede-cbc des-ede-cfb
des-ede-ofb des-ede3 des-ede3-cbc des-ede3-cfb des-ede3-ofb
des-ofb des3 desx rc2 rc2-40-cbc
rc2-64-cbc rc2-cbc rc2-cfb rc2-ecb rc2-ofb


=========================================
openssl ca help
unknown option help
usage: ca args

-verbose - Talk alot while doing things
-config file - A config file
-name arg - The particular CA definition to use
-gencrl - Generate a new CRL
-crldays days - Days is when the next CRL is due
-crlhours hours - Hours is when the next CRL is due
-startdate YYMMDDHHMMSSZ - certificate validity notBefore
-enddate YYMMDDHHMMSSZ - certificate validity notAfter (overrides -days)
-days arg - number of days to certify the certificate for
-md arg - md to use, one of md2, md5, sha or sha1
-policy arg - The CA 'policy' to support
-keyfile arg - private key file
-keyform arg - private key file format (PEM or ENGINE)
-key arg - key to decode the private key if it is encrypted
-cert file - The CA certificate
-in file - The input PEM encoded certificate request(s)
-out file - Where to put the output file(s)
-outdir dir - Where to put output certificates
-infiles .... - The last argument, requests to process
-spkac file - File contains DN and signed public key and challenge
-ss_cert file - File contains a self signed cert to sign
-preserveDN - Don't re-order the DN
-noemailDN - Don't add the EMAIL field into certificate' subject
-batch - Don't ask questions
-msie_hack - msie modifications to handle all those universal strings
-revoke file - Revoke a certificate (given in file)
-subj arg - Use arg instead of request's subject
-extensions .. - Extension section (override value in config file)
-extfile file - Configuration file with X509v3 extentions to add
-crlexts .. - CRL extension section (override value in config file)
-engine e - use engine e, possibly a hardware device.
-status serial - Shows certificate status given the serial number
-updatedb - Updates db for expired certificates


------------------
keep doing like this, you can get details help regarding openssl command.

Wednesday, April 2, 2008

How to generate OpenSSL RSA/DSA private and public keys and certificates

1. Generating a RSA key
# openssl genrsa -out roger_rsa.key
# cat roger_rsa.key
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBALQzLRNx0hTPufHzeDigNDvmd92uQlgHfQ3qSrbrpy+RZB4LpmLE
xEMsQ9CoaDgixjrHQVdUX+tCeVuybp0NWK0CAwEAAQJAPQ1JrFjX0G1AlpTimmzM
xa6j1duAZsrCt8A1aBwXHKoXXUbWELE7r7JfCVDl+dP5tWtenwZDNsVQwM/C8ox/
EQIhAO8WuYOofg3YXZO0CxjLKQQV6z4/VtNMT0LnjD8b2c2nAiEAwPIgnNph3yDn
JR3EqCvJ5LddAM5sHTA3DrjEO+4LuYsCIBPU0rZ091+2nqxttq3rzA8mskiLgGwu
XDS0eBGUAdDpAiApKT412Ay7CgzliSUz7yuB5HAtxNuhmnCUbmxGkLDlowIhAI4n
MFX/zrbhaJY4SW5WHn+jiR0GZUM75yK5doKk8yCL
-----END RSA PRIVATE KEY-----

Note:RSA key contains both private and public keys.
2. Viewing the components of RSA key
Private-Key: (512 bit)
modulus:
00:b4:33:2d:13:71:d2:14:cf:b9:f1:f3:78:38:a0:
34:3b:e6:77:dd:ae:42:58:07:7d:0d:ea:4a:b6:eb:
a7:2f:91:64:1e:0b:a6:62:c4:c4:43:2c:43:d0:a8:
68:38:22:c6:3a:c7:41:57:54:5f:eb:42:79:5b:b2:
6e:9d:0d:58:ad
publicExponent: 65537 (0x10001)
privateExponent:
3d:0d:49:ac:58:d7:d0:6d:40:96:94:e2:9a:6c:cc:
c5:ae:a3:d5:db:80:66:ca:c2:b7:c0:35:68:1c:17:
1c:aa:17:5d:46:d6:10:b1:3b:af:b2:5f:09:50:e5:
f9:d3:f9:b5:6b:5e:9f:06:43:36:c5:50:c0:cf:c2:
f2:8c:7f:11
prime1:
00:ef:16:b9:83:a8:7e:0d:d8:5d:93:b4:0b:18:cb:
29:04:15:eb:3e:3f:56:d3:4c:4f:42:e7:8c:3f:1b:
d9:cd:a7
prime2:
00:c0:f2:20:9c:da:61:df:20:e7:25:1d:c4:a8:2b:
c9:e4:b7:5d:00:ce:6c:1d:30:37:0e:b8:c4:3b:ee:
0b:b9:8b
exponent1:
13:d4:d2:b6:74:f7:5f:b6:9e:ac:6d:b6:ad:eb:cc:
0f:26:b2:48:8b:80:6c:2e:5c:34:b4:78:11:94:01:
d0:e9
exponent2:
29:29:3e:35:d8:0c:bb:0a:0c:e5:89:25:33:ef:2b:
81:e4:70:2d:c4:db:a1:9a:70:94:6e:6c:46:90:b0:
e5:a3
coefficient:
00:8e:27:30:55:ff:ce:b6:e1:68:96:38:49:6e:56:
1e:7f:a3:89:1d:06:65:43:3b:e7:22:b9:76:82:a4:
f3:20:8b
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBALQzLRNx0hTPufHzeDigNDvmd92uQlgHfQ3qSrbrpy+RZB4LpmLE
xEMsQ9CoaDgixjrHQVdUX+tCeVuybp0NWK0CAwEAAQJAPQ1JrFjX0G1AlpTimmzM
xa6j1duAZsrCt8A1aBwXHKoXXUbWELE7r7JfCVDl+dP5tWtenwZDNsVQwM/C8ox/
EQIhAO8WuYOofg3YXZO0CxjLKQQV6z4/VtNMT0LnjD8b2c2nAiEAwPIgnNph3yDn
JR3EqCvJ5LddAM5sHTA3DrjEO+4LuYsCIBPU0rZ091+2nqxttq3rzA8mskiLgGwu
XDS0eBGUAdDpAiApKT412Ay7CgzliSUz7yuB5HAtxNuhmnCUbmxGkLDlowIhAI4n
MFX/zrbhaJY4SW5WHn+jiR0GZUM75yK5doKk8yCL
-----END RSA PRIVATE KEY-----


3. Encrypting the RSA key with DES.
# openssl rsa -in roger_rsa.key -des -out roger_rsa_des.key
This will read in a RSA key and encrypt it with DES-EDE3-CBC algorithm
#openssl genrsa -des3 -out roger_rsa_des.key
This will generate a RSA key with des encryption.

4. Generating self-signed Certificates

Certificate: A digitally signed statement from the issuer saying that the public key of the subject has some specific value.

The above definition is copied from the JDK 1.3.1 documentation. It has a couple of important terms:

  • "signed statement" - The certificate must be signed by the issuer with a digital signature.
  • "issuer" - The person or organization who is issuing this certificate.
  • "public key" - The public key of a key pair selected by the subject.
  • "subject" - The person or organization who owns the public key.

X.509 Certificate - A certificate written in X.509 standard format. X.509 standard was introduction in 1988. It requires a certificate to have the following information:

  • Version - X.509 standard version number.
  • Serial Number - A sequence number given to each certificate.
  • Signature Algorithm Identifier - Name of the algorithm used to sign this certificate by the issuer
  • Issuer Name - Name of the issuer.
  • Validity Period - Period during which this certificate is valid.
  • Subject Name - Name of the owner of the public key.
  • Subject Public Key Information - The public key and its related information

Generating Self-Signed Certificates

A self-signed certificate is a certificate that the "issuer" is the "subject" himself. In other words, a seft-signed certificate is a certificate where the "issuer" signs his own public key with his private key.

If you want to generate a self-signed certificate for yourself, here what you to need to do:

  • Enter your own name as the "subject".
  • Provide your public key.
  • Sign it with your private key.
  • Put everything in the X.509 format.
Here's the command to generate a self-signed certificates based on a RSA key pair file, roger_rsades.key
#openssl req -new -key roger_rsa_des.key -x509 -out roger.crt
-config openssl.cnf

$ cat roger.crt
-----BEGIN CERTIFICATE-----
MIIC3TCCAoegAwIBAgIBADANBgkqhkiG9w0BAQQFADCBgzELMAkGA1UEBhMCVVMx
CzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlTdW5ueXZhbGUxETAPBgNVBAoTCEZvcnRp
bmV0MQwwCgYDVQQLEwNFbmcxETAPBgNVBAMTCFdlbmRlIExpMR8wHQYJKoZIhvcN
AQkBFhB3bGlAZm9ydGluZXQuY29tMB4XDTA4MDQwMzAwMTYwMloXDTA4MDUwMzAw
MTYwMlowgYMxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vu
bnl2YWxlMREwDwYDVQQKEwhGb3J0aW5ldDEMMAoGA1UECxMDRW5nMREwDwYDVQQD
EwhXZW5kZSBMaTEfMB0GCSqGSIb3DQEJARYQd2xpQGZvcnRpbmV0LmNvbTBcMA0G
CSqGSIb3DQEBAQUAA0sAMEgCQQC0My0TcdIUz7nx83g4oDQ75nfdrkJYB30N6kq2
66cvkWQeC6ZixMRDLEPQqGg4IsY6x0FXVF/rQnlbsm6dDVitAgMBAAGjgeMwgeAw
HQYDVR0OBBYEFAC/Mk5gQKdJ3I4FQgn7bm/FHN9xMIGwBgNVHSMEgagwgaWAFAC/
Mk5gQKdJ3I4FQgn7bm/FHN9xoYGJpIGGMIGDMQswCQYDVQQGEwJVUzELMAkGA1UE
CBMCQ0ExEjAQBgNVBAcTCVN1bm55dmFsZTERMA8GA1UEChMIRm9ydGluZXQxDDAK
BgNVBAsTA0VuZzERMA8GA1UEAxMIV2VuZGUgTGkxHzAdBgkqhkiG9w0BCQEWEHds
aUBmb3J0aW5ldC5jb22CAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAANB
ABn3An7PFvP1IF879EnPRApzfN4LOC7yUi40DkYLCpy3Hqguhp/dQdc3zxldXMfj
cR81u2HXp6nrt/W8/d58TFk=
-----END CERTIFICATE-----

6. Viewing the certificate
$ openssl x509 -in roger.crt -noout -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 0 (0x0)
Signature Algorithm: md5WithRSAEncryption
Issuer: C=US, ST=CA, L=Sunnyvale, O=Fortinet, OU=Eng, CN=Wende Li/emailAddress=wli@fortinet.com
Validity
Not Before: Apr 3 00:16:02 2008 GMT
Not After : May 3 00:16:02 2008 GMT
Subject: C=US, ST=CA, L=Sunnyvale, O=Fortinet, OU=Eng, CN=Wende Li/emailAddress=wli@fortinet.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public Key: (512 bit)
Modulus (512 bit):
00:b4:33:2d:13:71:d2:14:cf:b9:f1:f3:78:38:a0:
34:3b:e6:77:dd:ae:42:58:07:7d:0d:ea:4a:b6:eb:
a7:2f:91:64:1e:0b:a6:62:c4:c4:43:2c:43:d0:a8:
68:38:22:c6:3a:c7:41:57:54:5f:eb:42:79:5b:b2:
6e:9d:0d:58:ad
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
00:BF:32:4E:60:40:A7:49:DC:8E:05:42:09:FB:6E:6F:C5:1C:DF:71
X509v3 Authority Key Identifier:
keyid:00:BF:32:4E:60:40:A7:49:DC:8E:05:42:09:FB:6E:6F:C5:1C:DF:71
DirName:/C=US/ST=CA/L=Sunnyvale/O=Fortinet/OU=Eng/CN=Wende Li/emailAddress=wli@fortinet.com
serial:00

X509v3 Basic Constraints:
CA:TRUE
Signature Algorithm: md5WithRSAEncryption
19:f7:02:7e:cf:16:f3:f5:20:5f:3b:f4:49:cf:44:0a:73:7c:
de:0b:38:2e:f2:52:2e:34:0e:46:0b:0a:9c:b7:1e:a8:2e:86:
9f:dd:41:d7:37:cf:19:5d:5c:c7:e3:71:1f:35:bb:61:d7:a7:
a9:eb:b7:f5:bc:fd:de:7c:4c:59

Note: the issuer and subject are identical as it is self-signed certificate.
  • The subject's public key is included in it
  • The certificate is valid for one month(April 3 to May 3)
  • The certicate is signed by the issuer with signature at the end
8.Certification path testing with OpenSSL
1. Generate a self-signed certificate for roger
* Generating keys for roger
openssl genrsa -des3 -out roger_rsa.key
* Generating a self-signed cerfiticate for roger
openssl req -new key roger_rsa.key -x509 -out roger.crt -config openssl.cnf

2. Generating keys for john
openssl genrsa -des3 -out john_rsa.key
3. Generating a certificate signing request for john
openssl req -new -key john_rsa.key -out john.csr -config openssl.cnf
4. Signing a john 's request by roger's key
openssl x509 -req -in john.csr -CA roger.crt -CAkey roger_rsa.key -out john.crt -set_serial 3

Tuesday, April 1, 2008

iptable primer

http://www.higherpass.com/linux/Tutorials/Iptables-Primer/2/
1. Rules, Chain and Tables
iptables rules are grouped into chains. A chain is a set of rules used to determine what to do with a packet. These chains are grouped into tables. Iptables has three built in tables: filter, NAT, mangle and Raw
Filter table
The filter table is used to allow or block traffic and contains three chains: INPUT,OUTPUT and FORWARD.
The input chain is used to filter traffic destined for the local machine.
The output chain is used to filter packets created by the local system.
The forward chain is used to filter packets passing through the system, eg. gateway
NAT table
The NAT table is used to setup the rules to rewrite packets allowing NAT to happen. This table has three chains: PREROUTING, POSTROUTING and OUTPUT. Packets in a stream only traverse this table once.
This is the main reason why you should not do any filtering in this table
The prerouting chain is where packets come to prior to being parsed by the local routing table
The OUTPUT chain is used for altering locally generated packets (i.e., on the firewall) before they get to the routing decision.
The Postrouting chian s
which is used to alter packets just as they are about to leave the firewall.
Raw Table
The raw table and its chains are used before any other tables in netfilter. It was introduced to use the NOTRACK target. It contain two chains: PREROUTING and OUTPUT,where they will handle packets before they hit any of the other netfilter subsystems


The PREROUTING chain can be used for all incoming packets to this machine, or that are forwarded
the OUTPUT chain can be used to alter the locally generated packets before they hit any of the other netfilter subsystems.



Basic Uses

Structure

Many iptables commands have the following structure:

iptables [-t ]    \

In this example, the option allows the user to select a table other than the default filter table to use with the command. The option dictates a specific action to perform, such as appending or deleting the rule specified by the option. Following the are pairs of parameters and options that define what will happen when a packet matches the rule.

When looking at the structure of an iptables command, it is important to remember that, unlike most other commands, the length and complexity of an iptables command can change based on its purpose. A simple command to remove a rule from a chain can be very short, while a command designed to filter packets from a particular subnet using a variety of specific parameters and options can be rather lengthy. When creating iptables commands it is helpful to recognize that some parameters and options may create the need for other parameters and options to further specify the previous option's request. In order to construct a valid rule, this must continue until every parameter and option that requires another set of options is satisfied.

Commands tell iptables to perform a specific action. Only one command is allowed per iptables command string. With the exception of the help command, all commands are written in upper-case characters.

The iptables commands are as follows:

  • -A — Appends the iptables rule to the end of the specified chain. This is the command used to simply add a rule when rule order in the chain does not matter.

  • -C — Checks a particular rule before adding it to the user-specified chain. This command can help you construct complicated iptables rules by prompting you for additional parameters and options.

  • -D — Deletes a rule in a particular chain by number (such as 5 for the fifth rule in a chain). You can also type the entire rule, and iptables will delete the rule in the chain that matches it.

  • -E — Renames a user-defined chain. This does not affect the structure of the table.

  • -F — Flushes the selected chain, which effectively deletes every rule in the the chain. If no chain is specified, this command flushes every rule from every chain.

  • -h — Provides a list of command structures, as well as a quick summary of command parameters and options.

  • -I — Inserts a rule in a chain at a point specified by a user-defined integer value. If no number is specified, iptables will place the command at the top of the chain.

  • -L — Lists all of the rules in the chain specified after the command. To list all rules in all chains in the default filter table, do not specify a chain or table. Otherwise, the following syntax should be used to list the rules in a specific chain in a particular table: iptables -L -t
  • -N — Creates a new chain with a user-specified name.

  • -P — Sets the default policy for a particular chain, so that when packets traverse an entire chain without matching a rule, they will be sent on to a particular target, such as ACCEPT or DROP.

  • -R — Replaces a rule in a particular chain. The rule's number must be specified after the chain's name. The first rule in a chain corresponds to rule number one.

  • -X — Deletes a user-specified chain. Deleting a built-in chain for any table is not allowed.

  • -Z — Zeros the byte and packet counters in all chains for a particular table.


Parameters

Once certain iptables commands are specified, including those used to add, append, delete, insert, or replace rules within a particular chain, parameters are required to construct a packet filtering rule.

  • -c — Resets the counters for a particular rule. This parameter accepts the PKTS and BYTES options to specify what counter to reset.

  • -d — Sets the destination hostname, IP address, or network of a packet that will match the rule. When matching a network, the following IP address/netmask formats are supported:

    • N.N.N.N/M.M.M.M — Where N.N.N.N is the IP address range and M.M.M.M is the netmask.

    • N.N.N.N/M — Where N.N.N.N is the IP address range and M is the netmask.

  • -f — Applies this rule only to fragmented packets.

    By using the ! option after this parameter, only unfragmented packets will be matched.

  • -i — Sets the incoming network interface, such as eth0 or ppp0. With iptables, this optional parameter may only be used with the INPUT and FORWARD chains when used with the filter table and the PREROUTING chain with the nat and mangle tables.

    This parameter also supports the following special options:

    • ! — Tells this parameter not to match, meaning that any specified interfaces are specifically excluded from this rule.

    • + — A wildcard character used to match all interfaces which match a particular string. For example, the parameter -i eth+ would apply this rule to any Ethernet interfaces but exclude any other interfaces, such as ppp0.

    If the -i parameter is used but no interface is specified, then every interface is affected by the rule.

  • -j — Tells iptables to jump to a particular target when a packet matches a particular rule. Valid targets to be used after the -j option include the standard options, ACCEPT, DROP, QUEUE, and RETURN, as well as extended options that are available through modules loaded by default with the Red Hat Linux iptables RPM package, such as LOG, MARK, and REJECT, among others. See the iptables man page for more information on these and other targets.

    You may also direct a packet matching this rule to a user-defined chain outside of the current chain so that other rules can be applied to the packet.

    If no target is specified, the packet moves past the rule with no action taken. However, the counter for this rule is still increased by one, as the packet matched the specified rule.

  • -o — Sets the outgoing network interface for a rule and may only be used with OUTPUT and FORWARD chains in the filter table, and the POSTROUTING chain in the nat and mangle tables. This parameter's options are the same as those of the incoming network interface parameter (-i).

  • -p — Sets the IP protocol for the rule, which can be either icmp, tcp, udp, or all, to match every supported protocol. In addition, any protocols listed in /etc/protocols may also be used. If this option is omitted when creating a rule, the all option is the default.

  • -s — Sets the source for a particular packet using the same syntax as the destination (-d) parameter.


16.3.5. Match Options

Different network protocols provide specialized matching options which may be set in specific ways to match a particular packet using that protocol. Of course, the protocol must first be specified in the iptables command, by using -p tcp (where is the target protocol), to make the options for that protocol available.

16.3.5.1. TCP Protocol

These match options are available for the TCP protocol (-p tcp):

  • --dport — Sets the destination port for the packet. Use either a network service name (such as www or smtp), port number, or range of port numbers to configure this option. To browse the names and aliases of network services and the port numbers they use, view the /etc/services file. The --destination-port match option is synonymous with --dport.

    To specify a specific range of port numbers, separate the two numbers with a colon (:), such as -p tcp --dport 3000:3200. The largest acceptable valid range is 0:65535.

    Use an exclamation point character (!) after the --dport option to tell iptables to match all packets which do not use that network service or port.

  • --sport — Sets the source port of the packet using the same options as --dport. The --source-port match option is synonymous with --sport.

  • --syn — Applies to all TCP packets designed to initiate communication, commonly called SYN packets. Any packets that carry a data payload are not touched. Placing an exclamation point character (!) as a flag after the --syn option causes all non-SYN packets to be matched.

  • --tcp-flags — Allows TCP packets with specific bits, or flags, set to be matched with a rule. The --tcp-flags match option accepts two parameters. The first parameter is the mask, which sets the flags to be examined in the packet. The second parameter refers to the flag that must be set in order to match.

    The possible flags are:

    • ACK

    • FIN

    • PSH

    • RST

    • SYN

    • URG

    • ALL

    • NONE

    For example, an iptables rule which contains -p tcp --tcp-flags ACK,FIN,SYN SYN will only match TCP packets that have the SYN flag set and the ACK and FIN flags unset.

    Using the exclamation point character (!) after --tcp-flags reverses the effect of the match option.

  • --tcp-option — Attempts to match with TCP-specific options that can be set within a particular packet. This match option can also be reversed with the exclamation point character (!).

16.3.5.2. UDP Protocol

These match options are available for the UDP protocol (-p udp):

  • --dport — Specifies the destination port of the UDP packet, using the service name, port number, or range of port numbers. The --destination-port match option is synonymous with --dport. Refer to the --dport match option in Section 16.3.5.1 TCP Protocol for ways to use this option.

  • --sport — Specifies the source port of the UDP packet, using the service name, port number, or range of port numbers. The --source-port match option is synonymous with --sport. Refer to the --sport match option in Section 16.3.5.1 TCP Protocol for ways to use this option.

16.3.5.3. ICMP Protocol

These match options are available for the Internet Control Message Protocol (ICMP) (-p icmp):

  • --icmp-type — Sets the name or number of the ICMP type to match with the rule. A list of valid ICMP names can be seen by typing the iptables -p icmp -h command.

16.3.5.4. Modules with Additional Match Options

Additional match options are also available through modules loaded by the iptables command. To use a match option module, load the module by name using the -m option, such as -m (replacing with the name of the module).

A large number of modules are available by default. It is even possible to create your own modules to provide additional match option functionality.

Many modules exist, but only the most popular modules are discussed here.

  • limit module — Allows limit to be placed on how many packets are matched to a particular rule. This is especially beneficial when logging rule matches so that a flood of matching packets will not fill up the system logs with repetitive messages or use up system resources.

    The limit module enables the following options:

    • --limit — Sets the number of matches for a particular range of time, specified with a number and time modifier arranged in a / format. For example, using --limit 5/hour only lets a rule match five times in a single hour.

      If a number and time modifier are not used, the default value of 3/hour is assumed.

    • --limit-burst — Sets a limit on the number of packets able to match a rule at one time. This option should be used in conjunction with the --limit option, and it accepts a number to set the burst threshold.

      If no number is specified, only five packets are initially able to match the rule.

  • state module — Enables state matching.

    The state module enables the following options:

    • --state — match a packet with the following connection states:

      • ESTABLISHED — The matching packet is associated with other packets in an established connection.

      • INVALID — The matching packet cannot be tied to a known connection.

      • NEW — The matching packet is either creating a new connection or is part of a two-way connection not previously seen.

      • RELATED — The matching packet is starting a new connection related in some way to an existing connection.

      These connection states can be used in combination with one another by separating them with commas, such as -m state --state INVALID,NEW.

  • mac module — Enables hardware MAC address matching.

    The mac module enables the following option:

    • --mac-source — Matches a MAC address of the network interface card that sent the packet. To exclude a MAC address from a rule, place an exclamation point (!) after the --mac-source match option.

To view other match options available through modules, refer to the iptables man page.

16.3.6. Target Options

Once a packet has matched a particular rule, the rule can direct the packet to a number of different targets that decide its fate and, possibly, take additional actions. Each chain has a default target, which is used if none of the rules on that chain match a packet or if none of the rules which match the packet specify a target.

The following are the standard targets:

  • — Replace with the name of a user-defined chain within the table. This target passes the packet to the target chain.

  • ACCEPT — Allows the packet to successfully move on to its destination or another chain.

  • DROP — Drops the packet without responding to the requester. The system that sent the packet is not notified of the failure.

  • QUEUE — The packet is queued for handling by a user-space application.

  • RETURN — Stops checking the packet against rules in the current chain. If the packet with a RETURN target matches a rule in a chain called from another chain, the packet is returned to the first chain to resume rule checking where it left off. If the RETURN rule is used on a built-in chain and the packet cannot move up to its previous chain, the default target for the current chain decides what action to take.

In addition to these standard targets, various other targets may be used with extensions called target modules. For more information about match option modules, see Section 16.3.5.4 Modules with Additional Match Options.

There are many extended target modules, most of which only apply to specific tables or situations. A couple of the most popular target modules included by default in Red Hat Linux are:

  • LOG — Logs all packets that match this rule. Since the packets are logged by the kernel, the /etc/syslog.conf file determines where these log entries are written. By default, they are placed in the /var/log/messages file.

    Various options can be used after the LOG target to specify the way in which logging occurs:

    • --log-level — Sets the priority level of a logging event. A list of priority levels can be found in the syslog.conf man page.

    • --log-ip-options — Any options set in the header of a IP packet is logged.

    • --log-prefix — Places a string of up to 29 characters before the log line when it is written. This is useful for writing syslog filters for use in conjunction with packet logging.

    • --log-tcp-options — Any options set in the header of a TCP packet are logged.

    • --log-tcp-sequence — Writes the TCP sequence number for the packet in the log.

  • REJECT — Sends an error packet back to the remote system and drops the packet.

    The REJECT target accepts --reject-with (where is the rejection type) which allows more detailed information to be sent back with the error packet. The message port-unreachable is the default error given if no other option is used. For a full list of options that can be used, see the iptables man page.

Other target extensions, including several that are useful for IP masquerading using the natmangle table, can be found in the iptables man page. table or with packet alteration using the

16.3.7. Listing Options

The default list command, iptables -L, provides a very basic overview of the default filter table's current chains. Additional options provide more information:

  • -v — Display verbose output, such as the number of packets and bytes each chain has seen, the number of packets and bytes each rule has matched, and which interfaces apply to a particular rule.

  • -x — Expands numbers into their exact values. On a busy system, the number of packets and bytes seen by a particular chain or rule may be abbreviated using K (thousands), MG (billions) at the end of the number. This option forces the full number to be displayed. (millions), and

  • -n — Displays IP addresses and port numbers in numeric format, rather than the default hostname and network service format.

  • --line-numbers — Lists rules in each chain next to their numeric order in the chain. This option is useful when attempting to delete a specific rule in a chain, or to locate where to insert a rule within a chain.

  • -t — Specifies a table name.

Allow traffic
iptables allow you to allow traffic based on a number of different conditions, such as Ethernet interface, IP address, port and protocol.
Allowing incoming TCP traffic on port 22(ssh) for adapter eth0
iptables -A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT