December 27, 2012

putty and gnu screen scroll back with mouse


Summary: add the line to your .screenrc file:
termcapinfo xterm ti@:te@
Reference ( Putty FAQ )
PuTTY's terminal emulator has always had the policy that when the ‘alternate screen’ is in use, nothing is added to the scrollback. This is because the usual sorts of programs which use the alternate screen are things like text editors, which tend to scroll back and forth in the same document a lot; so (a) they would fill up the scrollback with a large amount of unhelpfully disordered text, and (b) they contain their own method for the user to scroll back to the bit they were interested in. We have generally found this policy to do the Right Thing in almost all situations.
Unfortunately, screen is one exception: it uses the alternate screen, but it's still usually helpful to have PuTTY's scrollback continue working. The simplest solution is to go to the Features control panel and tick ‘Disable switching to alternate terminal screen’. (See section 4.6.4 for more details.) Alternatively, you can tell screen itself not to use the alternate screen: the screen FAQ suggests adding the line ‘termcapinfo xterm ti@:te@’ to your .screenrc file.

November 30, 2012

run as user in inittab or init

Sometimes sudo -u USERNAME gives error.

You can try to to use su USERNAME -c "COMMAND" instead.

November 28, 2012

Start screen after sudo su to another user


Sudo'ing to a user then running screen doesn't work out of the box.  Typically you get the following error:
Cannot open your terminal '/dev/pts/1' - please check.
The solution:
sudo su - someuser
script /dev/null
screen

Source: http://dbadump.blogspot.com/2009/04/start-screen-after-sudo-su-to-another.html 

November 26, 2012

Creating a self-signed certificate with ADT


http://help.adobe.com/en_US/air/build/WS5b3ccc516d4fbf351e63e3d118666ade46-7f74.html

You can use self-signed certificates to produce a valid AIR installation file. However, self-signed certificates only provide limited security assurances to your users. The authenticity of self-signed certificates cannot be verified. When a self-signed AIR file is installed, the publisher information is displayed to the user as Unknown. A certificate generated by ADT is valid for five years.
If you create an update for an AIR application that was signed with a self-generated certificate, you must use the same certificate to sign both the original and update AIR files. The certificates that ADT produces are always unique, even if the same parameters are used. Thus, if you want to self-sign updates with an ADT-generated certificate, preserve the original certificate in a safe location. In addition, you will be unable to produce an updated AIR file after the original ADT-generated certificate expires. (You can publish new applications with a different certificate, but not new versions of the same application.)
Important: Because of the limitations of self-signed certificates, Adobe strongly recommends using a commercial certificate issued by a reputable certification authority for signing publicly released AIR applications.
The certificate and associated private key generated by ADT are stored in a PKCS12-type keystore file. The password specified is set on the key itself, not the keystore.

Certificate generation examples

adt -certificate -cn SelfSign -ou QE -o "Example, Co" -c US 2048-RSA newcert.p12 39#wnetx3tl 
adt -certificate -cn ADigitalID 1024-RSA SigningCert.p12 39#wnetx3tl

To
use these certificates to sign AIR files, you use the following
signing options with the ADT -package or -prepare commands:

-storetype pkcs12 -keystore newcert.p12 -keypass 39#wnetx3tl 
-storetype pkcs12 -keystore SigningCert.p12 -keypass 39#wnetx3tl

Note: Java versions 1.5 and above do not accept high-ASCII characters in passwords used to protect PKCS12 certificate files. Use only regular ASCII characters in the password.


ADT -package command examples

Package specific application files in the current directory for a SWF-based AIR application:

adt –package -storetype pkcs12 -keystore cert.p12 myApp.air myApp.xml myApp.swf components.swc

Download older version of flex SDK

http://blogs.adobe.com/flex/files/2012/05/FlexLicense.swf

November 10, 2012

netcat/ncat server file as a web server

I will use the ncat (part of nmap) tool:

1. first create a bash file with the following contents, and save it as nchttp.sh, and chmod+x on it:
#!/bin/sh
echo "HTTP/1.1 200 OK"
mydate=`date -R`
echo "Date: $mydate"
echo "Server: Apache"
echo "Last-Modified: $mydate"
echo "Accept-Ranges: bytes"
echo "Content-Disposition: inline; filename=\"$1\"";
mysize=`stat $1 |awk '/Size/{print $2}'`
echo "Content-Length: $mysize"
echo "Keep-Alive: timeout=30, max=300"
echo "Connection: Keep-Alive"
echo "Content-Type: application/octet-stream"
echo
cat $1

2. ./nchttp.sh the-file-to-be-downloaded | ncat -l -vv 8001

3. point your brower to your http://YOURSERVERIP:8001, your file will be downloaded

November 9, 2012

Faster ssh X11 Forwarding


I use ssh daily to connect to my servers and laptops around my home office. Most of the time I'm using ssh to login and build software, so it's plain and simple command line activity. However, sometimes I need to run an X11 application on a remote machine, in which case I use X forwarding to display the remote X application on my laptop. However, this can be slow. Today I stumbled on the following incantation to speed up X11 forwarding over ssh:


ssh -c arcfour,blowfish-cbc -X -C user@remotehost

Thanks to Samat Jain for this info.

The choice of cipher is based on some performance benchmarks as noted in LaunchPad bug #54180

Source: http://smackerelofopinion.blogspot.com/2009/07/faster-ssh-x11-forwarding.html

November 7, 2012

php mail() function data flow

php mail() called /usr/sbin/sendmail, which may be a symbolic link to exit4 or sendmail.postfix or whatever sendmail "MTA" installed on your system. If you change that to your own sendmail, you can probably log all outgoing emails for debugging purpose.

November 6, 2012

Build and install python and mercurial from scratch on a system


wget http://www.python.org/ftp/python/2.5.4/Python-2.5.4.tgz
wget http://www.selenic.com/mercurial/release/mercurial-1.2.1.tar.gz
tar zxvf mercurial-1.2.1.tar.gz
tar zxvf Python-2.5.4.tgz

Configure and build Python using /opt - you could use /usr/local or similar but I preferred to keep it out of my $PATH:

cd Python-2.5.4
./configure --prefix=/opt
make
su -c "make install"

Test Python installed properly:

/opt/bin/python
Python 2.5.4 (r254:67916, Mar 25 2009, 12:16:36)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Build Mercurial, using your Python 2.5:

cd ../mercurial-1.2.1
su -c "make install PYTHON=/opt/bin/python PREFIX=/opt"

Test Mercurial installed properly:

/opt/bin/hg --version
Mercurial Distributed SCM (version 1.2.1)
Copyright (C) 2005-2009 Matt Mackall and others

You may wish to symlink hg from somewhere in your $PATH:
su -c "ln -s /opt/bin/hg /usr/local/bin/hg"

Obviously you'll need a C compiler and associated development tools installed. You may find that the Python configure command complains of missing libraries, such as zlib-devel which can be installed via yum if required

Source: http://blog.friedland.id.au/2009/03/installing-mercurial-on-rhelcentos-3.html

November 2, 2012

When running configure, “.infig.status: error: cannot find input file:” error was generated:


This appears to be caused by by having DOS style line endings in the configure script.
You should be able to use the dos2unix command or alternatively, the tr command:

$ tr -d "\15\32" < configure > configure.new
$ mv configure.new configure
     $ chmod +x configure

 Original Post Here

November 1, 2012

linux console get image size

On linux console, if you need to get an image size, and imagemagick is not installed, you can use the following script (save it as "getimgsize.php", chmod +x, then run it with your image file":


#!/usr/bin/php -f
<?php
if ($argc<2){
        die("Usage: getimagesize IMAGEFILE\n");
}
list($width, $height, $type, $attr) = getimagesize($argv[1]);
echo "Size is $width x $height\n";

October 30, 2012

Windows 8 and Ubuntu 12.10 dual boot issue

I recently bought a HP Envy dv4 laptop for work. It came with Windows 8, and I wanted to install Ubuntu 12.10 Server on it. Here is the problems I ran into and how they were solved:

1. Internal CDROM install did not work correctly. First I thought it was because the CDROM was broken. Later on I found out that legacy BIOS support is not enabled in the UEFI. Once Legacy support is enabled in UEFI, installing from CDROM worked fine.

2. Ubuntu 12.10 64-bit did not detect that the system is using UEFI and installed GRUB-PC(which is for the old BIOS/MBR) instead. So after installation the system booted straight into Windows 8 with no  option to boot into Linux.

3. I downloaded the Boot Repair and ran it. It uninstalled the grub-pc and installed grub-efi but at the end it stated that error occurred and suggested that I move the Linux into the first partition. This was not an easy option for me. So the system still cannot boot into Linux.

4. What saved the day was the tool called "rEFInd" found in  This Post . The actual website is located at HERE. A great piece of software with clear instructions. So I booted into Windows 8 and followed the instruction listed under "

Installing rEFInd Manually Using Windows"


5. It worked great!! Later on I used the "bcdedit" command to set the boot manager to grubx64 directly and it worked as well.

Thanks Rod!


October 23, 2012

How to Tell if Your CPU supports Virtulization Technology on Linux


It’s quite simple: We’ll need to take a peek inside the /proc/cpuinfo file and look at the flags section for one of two values, vmx or svm.
  • vmx – (intel)
  • svm – (amd)
You can use grep to quickly see if either value exists in the file by running the following command:
egrep ‘(vmx|svm)’ /proc/cpuinfo
If your system supports VT, then you’ll see vmx or svm in the list of flags. My system has two processors, so there are two separate sections:

flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx lm constant_tsc pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr lahf_lm
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx lm constant_tsc pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr lahf_lm
VT technology can still be disabled in your computer’s BIOS, however, so you’ll want to check there to make sure that it hasn’t been disabled. The flags in cpuinfo simply mean that your processor supports it.


Source: http://www.howtogeek.com/howto/linux/linux-tip-how-to-tell-if-your-processor-supports-vt/

October 12, 2012

vmware and virtualbox usb device in use not able to attach to VM

If you have a USB device that cannot be detached from the HOST and attach to your VM, one possible reason is because you are using USB 3.0 port the device. Change to a USB 2.0 port should help in that case. This was my case with Windows 7 running on Thinkpad T530.

September 19, 2012

Resolve IP Fragmentation, MTU, MSS, and PMTUD Issues with GRE and IPSEC


Resolve IP Fragmentation, MTU, MSS, and PMTUD Issues with GRE and IPSEC


Excerpt:

Avoiding IP Fragmentation: What TCP MSS Does and How It Works

The TCP Maximum Segment Size (MSS) defines the maximum amount of data that a host is willing to accept in a single TCP/IP datagram. This TCP/IP datagram may be fragmented at the IP layer. The MSS value is sent as a TCP header option only in TCP SYN segments. Each side of a TCP connection reports its MSS value to the other side. Contrary to popular belief, the MSS value is not negotiated between hosts. The sending host is required to limit the size of data in a single TCP segment to a value less than or equal to the MSS reported by the receiving host.
Originally, MSS meant how big a buffer (greater than or equal to 65496K) was allocated on a receiving station to be able to store the TCP data contained within a single IP datagram. MSS was the maximum segment (chunk) of data that the TCP receiver was willing to accept. This TCP segment could be as large as 64K (the maximum IP datagram size) and it could be fragmented at the IP layer in order to be transmitted across the network to the receiving host. The receiving host would reassemble the IP datagram before it handed the complete TCP segment to the TCP layer.

September 18, 2012

vboxheadless does not listen on VRDE port

vboxheadless in virtualbox is really good, but it does not report error messages very well. If you see it running but does not listen on the VRDE port, there is a chance that you have the following issue:

This supposes that your host is Linux.

Your host may have loaded the linux KVM modules, which conflicts the VirtualBox.  Do a "lsmod" to see whether you have the following modules installed:


 kvm_intel
 kvm

If you do, "rmmod" them. To make it permanent, put them in /etc/modprobe.d/blacklist.conf


September 14, 2012

debug udev rules

To debug your udev rules, just run udevd as:

udevd --debug

Keep in mind that some udevd cannot detect changes in rule files so make sure you restart udevd after rule changes.

Qt embedded Linux usb keyboard auto detect

Qt in embedded Linux can detect the plug/unplug of an USB Mouse and enable it when USB mouse is plugged in. For USB keyboard, it does not support such capability.

To solve this problem, I have to resort to qt plugin. The following links will provide all the necessary material to write and deploy a plugin.

The plugin is a dynamic library that qt app looks for when it starts. In this case, the "customized qt keyboard driver" is located at qt-binary-directory/kbddrivers/libhotplugkbplugin.so. Before start the app, set the key board environment variable:


export QWS_KEYBOARD="HotPlugKb"

The plugin is based on the simplestyle plugin below structure-wise and based on the qt internal linuxInput driver function-wise.


http://doc.qt.nokia.com/4.7-snapshot/qkbddriverplugin.html
http://qt-project.org/doc/qt-5.0/deployment-plugins.html
http://doc.qt.nokia.com/4.7-snapshot/plugins-howto.html
http://doc.qt.nokia.com/4.7-snapshot/tools-styleplugin.html
http://doc.qt.nokia.com/4.7-snapshot/qt-embedded-charinput.html

Debugging Plugins

export QT_DEBUG_PLUGINS='2'

September 7, 2012

Makefile and autoconf/automake gcc version check

Makefile:

GCC_VERSION_GE_45 := $(shell g++ -dumpversion | gawk '{print $$1>=4.5?"1":"0"}')
ifeq ($(GCC_VERSION_GE_45),1)
    AM_CXXFLAGS +=-Wunreachable-code
endif

Note the use of double $ sign inside gawk script.


In Autoconf/Automake:
1. Add the following line to configure.ac
  AM_CONDITIONAL(GCC_GE_45, test `g++ -dumpversion | gawk '{print $1>=4.5?"1":"0"}'` = 1)

2. Add the following line to Makefile.am
  include $(top_srcdir)/common.mk

3. Add the following lines to common.mk
if GCC_GE_45
    AM_CXXFLAGS +=-Wunreachable-code
endif

September 6, 2012

buffer overflow example and gcc flags

If you want to try some buffer overflow examples online, make sure you compile your C code with the gcc flag:

     -mno-accumulate-outgoing-args 

otherwise your assembly code may look different than the assembly code on the book. Read more at this Stackoverflow post

August 30, 2012

hg serve multiple projects


1. Create a file under the parent directory of the multiple project hg directories
Example:
#> cat webconf
[collections]
repos/ = .

[web]
allow_push = *
push_ssl = false


2.  hg serve --web-conf ./webconf -d

debian add key


sudo gpg --keyserver subkeys.pgp.net --recv-keys 55BE302B
sudo gpg -a --export 55BE302B | sudo apt-key add -

August 29, 2012

vim man page skip command line

In vim, when you want to get the man page of the word under the cursor, you can just type shift-k or "K". However, for some functions, there is a "command line" tool with the same time, so you will get the man page for that command line instead of the function you are looking for.

For example, if you hit "K" on "unlink", you will get the bash unlink man page instead of the system call unlink(). To solve this problem, put the following line in your .bashrc:

    export MANSECT=3,2,1,4,5,6,7,8,9

This tells man to search section 3 first, then section 2, then section 1, etc., thus solved the problem of section 1 coming up before section 2 or 3.

While on this topic, you can also add the following line to your .bashrc file to make your man page have colors. Make sure you installed the program "most" on your computer.


    export MANPAGER="/usr/bin/most -s"

Or you can use the default "less" program and add the following lines to .bashrc to make "less" colorful:


man() {
 env \
  LESS_TERMCAP_mb=$(printf "\e[1;31m") \
  LESS_TERMCAP_md=$(printf "\e[1;31m") \
  LESS_TERMCAP_me=$(printf "\e[0m") \
  LESS_TERMCAP_se=$(printf "\e[0m") \
  LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
  LESS_TERMCAP_ue=$(printf "\e[0m") \
  LESS_TERMCAP_us=$(printf "\e[1;32m") \
   man "$@"
}

August 23, 2012

Flags to enable thorough and verbose g++ warnings


Flags to enable thorough and verbose g++ warnings


-pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror-Wno-unused


A good base setup for C is:
-std=c99 -pedantic -Wall -Wextra -Wwrite-strings -Werror
and for C++
-ansi -pedantic -Wall -Wextra -Weffc++

My C++ version:

-g -O -Wall -Wextra -Weffc++ -pedantic -Wformat=2 \
 -Waggregate-return -Wcast-align \
 -Wcast-qual   -Wconversion \
 -Wdisabled-optimization  -Wfloat-equal   \
 -Winit-self  -Winline \
 -Winvalid-pch   -Wunsafe-loop-optimizations  -Wmissing-braces \
 -Wmissing-format-attribute   \
 -Wmissing-include-dirs \
 -Wpacked  -Wpadded -Wpointer-arith \
 -Wredundant-decls -Wshadow  -Wstack-protector \
 -Wswitch-default  -Wswitch-enum \
 -Wunknown-pragmas  -Wunreachable-code -Wunused \
 -Wvariadic-macros  -Wwrite-strings \
 -Wlogical-op -Wsign-conversion  \
 -Wstrict-overflow=5 -Wundef

August 2, 2012

Windows 7 change alt-tab preview deplay


Open Registry Editor and create the following registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\AltTab.

In that key, create the following DWORD value: LivePreview_ms and set it to the delay (in milliseconds) of the first live preview.

Restart Explorer to see the changes.

Other Aero-peek related registry entries that I've found on the net are:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced

    DesktopLivePreviewHoverTime
    ThumbnailLivePreviewHoverTime
    ExtendedUIHoverTime

These control the delay of other components of Aero-peek.

Give regular user right to start/stop service in Windows 7


  1. Download and install SubInACL.exe
  2. run "C:\Program Files\Windows Resource Kits\Tools\subinacl" /service Spooler /grant=<username>=TO
SubInACL works on Windows 7.
The T grant parameter is for start service access and the O parameter is stop service access.
Now <username> can:
  • run sc stop Spooler and sc start Spooler
  • run net stop "Print Spooler" and net start "Print Spooler"
  • use the Restart button on the Print Spooler item in services.msc
Source: http://superuser.com/questions/419194/is-there-a-way-to-allow-standard-users-to-restart-stop-start-the-print-spooler

Update: The single subinacl.exe download seems to be not available anymore. Try download the windows 2003 resource toolkit at

Windows Server 2003 Resource Kit Tools

July 27, 2012

How to Resolve “mount error(12): Cannot allocate memory” on a Windows Share


From: http://jlcoady.net/windows/how-to-resolve-mount-error12-cannot-allocate-memory-windows-share

If you mount a Windows 7 share using Samba/CIFS you may run into “mount error(12): Cannot allocate memory” if you are using very large files on the Windows machine. Looks like in certain situations Windows needs to be told to run as a file server and to expect large files. You can read more details at Large Files are locking up Windows 7 32 bit and 64 bit, but the solution is to make two registry edits and then restart a service:
  1. Set “HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\LargeSystemCache” to “1″.
  2. Set “HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size” to “3″.
  3. Restart the “server” service.
Once you have done that you should be able to mount the share using a command like “sudo mount -a” or just reboot the Linux machine.

July 18, 2012

__USE_GNU (use GNU specific feature)


Directly define __USE_GNU is wrong, __USE_GNU is glibc internal macro that shouldn't be ever defined by apps.
The way to select GNU feature set in glibc headers is to define _GNU_SOURCE, either before including first include header in the source .c/.C file, or by defining it on the command line (-D_GNU_SOURCE).

July 16, 2012

VirtualBox USB from the command line

Credit: http://richardhorwood.com/108/virtualbox-usb-from-the-command-line/

How to add a USB device using vboxmanage


  1. Ensure you actually have USB support for your target VM:
    # VBoxManage showvminfo "somevm" | grep USB
    USB:             enabled
  2. If it’s not set to “enabled” you’ll have to add USB support to your VM.  You’ll need to power off the VM to do this:

    # VBoxManage modifyvm "somevm" --usb on --usbehci on
  3. To attach a device that’s plugged into the same system as your VM (in my case, a Sony USB memory stick), grab its UID as follows:
    # VBoxManage list usbhost
    Sun VirtualBox Command Line Management Interface Version 3.1.4
    (C) 2005-2010 Sun Microsystems, Inc.
    All rights reserved.
    
    Host USB Devices:
    [...]
    UUID:               2a2c7255-3b90-448e-aa7a-b1c5710ddd79
    VendorId:           0x054c (054C)
    ProductId:          0x0243 (0243)
    Revision:           1.0 (0100)
    Manufacturer:       Sony
    Product:            Storage Media
    SerialNumber:       6A08102832911
    Address:            0x54c:0x243:256:/pci@0,0/pci108e,5347@2,1
    Current State:      Busy
    
  4. Create a usb filter which will tell VirtualBox to provide the USB device to your virtual machine when it’s detected as plugged in on the host:
    # VBoxManage usbfilter add 0 --target "somevm" --name usbstick \
                   --vendorid 054C --productid 0243
  5. Go ahead and power on your Virtual Machine.  You’ll notice that the USB device (if it’s currently plugged in) immediately becomes unavailable on the host.  You can confirm that it’s attached and that you didn’t make a typo with the vendor and/or product IDs:
    # VBoxManage showvminfo "somevm"
    [...]
    Currently Attached USB Devices:
    
    UUID:               582313d4-1d51-41ea-a053-ba5ac552d2e5
    VendorId:           0x054c (054C)
    ProductId:          0x0243 (0243)
    Revision:           1.0 (0100)
    Manufacturer:       Sony
    Product:            Storage Media
    SerialNumber:       6A08102832911
    Address:            0x54c:0x243:256:/pci@0,0/pci108e,5347@2,1
That’s it.  You can mount and unmount this device now inside your VM.

July 13, 2012

Import certificate and key into java key store using keytool

If you have the certificate and key in pkcs12 format you can directly import it into an existing java key store:

keytool -importkeystore -srckeystore server.p12 -srcstoretype pkcs12 -destkeystore server.jks -deststoretype jks

If you have it in PEM you can convert it to pkcs12 first:
cat server_key.pem server_cert.pem server_cacert.pem > server.pem
openssl pkcs12 -export -out server.p12 -in server.pem

July 2, 2012

Windows VPN: this connection requires an active internet connection

Even though selecting Start>Connect To won't let you connect, this will:
 - Go to Control Panel > Network and Sharing center
 - Click on Manage Network Connections
 - You can see the VPN connection(s) and connect to it (right click and select "Connect")

June 29, 2012

Command line tools on Linux to beautify CSS ,Javascript, and PHP

For CSS, I use "csstidy", the C++ version. I added CSS 3.0 support to it and also added a default "indented" template. You can get the latest version at:
    https://bitbucket.org/tiebingzhang/csstidy

For Javascript, I use the command line version of jsbeautifier, which can be downloaded at
http://github.com/einars/js-beautify/zipball/master

For PHP, I use an enhanced version of phptidy:
https://bitbucket.org/tiebingzhang/phptidy

June 18, 2012

php.ini send email on Linux

If you just want to send email (not receiving email) from your PHP server, and you have a SMTP Email server, here is how you do it:

(First, you don't need to edit your php.ini file SMTP settings, because on Linux those are not used by PHP)

1. Install SSMTP on your system (Debian/Ubuntu via apt-get, RHEL/CentOS using the Fedora EPEL Package search to find the package.
2. Use "ssmtp" to replace "sendmail" on your system. ssmtp use the same command argument as sendmail.
3. configure your /etc/ssmtp/ssmtp.conf file:


root=postmaster
mailhub=SMTP SERVER IP ADDRESS
RewriteDomain=your_from_domain.com
#this allows you to specify your from address
FromLineOverride=YES

4.  Now send an email. Type
ssmtp recipient_email@example.com
sSMTP will then wait for you to type your message, which needs to be formatted like this:
To: recipient_email@example.com
From: myemailaddress@gmail.com
Subject: test email

hello world!

Note the blank like after the subject, everything after this line is the body of the email. When you’re finished, press Ctrl-D.

You can also use script. Create a file msg.txt, then send it:
ssmtp myemailaddress@gmail.com < msg.txt


msg.txt is a simple text using the proper formatting for sSMTP:
To: myemailaddress@gmail.com
From: myemailaddress@gmail.com
Subject: alert

The server is down!



Credit: http://tombuntu.com/index.php/2008/10/21/sending-email-from-your-system-with-ssmtp/

June 15, 2012

CentOS or RHEL enable PHP to make TCP Connect

setsebool -P httpd_can_network_connect 1

June 7, 2012

RHEL/Centos sysconfig network scripts



The /etc/sysconfig/network-scripts/ifcfg-ethN files

File configurations for each network device you may have or want to add on your system are located in the /etc/sysconfig/network-scripts/ directory with Red Hat Linux 6.1 or 6.2 and are named ifcfg-eth0 for the first interface and ifcfg-eth1 for the second, etc. Following is a example /etc/sysconfig/network-scripts/ifcfg-eth0 file:

           DEVICE=eth0
           IPADDR=208.164.186.1
           NETMASK=255.255.255.0
           NETWORK=208.164.186.0
           BROADCAST=208.164.186.255
           ONBOOT=yes
           BOOTPROTO=none
           USERCTL=no
           
If you want to modify your network address manually, or add a new network on a new interface, edit this file -ifcfg-ethN, or create a new one and make the appropriate changes.

  • DEVICE=devicename, where devicename is the name of the physical network device.
  • IPADDR=ipaddr, where ipaddr is the IP address.
  • NETMASK=netmask, where netmask is the netmask IP value.
  • NETWORK=network, where network is the network IP address.
  • BROADCAST=broadcast, where broadcast is the broadcast IP address.
  • ONBOOT=answer, where answer is yes or no. Do the interface need to be active or inactive at boot time.
  • BOOTPROTO=proto, where proto is one of the following :

    1. none - No boot-time protocol should be used.
    2. bootp - The bootp now pump protocol should be used.
    3. dhcp - The dhcp protocol should be used.
  • USERCTL=answer, where answer is one of the following:

    1. yes - Non-root users are allowed to control this device.
    2. no - Only the super-user root is allowed to control this device.  


      NM_CONTROLLED="no"/"yes" : Whether Network-Manager controlled

              

May 25, 2012

xargs argument replacement

This is how xargs works:

cat listfile | xargs ls 

but if you want to use the argument in the middle, such as "mv", you need to do the following:

cat listfile | xargs -I {} mv {} trash

-I {} tells xargs to replace all instances of {} with the argument from listfile.

So you can use other weird strings as long as you know it does not appear in the listfile, such as

cat listfile | xargs -I HAHA mv HAHA trash

May 18, 2012

Windows 7 IKEv2 with StrongSwan Certificate Generation Guide

Windows 7 supports IPSec IKEv2 with machine certificate authentication. Using StrongSwan on Linux for server, this is a good solution for Road Warrior remote access.

The problem with Windows 7 IKEv2 client is that it does not provide any log for trouble-shooting at all. So if it does not like something in your setup, it simply throws an error number and a very vague error message.  Error 13806 is one of them.

I spent a few days finally got my Windows 7 running IKEv2 machine authentication with my strongswan server. Below are a few tips for Error 13806:

1. Error 13806 is because the machine certificate or CA certificate  on the Windows 7 has problems. This is NOT about the Server's certificate. So focus on fixing the Windows 7 certificates. The error message does not really tell you this clearly.

2. There are a few variables in your client certificate that are important, whether you use OpenSSL or StrongSwan ipsec pki to generate your certs:


  1. The Common Name (CN) in the subject of your certificate
  2. The Subject Alternative Name (SAN) 
  3. The Key Usage
  4. The Extended Key Usage, where you can specify "clientAuth", "serverAuth", "1.3.6.1.5.5.8.2.2", either one or a combination of them.


Here is what works and what does not work in my tests (For Windows 7 client only, not for StrongSwan server):

  • You do not need to set Key Usage and Extended Key Usage(EKU). If you set them, some combinations may cause trouble. see more below.
  •  You do not need to set SAN. If you really want to set it, it has to be exactly the same as the CN. Otherwise you will get Error 13806.
  •  Set CN to either a full DNS name such as "win7.mycompany.local", or just a string name "win7". Either one works.
  •  If you set Key Usage to "nonRepudiation, digitalSignature, keyEncipherment", and Extended Key Usage to "1.3.6.1.5.5.8.2.2,serverAuth,clientAuth", you MUST set your CN to the long form of DNS name such as "win7.mycompany.local". Using the short form "win7" will fail and cause error 13806.

The name win7.mycompany.local does not have to be in your DNS server.

What works:

  • CN="win7", no SAN, No Keyusage, No EKU.
  • CN="win7", SAN="win7", No Keyusage, No EKU.
  • CN="win7.mycompany.local", SAN="win7.mycompany.local", No Keyusage, No EKU.
  • CN="win7.mycompany.local", SAN="win7.mycompany.local",keyUsage = nonRepudiation,   digitalSignature, keyEncipherment,  extendedKeyUsage = 1.3.6.1.5.5.8.2.2,serverAuth,clientAuth

What does not work (Error 13806):

  • CN="win7", SAN="something else", No Keyusage, No EKU.
  • CN="win7", SAN="win7",keyUsage = nonRepudiation,   digitalSignature, keyEncipherment,  extendedKeyUsage = 1.3.6.1.5.5.8.2.2,serverAuth,clientAuth

Your server certificate should have the following:
  •   CN 
  •   SAN, which should be exactly the same as your CN
  •   keyUsage = nonRepudiation,   digitalSignature, keyEncipherment,  
  •   extendedKeyUsage = 1.3.6.1.5.5.8.2.2,serverAuth
Your Windows 7 VPN connection host name should exactly the same as the Server's CN. And that CN name should be DNS resolvable. The easiest way to do that in a test environment is to add the CN name to your local computer's host file, located at "c:\windows\system32\drivers\etc\hosts"

Of course you should read StrongSwan's Wiki page on Windows 7. Very helpful, although can be a little bit more detailed on the client side. (http://wiki.strongswan.org/projects/strongswan/wiki/Windows7)

Andreas at StrongSwan also pointed out to me that although ECDSA has been supported by Windows since Windows Vista, it only works in IKEv1. IKEv2 in Windows 7 and Windows 2008 R2 does not support ECDSA. I have also personally verified that this is true.

One more important note:

Please make sure all your certificates has the PKIX recommended "Authority Key Identifier" in it. Otherwise, Windows 7 will give an Error 13806.


If you use OpenSSL to generate your certs, make sure the following line is in your openssl.conf file:

authorityKeyIdentifier=keyid,issuer

"Subject Key Identifier" seems to be optional for Windows 7.

Another useful post on this subject: http://forums.opensuse.org/english/get-technical-help-here/network-internet/435097-strongswan-opensuse-11-2-quick-setup.html

More Update:
Following above-written rules, I was able to generate certificates using StrongSwan ipsec pki command for both Windows 7 and StrongSwan, and the IKEv2 connection was established.

Here are the scripts:

First, Generate the CA:



bits=2048
ipsec pki --gen --type rsa --size $bits --outform pem > ca.key
ipsec pki --self --flag serverAuth --in ca.key --type rsa --digest sha1 --dn "C=CH, O=strongSwan, CN=pkiCA" --ca > caCert.der

Next, generate two certs, one for Server and one for Win7

bits=2048
for user in server win7; do
    ipsec pki --gen --type rsa --size $bits --outform pem > $user.key
    flags="";
    [ "$user" = "server" ] && flags="--flag serverAuth";
    ipsec pki --pub --in $user.key --type rsa | ipsec pki --issue --cacert caCert.der --cakey ca.key --digest sha1 \
        --dn "C=CH, O=strongSwan, CN=$user.mycompany.local" --san "$user.mycompany.local" $flags --outform pem > $user.cert
done;

Next convert Win7 cert to P12 format:

# Usage: ./convert-to-p12.sh Username
user=$1
openssl pkcs12 -export -inkey $user.key -in $user.cert -name "$user" -certfile caCert.der -caname "vpnserver7" -out $user.p12

then run ./convert-to-p12.sh win7

Next convert Server key to DER format so that Strongswan can take it:

openssl rsa -in $1.key  -out $1.der -outform DER

where $1 is "server"


May 4, 2012

[Solved] apt-get “is to be installed” errors in Debian



Fortunately, you can force the version in apt-get:

March 21, 2012

use vimdiff for hg diff

put the following to your ~/.hgrc file


[extensions]
hgext.extdiff =

[extdiff]
cmd.vimdiff =

[alias]
vi  = vimdiff
vim = vimdiff

March 12, 2012

ubuntu update issue

If your ubuntu is failing to update/install software, make sure you have the ubuntu update repository set in your apt source.list file:


###### Ubuntu Main Repos
deb http://us.archive.ubuntu.com/ubuntu/ lucid main restricted universe multiverse 

###### Ubuntu Update Repos
deb http://us.archive.ubuntu.com/ubuntu/ lucid-security main restricted universe multiverse 
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates main restricted universe multiverse 

February 23, 2012

FINDDUPE: Duplicate file detector and eliminator


FINDDUPE: Duplicate file detector and eliminator


This tools is cool. Especially the hard-linking feature:

Freeing hard drive space
Sometimes its intentional to have certain media in multiple places. By running finddupe, and hard linking the identical files, you can keep the files in multiple places, while only having one physical copy on the hard drive.
 

February 1, 2012

IE and IPv6 address

To use IPv6 address in your IE8/IE9 address bar, you have to add a square bracket to the beginning and the end of the IP address. Your IPv6 URL will look something like this:

http://[2001:1:1::02]

January 24, 2012

Change WireShark Dispaly Time to GMT/UTC or other timezone


On Windows:
1. Open a CMD window
2. set TZ=GMT or TZ=GMT10 or set TZ=GMT-5 (whatever you want your timezone to be)
3. lunch wireshark by: "C:\Program Files\Wireshark\wireshark.exe"

On Linux:
TZ=GMT wireshark





January 13, 2012

rsync using a different ssh port

# rsync -avz -e "ssh -p $portNumber" user@remoteip:/path/to/files/ /local/path/