Script to download email and attachment using perl

Download email and attachment using Perl script.

#!/usr/bin/perl

use strict;
use warnings;

use Net::POP3;
use Email::MIME;
#use Email::MIME::Attachment::Stripper;

my $pop3server = ‘mypopservername';
my $username   = ‘myemail@address';
my $password   = ‘myPassW0rd';

my $popclient = Net::POP3->new( $pop3server, Timeout => 60 );

if ( $popclient->login( $username, $password ) > 0 )
{
foreach my $msgnum ( keys %{$popclient->list() } )
{
my $msg     = $popclient->get($msgnum);
my $message = join ”, @{$msg};

my $parsed = Email::MIME->new($message);
print ” No new mail arrived .\n”;

foreach my $part ( $parsed->parts() )
{
my $filename = $part->filename(1);

print “Read messagae $part .. my $filename. \n”;
open FILE, ‘>’, $filename
or do { warn “can’t open $filename – $!”; next; };
print FILE $part->body();
close FILE;
}
#$popclient->delete($msgnum); # remove # if you do not want to keep the message in the mailbox
}
}
$popclient->quit();

 


You would require to download the Net::POP3 and Email::MIME perl module for this script.

You can either download install from cpan or http://search.cpan.org individual installation.

Posted in Perl Script | Tagged , , , , , | Leave a comment

WordPress sites backup shell script

WordPress sites backup shell script

#! /bin/bash

## backup script for the wordpress site
## taking complete backup of website folder, database & apache configuration files
## itquery(at)gmail.com

TIMESTAMP=$(date +”%F”)
IPA=`hostname -I| awk ‘{print ($1)}’`
BACKUP_DIR=”/backup/BKP_$IPA/$TIMESTAMP”

#### Website folder path details ###
WWW=/opt/www

### MYSQL details ###
MYSQL_USER=”root”
MYSQL=/usr/bin/mysql
MYSQL_PASSWORD=”password”
MYSQLDUMP=/usr/bin/mysqldump

echo “Backup started `date`..”

mkdir -p “$BACKUP_DIR/mysql”

databases=`$MYSQL –user=$MYSQL_USER -p$MYSQL_PASSWORD -e “SHOW DATABASES;” | grep -Ev “(Database|information_schema|performance_schema)”`

for db in $databases; do
$MYSQLDUMP –force –opt –user=$MYSQL_USER -p$MYSQL_PASSWORD –databases $db | gzip > “$BACKUP_DIR/mysql/$db.gz”
done

mkdir -p “$BACKUP_DIR/conf.d”
cp -rvf /etc/httpd/conf.d/* $BACKUP_DIR/conf.d

ListFolder=`ls -1 $WWW`

for folder in $ListFolder; do
tar -zcvf $BACKUP_DIR/$folder.gz /opt/www/$folder

done

echo “Backup completed `date`..”

Posted in Database, Shell script | Leave a comment

Installation of Microsoft Security Essentials on Windows Server 2012 and 2012 R2

 Installation of  Microsoft Security Essentials on Windows Server 2012 and Windows Server 2012 R2

Download Microsoft Security Essentials from Microsoft download site –
http://windows.microsoft.com/en-us/windows/security-essentials-all-versions

>>  Right Click on the mseinstall.exe.
>> Properties
>> Compatibility tab.
>> Locate the Compatibility section.
>> Run this program in compatibility mode for
>> Select From the drop down menu Windows 7.
>> Open a Command Prompt with run as Administrator.
>> change current location to your download folder.
>> mseinstall /disableoslimit
>>  Follow the instruction of ms installer

Posted in Windows | Tagged , | Leave a comment

POODLE : Secure SSL configuration on apache

What is POODLE?

POODLE stands for Padding Oracle On Downgraded Legacy Encryption

Common Vulnerabilities and Exposures:
CVE-2014-3566

What is POODLE attack?

A man-in-the-middle exploit, which takes advantage of Internet and security software clients’ fallback to SSL 3.0

The attack occurs when an attacker is able to downgrade the client to use SSLv3. By simulating a failure during the negotiation process, an attacker can force a browser and a server to renegotiate using an older protocol, right back down to SSLv3.
Attacker aims to capture the session cookie within a HTTPS tunnel through MITM. Attacker injects a piece of JavaScript and intercepts the outgoing messages and reorganizes them. This JavaScript tells the browser to repeatedly try to load an image from the Web application transmitting a session cookie. This image request will carry with it the session cookie and the JavaScript ensures that each of these requests is constructed in such a way as to ensure that one byte of the session cookie is placed in a particular place within each SSL message.
In this way, attacker will learn a single byte of the session cookie with every request and the complete session cookie can be decrypted to gain malicious access to the application.
How to check if I am vulnerable?

Check your browser security using the below URL would confirm if the vulnerability exists.

https://dev.ssllabs.com/ssltest/viewMyClient.html

How to fix it?

Disable SSLv3 support on the server.
Use TLS_FALLBACK_SCSV, a mechanism that prevents attackers from forcing Web browsers to use SSL 3.0.For TLS clients:
TLS clients that use a downgrade dance to improve interoperability should include the value 0x56, 0x00 (TLS_FALLBACK_SCSV) in ClientHello.cipher_suites in any fallback handshakes. Thus, in case of a downgrade attack, clients would always fall back to the next lower version (if starting at TLS 1.2, try TLS 1.1 next, then TLS 1.0, then SSL 3.0) (With TLS_FALLBACK_SCSV, skipping a version also could entirely prevent a successful handshake if it happens to be the version that should be used with the server in question.)
For TLS servers:
In TLS servers, whenever an incoming connection includes 0x56, 0x00 (TLS_FALLBACK_SCSV) in ClientHello.cipher_suites, compare ClientHello.client_version to the highest protocol version supported by the server. If the server supports a version higher than the one indicated by the client, reject the connection with a fatal alert.
This use of TLS_FALLBACK_SCSV will ensure that SSL 3.0 is used only when a legacy implementation is involved and attackers can no longer force a protocol downgrade. (Attacks remain possible if bothparties allow SSL 3.0 but one of them is not updated to support TLS_FALLBACK_SCSV, provided that the client implements a downgrade dance down to SSL 3.0.)
Avoid potential phishing emails from attackers – to avoid going to an impersonated website.

How to fix this vulnerability on servers?
APACHE:

To disable SSLv3 on the Apache server, the following can be configured:

SSLProtocol All +TLS1 –SSLv2 –SSLv3
This will ensure that TLSv1.0, TLSv1.1 and TLSv1.2 are supported and explicitly remove support for SSLv2 and SSLv3. Check the config and then restart Apache.

$apachectl configtest
$service httpd restart

Posted in Apache | Tagged , , , | Leave a comment

Web server securing guide

1   OS Hardening

1.1          Kernel hardening

Update kernel parameter on /etc/sysctl.conf

# Turn on exec shield

kernel.exec-shield=1

kernel.randomize_va_space=1

# Enable IP spoofing protection

net.ipv4.conf.all.rp_filter=1

# Disable IP source routing

net.ipv4.conf.all.accept_source_route=0

# Ignoring broadcasts request

net.ipv4.icmp_echo_ignore_broadcasts=1

net.ipv4.icmp_ignore_bogus_error_messages=1

# Make sure spoofed packets get logged

net.ipv4.conf.all.log_martians = 1

1.2          Banner

This line should be present Banner /etc/issue.net In above file below entries should be present.

/etc/issue.net

WARNING!!

This system is the property of the ITQuery Solutions Ltd. and should be accessed only by authorized users. Unauthorized use of this system is strictly prohibited and will be subject to disciplinary action and prosecution. Systems and Technology Department may monitor any activity or communication on this system and retrieve any information stored within the system.

1.3          Password Policy

/etc/login.defs

Below 4 Values should be present.

PASS_MAX_DAYS   30

(Maximum number of days a password may be used. If the          password is older than this, a password change will be forced.)

PASS_MIN_DAYS   0                 

(Minimum number of days allowed between password changes. Any password changes attempted sooner than this will be rejected)

PASS_MIN_LEN    8                    

(Minimum Password Length)

PASS_WARN_AGE   15   

(Number of days warning given before a password expires. A zero means warning is given only upon the day of expiration, a negative value means no warning is given. If not specified, no warning will be provided.)

1.4          Disable     rsh service status

/etc/xinetd.d/rsh

Disable = yes

Check for # chkconfig --list rsh

rsh             off

1.5          Telnet service status

/etc/xinetd.d/telnet

disable= yes

Check for # chkconfig --list telnet

telnet=off

1.6          Disable CTRL+ALT+DEL

cat /etc/inittab |grep ctrl

#ca::ctrlaltdel:/sbin/shutdown -t3 -r now

Comment out above line in inittab to disable ctrl+alt+del key sequence which can reboot the system

1.7          iptables Rules

The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:

#!/bin/bash

inet_if=eth1

ssh_port=22

$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --set

$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --update --seconds 60 --hitcount 5 -j DROP

 

Call above script from your iptables scripts. Another config option:

 


$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT

$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT

$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT

# Another one line example


$IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT

1.8   Thwart SSH Crackers (Brute Force Attack)

Download and install “DenyHosts” from http://denyhosts.sourceforge.net

DenyHosts is a Python based security tool for SSH servers.

It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.

 

1.9   Audit

Install audit package if not present and enable in init


$chkconfig auditd on

1.9.1   Set a watch on a file for auditing

$ auditctl -w /etc/passwd -p war -k password-file

$ auditctl -w /etc/shadow -k shadow-file -p rwxa

$ auditctl -a exit,never -S mount

$ auditctl -a entry,always -S all -F pid=1005

1.9.2   Enabled audit rules

vi /etc/audit/audit.rules

Add below lines, more can also be customized as per requirement

-a exit,always -F path=/bin/rm -k rmcommand

-a exit,always -F path=/bin/mv -k mvcommand

-a exit,always -F path=/bin/kill -k killcommand

-a exit,always -F path=/usr/bin/passwd -k passwdcommand

-a exit,always -F path=/bin/chown -k chowncommand

-a exit,always -F path=/bin/chmod -k chmodcommand

-a exit,always -F path=/bin/vi -k vicommand

-a exit,always -F path=/usr/bin/vim -k vimcommand

-a exit,always -F path=/usr/bin/crontab -k crontabcommand

 

vi  /etc/audit/auditd.conf

num_logs = 8

max_log_file = 50

# service auditd restart

 

1.10      PAM

vi /etc/pam.d/system-auth

Enter this entry in password section:

 

auth        required      pam_env.so

auth        required      pam_tally2.so deny=5 onerr=fail unlock_time=1800

auth        sufficient    pam_unix.so nullok try_first_pass

 

 

password    requisite     pam_cracklib.so retry=5 minlen=8 lcredit=1 ucredit=1 dcredit=1 ocredit=1 difok=3

password    sufficient     pam_unix.so nullok use_authtok md5 shadow remember=5

 

vi /etc/ssh/sshd_config

 

 

# Change to no to disable s/key passwords

ChallengeResponseAuthentication yes

ChallengeResponseAuthentication no

 

 

1.11   Below Services should be disabled on newly installed server.


bluetooth
cups
avahi-daemon
hplip
hidd
ip6tables
iptables
isdn
mcstrans
pcscd
tog-pegasus

 

1.12   Other system wide sanity check

1.12.1Check Current Status of Startup Services

chkconfig –list | grep ‘3:on’

 

1.12.2Remove not required packages from system

yum erase inetd xinetd ypserv tftp-server telnet-server rsh-serve

1.12.3Enable SELinux

/etc/sysconfig/selinux

SELINUX= enforcing

1.12.4Check system wide guest rwx

systemwide directory having write rwx access for guest/other user

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print

 

1.12.5 Non existing owner file check

find / -xdev \( -nouser -o -nogroup \) -print

 

1.12.6Write Protect Apache, PHP, and, MySQL Configuration Files

chattr +i /etc/php.ini

chattr +i /etc/php.d/*

chattr +i /etc/my.ini

chattr +i /etc/httpd/conf/httpd.conf

chattr +i /etc/

2      VSFTP configuration

 

/etc/vsftpd/vsftpd.conf

# You may fully customize the login banner string:

ftpd_banner=Welcome to ITQueryt Solutions’s FTP Server.

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

use_localtime=YES

pasv_enable=YES

anonymous_enable=NO

chmod_enable = NO

chroot_list_enable = NO

guest_enable= NO

 

 

/etc/vsftpd/user_list

# vsftpd userlist

# If userlist_deny=NO, only allow users in this file

# If userlist_deny=YES (default), never allow users in this file, and

# do not even prompt for a password.

# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers

# for users that are denied.

root

bin

daemon

adm

lp

sync

shutdown

halt

mail

news

uucp

operator

games

nobody

 

cat /etc/vsftpd/ftpusers

# Users that are not allowed to login via ftp

root

bin

daemon

adm

lp

sync

shutdown

halt

mail

news

uucp

operator

games

nobody

 

 

 

 

3      SSH Hardening

3.1 Secure OpenSSH Server (/etc/ssh/sshd_config)

No Remote root Login

Allow Users xyz abc etc

Configure Idle Log out Timeout Interval

Disable .rhosts Files

Disable Empty Passwords

ClientAliveInterval 300

ClientAliveCountMax 0

PermitRootLogin no

IgnoreRhosts yes

PermitEmptyPasswords no

 

3.2 Use TCP Wrappers to enable ssh login from given ip address only (/etc/hosts.allow)

sshd : 192.xx.xx.xx 172.xx.xx.xx etc..

(/etc/hosts.deny)

sshd: ALL

 

3.3  Hide openssh version

#  Turn on privilege separation

UsePrivilegeSeparation yes

# Prevent the use of insecure home directory and key file permissions

StrictModes yes

# Turn on reverse name checking

VerifyReverseMapping yes

# Do you need port forwarding?

AllowTcpForwarding no

X11Forwarding no

#  Specifies whether password authentication is allowed.  The default is yes.

#  Use this only when you have key base authentication

PasswordAuthentication no 

 

 

 

 

4      Send mail Hardening

4.1          Configure Mail Submission

Edit /etc/sysconfig/sendmail modify the line:

DAEMON=no

machine should forward it’s all outgoing mail.

# Edit /etc/mail/submit.cf

D{MTAHost}mail.itquery.com

 

4.2          Mail server masquerading

Sendmail config file /etc/mail/sendmail.mc:

Append/add/modify the lines as follows:

 

MASQUERADE_AS(itquery.com)dnl

FEATURE(masquerade_envelope)dnl

FEATURE(masquerade_entire_domain)dnl

MASQUERADE_DOMAIN(itquery.com)dnl

 

Update and restart sendmail server:

$ m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf

$ /etc/init.d/sendmail restart

 

5      Apache Hardening

Create separate partitions for Apache and FTP server roots (/opt/www/).

Edit /etc/fstab file and make sure you add the following configuration options:

noexec - Do not set execution of any binaries on this partition (prevents execution of binaries but allows scripts).

nodev - Do not allow character or special devices on this partition (prevents use of device files such as zero, sda etc).

nosuid - Do not set SUID/SGID access on this partition (prevent the setuid bit).

Sample /etc/fstab entry to to limit user access on /dev/sda5 (ftp server root directory):

5.1   Suggestion for apache installations –

It is highly recommended to have web server (apache) installation to have a separate instance in DMZ environment, application and database should reside on separate instance behind the DMZ server.

5.2   Suggestive apache configuration

Directive and configuration setting

Description

ServerSignature Off

Prevents server from giving version info on error pages.

ServerTokens Prod

Prevents server from giving version info in HTTP headers

User apache

Ensure that the child processes run as unprivileged user

Group apache

Ensure that the child processes run as unprivileged group

ErrorDocument 404 errors/404.html
ErrorDocument 500 errors/500.html
etc…

To further obfuscate the web server and version, this will redirect to a page that you should create, rather than using the default Apache pages.

ServerAdmin webmaster@itquery.com

Use a mail alias – never use a person’s email address here.

UserDir disabled root

Remove the UserDir line, since we disabled this module.  If you do enable user directories, you’ll need this line to protect root’s files.


 

 

<Directory />
Order Deny, Allow
Deny from all
</Directory>

Deny access to the root file system.

<Directory /opt/www ">
<LimitExcept GET POST>
Deny from all</LimitExcept>

Options -FollowSymLinks -Includes -Indexes  -MultiViews  AllowOverride None

Order allow,deny
Allow from all
</Directory>

LimitExcept prevents TRACE from allowing attackers to find a path through cache or proxy servers.

The “-“ before any directive disables that option.

FollowSymLinks allows a user to navigate outside the doc tree, and Indexes will reveal the contents of any directory in your doc tree.

Includes allows .shtml pages, which use server-side includes (potentially allowing access to the host).  If you really need SSI, use IncludesNoExec instead.

AllowOverride None will prevent developers from overriding these specifications in other parts of the doc tree.

AddIcon
IndexOptions
AddDescription
ReadmeName
HeaderName
IndexIgnore

Remove all references to these directives, since we disabled the fancy indexing module.

Alias /manual

Don’t provide any accessible references to the Apache manual, it gives attackers too much info about your server. (remove)

 

 

 

5.3   Apache module “mod_security“

 

ModSecurity™is an open source, free web application firewall (WAF) Apache module. With over 70% of all attacks now carried out over the web application level, organizations need all the help they can get in making their systems secure. WAFs are deployed to establish an external security layer that increases security, detects and prevents attacks before they reach web applications. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.

It is recommended to Install and configure mod_secutiry a plugin for apache’ httpd server to secure and filter the request received and served.

This can be downloaded from http://www.modsecurity.org/

6      PHP Hardening

 

PHP perform better with a reduced modules and security, hence would recommend to remove these item –

SQLITE -

mv /etc/php.d/sqlite3.ini /etc/php.d/sqlite3.disable

Modify/update php configuration with suggested parameter -

/etc/php.ini

file_uploads=On

# user can only upload upto 1MB via php

upload_max_filesize=1M

allow_url_include=Off

open_basedir="/opt/www"

disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

Update modify security configuration -

/etc/php.d/security.ini

expose_php=Off

log_errors=On

error_log=/var/log/httpd/php_scripts_error.log

Posted in Apache, Shell script, Unix/Linux | Leave a comment

Find and replace character in SQL script

 Find and replace character in SQL script

UPDATE TABLE SET LoginId = REPLACE( LoginId, ‘_’, ‘.’ ), SSO = REPLACE(SSO, ‘_’, ‘.’ ) WHERE LoginId IS NOT NULL

Posted in Database, Unix/Linux | Tagged | 1 Comment

awk one liners

### In order to join 2 lines seprated with new line “^M” character

$awk ‘/^M$/ {print;next;} {printf(“%s”,$0);}’ FileName.txt

Posted in Shell script, Unix/Linux | Leave a comment

Error during apache httpd starup

1. “[error] Init: SSLPassPhraseDialog builtin is not supported on Win32″

Reason - Apache has been installed on windows and unable to start because HTTPS  configuration.

Solution -

  • a. Remove/comment SSLPassPhrase context fromssl.conf or httpd.conf
  • b. Make a copy of the private key and call it “server.key.org”
  • c. Use the OpenSSL command to remove the passphrase such as;

# openssl rsa -in server.key.org -out server.key

server.key will be your new private key with the passphrase removed.

Restart apache httpd service.

Posted in Apache, Unix/Linux, Windows | Tagged , , | Leave a comment

4 Easy step for password less Self Signed Certificate

4 Easy step for password less Self Signed Certificate

#openssl genrsa -des3 -out server.passwd.key 1024

#openssl rsa -in server.passwd.key -out server.key

#openssl req -new -key server.key -out server.csr

#openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Posted in Unix/Linux | Tagged | Leave a comment

Logging exception stacktrace

Logging standard message is simple

Following are the different ways to log messages using Log4J

  • Log.debug (“Debug Message”);
  • Log.info (“Info Message”);
  • Log.warn (“Warning Message”);
  • Log.error (“Error Message”);

But sometime we need to log exception along with stacktrace, for that we need to use

LOG.log(Level.ERROR, exception.getMessage(), exception);

No special configuration required for this behaviour.

Posted in Java | Leave a comment