8.13.2015

How to Create and Use SSL Certificates

From this post.
1. ~]$ mkdir CA
2. ~]$ cd CA
3. CA]$ mkdir newcerts private
4. CA]$ echo '01' >serial
5. CA]$ touch index.txt

Create a Root Certificate

6. CA]$ vi openssl.cnf # # OpenSSL configuration file. # # Establish working directory. dir = . [ ca ] default_ca = CA_default [ CA_default ] serial = $dir/serial database = $dir/index.txt new_certs_dir = $dir/newcerts certificate = $dir/cacert.pem private_key = $dir/private/cakey.pem default_days = 365 default_md = md5 preserve = no email_in_dn = no nameopt = default_ca certopt = default_ca policy = policy_match [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional [ req ] default_bits = 1024 # Size of keys default_keyfile = key.pem # name of generated keys default_md = md5 # message digest algorithm string_mask = nombstr # permitted characters distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] # Variable name Prompt string #---------------------- ---------------------------------- 0.organizationName = Organization Name (company) organizationalUnitName = Organizational Unit Name (department, division) emailAddress = Email Address emailAddress_max = 40 localityName = Locality Name (city, district) stateOrProvinceName = State or Province Name (full name) countryName = Country Name (2 letter code) countryName_min = 2 countryName_max = 2 commonName = Common Name (hostname, IP, or your name) commonName_max = 64 # Default values for the above, for consistency and less typing. # Variable name Value #------------------------------ ------------------------------ 0.organizationName_default = The Sample Company localityName_default = Metropolis stateOrProvinceName_default = New York countryName_default = US [ v3_ca ] basicConstraints = CA:TRUE subjectKeyIdentifier = hash authorityKeyIdentifier = keyid:always,issuer:always [ v3_req ] basicConstraints = CA:FALSE subjectKeyIdentifier = hash 7. CA]$ openssl req -new -x509 -extensions v3_ca -keyout private/cakey.pem -out cacert.pem -days 3650 -config ./openssl.cnf Generating a 1024 bit RSA private key ....................++++++ ................++++++ writing new private key to 'private/cakey.pem' Enter PEM pass phrase:demo Verifying - Enter PEM pass phrase:demo ----- 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. ----- Organization Name (company) [The Sample Company]:My Company Organizational Unit Name (department, division) []:CA Division Email Address []:ca@sample.com Locality Name (city, district) [Metropolis]:Santa Clara State or Province Name (full name) [New York]:California Country Name (2 letter code) [US]: Common Name (hostname, IP, or your name) []:TSC Root CA

Create a Certificate Signing Request

8. CA]$ openssl req -new -nodes -out req.pem -config ./openssl.cnf Generating a 1024 bit RSA private key ...++++++ .....................++++++ writing new private key to 'key.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. ----- Organization Name (company) [The Sample Company]:My Company Organizational Unit Name (department, division) []:Web Server Email Address []:ca@test.com Locality Name (city, district) [Metropolis]:Santa Clara State or Province Name (full name) [New York]:California Country Name (2 letter code) [US]:US Common Name (hostname, IP, or your name) []:hostname.domain.com

Sign a Certificate

9. CA]$ openssl ca -out cert.pem -config ./openssl.cnf -infiles req.pem Using configuration from ./openssl.cnf Enter pass phrase for ./private/cakey.pem:demo Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows organizationName :PRINTABLE:'My Company' organizationalUnitName:PRINTABLE:'Web Server' localityName :PRINTABLE:'Santa Clara' stateOrProvinceName :PRINTABLE:'California' countryName :PRINTABLE:'US' commonName :PRINTABLE:'hostname.domain.com' Certificate is to be certified until Aug 12 18:22:03 2016 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 Data Base Updated 10. CA]$ cat key.pem cert.pem >key-cert.pem 11. CA]$ ls *.pem cacert.pem cert.pem key-cert.pem key.pem req.pem

Deploy Certificate

12. Copy the appropriate files, usually cert.pem and key.pem to the location where the certificates will be used as specified by the application.

8.12.2015

Rails configure Webrick to use SSL

Came from this post. Change bin/rails to be...

To generate certificates, follow this post.

#!/usr/bin/env ruby

require 'rails/commands/server'
require 'rack'
require 'webrick'
require 'webrick/https'

if ENV['SSL'] == "true"
  module Rails
      class Server < ::Rack::Server
          def default_options
              super.merge({
                  :Port => 3001,
                  :environment => (ENV['RAILS_ENV'] || "development").dup,
                  :daemonize => false,
                  :debugger => false,
                  :pid => File.expand_path("tmp/pids/server.pid"),
                  :config => File.expand_path("config.ru"),
                  :SSLEnable => true,
                  :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
                  :SSLPrivateKey => OpenSSL::PKey::RSA.new(
                                   File.open("certs/key.pem").read),
                  :SSLCertificate => OpenSSL::X509::Certificate.new(
                                   File.open("certs/cert.pem").read),
                  :SSLCertName => [["CN", WEBrick::Utils::getservername]],
              })
          end
      end
  end
end

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'
For self-signed certificates as outlined here.
#!/usr/bin/env ruby

require 'rails/commands/server'
require 'rack'
require 'webrick'
require 'webrick/https'

if ENV['SSL'] == "true"
  module Rails
      class Server < ::Rack::Server
          def default_options
              super.merge({
                  :Port => 3001,
                  :environment => (ENV['RAILS_ENV'] || "development").dup,
                  :daemonize => false,
                  :debugger => false,
                  :pid => File.expand_path("tmp/pids/server.pid"),
                  :config => File.expand_path("config.ru"),
                  :SSLEnable => true,
                  :SSLCertName => [["CN", WEBrick::Utils::getservername]],
              })
          end
      end
  end
end

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'
Then run server as...
$ SSL=true rails s

A Simple Ruby DSL

It's very easy to create a new language with ruby, here's a simple DSL
class SleepActivity

  def initialize(name)
    @name = name
  end

  def start(&block)
    sleep 1
    puts "#{@name} goes to bed"
    instance_eval &block if block_given?
  end

  def slumber(&block)
    sleep 1
    puts "#{@name} is starting to sleep"
    instance_eval &block if block_given?
  end

  def cycle(period, &block)
    sleep 1
    period.times do |time|
      puts "Sleep cycle #{time + 1}:"
      instance_eval &block if block_given?
    end
  end

  def awake(duration)
    sleep 1
    puts "Still awake for #{duration} minutes"
  end

  def light_sleep(duration)
    sleep 1
    puts "Sleeping lightly for #{duration} minutes"
  end

  def deep_sleep(duration)
    sleep 1
    puts "Sleeping deeply for #{duration} minutes"
  end

  def rem(duration)
    sleep 1
    puts "REM for #{duration} minutes"
  end

end

if $PROGRAM_NAME == __FILE__
  sleep_activity = SleepActivity.new("Sam")
  sleep_activity.start do
    awake 5
    slumber do
      cycle 5 do
        light_sleep 20
        deep_sleep 60
        rem 10
      end
    end
  end
end
Here's the output
samdc@mango:~/dev/ruby/projects/dsl$ ruby dsl_interpreter.rb 
Sam goes to bed
Still awake for 5 minutes
Sam is starting to sleep
Sleep cycle 1:
Sleeping lightly for 20 minutes
Sleeping deeply for 60 minutes
REM for 10 minutes
Sleep cycle 2:
Sleeping lightly for 20 minutes
Sleeping deeply for 60 minutes
REM for 10 minutes
Sleep cycle 3:
Sleeping lightly for 20 minutes
Sleeping deeply for 60 minutes
REM for 10 minutes
Sleep cycle 4:
Sleeping lightly for 20 minutes
Sleeping deeply for 60 minutes
REM for 10 minutes
Sleep cycle 5:
Sleeping lightly for 20 minutes
Sleeping deeply for 60 minutes
REM for 10 minutes

7.21.2015

Bash Cheat Sheet

1. Run a script with no output and in the background
$ ./my_script.sh > /dev/null 2>&1 &

2.  Run a script with no output and in the background and see the pid
$ ./my_script.sh > /dev/null 2>&1 & echo $!

3. Template script that loops thru and writes to a file
#!/bin/bash

# $1 - number of minutes
# $2 - task id
COUNTER=$(($1*60/5))
TOTAL=$COUNTER
echo Perfload will run for $1 minutes
echo "Perfload will run for $1 minutes" > /tmp/$2.log
until [  $COUNTER -eq 0 ]; do
    echo The counter is $COUNTER
    PROGRESS=$(echo "scale=2;($TOTAL - $COUNTER)*100/$TOTAL" | bc -l)
    echo "Perfload RUNNING $PROGRESS %" >> /tmp/$2.log
    let COUNTER-=1
    sleep 5
done
echo "Perfload SUCCESS" >> /tmp/$2.log


7.14.2015

Cisco Switch Cheat Sheet


sho lldp neighbors
sho cdp ne

switch-name# show mac address-table | i 0060.165c.f83e
* 2016     0060.165c.f83e    dynamic     ~~~      F    F  Eth1/22

switch-name# sho int description | grep 'yogi34 eth4b'
Eth8/19       eth    10G     yogi34 eth4b 90E2BA068BB1

switch-name# show interface ethernet 2/27 description
-------------------------------------------------------------------------------
Port          Type   Speed   Description
-------------------------------------------------------------------------------
Eth2/27       eth    10G     artemis59-eth3b 0060.1645.505a

switch-name(config)# config
switch-name(config)# int e8/19
switch-name(config-if)# inherit port-profile Apposite
switch-name(config-if)# exit
switch-name(config)# exit
switch-name# copy run startup-config

switch-name# show interface ethernet 1/28 switchport

# If missing VLANs, can set using...
switch-name(config-if)# switchport trunk allow vlan 2016,2030-2049

5.15.2015

Configure VLAN tagging via CLI

1. Create VLAN interface
# ip link add link eth4 name eth4.2030 type vlan id 2030

2. Assign IP
# ifconfig eth4.2030 11.0.20.1 netmask 255.255.240.0

3. Make sure new interface is enabled
# ifconfig eth4.2030 up

4. Check 
# ifconfig eth4.2030
eth4.2030 Link encap:Ethernet  HWaddr 90:E2:BA:6D:B5:95
          inet addr:11.0.20.1  Bcast:11.0.31.255  Mask:255.255.240.0
          inet6 addr: fe80::92e2:baff:fe6d:b595/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:10 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1046 (1.0 KiB)  TX bytes:468 (468.0 b)

5. Remove VLAN
# ip link delete eth4.2030

4.29.2015

Sync Clock Automatically on CentOS

Got it from here.
1. Install
# yum install ntp ntpdate ntp-doc

2. Turn on service
# chkconfig ntpd on

3. Sync one time
# ntpdate pool.ntp.org

4. Configure ntpd
# vi /etc/ntp.conf
Add public servers
server 0.rhel.pool.ntp.org
server 1.rhel.pool.ntp.org
server 2.rhel.pool.ntp.org

5. Start the NTP server. The following will continuously adjusts system time from upstream NTP server. No need to run ntpdate:
# /etc/init.d/ntpd start