Ady Wicaksono Daily Activities

Archive for the ‘Linux’ Category

Sendmail STARTTLS, how to force email relay to use TLS

with 2 comments

Sendmail STARTTLS Issue
=======================

The idea of this paper is how to force email relay/end SMTP destination to retrieve our
email securely using TSL (Transport Security Layer). If the relay or mail destination 
doesn't support TLS, email will not be delivered to it.

Such scenario is simply given in this diagram:

                      (1)                         (2)                        
[ mail client ] === send email ===> [ MTA1 ] === relay to 
                                                   |
+==================================================V
| (3)                     (4)
+======> [ MTA2 ] === delivery to ===> [ mail server (SMTP destination) ]

I assume:
=========
MTA1: 10.254.80.31
MTA2: 10.254.70.8

Our purpose now is to make MTA1 - MTA2 communication is secured using TLS.

I) What happened if MTA2 doesn't support TLS? Let us try by following this scenario below:

Step 1. (to be done on MTA2)
   - disable STARTTLS 
   - Edit /etc/mail/access append this line:
   
	Connect:10.254.80.31                    RELAY

     After append that line above, please run this command (as root)

	makemap hash /etc/mail/access.db = 128 bits. If not, then MTA1 
     will not relay email to MTA2.
     
     After append that line above, please run this command (as root)

	     makemap hash /etc/mail/access.db < /etc/mail/access

Step 3. (to be done on email client)
Try to send email now using MTA1, now monitor MTA1, wait and check mail queue there:

- Using mailq command you get like this

-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------
m675MXpo001370      536 Mon Jul  7 05:22 
                 (Deferred: 403 4.7.0 encryption too weak 0 less than 128)
                                         

Message is deferred, since based on our rule, message send through 10.254.70.8 (MTA2) 
which is our relay must be encrypted, but we didn't configure MTA2 to be TLS enabled. 
Error message:

        403 4.7.0 encryption too weak 0 less than 128
 
there describe that we want encryption but relay mail server doesn't support it.

II) What happened if MTA2 support TLS? Simply enable TLS on MTA2 and see what happened :)
    Email should be delivered normally now  

FAQ:
* How to check if the SMTP support TLS? 
  Try to connect (using telnet) to port 25, say hello and you will see "250-STARTTLS" there.
  E.g:
	# telnet localhost 25
	Trying 127.0.0.1...
	Connected to CM (127.0.0.1).
	Escape character is '^]'.
	220 localhost.localdomain ESMTP Sendmail 8.12.10/8.12.11; 
	EHLO localhost
	250-localhost.localdomain Hello CM [127.0.0.1], pleased to meet you
	250-ENHANCEDSTATUSCODES
	250-PIPELINING
	250-8BITMIME
	250-SIZE
	250-DSN
	250-ETRN
	250-AUTH GSSAPI DIGEST-MD5 CRAM-MD5
	250-STARTTLS
	250-DELIVERBY
	250 HELP

* How to enable/disable TLS feature on sendmail?
  See: http://www.sendmail.org/~ca/email/starttls.html#starttlssetup

Link related:
 1. www.sendmail.org
     	     



Written by adywicaksono

July 7, 2008 at 5:53 am

Posted in Linux, networking

I got it again (Master Linux Brainbench Certification)

with 9 comments

Yes, I got it again after a few years ago. The reason I applied for it is because Brainbench.com offer this test for free, yes they have a promo :).


Here are some certificates I got from Brainbench long time ago (Why I publish it, because nothing I can sell now except my skill):

1. Master Apache 1.3.x

2. Master PHP 4

3. Master Java 2

4. Master TCP/IP

5. C Programmer

6. Master Unix Administrator

7. Master Linux Administrator

8. Perl Programmer

10. Unix Programmer

Written by adywicaksono

April 8, 2008 at 1:36 pm

Posted in Linux

When will your SBS Transit Bus arrive?

leave a comment »

Iris next bus is provided by SBS Transit (www.sbstransit.com.sg) for us here at Singapore to check the estimated time of SBS bus arrival. It’s very important for us, especially if we don’t want to wait for the bus too long 😦

This service is accessible by internet freely, simply put bus number and bus stop we can get the
information.

Just now I create a simple perl script to access this service
Here an example session of my script in my linux box

$ perl sbs.pl
Enter Bus Number           : 91
Enter Bus Stop Number      : 18069
Bus Stop Name              : AYER RAJAH CRES - OPP BLK 71
Next Bus Arriving in       : 15 minutes
Subsequent Bus Arriving in : 32 minutes

Here the similar screen capture from web


iris-next-bus1.jpg

The HTTP transaction to get the next bus information from Iris Next Bus system is like this:

Step 1. From Browser (Firefox) we send this HTTP request
========================================================
POST http://www.sbstransit.com.sg/index.aspx HTTP/1.1
Host: www.sbstransit.com.sg
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12
Cookie: rl-sticky-key=c0a8089c; ASP.NET_SessionId=1qtfoortt4l2id45wgafpbzz
Content-Type: application/x-www-form-urlencoded
Content-Length: 197

__VIEWSTATE=dDwyNjcxMTQzMTA7O2w8aGVhZGVyMDppbWdidG5TZWFyY2g7Sm91cm5leXBsYW46aW1nR287aVJJUzpidG5nbzs%2BPg%3D%3D
&keyword=&iRIS%3Atxtsvcno=91&iRIS%3Atxtbusstop=18069&iRIS%3Abtngo.x=28&iRIS%3Abtngo.y=8

Step 2. SBSTransit.com.sg respond with this HTTP response
=========================================================
HTTP/1.0 302 Moved Temporarily
Date: Tue, 26 Feb 2008 02:46:52 GMT
Location: /iris3/myirisnextbus.aspx?svcno=91&stopcode=18069
Server: Concealed by Juniper Networks DX
Via: 1.1 dx2 (Juniper Networks Application Acceleration Platform - DX 5.2.6 0)
Set-Cookie: rl-sticky-key=c0a8089c; path=/;

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href='/iris3/myirisnextbus.aspx?svcno=91&amp;stopcode=18069'>here</a>.</h2>
</body></html>

Step 3. From Browser (Firefox) we send this HTTP request
=========================================================
GET http://www.sbstransit.com.sg/iris3/myirisnextbus.aspx?svcno=91&stopcode=18069 HTTP/1.1
Host: www.sbstransit.com.sg
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12
Referer: http://www.sbstransit.com.sg/
Cookie: rl-sticky-key=c0a8089c; ASP.NET_SessionId=1qtfoortt4l2id45wgafpbzz

Step 4. SBSTransit.com.sg respond with this HTTP response
=========================================================
HTTP/1.0 200 OK
Date: Tue, 26 Feb 2008 02:46:53 GMT
Server: Concealed by Juniper Networks DX
Content-Encoding: deflate
Warning: 214  "Juniper Networks DX Active"
Vary: Accept-Encoding, User-Agent
Via: 1.1 dx2 (Juniper Networks Application Acceleration Platform - DX 5.2.6 0)
Set-Cookie: rl-sticky-key=c0a8089c; path=/;

[Web content in gzip-deflate format]

base on the HTTP transaction above, we can create a perl code like this

#!/usr/bin/perl
# Iris Next Bus
# Usage:
#  perl sbs.pl

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Status;

do{
	print "Enter Bus Number: ";
	chop($bus_number = <STDIN>);
	if($bus_number !~ /^[0-9]+[A-Z}*[a-z]*$/){
		$bus_number = '';
	}
}while($bus_number == '');
do{
	print "Enter Bus Stop Number: ";
	chop($bus_stop_number = <STDIN>);
	if($bus_stop_number !~ /^[0-9]+$/){
		$bus_stop_number = '';
	}
}while($bus_stop_number == '');

$DEBUG  = 0;
$cookie = "rl-sticky-key=c0a8089c; ASP.NET_SessionId=1qtfoortt4l2id45wgafpbzz";
$ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (Windows) Gecko/20080201 Firefox/2.0.0.12");

# Create Request
$req = HTTP::Request->new(POST => "http://www.sbstransit.com.sg/index.aspx");
$req->content_type('application/x-www-form-urlencoded');
$req->header("Cookie" => "$cookie");
$cnt  = '__VIEWSTATE=dDwyNjcxMTQzMTA7O2w8aGVhZGVyMDppbWdidG5TZWFyY2g7Sm91';
$cnt .= 'cm5leXBsYW46aW1nR287aVJJUzpidG5nbzs%2BPg%3D%3D&keyword=&iRIS%3Atxtsvcno=';
$cnt .= $bus_number;
$cnt .= '&iRIS%3Atxtbusstop=';
$cnt .= $bus_stop_number;
$cnt .= '&iRIS%3Abtngo.x=28&iRIS%3Abtngo.y=8';
$req->content($cnt);
if($DEBUG){
	print $req->as_string."n";
}

# Send Request
my $res = $ua->request($req);
my $rc  = $res->code;
if($DEBUG){
	print $res->content;
}
if (is_redirect($rc)){
	$referral_uri = $res->header('Location');
	# Create Request
	$req          = HTTP::Request->new(GET => 
	                                 "http://www.sbstransit.com.sg/".$referral_uri);
	$req->header("Cookie" => "$cookie");
	$req->header("Referer" => "http://www.sbstransit.com.sg/");
	if($DEBUG){
		print $req->as_string."n";
	}
	# Send Request
	$res = $ua->request($req);
	$cnt = $res->content;
	# Find Bus Stop Info
	$cnt   =~ s/^.*id="lblroadesc"[^>]*>//gs;
	$binfo = $cnt;
	$binfo =~ s/</span.*$//gs;
	$cnt   =~ s/^.*id="bus1"[^>]*>//gs;
	$arrive= $cnt;
	$arrive=~ s/</span.*$//gs;
	$cnt   =~ s/^.*id="bus2"[^>]*>//gs;
	$next  = $cnt;
	$next  =~ s/</span.*$//gs;
	print "Bus Stop Name              : $binfon";
	print "Next Bus Arriving in       : $arriven";
	print "Subsequent Bus Arriving in : $nextn";
	if($DEBUG){
		#print $cnt;
	}
}

Written by adywicaksono

February 26, 2008 at 8:33 am

Posted in life, Linux, perl

Add swap space on linux without restarting linux

leave a comment »

1. Allocate new file for swap, e.g 10 Mbytes

   # dd if=/dev/zero of=/swapfile01 bs=1024 count=10000
     10000+0 records in
     10000+0 records out
   # ls -l /swapfile01
     -rw-r--r--    1 root     root     10240000 Jan 26 17:27 /swapfile01

Now we have /swapfile01 for our swapfile

2. Now setup swaparea first

   # mkswap /swapfile01
     Setting up swapspace version 1, size = 9996 KiB

Check our current swap value

    # free
                total       used       free     shared    buffers     cached
    Mem:        604020     562100      41920          0      34100      42848
    -/+ buffers/cache:     485152     118868
    Swap:      1546056     692200     853856

3. activate our swap

 swapon /swapfile01

Check our current swap value

    # free
                total       used       free     shared    buffers     cached
    Mem:        604020     566796      37224          0      35576      43520
    -/+ buffers/cache:     487700     116320
    Swap:      1556048     691564     864484

Our swap file is increase by 10240000 bytes 🙂

Anytime we want to deactivate this swap file area, simply run

   swapoff /swapfile01

Written by adywicaksono

November 19, 2007 at 6:02 am

Posted in Linux

Rejecting “ping” to your linux server

with one comment

Sometimes you’re so paranoid so you don’t like
others to “ping” your server. How to do this?
Read the article below to get the answer

I assume our linux IP server is 10.160.154.102
In normal condition we can ping like this:

c:>ping 10.160.154.102

Pinging 10.160.154.102 with 32 bytes of data:

Reply from 10.160.154.102: bytes=32 time<10ms TTL=64
Reply from 10.160.154.102: bytes=32 time<10ms TTL=64
Reply from 10.160.154.102: bytes=32 time<10ms TTL=64
Reply from 10.160.154.102: bytes=32 time<10ms TTL=64

Ping statistics for 10.160.154.102:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum =  0ms, Average =  0ms

But if we reject this ICMP echo-request using iptables like this

iptables -I INPUT -p icmp --icmp-type echo-request -j REJECT

Now we get destination port unreachable

C:>ping 10.160.154.102

Pinging 10.160.154.102 with 32 bytes of data:

Reply from 10.160.154.102: Destination port unreachable.
Reply from 10.160.154.102: Destination port unreachable.
Reply from 10.160.154.102: Destination port unreachable.
Reply from 10.160.154.102: Destination port unreachable.

Ping statistics for 10.160.154.102:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum =  0ms, Average =  0ms

Actually our server is not purely drop the ICMP packet, but simply
send ICMP destination-unreachable. If we want to drop it, then you use
this iptables command

iptables -I INPUT -p icmp --icmp-type echo-request -j DROP

Now the ping result will be different:

C:>ping 10.160.154.102

Pinging 10.160.154.102 with 32 bytes of data:

Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 10.160.154.102:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum =  0ms, Average =  0ms

So, happy protecting

Written by adywicaksono

November 9, 2007 at 9:38 am

Posted in Linux, networking

Detecting MAC Address using C application

with 10 comments

I got this code long time ago from somewhere (off course from internet), using this C code it’s now simpler for you to create application that needs to detect MAC address.

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#ifdef Linux
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if.h>
#endif

#ifdef HPUX
#include <netio.h>
#endif

#ifdef AIX
#include <sys/ndd_var.h>
#include <sys/kinfo.h>
#endif

long mac_addr_sys ( u_char *addr)
{
/* implementation for Linux */
#ifdef Linux
    struct ifreq ifr;
    struct ifreq *IFR;
    struct ifconf ifc;
    char buf[1024];
    int s, i;
    int ok = 0;

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s==-1) {
        return -1;
    }

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    ioctl(s, SIOCGIFCONF, &ifc);

    IFR = ifc.ifc_req;
    for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {

        strcpy(ifr.ifr_name, IFR->ifr_name);
        if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
                if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
                    ok = 1;
                    break;
                }
            }
        }
    }

    close(s);
    if (ok) {
        bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
    }
    else {
        return -1;
    }
    return 0;
#endif

/* implementation for HP-UX */
#ifdef HPUX

#define LAN_DEV0 "/dev/lan0"

    intfd;
    struct fisiocnt_block;
    inti;
    charnet_buf[sizeof(LAN_DEV0)+1];
    char*p;

    (void)sprintf(net_buf, "%s", LAN_DEV0);
    p = net_buf + strlen(net_buf) - 1;

    /*
     * Get 802.3 address from card by opening the driver and interrogating it.
     */
    for (i = 0; i < 10; i++, (*p)++) {
        if ((fd = open (net_buf, O_RDONLY)) != -1) {
iocnt_block.reqtype = LOCAL_ADDRESS;
ioctl (fd, NETSTAT, &iocnt_block);
close (fd);

            if (iocnt_block.vtype == 6)
                break;
        }
    }

    if (fd == -1 || iocnt_block.vtype != 6) {
        return -1;
    }

bcopy( &iocnt_block.value.s[0], addr, 6);
return 0;

#endif /* HPUX */

/* implementation for AIX */
#ifdef AIX

    int size;
    struct kinfo_ndd *nddp;

    size = getkerninfo(KINFO_NDD, 0, 0, 0);
    if (size <= 0) {
        return -1;
    }
    nddp = (struct kinfo_ndd *)malloc(size);
        
    if (!nddp) {
        return -1;
    }
    if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
        free(nddp);
        return -1;
    }
    bcopy(nddp->ndd_addr, addr, 6);
    free(nddp);
    return 0;
#endif

/* Not implemented platforms */
return -1;
}

/***********************************************************************/
/*
 * Main (only for testing)
 */
#ifdef MAIN
int main( int argc, char **argv)
{
    long stat;
    int i;
    u_char addr[6];

    stat = mac_addr_sys( addr);
    if (0 == stat) {
        printf( "MAC address = ");
        for (i=0; i<6; ++i) {
            printf("%2.2x", addr[i]);
        }
        printf( "\n");
    }
    else {
        fprintf( stderr, "can't get MAC address\n");
        exit( 1);
    }
    return 0;
}
#endif

E.g you want to use on Linux, save it as file.c simply compile like this:

   gcc -O2 -DMAIN -DLinux file.c -o file

And run it

./file
MAC address = 0008c7e9e386

Compare with /sbin/ifconfig result:

/sbin/ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:08:C7:E9:E3:86
          inet addr:***.***.***.***  Bcast:***.***.***.***  Mask:255.255.255.0
          inet6 addr: ********************* Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:265555947 errors:0 dropped:0 overruns:0 frame:0
          TX packets:50507373 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4090310752 (3.8 GiB)  TX bytes:1085018636 (1.0 GiB)

It’s the same 🙂

Written by adywicaksono

November 8, 2007 at 9:29 am

Posted in C/C++, Linux

How much memory space we could allocate for single process in linux?

leave a comment »

Try this C code

#include <stdio.h>
#include <stdlib.h>

int main(){
	size_t siz = 100 * 1024 * 1024 ;
	size_t idx = 1 ;
	void *ptr;

	for (;;){
		ptr = malloc ( siz * idx );
		if(!ptr)
			break ;
		free(ptr);
		idx++;
	}
	printf ("Max malloc %d * 100 MB \n", idx - 1 );
	return (0);
}

On my linux 2.4 the limitation is 2000 MB ~ 2 G
On my linux 2.6 the limitation is 2800 MB ~ 2.8 G
No matter how big your RAM is, 1 process could only occupied 2.8 G on kernel 2.6 (in my case I have 4 Gbytes), next I will share you how to reconfigure the kernel to allow us use bigger memory. This is very important, especially if you run a database like MySQL that handle huge transaction and data, but your mysqld process itself is limited to use 2.8 Gbytes memory, you buy more memory but impact nothing 🙂

$ free
             total       used       free     shared    buffers     cached
Mem:       4149288    4026472     122816          0     108004    1277016
-/+ buffers/cache:    2641452    1507836
Swap:      4192924        836    4192088

$ uname -a
Linux x 2.6.11-1.1369_FC4smp #1 SMP Thu Jun 2 23:08:39 EDT 2005 i686 i686 i386 GNU/Linux

$ ./a.out
Max malloc 28 * 100 MB

Written by adywicaksono

November 8, 2007 at 5:25 am

Posted in Linux