Posts Tagged ‘cd home’

How to make sure your Linux system users won’t hide or delete their .bash_history / Securing .bash_history file – Protect Linux system users shell history

Monday, July 19th, 2010

linux-bin-bash-600x600logo
If you're running multi user login Linux system, you have probably realized that there are some clever users that prefer to prevent their command line executed commands to be logged in .bash_history.
To achieve that they use a number of generally known methodologist to prevent the Linux system from logging into their $HOME/.bash_history file (of course if running bash as a default user shell).
This though nice for the user is a real nightmare for the sysadmin, since he couldn't keep track of all system command events executed by users. For instance sometimes an unprivilegd user might be responsible for executing a malicious code which crashes or breaks your server.
This is especially unpleasent, because you will find your system crashed and if it's not some of the system services that causes the issue you won’t even be able to identify which of all the users is the malicious user account and respectively the code excecuted which fail the system to the ground.
In this post I will try to tell you a basic ways that some malevolent users might use to hide their bash history from the system administrator.
I will also discuss a few possible ways to assure your users .bash_history keeps intact and possibly the commands executed by your users gets logged in in their.
The most basic way that even an unexperienced shell user will apply if he wants to prevent his .bash_history from sys admins review would be of directly wiping out the .bash_history file from his login account or alternatively emptying it with commands like:

malicious-user@server:~$ rm -f. bash_history
ormalicious-user@server:~# cat /dev/null > ~/.bash_history

In order to prevent this type of attack against cleaning the .bash_history you can use the chattr command.
To counter attack this type of history tossing method you can set your malicious-user .bash_history’s file the (append only flag) with chattr like so:

root@server:~# cd /home/malicious-user/
root@server:~# chattr +a .bash_history

It’s also recommended that the immunable flag is placed to the file ~/.profile in user home

root@server:~# chattr +i ~/.profile

It would be probably also nice to take a look at all chattr command attributes since the command is like swiss army knife for the Linux admin:
Here is all available flags that can be passed to chattr
append only (a)
compressed (c)
don~@~Yt update atime (A)
synchronous directory updates (D)
synchronous updates (S)
data journalling (j)
no dump (d)
top of directory hierarchy (T)
no tail-merging (t)
secure deletion (s)
undeletable (u)
immutable (i)

It’s also nice that setting the “append only” flag in to the user .bash_history file prevents the user to link the .bash_history file to /dev/null like so:

malicious-user@server:~$ ln -sf /dev/null ~/.bash_history
ln: cannot remove `.bash_history': Operation not permitted

malicious-user@server:~$ echo > .bash_history
bash: .bash_history: Operation not permitted

However this will just make your .bash_history append only, so the user trying to execute cat /dev/null > .bash_history won’t be able to truncate the content of .bash_history.

Unfortunately he will yet be able to delete the file with rm so this type of securing your .bash_history file from being overwritten is does not completely guarantee you that user commands will get logged.
Also in order to prevent user to play tricks and escape the .bash_history logging by changing the default bash shell variables for HISTFILE an d HISTFILESIZE, exporting them either to a different file location or a null file size.
You have to put the following bash variables to be loaded in /etc/bash.bashrc or in /etc/profile
# #Prevent unset of histfile, /etc/profile
HISTFILE=~/.bash_history
HISTSIZE=10000
HISTFILESIZE=999999
# Don't let the users enter commands that are ignored# in the history file
HISTIGNORE=""
HISTCONTROL=""
readonly HISTFILE
readonly HISTSIZE
readonly HISTFILESIZE
readonly HISTIGNORE
readonly HISTCONTROL
export HISTFILE HISTSIZE HISTFILESIZE HISTIGNORE HISTCONTROL

everytime a user logs in to your Linux system the bash commands above will be set.
The above tip is directly taken from Securing debian howto which by the way is quite an interesting and nice reading for system administrators 🙂

If you want to apply an append only attribute to all user .bash_history to all your existing Linux server system users assuming the default users directory is /home in bash you can execute the following 1 liner shell code:

#Set .bash_history as attr +a
2. find /home/ -maxdepth 3|grep -i bash_history|while read line; do chattr +a "$line"; done

Though the above steps will stop some of the users to voluntary clean their .bash_history history files it won’t a 100% guaranttee that a good cracker won’t be able to come up with a way to get around the imposed .bash_history security measures.

One possible way to get around the user command history prevention restrictions for a user is to simply using another shell from the ones available on the system:
Here is an example:

malicious-user:~$ /bin/csh
malicious-user:~>

csh shell logs by default to the file .history

Also as far as I know it should be possible for a user to simply delete the .bash_history file overwritting all the .bash_history keep up attempts up-shown.
If you need a complete statistics about accounting you’d better take a look at The GNU Accounting Utilities

In Debian the GNU Accounting Utilities are available as a package called acct, so installation of acct on Debian is as simple as:

debian:~# apt-get install acct

I won’t get into much details about acct and would probably take a look at it in my future posts.
For complete .bash_history delete prevention maybe the best practice is to useg grsecurity (grsec)

Hopefully this article is gonna be a step further in tightening up your Server or Desktop Linux based system security and will also give you some insight on .bash_history files 🙂 .

Weblogic – How to change / remove IP/hostname quick and dirty howto

Wednesday, March 11th, 2015

Oracle-Weblogic-Server-logo-how-to-change-ip-hostname-weblogic-quick-and-dirty-howto

This is just quick & dirty doc on how to change/remove IP/host on Oracle WebLogic Application server

– In logs the Error message will be message like:

 

<Oct 21, 2013 1:06:51 AM SGT> <Warning> <Security> <BEA-090504> <Certificate chain received from cluster2.yourdomain.com – 192.168.1.41 failed hostname verification check. Certificate contained cluster1.yourdomain.com but check expected cluster2.yourdomain.com>

 

 

Solution:

On web console – change/remove IP/hostname

 

As root / admin supersuser:

 

– Stop Weblogic Webserver 

As this is RHEL Linux, to stop WLS use standard init script start / stop service command

 

service wls stop

 

– As Application user create directory where new key will be created

 

mkdir /home/uwls11pp/tmp_key
cd /home/uwls11pp/tmp_key

 

– Make backup of current JKS (Keystore File)

 

cp /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks_11032015

 

– Execute set env . script

 

/WLS/app/oracle/wls1036/wlserver_10.3/server/bin/setWLSEnv.sh

 

– Copy & paste output from script above and export variables

 

export CLASSPATH;
export PATH;

 

– Check old certificate in keystore

 

/WLS/app/oracle/jdk1.7.0_25/bin/keytool -list -v -keystore /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks  -storepass DemoIdentityKeyStorePassPhrase

 

– Delete old Weblogic keystore JKS file

 

/WLS/app/oracle/jdk1.7.0_25/bin/keytool -delete -alias demoidentity -keystore /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks -storepass DemoIdentityKeyStorePassPhrase

 

– Check wether proper Java version is used

 

java -version

 

– Get hostname from hosts file

 

cat /etc/hosts

 

#Replace weblogic1 with your FQDN (Fully Qualified Domain Name) – this step will create new certificate with new hostname

 

java utils.CertGen -cn weblogic1 -keyfilepass DemoIdentityPassPhrase -certfile newcert -keyfile newkey

 

#Import certificate to “official” keystore

 

java utils.ImportPrivateKey -keystore /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks -storepass DemoIdentityKeyStorePassPhrase -keyfile newkey.pem -keyfilepass DemoIdentityPassPhrase -certfile newcert.pem -alias demoidentity

 

#Recheck once again if correct certificate is in use

 

/WLS/app/oracle/jdk1.7.0_25/bin/keytool -list -v -keystore /WLS/app/oracle/wls1036/wlserver_10.3/server/lib/DemoIdentity.jks  -storepass DemoIdentityKeyStorePassPhrase


– Finally issue as root user restart Weblogic server again

 

 

service wls start

Qmail’s Voodoo spells and magics ! Workarounds to some common problems, QMAIL HELL!

Friday, October 2nd, 2009

It's one of this days, when you'd wish to be dead and never born ever!

I experienced terrible problems with Qmail once AGAIN!

Most of the qmail administrators out there are probably aware, Everytime qmail stops working it's like

walking in a dark room without a light torch before you fix it up.

To fix a broken qmail your only friend could be patience. It's fucking insane seriously I more and more start hating qmail when it's broken.

I've experienced the following error messages today on our corporate qmail:

delivery xx: failure: Sorry._Although_I'm_listed_as_a_best-preference_MX_or_A_for_that_host,/it_isn't_in_my_control/locals_file,_so_I_don't_treat_it_as_local.
as well as:
delivery 232: deferral: Sorry,_I_wasn't_able_to_establish_an_SMTP_connection._(#4.4.1)/

A lot of this junk filled the qmail logs. I still am not completely sure the exact reasons

what caused the problems. However I fixed the situation tweakening some of the common

qmail and vpopmail configuration files and respectively their cdb files.

Here is the list of files I got to rebuild and the things I've did to resolve the qmail issues:

cd /home/vpopmail/domains;
for i in *; do echo +$i-:$i:89:89:/home/vpopmail/domains/$i:-:: >>assign; done
# backup old assign file just in case something goes wrong
cp -rpf /var/qmail/users/assign /var/qmail/users/assign.bak
mv assign /var/qmail/users/assign
# backup virtualdomains list file
cp -rpf /var/qmail/control/virtualdomains /var/qmail/control/virtualdomains.bak
for i in *; do echo $i:$i >>virtualdomains; done
mv virtualdomains /var/qmail/control/
# Make sure your /var/qmail/control/rcpthosts contains all the vpopmail domains
# backup rcpthosts for laters
cp -rpf /var/qmail/control/rcpthosts /var/qmail/control/rcpthosts.bak
for i in *; do echo $i >>rcpthosts; done
cp -rpf rcpthosts /var/qmail/control/
# backup morercpthosts
cp -rpf morercpthosts /var/qmail/control/morercpthosts.bak
# overwrite the old morercpthosts
# in my case morercpthosts was missing all the vpopmail virtual domains
# thus the domains missing the file wasn't able to receive mail
cp -rpf rcpthosts /var/qmail/control/morercpthosts
# Another problem if you're using qmail check user patch might be in /var/qmail/users/recipients
# Thus rebuilding the recipients file is a good idea.
# Rebuilding it might be done through qmail-vpopmail2recipients script
# the script has a bug the last if statement, where two if's have to be commented to make it wokring
# Below I'll put a link to a working version of the qmail-vpopmail2-recipients script
# Another possible problem could be in /var/qmail/users/cdb
# Therefore it might be a good idea to rebuild it with
/var/qmail/bin/qmail-newu
# Another thing to do is to rebuild the /var/qmail/control/morercpthosts.cdb file with the command
/var/qmail/bin/qmail-newmrh
# Other things I did was
# to assure myself that /var/qmail/control/me contains my mail server host name
# /var/qmail/control/locals should contain "localhost" as well as the FQDN (Fully Qualified Domain Name) (e.g. your domain name)
# Also I checked my /etc/tcp.smtp and assured myself everything is correct there.
# After which I executed
qmailctl cdb
# That rebuilded my /etc/tcp.smtp.cdb file
# Well that was mostly what I did to fix my problems.
# Another think that might be a good idea is to try
cd /home/vpopmail/domains;
for i in *; do /home/vpopmail/bin/vdominfo $i; done
# If you observe some domain's domain info cannot be shown
# then that might be due to some problem with your vpopmail
# It might be a good idea to check your
/var/qmail/bin/qmail-showctl
# qmail-showctl is a handy diagnosis qmail tool
# While looking over the command output
# I had to make sure my cdb files are "Modified Recently"
# and my virtualdomains are all showing up
# THat's mostly what fixed qmail for me
# Next I executed
qmailctl stop; sleep 10; qmailctl start
# that restarted my qmail
# However qmail doesn't always start logging to /var/log/qmail directory right away
# after restart
# SOmetimes the qmail server needs a couple of restarts before it starts serving mail
# Thus restarting it is always full of uncertancies and a lot of broken nerves!

I love qmail it absolutely works brilliant as long as it works, quite often

if you do even minor changes that usually means a broken qmail and qmail hell again!

I truly hope this post could be helpful to somebody out there

Here is a link to a working version of qmail-vpopmail2-recipients

Improve Websites SEO: Optimize images to Increase website loading performance on Linux server – Image Compress tools

Friday, December 5th, 2014

Optimize-website-images-pictures-to-Increase-website-loading-performance-on-Linux-server_Image_Compress_tools-Improve-Websites_SEO
Part of our daily life as Web hosting system adminstrators is to constantly strive to better utilize our Linux / Windows hosting servers hardware.
Therefore it is our constant task to look for new better ways to optimize our Apache Sites and Webservers in order to return served application content light fast to keep the Boss and customers happy 🙂

There are things to tune up for better server performance and better CPU / memory utilization on both server Application server side as well as the website programming code backend, html and pictures / images

Thus it is critically important to not only keep the Webserver / PHP engine optimized but keep hosted sites  stored images and source code clean and efficient.

We as admins usually couldn't directly interfere with clearning the source code and often we have to host a crappy written sites with picture upload forms with un-optimized Image files that was  produced on old Photo Cameras, "Ancient" Mobile Mobiles, Win XP MS Paint, various versions Photoshop, Gimp etc.).

It is a well known fact that a big part from a Website User Experience is how fast the user loads a page, thus if HTML / CSS loaded images loads slow has a negative impact on user look & feel about website

Therefore by optimizing the size of hosted sites Images, you Save Network bandwidth and in some cases when Large Gallery sites HDD disk space.

On Linux, there are already a many command line tools to inspect and optimize (compress) the size of PNG, JPEG, GIF, BMP, PNM, Tiff Images, most famous ones are:

  • optipng – PNG optimizer that recompresses image files to a smaller size, without losing any information.
  • jpegoptim –   lossless JPEG optimization (based on optimizing the Huffman tables) and "lossy" optimization based on setting a maximum quality factor.
  • pngcrush – Recommended tool to use by Stoyan Stefanov (Yahoo Yslow Developer)
  • jpegtran – Recommended to use by Google 
  • gifsicle –  command-line tool for creating, editing, and getting information about GIF images and animations. 

It is hence useful to first run manually availale Linux image optimization tools (to get an idea what they do) and later automate them to run as scripts to optimize server stored images size and make pictures load faster on websites and thus improve End Users Experience and speed up Image content delivery to GoogleBot / YahooBot / Bing Crawlers which will make Search Engines to position server hosted sites better (more SEO Friendly).

 

  • How much percents of  space (Mega / Gigabytes ) Pictures compress can save you?

If you run it on 500MB image directory, you can probably save about 20 to 50MB of size, so don't expect extraordinary file reduce, however 5% to 10% reduce in size is not bad too. If you host 100 sites each with half gigas of data this would mean saving of 5GB of data and some 5GB from backups 🙂 At extraordinary cases you can expect 20% to 30% of storage reduce. For even better image compression you can try out GIMP's – Save for Web option.
 

  • Installing jpegtran, optpng, jpegoptim, pngcrush gifsicle on Debian / Ubuntu (deb based) Linux
     

apt-get install –yes libjpeg-progs optipng jpegoptim pngcrush gifsicle

 

  • Installing  jpegtran, optpng, jpegoptim, pngcrush, gifsicle on Fedora / CentOS / RHEL (RPM based distros)
     

yum -y install pngcrush libjpeg-turbo-utils opt-jpg opt-png opt-gif


gifsicle is not availale by default on Redhacks 🙂 but there is a RPM package for fedora from http://pkgs.repoforge.org/gifsicle/

 

Some examples of running image compression on GNU / Linux

  • optipng and jpegoptim optimize for all files in directory
     

cd /home/sites/

find . -iname '*.png' -print0 | xargs -0 optipng -o7 -preserve
find . -iname '*.jpg' -print0 |
 xargs -0 jpegoptim –max=90 –strip-all –preserve –totals


In jpegoptim command, the option –strip-all will strip any metadata including Exif data from images. For websites JPEG metadata is usually not needed, so usually its ok to strip them.

Above jpegoptim example will decrease slightly JPEG image quality to 90%. quality level of 90 is still high enough and website visitors are unlikely to spot any visible quality reduction / defects in the image.

 

  • pngcrush all files in a directory example
     

cd /home/sites/

for png in `find $IMG_DIR -iname "*.png"`; do
    echo "crushing $png …"
        pngcrush -rem alla -reduce -brute "$png" temp.png

 

    # preserve original on error
    if [ $? = 0 ]; then
        mv -f temp.png $png
        else
        rm temp.png
        fi
done

  • Run jpegtran on sites directory
     

find /home/sites -name "*.jpg" -type f -exec jpegtran -copy none -optimize -outfile {} {} ;

 

  • Set a script to compress / reduce size of Sites Images


Here is a basic optimize_images.sh which I used earlier before and was reducing the overall images size just 5 to 10%, then I found the much improved version of optimize images shell script  (useful to  clear up EXIF picture data / And Comments from JPG / PNG files). The script execution could take very long time on large image directories and thus could cause a high HDD disk I/O, however if ran once a week at night time its not such a big deal. 

To set it to run on your server as a cronjob:
 

cd /usr/sbin/
wget -q https://www.pc-freak.net/bshscr/optimize_images2.sh
crontab -u root -e 


Sample cron job to run once a month on 10th and 27th in 3 o'clock AM:
 

 00 3 10,27 * * /usr/sbin/optimize_images2.sh 2>&1 >/dev/null


Also if you need to further optimize million of tiny sized PNG files Yahoo Smush.it service could be helpful. For compression maniacs its worthy to check out also TinyPNG Service (however be awre that this service compresses files with significant quality loss) making picture quality visibly deteriorated.

Besides optimizing server stored Pictures, here are some other stuff that helps in increasing server utilization / lower webpages loading time.

Starting up with the installation (when site is to use Apache + PHP) for its backend, the first thing to on the freshlyinstalled Linux server is to implement the following list of Apache common Timeout variables that help better scale the webserver for the CMS-es hosted, enable Webserver caching with (mod_deflate), enable eAccelerator tune PHP common php variable etc.

Other thing  I sometimes use to speed-up performance of Apache child responce time up to 20-30  is to Include into Virtualhost / httpd.conf Apache configuration any htacces mod_rewrite rules.

On too heavily loaded sites On-line stores / Large Company website portals with more than 60 000 – 100 000 unique IP visitors a day it is useful tip to disable completely Apache logging in access.log / error.log.

Often when old architecture websites are moved from older Linux OS version to a newer one with newer versions of Apache / PHP often sites are working without major code rework, but use many functions which are already obsolete and thus many WARNING messages crap is logged into php_error.log / error.log. Thus to save disk space and decrease hard disk I/O operations it is good to Disable PHP Notices and Warnings messages
 

Create PDF file from (png, jpg, gif ) images / pictures in Linux

Tuesday, September 14th, 2010

I’ve recently received a number of images in JPEG format as a feedback on a project plan that was constructed by a team I’m participating at the university where I study.

Somebody from my project group has scanned or taken snapshots of each of the hard copy paper feedback and has sent it to my mail.

I’ve received 13 images so I had to open them one by one to get each of the Project Plan to read the feedback on the page this was really unhandy, so I decided to give it a try on how to generate a common PDF file from all my picture files.

Thanksfully it happened to be very easy and trivial using the good old Image Magick

In order to complete the task of generating one PDF from a number of pictures all I did was.1. Switch to the directory where I have saved all my jpeg images

debian:~# cd /home/hipo/Desktop/my_images_directory/

2. Use the convert binary part of imagemagick package to generate the actual PDF file from the group of images

debian:~# convert *.jpg outputpdffile.pdf

If the images are numbered and contain many scanned pages of course you can always pass by all the images to the /usr/bin/convert binary, like for instance:

debian:~# convert 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg outputpdffile.pdf
Even though in my case I had to convert to PDF from multiple JPEG (JPG) pictures, convertion with convert is not restricted to convert only from JPEG, but you can also convert to PDF by using other graphical file formats.

For instance to convert multiple PNG pictures to a single PDF file the command will be absolutely the same except you change the file extension of the graphic files e.g.:

debian:~# convert 1.PNG 2.PNG 3.PNG 4.PNG 5.PNG OUTPUT-PDF-FILE.PDF

I was quite happy eventually to know Linux is so flexible and such a trivial things are able to be completed in such an easy way.

Filter messages in Qmail with unwanted words, get rid of the Viagra annoying spam with Qtrap

Sunday, September 4th, 2011

Drop qmail received mail containing banned / unwanted words to get rid of Viagra and Sex related spam

Recently the annoying Viagra spam has emerged again. Therefore I decided to clean up some of the mails received to one of the qmail servers to protect users emailbox from this viagra peril.

To do so I’ve remember about an old script which used to be part of qmailrocks.org qmail install, the script is called qtrap and is able to filter emails based on list of specific mail contained words.
Since qmailrocks.org is gone (down) for some time and its still available only on few mirrored locations which by the way are not too easy to find I decided to write a little post on how qtrap.sh could be integrated quick & easy with any Qmail + Vpopmail install out there.

Hereby I include the description for qtrap.sh given by the script author:

“qtrap.sh script is applied on a per domain basis and serves as a “bad word” scanner to catch any spam that Spamassassin may have missed. This filter serves as the last defense against SPAM before it arrived in your inbox. I like this filter because it helps to get rid of any SPAM that happens to make it by Spamassassin. Without any protection at all, my mailbox gets a shit ton of SPAM every day. Within the first 3 months I enacted the Qtrap filter, Qtrap logged over 9,000 deleted SPAM messages, none of which were legitimate e-mails. My keyboard’s delete key was very appreciated the extra rest.

Any emails that are scanned and contain a banned word will be automatically deleted and logged by the qtrap script. A whitelist feature now exists so that individual addresses or domains can be exempt from the qtrap scan.”

Now as one might have general idea on what the script does. Here is the step by step qtrap.sh integration;

1. Create necessery qtrap directory and logs and set proper permissions

If the vpopmail is installed in /home/vpopmail , issue the following commands.

debian:~# cd /home/vpopmail
debian:~# mkdir -p qtrap/logs
debian:/home/vpopmail/qtrap# cd qtrap
debian:/home/vpopmail/qtrap# wget https://www.pc-freak.net/files/qtrap.sh
...
debian:/home/vpopmail/qtrap# cd ~
debian:~# touch /home/vpopmail/qtrap/logs/qtrap.logdebian:~# chown -R vpopmail:vchkpw /home/vpopmail/qtrapdebian:~# chmod -R 755 /home/vpopmail/qtrap

On older qmail installations it could be vpopmail is installed in /var/vpopmail if that’s the case, link /var/vpopmail to /home/vpopmail and go back to step 1. To link:

debian:~# ln -sf /var/vpopmail/ /home/vpopmail

2. Edit qtrap.sh to whitelist email addresses and build a ban words list

a) Include the email addresses mail arriving from which would not be checked by qtrap.sh

Inside qtrap.sh in line 63, there is a shell function whitelist_check(), the function looks like so:

whitelist_check () {
case $WHITELIST in
address@somewhere.com|address@somewhereelse.com)
echo $SENDER found in whitelist on `date "+%D %H:%M:%S"` >> /home/vpopmail/qtrap/logs/qtrap.log
exit 0;;
*)
;;
esac
}

By default the script has just two sample mails which gets whitelisted this is the line reading:

address@somewhere.com|address@somewhereelse.com

The whitelisted emails should be separated with a pipe, thus to add two more sample emails to get whitelisted by script the line should be changed like:

address@somewhere.com|address@somewhereelse.com|hipod@mymailserver.com|hipo@gmail.com

In order to whitelist an entire domain let’s say yahoo.com add a line to the above code like:

address@somewhere.com|address@somewhereelse.com|hipod@mymailserver.com|hipo@gmail.com|*yahoo.com

b) Defining the bad words ban list, mails containing them should not be delivery by qmail

The function that does check for the ban word list inside the script is checkall();, below is a paste from the script function:

checkall () {
case $BANNED_WORDS in
porn|PORN|Sex|SEX)
printout $BANNED_WORDS
echo MESSAGE DROPPED from $SENDER because of $BANNED_WORDS on `date "+%D %H:%M:%S"` >> /home/vpopmail/qtrap/logs/qtrap.log
exit 99;;
*)
;;
esac
}

checkall(); is located on line 74 in qtrap.sh, the exact list of banned words which the script should look for is located on line 76, the default qtrap.sh filters only mails containing just 4 words, e.g.:

porn|PORN|Sex|SEX)

To add the Viagra and VIAGRA common spam words to the list, modify it and expand like so:

porn|PORN|Sex|SEX|viagra|Viagra)

The delimiter is again | , so proceed further and add any unwanted spam words that are not common for any legit mails.

3. Install qtrap.sh to process all emails delivered to vpopmail

If its necessery to install the dropping of mails based on word filtering only to a single vpopmail virtualdomain do it with cmd:

debian:~# cd /home/vpopmail/domains/yourdomain.com
debian:/home/vpopmail/domains/yourdomain.com# touch .qmail-default.new
debian:/home/vpopmail/domains/yourdomain.com# echo '| /home/vpopmail/qtrap/qtrap.sh' >> .qmail-default.new
debian:/home/vpopmail/domains/yourdomain.com# echo "| /home/vpopmail/bin/vdelivermail '' bounce-no-mailbox" >> .qmail-default.new
debian:/home/vpopmail/domains/yourdomain.com# chown vpopmail:vchkpw .qmail-default.new
debian:/home/vpopmail/domains/yourdomain.com# cp -rpf .qmail-default .qmail-default.bak; mv .qmail-default.new .qmail-default
If however qtrap.sh needs to get installed for all existing vpopmail virtualdomains on the qmail server, issue a one liner bash script:

debian:~# cd /home/vpopmail/domains
debian:/var/vpopmail/domains# for i in *; do cd $i; echo "| /home/vpopmail/qtrap/qtrap.sh" >> $i/.qmail-default.new;
echo "| /home/vpopmail/bin/vdelivermail '' bounce-no-mailbox" >> $i/.qmail-default.new;
chown vpopmail:vchkpw .qmail-default.new; mv .qmail-default .qmail-default.old; mv .qmail-default.new .qmail-default; cd ..; done

This for loop will add ‘| /home/vpopmail/qtrap/qtrap.sh’ to all .qmail-default for all vpopmail domains.

Afterwards the .qmail-default file should contain the following two lines:

| /home/vpopmail/qtrap/qtrap.sh
| /home/vpopmail/bin/vdelivermail '' delete

A very important thing here you should consider that adding some common words, as let’s say hello or mail etc. could easily drop almost all the emails the qmail hands in to vpopmail.

Caution!! Never ever implement common words in the list of words !!
Always make sure the banned words added to qtrap.sh are words that are never enter an everyday legit email.

Another thing to keep in mind is that qtrap.sh doesn’t make a copy of the received message ,though it can easily be modified to complete this task.
Any mail that matches the banned words list will be dropped and lost forever.

4. Check if qtrap.sh is working

To check, if qtrap is working send mail to some mailbox located on the qmail server containing inside subject or mail message body the unwanted word defined inside qtrap.sh.

The mail should not be received in the mailbox to which its sent, if qtrap is working moreover qtrap.sh should log it inside it’s log file:

debian:~# cat /home/vpopmail/qtrap/logs/qtrap.log
MESSAGE DROPPED from hipo@mytestmail.com because of viagra on 09/03/11 11:34:19
MESSAGE DROPPED from support@mymailserver.com because of Viagra on 09/03/11 11:39:29

If the qtrap.log contains records similar to the one above, and the mail matching the banned word is not delivered, qtrap.sh is properly configured. If any issues check in qmail logs, they should have a good pointer on what went wrong with qtrap.sh invokation.

Note that I’ve integrated qtrap.sh to custom qmail install running on Debian Lenny 5.0 GNU/Linux.
If I have time I’ll soon test if its working fine on the latest stable Debian Squeeze and will report here in comments.
If however someone is willing to test if the script works on Debian Squeeze 6.0 or have tested it already please drop a comment to report if it works fine.
qtrap.sh, is a bit oldish and is not written to work too optimal therefore on some heavy loaded mail servers it can create some extra load and a bit delay the mail delivery. Thus when implementang one needs to consider the downsides of putting it in.

Also I was thinking tt might be nice if the script is rewritten to read the ban words and whitelist mails from files instead of as it is now as the words are hard coded in the script.
If I have some free time, I’ll probably do this, though I’m not sure if this is a too good idea as this might have a negative performance impact on the script execution time, as each instance of the script invoked should do one more operation of reading a file storing the ban words.

Well that’s pretty much it, enjoy 😉

How to convert UTF-8 encoding files to Windows CP1251 on GNU / Linux

Friday, October 21st, 2011

I needed to convert a file which had a Bulgarian text written in UTF-8 encoding to Windows CP1251 in order to fix a website encoding problems after a move of the website from one physical server to another.

I tried first with enca( detects and convert encoding of text files from one encoding to another).

The exact way I tried to convert was:

linux:~# enca -L bg /home/site/www/includes/utf8_encoded_file.php
...
Unfortunately this attempt to conver was unsucesfully, and the second logical guess was to use iconvConvert encoding of given files from one encoding to another to do the utf8 to cp1251 conversion.
I reached for some help in irc.freenode.net, #varnalab channel and Alex Kuklin helped me, giving me an example command line to do the conversion.
iconv winedows to cp1251 conversion line, he pointed to me was:

linux:~# iconv -f utf8 -t cp1251 < in > out

Further on I adapted Alex’s example to convert my utf8_encoded_file.php encoded Bulgarian characted to CP1251 and used the following commands to convert and create backups of my original UTF8 file:

linux:~# cd /home/site/www/includes
linux:/home/site/www/includes# iconv -f utf8 -t cp1251 < utf8_encoded_file.php in > utf8_encoded_file.php.cp1251
linux:/home/site/www/includes# mv utf8_encoded_file.php utf8_encoded_file.php.bak
linux:/home/site/www/includes# mv utf8_encoded_file.php.cp1251 utf8_encoded_file.php