March 3, 2015

replace systemd with a simple busybox inittab

1. install busybox
2. create file /etc/inittab with the following content:
# Start "rc init" on boot
::sysinit:/opt/rc init

# Set up the TTY's 1 through 4
tty1::askfirst:/sbin/agetty -8 -s 38400 tty1 linux
tty2::respawn:/sbin/agetty -8 -s 38400 tty2 linux

# Stop all services on shutdown
::shutdown:/opt/rc shutdown

# Killing everything on shutdown
::shutdown:echo :: sending SIGTERM to all
::shutdown:/bin/kill -s TERM -1
::shutdown:sleep 1
::shutdown:echo :: sending SIGKILL to all
::shutdown:/bin/kill -s KILL -1

# Unmount everything on shutdown
::shutdown:echo :: unmounting everything
::shutdown:/bin/umount -a -r
::shutdown:/bin/mount -o remount,ro /

3. ln -s /bin/busybox /opt/init
4. create /opt/rc with the following content:
#!/bin/sh
on_boot() {
    #===================
    # mount the API filesystem
    # /proc, /sys, /run, /dev, /run/lock, /dev/pts, /dev/shm
    echo 3 mounting API filesystem...
    mountpoint -q /proc    || mount -t proc proc /proc -o nosuid,noexec,nodev
    mountpoint -q /sys     || mount -t sysfs sys /sys -o nosuid,noexec,nodev
    mountpoint -q /run     || mount -t tmpfs run /run -o mode=0755,nosuid,nodev
    mountpoint -q /dev     || mount -t devtmpfs dev /dev -o mode=0755,nosuid
    mkdir -p /dev/pts /dev/shm
    mountpoint -q /dev/pts || mount -t devpts devpts /dev/pts -o mode=0620,gid=5,nosuid,noexec
    mountpoint -q /dev/shm || mount -t tmpfs shm /dev/shm -o mode=1777,nosuid,nodev

    #===================
    # initialize system
    echo 3 setting up loopback device...
    /usr/sbin/ip link set up dev lo

    echo 3 initializing udev...
        busybox mdev -s
        echo /sbin/mdev > /proc/sys/kernel/hotplug

    echo 3 setting hostname...
    cat /etc/hostname >| /proc/sys/kernel/hostname

    echo 3 mounting...
    mount -a
    mount -o remount,rw /

        dhclient eth0&
        /etc/init.d/ssh start&
}

on_shutdown() {
    #===================
    echo 3 shutting down udev...
        killall busybox
        killall mdev

    #===================
    # umount the API filesystem
    echo 3 unmounting API filesystem...
    umount -r /run
}

#===================
# handle arguments
case "$1" in
init)
    on_boot;;
shutdown)
    on_shutdown;;
esac

5. reboot and add the following parameter to your kernel command line on grub:
init=/opt/init

Enjoy

February 26, 2015

Golang parse xml simple example

package main

import (
        "encoding/xml"
        "fmt"
)

func main() {
        type Email struct {
                Where string `xml:",attr"`
                Addr  string
        }
        type Result struct {
                Email   []Email `xml:"email"`
        }
        v := Result{}

        data := `
        <person>
        <email where="home">
        <Addr>gre@example.com</Addr>
        </email>
        <email where='work'>
        <Addr>gre@work.com</Addr>
        </email>
        </person>
        `
        err := xml.Unmarshal([]byte(data), &v)
        if err != nil {
                fmt.Printf("error: %v", err)
                return
        }
        fmt.Printf("v: %#v\n", v)
}

February 23, 2015

Asynchronous PHP port scanner on Windows

The following PHP code scans IP range 192.168.204.200 to 192.168.204.254 port 443 in 5 seconds. It's tested on Windows with PHP 5.3, with php_socket extension enabled. 


<?php
$port = "443";
$timeout = 5;  //timeout in seconds

$write=array();
for ($i=200;$i<255;$i++){
$host="192.168.204.$i";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Unable to create socket\n");
socket_set_nonblock($socket) or die("Unable to set nonblock on socket\n");
$connected=@socket_connect($socket, $host, $port);
if (!$connected) {
$error = socket_last_error($socket);
if ($error != 10035 && $error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
socket_close($socket);
}else{
$write[]=$socket;
}
}
}

$count=0;
$write0=$write;
$mynil=NULL;
$timeout_us=0;
$endtime=microtime(true)+$timeout;
$address="";
while(true){
$ret=socket_select($mynil,$write,$mynil,$timeout,$timeout_us);
if ($ret==0){
die("Done. Total $count found.\n");
}
if ($ret>0){
foreach ($write as $sock){
socket_getpeername($sock,$address);
echo "$address\n";
$count++;
socket_close($sock);
}
$write=array_diff($write0,$write);
$write0=$write;
$newtimeout=$endtime-microtime(true);
$timeout=floor($newtimeout);
$timeout_us=$newtimeout-$timeout;
}
}

PHP asynchronous host scanner on Windows

The following PHP code scans IP range 192.168.5.1-192.168.5.254 in 3 seconds and returns the reachable hosts.

<?php
$timeout=3;

function ping($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket  = socket_create(AF_INET, SOCK_RAW, 1);
socket_connect($socket, $host, null);

$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
return $socket;
}

$read=array();
for ($i=1;$i<255;$i++){
$host="192.168.5.$i";
$socket=ping($host);
$read[]=$socket;
}

$read0=$read;
$mynil=NULL;
$timeout_us=0;
$endtime=microtime(true)+$timeout;
while(true){
$ret=socket_select($read,$mynil,$mynil,$timeout,$timeout_us);
if ($ret==0){
die("Done\n");
}
if ($ret>0){
foreach ($read as $sock){
$address="";
socket_getpeername($sock,$address);
echo "$address\n";
}
$read=array_diff($read0,$read);
$read0=$read;
$newtimeout=$endtime-microtime(true);
$timeout=floor($newtimeout);
$timeout_us=$newtimeout-$timeout;
}
}

February 18, 2015

use stunnel for ssl proxy

stunnel.conf: (this setup one server and one client instance)

debug = 3
#foreground = yes
pid =
[server]
client = no
cert= ./server.pem
accept = 127.0.0.1:443
connect = 127.0.0.1:4434
[client]
client = yes
accept = 127.0.0.1:4434
connect = api.opscode.com:443

February 14, 2015

How to run an X program on a headless Linux server



# apt-get install xvfb

# Xvfb -shmem -screen 0 1280x1024x24

 To test it you can run a following command:

# DISPLAY=:0 xdpyinfo


February 4, 2015

snmp manager for Windows and Mac

In addition to the paid version (iReasonsing mibbrowser) and agentpp's mib explorer, there is a free and open source version called snmpb: http://snmpb.sf.net. I have tried it out for a short time and it worked well for me. It includes walk/get/set/table-view and also an trap receiver.

wireshark display filters

by Joke Snelders

Display Filters

To show just traffic from/to a specific station, use

wlan.addr==00:01:02:03:04:05

or wlan.ta , wlan.ra, wlan.sa, wlan.da

  • Show only the beacon frames:
    wlan.fc.type_subtype == 0x08
  • Show everything except the beacon frames:
    !wlan.fc.type_subtype == 0x08
  • Show only beacon frames and ack frames:
    (wlan.fc.type_subtype == 0x08) || (wlan.fc.type_subtype == 0x1d) 
  • Show everything except the beacon and ack frames
    (!wlan.fc.type_subtype == 0x08) && (!wlan.fc.type_subtype == 0x1d)
You will find more information in the Wireshark User's Guide and in the Wireshark Wiki.

In the Wireshark Display Filter Reference you will find an overview of the field names.
On the website Will Hack For Sushi you can find a cheat sheet, the 802.11 Pocket Reference Guide, with the type codes you can use in combination with wlan.fc.type and wlan.fc.type_subtype.

You can download the 802.11 Pocket Reference Guide here.



Here are some examples of the Display Filter Fields and next you will learn how to use them as a display filter:
Frame typeFilter
Management frameswlan.fc.type eq 0
Control frameswlan.fc.type eq 1
Data frameswlan.fc.type eq 2

Frame subtypeFilter
Association requestwlan.fc.type_subtype eq 0
Association responsewlan.fc.type_subtype eq 1
Probe requestwlan.fc.type_subtype eq 4
Probe responsewlan.fc.type_subtype eq 5
Beaconwlan.fc.type_subtype eq 8
Authenticationwlan.fc.type_subtype eq 11
Deauthenticationwlan.fc.type_subtype eq 12

Display Filters
  • Show beacons:
    wlan.fc.type_subtype eq 8
  • Show everything except the beacons:
    not wlan.fc.type_subtype eq 8
  • Show probe requests or probe responses:
    wlan.fc.type_subtype eq 4 or wlan.fc.type_subtype eq 5
  • Show everything except the beacons, probe requests or probe responses:
    not wlan.fc.type_subtype eq 4 and not wlan.fc.type_subtype eq 5 and not wlan.fc.type_subtype eq 8


Capture filters
When you use a capture filter only the packets that match the filter are dumped  to a file. This will reduce the amount of data to be captured.

Capture filters have a different syntax than display filters.

You enter the capture filters into the Filter field of the Wireshark Capture Options dialog box and hit the Start button.

Here are some examples:

  • Capture only beacon frames:
    wlan[0] == 0x80
  • Capture everything except beacon frames:
    wlan[0] != 0x80
  • Capture only beacon frames and ack frames:
    wlan[0] == 0xd4
  • Capture everything except beacon frames and ack  frames:
    wlan[0] != 0x80 and wlan[0] != 0xd4
You can use a wlan type or a wlan subtype as a capture filter.
Let me give you some capture filter samples.

WLAN type
Valid wlan types are mgt, ctl and data.

Capture filter examples
  • Capture only management frames:
    type mgt
  • Capture everything except control frames:
    not type ctl
  • Capture data frames to/from mac address 04:1e:64:ea:c3:ef
    wlan host 04:1e:64:ea:c3:ef and type data

WLAN subtype
Management frames
Valid subtypes are:
assocreq,  assocresp,  reassocreq,  reassocresp,  probereq, probresp, beacon, atim, disassoc, auth and deauth

Control frames
Valid subtypes are:
ps-poll, rts, cts, ack, cf-end and cf-end-ack

Data frames
Valid subtypes are:
data,  data-cf-ack,  data-cf-poll, data-cf-ack-poll, null, cf-ack, cf-poll, cf-ack-poll,  qos-data,  qos-data-cf-ack,  qos-data-cf-poll, qos-data-cf-ack-poll, qos, qos-cf-poll and qos-cf-ack-poll

Capture filters examples
  • Capture only beacons:
    subtype beacon
  • Capture everything except beacons:
    not subtype beacon
  • Capture beacons, probe requests and probe responses:
    subtype beacon or subtype probereq or subtype proberesp
  • Capture all frames except beacons, probe requests and probe responses:
    not subtype beacon and not subtype probereq and not subtype proberesp
  • Capture beacons, probe requests and probe responses to/from host 00:0c:f6:69:f8:69:
    (wlan host 00:0c:f6:69:f8:69 and subtype beacon) or (wlan host 00:0c:f6:69:f8:69 and subtype probereq) or (wlan host 00:0c:f6:69:f8:69 and subtype proberesp)

    You can also use this capture filter:

    wlan host 00:0c:f6:69:f8:69 and (subtype beacon or subtype probereq or subtype proberesp)
  • Capture probe requests from wlan host 00:0c:f6:69:f8:69 and probe responses from wlan host: 00:24:2c:69:f8:69
    (wlan host 00:0c:f6:69:f8:69 and subtype probereq) or (wlan host 00:24:2c:69:f8:69 and subtype proberesp)
  • Capture beacons, probe requests and probe responses to/from host 00:0c:f6:69:f8:69 or to/from host 00:24:2c:69:f8:69:
    (wlan host 00:0c:f6:69:f8:69 or wlan host 00:24:2c:69:f8:69) and (subtype beacon or subtype probereq or subtype proberesp)
  • Capture all packets from wlan src 00:24:2c:69:f8:69 except beacons, probe requests and probe responses:
    wlan src 00:24:2c:69:f8:69 and not subtype beacon and not subtype probereq and not subtype proberesp
  • Capture all association requests/responses, reassociation requests/responses, disassociation and (de)authentication frames and all eapols:
    (subtype assocreq or subtype assocresp or subtype reassocreq or subtype reassocresp or subtype disassoc or subtype auth or subtype deauth) or (ether proto 0x888e)
  • Capture all eapols, association requests/responses, reassociation requests/responses, disassociation and (de)authentication frames to/from wlan host 00:0c:f6:69:f8:69 or wlan host 00:24:2c:69:f8:69:
    (wlan host 00:0c:f6:69:f8:69 or wlan host 00:24:2c:69:f8:69) and (ether proto 0x888e or subtype assocreq or subtype assocresp or subtype reassocreq or subtype reassocresp or subtype disassoc or subtype auth or subtype deauth)
  • Capture all frames to/from wlan host 00:0c:f6:69:f8:69 or wlan host 00:24:2c:69:f8:69:
    wlan host 00:0c:f6:69:f8:69 or wlan host 00:24:2c:69:f8:69

Interesting links:
Understanding 802.11 Frame Types by Jim Geier
Ubuntu manual
Wireless Communications by Martin Land
WildPackets: Wireless LAN Overview
Packetstan: A blog about packets, tools, and bacon

  
Save the display and capture filters to file for future use
File dfilters
To save the display filters for future use you can modify the file dfilters. 
In Windows XP the file dfilters is located at:
C:\Documents and Settings\<user>\Application Data\Wireshark\dfilters
In Windows 7 or Windows Server 2008 at:
C:\Users\<user>\AppData\Roaming\Wireshark\dfilters
Notes:
  • You have to turn on "Show Hidden Files, Folders, and drives" to see the AppData folder:
    go to Control Panel\All Control Panel Items -> Folder Options -> View -> Show Hidden Files, Folders, and drives.
  • If there is no file dfilters at this location, you can copy and paste the file from C:\Program Files\Wireshark\dfilters to C:\Users\<user>\AppData\Roaming\Wireshark\dfilters.
  • The file dfilters has no extension.
Open the file dfilters with Notepad.
Copy and paste the following text to dfilters:
"WLAN DISPLAY FILTERS" HEADER
"    Beacon Frames" wlan.fc.type_subtype == 0x08
"    No Beacon Frames" !wlan.fc.type_subtype == 0x08
"    Beacon Frames or Ack's" (wlan.fc.type_subtype == 0x08) || (wlan.fc.type_subtype == 0x1d)
"    No Beacon Frames and No Ack" (!wlan.fc.type_subtype == 0x08) && (!wlan.fc.type_subtype == 0x1d)

Make sure to end the file with an empty line, otherwise you won't see the last filter.

File cfilters
Repeat the steps above to modify the file cfilters.

Copy and paste the following text to cfilters:
"WLAN CAPTURE FILTERS" HEADER
"    Capture only Ethernet type EAPOL" ether proto 0x888e
"    Beacon Frames" wlan[0] == 0x80
"    No Beacon Frames" wlan[0] != 0x80
"    Probe Requests" wlan[0] == 0x40
"    No Probe Requests" wlan[0] != 0x40
"    Probe Response" wlan[0] == 0x50
"    No Probe Response" wlan[0] != 0x50
"    Ack" wlan[0] == 0xd4
"    No Ack" wlan[0] != 0xd4
"    CF-End" wlan[0] == 0xe4
"    No CF-End" wlan[0] != 0xe4
"    Clear-to-send" wlan[0] == 0xc4
"    No Clear-to-send" wlan[0] != 0xc4
"    Beacon Frames - Probe Response/Request - Ack" wlan[0] == 0x80 or wlan[0] == 0x50 or wlan[0] == 0x40 or wlan[0] == 0xd4
"    No Beacon Frames - No Probe Response/Request - No Ack" wlan[0] != 0x80 and wlan[0] != 0x50 and wlan[0] != 0x40 and wlan[0] != 0xd4
"    Beacon Frames-Probe Resp/Req-Ack-CF-End-Clear-to-send" wlan[0] == 0x80 or wlan[0] == 0x50 or wlan[0] == 0x40 or wlan[0] == 0xd4 or wlan[0] == 0xe4 or wlan[0] == 0xc4
"    No Beacon Frames-Probe Resp/Req-Ack-CF-End-Clear-to-send" wlan[0] != 0x80 and wlan[0] != 0x50 and wlan[0] != 0x40 and wlan[0] != 0xd4 and wlan[0] != 0xe4 and wlan[0] != 0xc4

After you have edited the files and restarted Wireshark the new filters show up in the "Display Filters" and "Capture Filters" dialog boxes.

The original post: http://www.lovemytool.com/blog/2010/07/wireshark-wireless-display-and-capture-filters-samples-part-2-by-joke-snelders.html


January 30, 2015

wifi channel and frequency list

Channel Frequency(MHz)
1 2412
2 2417
3 2422
4 2427
5 2432
6 2437
7 2442
8 2447
9 2452
10 2457
11 2462
12 2467
13 2472
14 2484
36 5180
40 5200
44 5220
48 5240
52 5260
56 5280
60 5300
64 5320
100 5500
104 5520
108 5540
112 5560
116 5580
120 5600
124 5620
128 5640
132 5660
136 5680
140 5700
149 5745
153 5765
157 5785
161 5805
165 5825

5Ghz WiFi Channels (US)


Source: http://www.revolutionwifi.net/blog/?month=april-2014&view=calendar

convert pdf to png gray

gs -sDEVICE=pnggray -sOutputFile=page-%03d.png -r600x600   -f test-ecg.pdf

December 18, 2014

Install a minimal X on Linux

apt-get install xinit i3 rxvt

i3 is the lightweight window manager
rxvt is the terminal
xinit gives you X windows and the famous "startx" command

To make i3 use your full screen resolution, create the file ~/.xinitrc and put the following there

xrandr --output Virtual1 --mode 1680x1050
exec i3


You may need to change the name "Virtual1" to something else. Use xrandr to list all the known windows (you first need to have X windows  running though)

December 9, 2014

p11tool, gnutls and PIV CAC card

p11tool --list-all-certs

p11tool --login --export "pkcs11:model=PKCS%2315%20emulated;manufacturer=piv_II;serial=36889385781093f6;token=PIV_II%20%28PIV%20Card%20Holder%20pin%29;id=%02;object=Certificate%20for%20Digital%20Signature;object-type=cert" > /tmp/02.cert

p11tool --list-all-privkeys --login



x509 certificate subject name and OID

In a X509 certificate, there is always a subject name like the following:

$ openssl x509 -in user-cert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1373122324 (0x51d82f14)
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=CA
        Validity
            Not Before: Jul  6 14:52:05 2013 GMT
            Not After : May 15 14:52:05 2023 GMT
        Subject: UID=test,CN=A user

Inside the subject line, there can be multiple subparts, such as CN=xxx, DC=xxxx, UID=xxx, OU=xxx, C=xxx, ... Each subpart is represented in the certificate as an OID that is globally unique and registred with IETF. For example, the OID of CN is 2.5.4.3, and the OID of UID is 0.9.2342.19200300.100.1.1. How are we supposed to find out the OID? Openssl provides a command option for just.  

openssl x509 -in user-cert.pem -text -noout -nameopt RFC2253,oid

This command will print out the cert with the OID=xxx instead of CN=xxx.

December 8, 2014

cross compile openconnect

Openconnect is a nice open source SSL VPN client for Cisco AnyConnect, and also for the open source SSL vpn server ocserv (hosted on the same website as openconnect). Below are some tips on how to cross compile openconnect for ARM, with GnuTLS

Openconnect works with both Openssl and GnuTLS. However, to use hardware token (smart card, etc), you will need GnuTLS.

Dependencies:

Openconnect depends on GnuTLS (3.3.9)
GnuTLS depends on libnettle, and libhogweed 2.7.1 (both in the nettle package)
libnettle depends on gnu GMP (libgmp, version 6.0.0)

To use hardware token, GnuTLS also depends on p11-kit (version 0.22.1) and pcsc-lite (version 1.8.11), and opensc (0.14.0), which depends on pcsc-lite.

All of these packages support autoconfig so that one can run "configure" to generate the makefile(s).  We use the --prefix "/opt/ncs-install" to install all packages. Below are the customized "configure" scripts for each package:

p11-kit-0.22.1:
CC=arm-none-linux-gnueabi-gcc CXX=arm-none-linux-gnueabi-g++ ./configure --host=arm-linux --prefix=/opt/ncs-install \
        --without-libffi --without-libtasn1

gmp-6.0.0:
CC=arm-none-linux-gnueabi-gcc CXX=arm-none-linux-gnueabi-g++ ./configure --host=arm-linux --prefix=/opt/ncs-install

nettle-2.7.1:
CFLAGS=-I/opt/ncs-install/include LDFLAGS=-L/opt/ncs-install/lib CC=arm-none-linux-gnueabi-gcc CXX=arm-none-linux-gnueabi-g++ ./configure --host=arm-linux --prefix=/opt/ncs-install

pcsc-lite-1.8.11:
CFLAGS="-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include/"
CC=arm-none-linux-gnueabi-gcc ./configure -host=arm-linux  --disable-libudev --enable-libusb \
        LIBUSB_CFLAGS="-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include/libusb-1.0/ -L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib"  \
        LIBUSB_LIBS="-lusb-1.0"

/opensc-0.14.0:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export LTLIB_LIBS="-L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib/ -lltdl"
export PCSC_CFLAGS="-I$DIR/../pcsc-lite-1.8.11/src/PCSC"
export LIBTOOL_SYSROOT_PATH=/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/
export CFLAGS="-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include -L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib"
export LDFLAGS="-lcrypto"
export CC=arm-none-linux-gnueabi-gcc
./configure -host=arm-linux  -v

gnutls-3.3.9:
CFLAGS=-I/opt/ncs-install/include LDFLAGS=-L/opt/ncs-install/lib \
ZLIB_CFLAGS=-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include/ \
ZLIB_LIBS="-L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib -lz" \
CC=arm-none-linux-gnueabi-gcc CXX=arm-none-linux-gnueabi-g++ ./configure --host=arm-linux --prefix=/opt/ncs-install \
 --with-nettle-mini --disable-crywrap \
 --with-p11-kit \
 --with-default-trust-store-file=/etc/ssl/certs/ca-certificates.crt


openconnect-7.00:
LIBPCSCLITE_CFLAGS=-I/opt/ncs-install/include/PCSC/ \
LIBPCSCLITE_LIBS="-L/opt/ncs-install/lib -lpcsclite" \
LIBXML2_CFLAGS=-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include/libxml2/ \
LIBXML2_LIBS="-L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib -lxml2" \
CFLAGS=-I/opt/ncs-install/include LDFLAGS=-L/opt/ncs-install/lib  \
LDFLAGS="-L/opt/ncs-install/lib -lp11-kit -lnettle -lhogweed -lgmp" \
ZLIB_CFLAGS=-I/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/include/ \
ZLIB_LIBS="-L/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/usr/lib -lz" \
CC=arm-none-linux-gnueabi-gcc ./configure --prefix=/opt/install --disable-nls --host=arm-linux --without-openssl --with-gnutls


December 4, 2014

how to verify certificate signed by intermediate CA

 openssl verify -untrusted intermediate-ca.pem your-cert.pem

Put the list of intermediate CA (in PEM format, concatenated ) in intermediate-ca.pem, and use the "-untrusted" option. That name tricked me initially, and that's the one to use. 

The above command is to use the system CA list to verify the cert. If you have your own CA, just use the option "-CAfile your-ca.pem".

November 25, 2014

How to make IE not cache your golang web app responses

var w http.ResponseWriter
w.Header().Set("cache-control", "priviate, max-age=0, no-cache")
w.Header().Set("pragma", "no-cache")
w.Header().Set("expires", "-1")

November 24, 2014

Clear windows event log

Run this following line in PowerShell as Admin:

wevtutil el | Foreach-Object {Write-Host "Clearing $_"; wevtutil cl "$_"}

November 19, 2014

Read godoc in vim using Shift K

Add the following to your ~/.vim/ftplugin/go.vim (the key here is to use <cfile> not <cword>)

fun! ReadMan()
  " Assign current file under cursor to a script variable:
  let s:man_word = expand('<cfile>')
  :exe ":Godoc " . s:man_word
endfun
" Map the K key to the ReadMan function:
map K :call ReadMan()<CR>

=======UPDATE========
Had a better way for this:

1. Create a file in your ~/bin called godoc.sh with the following content:
#!/bin/sh
fullpkg=`gawk -v "cmd=$1" '
{ FS="/" }
{
        if ($NF==cmd || $0 ==cmd){
                printf("%s",$0);
                exit;
        }
}' ~/bin/gopkg-list.txt`
echo -n $fullpkg

2. Create a text file in ~/bin/gopkg-list.txt with the following contents:
log/syslog
unicode/utf8
unicode/utf16
testing
hash/crc64
hash/adler32
hash/fnv
hash/crc32
archive/zip
archive/tar
expvar
mime
reflect
crypto/des
crypto/sha1
crypto/subtle
crypto/aes
crypto/md5
crypto/cipher
crypto/rand
crypto/ecdsa
crypto/tls
crypto/sha512
crypto/x509
crypto/sha256
crypto/elliptic
crypto/hmac
crypto/rsa
crypto/x509/pkix
crypto/rc4
crypto/dsa
flag
strings
sync
os/user
os/signal
os/exec
os
fmt
syscall
time
runtime/pprof
runtime/cgo
runtime/debug
runtime/race
net/http/httputil
net/http/cookiejar
net/http/fcgi
net/http/pprof
net/http/cgi
net/http/httptest
net/rpc/jsonrpc
net/mail
net/http
net/textproto
net/url
net/rpc
net/smtp
io/ioutil
math
database/sql/driver
database/sql
mime/multipart
bytes
errors
sort
bufio
encoding
log
path/filepath
index/suffixarray
net
crypto
sync/atomic
go/printer
go/doc
go/scanner
go/ast
go/parser
go/token
go/build
go/format
unicode
image
io
runtime
html/template
regexp
html
container/ring
container/list
container/heap
hash
path
regexp/syntax
text/template/parse
text/tabwriter
text/template
text/scanner
strconv
testing/quick
testing/iotest
compress/flate
compress/zlib
compress/lzw
compress/bzip2
compress/gzip
image/color
image/draw
image/color/palette
image/png
image/gif
image/jpeg
encoding/base64
encoding/base32
encoding/xml
encoding/asn1
encoding/pem
encoding/ascii85
encoding/csv
encoding/hex
encoding/json
encoding/binary
encoding/gob
debug/pe
debug/plan9obj
debug/dwarf
debug/elf
debug/gosym
debug/macho
math/rand
math/big
math/cmplx

3. In your ~/.vim/ftplugin/go.vim, add the following:
fun! ReadMan()
  " Assign current file under cursor to a script variable:
  let s:man_word = expand('<cword>')
  let s:full_word = system('~/bin/godoc.sh '. s:man_word)
  :exe ":Godoc " . s:full_word
endfun
" Map the K key to the ReadMan function:
map K :call ReadMan()<CR>

This will take the keyword under cursor, expanded using the shell script, and call :Godoc on it. This takes care of subpackages

November 14, 2014

ios validate self signed certificate

http://stackoverflow.com/questions/10979922/ios-and-ssl-unable-to-validate-self-signed-server-certificate

Quote:


I did figure out how to resolve this issue.
I ended up comparing the client and server trust certificates, byte-by-byte. Although there could be another way to resolve such issues of self-signed certificate, but for this solution did work. Here is how I'm doing comparison of the client and server certificates, byte-by-byte, using their CFData objects(you can also reference 'AdvancedURLConnections' example code provided by Apple):
success = NO;
        pServerCert = SecTrustGetLeafCertificate(trust);
        if (clientCert != NULL) {
            CFDataRef       clientCertData;
            CFDataRef       serverCertData;

            clientCertData = SecCertificateCopyData(clientCert);
            serverCertData   = SecCertificateCopyData(pServerCert);

            assert(clientCertData != NULL);
            assert(serverCertData   != NULL);

            success = CFEqual(clientCertData, serverCertData);

            CFRelease(clientCertData);
            CFRelease(serverCertData);
        }
        if (success) {
            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
            [self printLogToConsole:@"Success! Trust validation successful."];
        } else {
            [self printLogToConsole:@"Failed! Trust evaluation failed for service root certificate.\n"];
            [[challenge sender] cancelAuthenticationChallenge:challenge];
        }
Hope this will help someone, who is looking for solution of similar issue,

November 12, 2014

the ffmpeg command to explode video into still images

ffmpeg.exe -i IMG_0278.MOV -ss 0  -t 1 -f image2 -sameq -vcodec mjpeg "img-%03d.jpg"

-ss: start time, 0 means starting at 0 second mark
-t : number of seconds to explode


November 6, 2014

vim and error list

If you have text file that contains the list of errors with line positions, you can tell vim to use that to help you navigate through the list.

1. Edit the list to the following format (suppose it is named "errors.txt")
    xxxx.c:123: Warning/Error/Info rest-of-the-text
    where
    xxxx.c is the source code file name
    123 is the line number

2. vim -q errors.txt

3. now you can type ":cw" to open the "quickfix" window which list the errors, and use ":cn" and ":cp" to go through them. Mapping these to a short cut key will make life easier. I map mine to Ctrl-j and Ctrl-k for down and up (copy and the paste the following to your ~/.vimrc file)

    map <C-J> :cn<CR>
    map <C-K> :cp<CR>

November 5, 2014

check ip address owner

For an U.S IP address, you can go to the following site:

http://whois.arin.net

and put the IP address in the search box of top right corner, and you can get more info on it.

Once you find the owner, you can click on "Related Networks" to find all the IP addresses that owner owns.

November 3, 2014

How to dump Mac OS X dns cache

DNS cache information is not managed by Directory Services, contrary to popular opinion on this site. It's managed by mDNSResponder, and the man page contains the answer to your question:


A SIGINFO signal will dump a snapshot summary of the internal state to /var/log/system.log:

   % sudo killall -INFO mDNSResponder

October 31, 2014

Windows Active Directory (AD) LDAP binding account

The common way to bind to AD as an LDAP server is to use "Distinguished Name(DN)" and Password. The DN usually is in the form of:  CN=username,CN=Users,DC=yourdomain,DC=com

To find out DN, you can use Sysinternal's Active Directory Explorer to connect to AD and browse to the user to find out.

According to this post on stackoverflow, http://serverfault.com/questions/497368/ldap-activedirectory-binddn-syntax, you can also use UPN, which typically has the value of:

<sAMAccountName>@<domain FQDN>


Linux Frame buffer screen capture

1. Calculate the screen size. For example 1920 x 1080. Make sure that the width is a multiple of 4. For example, for HD screen resolution of 1366x768,  use 1368x768

2. dd if=/dev/fb1 bs=1368 count=3072 | gzip -c > screen.bgra.gz
   Each pixel is 4 byte, B-G-R-A. So 1368x768 resolution takes 1368*768*4=1368*3072 bytes

3. transfer the file to a Linux computer with imagemagick installed (needs a version released after 2010), and then convert it:
   gunzip screen.bgra.gz
   convert -size 1368x768 -depth 8 screen.bgra screen.png

Kerberos simplified

The 6 steps of Kerberos

Players:
  User
  Service (Can be any service that user wants to access, such as mail service)
  Kerberos Authentication Service (AS)
  Kerberos Ticket Granting Service (TGS)
  

                                      +--------------------+----------------------+
                                      |                    |                      |
                                      |     Kerberos AS    |     Kerberos TGS     |
                                      |                    |                      |
                                      +---------+----------+--------+-------------+
                                         ^      |              ^    |
                                         |      |              |    |
                                       1 |      |2           3 |    | 4
                                         |      |              |    |
                                         |      |              |    |
      +-------------------+              |      |              |    |                       +-----------------------+
      |                   |--------------+      |              |    |                       |                       |
      |                   |<--------------------+              |    |                       |                       |
      |                   +------------------------------------+    |                       |                       |
      |      User         |<----------------------------------------+         5             |     Mail Service      |
      |                   +---------------------------------------------------------------->|                       |
      |                   |<----------------------------------------------------------------+                       |
      +-------------------+                                                   6             +-----------------------+



Step 1: User          ---- Username, Timestamp                                               ----> Kerberos AS
Step 2: Kerberos AS   ---- TGT=[K(user,tgs)<-P(tgs)], K(user,tgs)<-P(user)                   ----> User
Step 3: User          ---- TGT<-P(tgs), user_name, service_name, authenticator<-K(user,tgs)  ----> Kerberos TGS
Step 4: Kerberos TGS  ---- ST=[K(user,service)<-P(service)], K(user,service)<-K(user,tgs)    ----> User
Step 5: User          ---- ST<-P(service), user_name, authenticator<-K(user,service)         ----> Service
Step 6: Service       ---- OK, authenticator<-K(user,service)                                ----> User


Authenticator = (sender_name, sender_address, timestamp, lifespan) <- SessionKey

K(user,tgs) : a session key, randomly generaged by Kerberos, shared betwee user and TGS
P(tgs)      : a key based on the password of the tgs service. It's a password known only by the tgs service
P(user)     : a key based on the password of the user
K(user,tgs)<-P(user) : meaning that K(user,tgs) is encrypted with the key of P(user)
TGT         : Ticket Granting Ticket. It's just a token that needed for the user to talk to TGS. It contains
              a session key known only by user and TGS.

Keytab files
In kerberos step 1, users can enter password to obtain the TGT from Kerberos TGS, what about services/devices? Kerberos allow the value P(user) to be exported and saved to a file, usually named keytab. This allows the service to authenticate users without talking to Kerberos server.

A really helpful story telling about Kerberos the authentication mechanism

http://web.mit.edu/kerberos/dialogue.html

I have read quite a few articles about Kerberos. Among them the above dialog is the most helpful. It does not hurt that it came from the original authors who help designed Kerberos.

October 17, 2014

Windows Server LDAP MaxPwdAge, MinPwdAge

When using AD Explorer software to query Windows Server, on a particular domain, you can see the maximum and minimum days required for password to change. These values show up as HEX values such as:

Max: 0xFFFFDEFF0AA68000
Min: 0xFFFFFF36D5964000

This is how to convert them to actual days:

( 0xFFFFFF36D5964000 - <64-bit value> ) / 0xC92A69C000 + 1 = answer ( in days)

Basically, the time unit here is 100ns (See http://en.wikipedia.org/wiki/System_time to see how Windows use 100ns as their system time unit). So
   1 day is 24*3600*10,000,000 = 864000000000 = 0xC92A69C000

Starting from an unsigned 64-bit 0 value,
1 day = 0 - 0xC92A69C000 = 0xFFFFFF36D5964000
2 day2 = 0xFFFFFF36D5964000   - 0xC92A69C000  = 0xFFFFFE6DAB2C8000
3 days = 0xFFFFFDA480C2C000
...
41 days = 0xFFFFDFC835104000
42 days = 0xFFFFDEFF0AA68000
43 days = 0xFFFFDE35E03CC000
44 days = 0xFFFFDD6CB5D30000
...
89 days = 0xFFFFBA10413C4000
90 days = 0xFFFFB94716D28000

So for the above example:

Max: 42 days
Min: 1 day

October 16, 2014

If you have a computer that joins to a domain, you can use LDAP to bind to the domain name controller and find a lot of information. Here is how you do it:

1. open a "cmd" window, and do: echo %logonserver% . This tells you the domain controller's name
2. download sysinternals AD explorer software, and connect to the domain controller
3. On the left tree, suppose your company's domain is abc.com, click on "DC=abc,DC=com"
4. In the subtree, click on "OU=...", and keep click on "OU=..." in the subtrees, until your find all the users with "CN=...". There you can see all the users of the domain, and all other information.