Postfix part 2 BCC Maps , SMTP Auth , relay domains

Blind Carbon Copy Maps

#vim /etc/postfix/main.cf

#always_bcc = username  -->this user will get the copy of every message traversing/communicating in your system.
always_bcc = root       #you can use file redirects insted of root user

save/exit
#service postfix reload/restart

For demo:
send mail from userX  to userY, the root user will get the copy of message.

-- -- -- --- -
To get BCC msg Sent (Received) by selective user

[root@server1 postfix]# vim /etc/postfix/main.cf
#always_bcc = root
sender_bcc_maps = hash:/etc/postfix/sender_bcc                                                       
#recipient_bcc_maps = hash:/etc/postfix/recipient_bcc    //mail received by user listed in recipient_bcc will be bcc'd to target user/file

[root@server1 postfix]#vim /etc/postfix/sender_bcc
#LHS(sender to match)   RHS(BCC Recipient)
salman                  root

[root@server1 postfix]#postmap sender_bcc

[root@server1 postfix]# file sender_bcc.db      < - hash db created
sender_bcc.db: Berkeley DB (Hash, version 9, native byte-order)

= = = = = = =  =  =
=   SMTP Auth  =
= = = = = = =  =  =

[root@server1 sasl2]# rpm -qa | grep sasl
cyrus-sasl-lib-2.1.23-13.el6_3.1.i686
cyrus-sasl-plain-2.1.23-13.el6_3.1.i686
cyrus-sasl-gssapi-2.1.23-13.el6_3.1.i686
cyrus-sasl-2.1.23-13.el6_3.1.i686
cyrus-sasl-devel-2.1.23-13.el6_3.1.i686
cyrus-sasl-md5-2.1.23-13.el6_3.1.i686

#vim /etc/postfix/main.cf
             #add
smtpd_sasl_path=smtpd             
smtpd_sasl_auth_enable = yes    

(we are using pam authentication)

#cat /etc/sysconfig/saslauthd                                       #for more info and modification

...................................................................................................................................................
#vim /usr/lib/sasl2/smtpd.conf

pwcheck_method: saslauthd
mech_list: PLAIN LOGIN


[root@server1 postfix]#service saslauthd start                    
OR
[root@server1 postfix]# saslauthd -a pam                           
[root@server1 postfix]# ps -ef | grep sasl
root      1281     1  0 07:54 ?        00:00:00 saslauthd -a pam
root      1282  1281  0 07:54 ?        00:00:00 saslauthd -a pam
root      1283  1281  0 07:54 ?        00:00:00 saslauthd -a pam
root      1284  1281  0 07:54 ?        00:00:00 saslauthd -a pam
root      1285  1281  0 07:54 ?        00:00:00 saslauthd -a pam
root      1290  1261  0 07:56 pts/0    00:00:00 grep sasl

# vim /etc/postfix/main.cf

smtpd_sasl_auth_enable = yes


smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination 



Relaydomain database
- - - -- - -  - - - - - - - --  --
Defining Rlay_domains Maps
# rpm -qa | grep db
Initially check for the Berkley DB packages are installed. These packages will be used by the postfix for database support.

/etc/postfix/main.cf

relay_domains = $ mydestination,  hash:/etc/postfix/relay_domains    #this could be any name


# vim /etc/postfix/relaydomains
domain1.com
domain2.com
domain3.com
domain4.com
domain5.com
# postmap /etc/postfix/relaydomains
# postfix reload

iptables

# Modify this file accordingly for your specific requirement.

# 1. Delete all existing rules

iptables -F

# 2. Set default chain policies

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# 3. Block a specific ip-address

#BLOCK_THIS_IP="x.x.x.x"
#iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP

# 4. Allow ALL incoming SSH
#iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# 5. Allow incoming SSH only from a sepcific network
#iptables -A INPUT -i eth0 -p tcp -s 192.168.200.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# 6. Allow incoming HTTP
#iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT

# Allow incoming HTTPS
#iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

# 7. MultiPorts (Allow incoming SSH, HTTP, and HTTPS)
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT

# 8. Allow outgoing SSH
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# 9. Allow outgoing SSH only to a specific network
#iptables -A OUTPUT -o eth0 -p tcp -d 192.168.101.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# 10. Allow outgoing HTTPSiptables -A OUTPUT -o eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

# 11. Load balance incoming HTTPS traffic
#iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
#iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
#iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

# 12. Ping from inside to outside
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

# 13. Ping from outside to inside
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

# 14. Allow loopback access
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# 15. Allow packets from internal network to reach external network.
# if eth1 is connected to external network (internet)
# if eth0 is connected to internal network (192.168.1.x)
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

# 16. Allow outbound DNS
#iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT
#iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT

# 17. Allow NIS Connections
# rpcinfo -p | grep ypbind ; This port is 853 and 850
#iptables -A INPUT -p tcp --dport 111 -j ACCEPT
#iptables -A INPUT -p udp --dport 111 -j ACCEPT
#iptables -A INPUT -p tcp --dport 853 -j ACCEPT
#iptables -A INPUT -p udp --dport 853 -j ACCEPT
#iptables -A INPUT -p tcp --dport 850 -j ACCEPT
#iptables -A INPUT -p udp --dport 850 -j ACCEPT

# 18. Allow rsync from a specific network
iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT

# 19. Allow MySQL connection only from a specific network
iptables -A INPUT -i eth0 -p tcp -s 192.168.200.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT

# 20. Allow Sendmail or Postfix
iptables -A INPUT -i eth0 -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT

# 21. Allow IMAP and IMAPS
iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT

iptables -A INPUT -i eth0 -p tcp --dport 993 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 993 -m state --state ESTABLISHED -j ACCEPT

# 22. Allow POP3 and POP3S

iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT

iptables -A INPUT -i eth0 -p tcp --dport 995 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 995 -m state --state ESTABLISHED -j ACCEPT

# 23. Prevent DoS attack
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

# 24. Port forwarding 422 to 22
iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22
iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT

# 25. Log dropped packets

iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7
iptables -A LOGGING -j DROP

Postfix part 1 DNS, aliases, vacation , sender receiver canonical maps

http://flurdy.com/docs/postfix/#config-imap-dovecot

Setup the system time
http://repos.oostergo.net/6/postfix-2.11/                              
[root@server1 postfix]# date --set="26 May 2014 22:56:00"
Mon May 26 22:56:00 NPT 2014

Setting up D.N.S record           Example 1                                                                             
#yum install bind*
On centos 6.5 problem in starting named may occur to resolve follow below step:-
 [root@mta1 ~]# service named start
Generating /etc/rndc.key:                               ..Stucks here


[root@mta1 ~]# rndc-confgen -a -r /dev/urandom
wrote key file "/etc/rndc.key"


 #service named start

--------------------------------------------------------------------------------------------

#cat /etc/named.conf
...
.......
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
zone "blues.com" IN {
    type master;
    file "blues.com";
    allow-update { none; };
};
zone "213.168.192.in-addr.arpa" IN {
    type master;
    file "192.168.213.zone";
    allow-update { none; };
};
recursion no;   #for testing in virtual enviroment
---------------------------------------------------------------------------------

Forward Zone 1                       
[root@localhost named]# cat blues.com
$TTL 1D ; time a RR may be cached(or saved) by another DNS server.
$ORIGIN blues.com.
@    IN SOA    server1.blues.com. dnsadmin.blues.com (
                    2014130501    ; serial
                    1D    ; refresh When the refreshvalue is reached, the slave name server for this zone will try to read the SOA RR from the zone master
                    1H    ; retry Defines the retry interval in secondsif the slave fails to make contact with the zone master during a refresh cycle. Typical values are from 10 to 60 minutes.
                    1W    ; expire Defines the time in seconds after which the zone records are assumed to be no longer authoritative
                    3H )    ; minimum
@  IN    NS    server1.blues.com.
@  IN   MX 10 server1.blues.com.

server1.blues.com.  IN    A 192.168.213.10


Setting up D.N.S record              Example  2                                                                          

                                       Forward Zone 2                                                 
[root@localhost named]# vim sagarmatha.org

$TTL 1D ; time a RR may be cached(or saved) by another DNS server.
$ORIGIN sagarmatha.org.
@    IN SOA    sagarmatha.org. dnsadmin.sagarmatha.org (
                    2014130502    ; serial
                    1D    ; refresh When the refreshvalue is reached, the slave name server for this zone will try to read the SOA RR from the zone master
                    1H    ; retry Defines the retry interval in secondsif the slave fails to make contact with the zone master during a refresh cycle. Typical values are from 10 to 60 minutes.
                    1W    ; expire Defines the time in seconds after which the zone records are assumed to be no longer authoritative
                    3H )    ; minimum

@  IN    NS    server1.sagarmatha.org.
@  IN   MX 10 server1.sagarmatha.org.

server1                       IN A 192.168.213.10
sagarmatha.org.           IN A 192.168.213.10
www                          IN CNAME server1.sagarmatha.org.
mail                            IN CNAME server1.sagarmatha.org.
Reverse Zone
[root@server1 named]# cat 192.168.213.zone
$TTL 1D
@    IN SOA    server1.blues.com. dnsadmin.blues.com. (
                    2014130504    ; serial
                    1D    ; refresh
                    1H    ; retry
                    1W    ; expire
                    3H )    ; minimum
213.168.192.in-addr.arpa.  IN    NS    server1.blues.com.

10 IN    PTR    server1.blues.com.

############
postfix aliases (mail will be redirected to users mentioned on list)                     

1)one to one
vim /etc/aliases
postmaster: root    <=this is one to one where root is reciepient
2)one to many (or List alias)
sales:  root,user12,user3    <=this is one to many where blue-highlighted items are recipients for group sales
3)include example:
support:  :include:/etc/postfix/support_list.txt
4)File eg.  abuse:  /var/log/mail/abuse.mail    <=mail will be appended to the target file (here the file is abuse.mail)
5)Pipes  eg-  help:  |/usr/local/bin/sendhelp   <=pipes allow another application or script take care of the mail.
Run #newaliases   
after changing /etc/aliases

##############
local.forward    File
any message destined to user1@exampledomain.com  can be further redirected to another account or another acc. on another machine 
First install the vacation program
youcan download the vacation binary here http://puias.math.ias.edu/data/puias/6/x86_64/os/Addons/vacation-1.2.7.0-7.puias6.x86_64.rpm
now in my case ,
[root@mailvm ~]# yum install vacation-1.2.7.0-7.puias6.x86_64.rpm
Transaction Test Succeeded
Running Transaction
  Installing : vacation-1.2.7.0-7.puias6.x86_64                                                                                                                    1/1
  Verifying  : vacation-1.2.7.0-7.puias6.x86_64                                                                                                                   1/1 Installed:
  vacation.x86_64 0:1.2.7.0-7.puias6

[root@mailvm ~]# which vacation
/usr/bin/vacation

Create a hidden file .vacation.msg and write your message on it :

[orange@mailvm ~]$ cat .vacation.msg
Hi !! I am on vacation

Create a hidden file .forward

[orange@mailvm ~]$ cat .forward
\orange, "|/usr/bin/vacation orange"    #here orange is a local linux acc user

Note :  the " \ "infront of "orange," will tell postfix not to do  any further lookups for alias orange and
|  will pipe the email to the vacation program to process

this notation \orange, "|/usr/bin/vacation orange"    caues the vacation message sent back to user.

Initialize the vacation program
$ vacation -i
$ls -al
 -rw-r--r--. 1 orange orange 12288 May 16 23:07 .vacation.db   <=new file created after initializing vacation program.
all the messages that are sent to sender as response are stored and know when/who to respond ,mitigates DOS attacks

Now for demo:
ssh into your machine as "root" and send mail to user  "orange" using mail or mutt here i used mutt
the message to the root appears like this
[root@mailvm Mail]# mutt

i:Exit  -:PrevPg  <Space>:NextPg v:View Attachm.  d:Del  r:Reply  j:Next ?:Help
Date: Fri, 16 May 2014 23:18:39 +0545 (NPT)
From: orange@mailvm.fender.com
To: root@mailvm.fender.com
User-Agent: 1.2.7 http://vacation.sourceforge.net

Hi Iam on vacation leave

#sendmail -v user11@remotesystem.com
testing remote mail
Ctrl+d( to send)
- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --

#cd /var/spool/postfix/maildrop
messages are dropped in maildrop using postfix compatible command called sendmail with/out postfix master process need not necessary to run

pickup process (usr/libexec/pickup)spawned by master program feeds locally submitted message to cleanup process(takes care of addressing task like

from: to: fqdn check etc)
message is then moved to qmgr process(deliver message using localmailing or localmailing and smtp)


# cat /etc/nsswitch.conf
this file contains directives which dictates order in which name resolution occurs

-- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- --  -- -- - myorigin / masquerading
-- -- -- -- -- -- -- -- -- --
Define outbound envelope information [masquerading] not header information
$mydomain=example1.com
$myorigin=$mydomain

$myorigin is used for masquerading



-- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- ---- -- --
note: mail routing is based on header information.  

 #service postfix reload

check for new mail check duration
user123@mailserver1.example.com$ set  | grep -i mail
MAIL=/var/mail/user123
MAILCHECK=60       ;;mailcheck is 60 seconds


"  canonical maps  "                                                                               
                         @For         --             Local users
Types :
  1. #canonical_maps = hash:/etc/postfix/canonical      //will effect   sender/receiver
  2. #sender_canonical_maps=hash:/etc/postfix/canonical   //will effect only sender part , rcpt portion is   untouched
  3. #recipient_canonical_maps=hash:/etc/postfix/canonical   //will effect only recipient part,sender portion is untouched 



(rewriting at cleanup process and trivial rewrite process is done)
canonical map will alter <envelope from> and <envelope to> addresses which are heading out of the machine to recipient.

vim /etc/postfix/canonical
#any message "from" user "apple" should be re written to "applefruit" and david to david.baekham
apple  applefruit
david      david.beckham


#vim /etc/postfix/main.cf

                                       [  type  :   /  location  ]     
canonical_maps =  hash:/etc/postfix/canonical


#postmap /etc/postfix/canonical    // this will generate (hash database) canonical.db file
note: postmap requires berkley library pkg's
@   with --> canonical_maps                                                               

{for inbound emaild}
#tail /var/log/maillog
May 26 18:46:21 mailvm postfix/pickup[1129]: EA2E0FF660: uid=501 from=<apple>
May 26 18:46:21 mailvm postfix/cleanup[1272]: EA2E0FF660: message-id=<20140526130121.GB1212@mailvm.urgens.com>
May 26 18:46:21 mailvm postfix/qmgr[1130]: EA2E0FF660: from=<applefruit@urgens.com>, size=433, nrcpt=1 (queue active)
May 26 18:46:22 mailvm postfix/local[1274]: EA2E0FF660: to=<root@mailvm.urgens.com>, relay=local, delay=0.11, delays=0.08/0.03/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
May 26 18:46:22 mailvm postfix/qmgr[1130]: EA2E0FF660: removed
 

#changing /etc/aliases
.;;[user]    is equivalent to local user dean ;;       
sales: user1,root,managersales
applefruit:      apple
save/exit
#new aliases


@/etc/postfix/main.cf
-- -- -- -- --   -- -- - - - -- -- - - -- -- - - - -- - - - -   - - -  - -- --  --  - - - -  
Summary
-- -- - --  --  -- - -- -- - -- -- - - -- -- - -- - -- - -   -- --  -- - -- - - - -- - - -
#canonical_maps = hash:/etc/postfix/canonical      //will effect sender/receiver


#sender_canonical_maps=hash:/etc/postfix/canonical   //will effect only sender part , rcpt portion is   untouched
#recipient_canonical_maps=hash:/etc/postfix/canonical   //will effect only recipient part,sender portion is untouched

----- 

with sender_canonical_maps                                            .

From applefruit@urgens.com  Mon May 26 23:36:02 2014
Return-Path: <applefruit@urgens.com>
X-Original-To: apple@mailvm.urgens.com
Delivered-To: apple@mailvm.urgens.com
Received: by mailvm.urgens.com (Postfix, from userid 501)
           id 30BE4FF6A0; Mon, 26 May 2014 23:36:02 +0545 (NPT)
Date: Mon, 26 May 2014 23:36:02 +0545
From: applefruit@urgens.com
To: apple@mailvm.urgens.com
Subject: sender canonical test
Message-ID: <20140526175102.GA1574@mailvm.urgens.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
User-Agent: Mutt/1.5.20 (2009-12-10)

with recipient_canonical_maps   

From apple@urgens.com  Mon May 26 23:39:42 2014
Return-Path: <apple@urgens.com>
X-Original-To: apple@mailvm.urgens.com
Delivered-To: applefruit@urgens.com
Received: by mailvm.urgens.com (Postfix, from userid 501)
           id 31346FF683; Mon, 26 May 2014 23:39:42 +0545 (NPT)
Date: Mon, 26 May 2014 23:39:42 +0545
From: apple@mailvm.urgens.com
To: applefruit@urgens.com
Subject: reciepient canonical test
Message-ID: <20140526175442.GB1574@mailvm.urgens.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
User-Agent: Mutt/1.5.20 (2009-12-10)

Notice the envelope and header parts ...


mysql reset user password

Setting, Changing And Resetting MySQL Root Passwords

 
This tutorial explains how you can set, change and reset (if you've forgotten the password) MySQL root passwords. Time and again I see problems like mysqladmin:  connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: YES)'. So I thought it's time to remind you how to solve MySQL related password problems. If you are just looking for a quick fix how to reset a MySQL root password you can find that at the bottom of this tutorial.

mysqladmin Command To Change Root Password

Method 1 - Set up root password for the first time

If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. To set up a root password for the first time, use the mysqladmin command at the shell prompt as follows:
$ mysqladmin -u root password newpass
If you want to change (or update) a root password, then you need to use the following command:
$ mysqladmin -u root -p oldpassword newpass
Enter password:
If you get...
mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost' (using password: YES)'
then follow the instructions below on how to recover your MySQL password.

Change MySQL password for other users

To change a normal user password you need to type:
$ mysqladmin -u user-name -p oldpassword newpass
 

Method 2 - Update or change password

MySQL stores usernames and passwords in the user table inside the MySQL database. You can directly update a password using the following method to update or change passwords:
1) Login to the MySQL server, type the following command at the shell prompt:
$ mysql -u root -p
2) Use the mysql database (type commands at the mysql> prompt):
mysql> use mysql;
3) Change password for a user:
mysql> update user set password=PASSWORD("newpass") where User='ENTER-USER-NAME-HERE';
4) Reload privileges:
mysql> flush privileges;
mysql> quit
This method you need to use while using PHP or Perl scripting.

Recover MySQL root password

You can recover a MySQL database server password with the following five easy steps:
Step # 1: Stop the MySQL server process.
Step # 2: Start the MySQL (mysqld) server/daemon process with the --skip-grant-tables option so that it will not prompt for a password.
Step # 3: Connect to the MySQL server as the root user.
Step # 4: Set a new root password.
Step # 5: Exit and restart the MySQL server.
Here are the commands you need to type for each step (log in as the root user):
Step # 1 : Stop the MySQL service:
# /etc/init.d/mysql stop
Output:
Stopping MySQL database server: mysqld.
Step # 2: Start the MySQL server w/o password:
# mysqld_safe --skip-grant-tables &
Output:
[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started
Step # 3: Connect to the MySQL server using the MySQL client:
# mysql -u root
Output:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
Step # 4: Set a new MySQL root user password:
mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
Step # 5: Stop the MySQL server:
# /etc/init.d/mysql stop
Output:
Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended

[1]+  Done                    mysqld_safe --skip-grant-tables
Start the MySQL server and test it:
# /etc/init.d/mysql start
# mysql -u root -p

mysql secure installation error touch: cannot touch `.my.cnf.4519': Read-only file system

[root@mailvm Packages]# mysql_secure_installation
touch: cannot touch `.my.cnf.4519': Read-only file system
touch: cannot touch `.mysql.4519': Read-only file system
chmod: cannot access `.my.cnf.4519': No such file or directory
chmod: cannot access `.mysql.4519': No such file or directory

Just change your directory to other than dvd or cd
eg. to / or
and run #mysql_secure_installation

setup icinga monitoring server and client complete (basic swap ,load,disk ,http service monitor)


Setting up icinga monitoring server on centos 6.4 (2014-May-13)
#yum install screen
1.    Install core pacakges needed by icinga
[root@zabbix ~]# yum install -y rsync vim wget curl git zip unzip mlocate make
#yum install httpd gcc glibc glibc-common gd gd-devel   -y
#yum install libjpeg libjpeg-devel libpng libpng-devel  -y
#yum install net-snmp net-snmp-devel net-snmp-utils   -y
 
 
2.    Build a download folder and get all the software from Icinga we will need.
[root@zabbix ~]# mkdir /opt/installs
[root@zabbix ~]# cd /opt/installs
This is the core package
This is web front end
Grab the nagios plugins
Get latest NRPE modules
[root@zabbix installs]# ls
icinga-1.10.1.tar.gz      nagios-plugins-2.0.1.tar.gz
icinga-web-1.10.0.tar.gz  nrpe-2.15.tar.gz
Create user  named   =   icinga
[root@zabbix installs]# passwd icinga
Changing password for user icinga.
New password:    password123
Retype new password:    password123
passwd: all authentication tokens updated successfully.
Check if icinga group and icinga user are there by command # groups  icinga
If not create icinga group and add icinga user to that group
For sending commands to classic interface you will need to :=
[root@zabbix installs]# groupadd icinga-cmd
[root@zabbix installs]# usermod -a -G icinga-cmd icinga
[root@zabbix installs]# usermod -a -G icinga-cmd apache
Compile and install icinga
# tar xvf icinga-1.10.1.tar.gz
# cd icinga-1.10.1
#\  Run the configure script and make the install
# ./configure --with-command-group=icinga-cmd --disable-idoutils
#make all
#make fullinstall
# make install-config
Run again.
# make install-config
 
Customizing configuration
 
[root@zabbix objects]# cat /usr/local/icinga/etc/objects/contacts.cfg
 
# template which is defined elsewhere.
define contact{
contact_name                    icingaadmin2                       ; Short name of user
use                                 generic-contact                       ; Inherit default values from generic-contact template (defined above)
alias                         Sarose(Admin)                ; Full name of user
;  email                           icinga@localhost        ; <<***** CHANGE THIS TO YOUR EMAIL ADDRESS ******
;added by urgen 5-13-2014 12:14pm
email                         alerts@urgens.com  ; <=put your email here
}
# CONTACT GROUPS
#
define contactgroup{
contactgroup_name       admins
alias                   Icinga Administrators
members                 icingaadmin2
}
-------------------------------------------------------------------------------
 
Configure the classic web interface:
 
[root@zabbix icinga-1.10.1]# pwd
/opt/installs/icinga-1.10.1
 
#make cgis
# make install-cgis
 # make install-html
Install the Apache config:
Install the Icinga Classic web config file in the Apache conf.d directory (conf-available starting with Apache 2.4).
# make install-webconf
Create an icingaadmin account for logging into the Icinga classic web interface. If you want to change it later, use the same command. Remember the password you assign to this account - you'll need it later.
[root@zabbix icinga-1.10.1]# htpasswd -c /usr/local/icinga/etc/htpasswd.users icingaadmin
New password: ********
Re-type new password: ********
Adding password for user icingaadmin
If you want to change it later or add another user:
htpasswd /usr/local/icinga/etc/htpasswd.users <USERNAME>
Now add apache to startup and restart apache
#chkconfig httpd on
#service httpd restart
Extract and configure nagios plugins
cd /opt/installs/
# tar -xvf nagios-plugins-2.0.1.tar.gz
# ./configure \
    --prefix=/usr/local/icinga --with-cgiurl=/icinga/cgi-bin \
    --with-nagios-user=icinga --with-nagios-group=icinga
#make
#make install
Configure NRPE plugin
#cd /opt/installs
#tar -xvf nrpe-2.15.tar.gz
#cd nrpe-2.15
# ./configure --with-ssl --with-nrpe-user=icinga --with-nrpe-group=icinga --with-nagios-user=icinga --with-nagios-group=icinga --libexecdir=/usr/local/icinga/libexec/ --bindir=/usr/local/icinga/bin/
#make all && make install

Add icinga core to start up

#chkconfig  --add icinga
#chkconfig  icinga on
Veryfy the config file
#/usr/local/icinga/bin/icinga -v /usr/local/icinga/etc/icinga.cfg
Output should look like
Checking for circular paths between hosts...
Checking for circular host and service dependencies...
Checking global event handlers...
Checking obsessive compulsive processor commands...
Checking misc settings...

Total Warnings: 0
Total Errors:   0

Things look okay - No serious problems were detected during the pre-flight check
--OR---
[root@zabbix nrpe-2.15]# /etc/init.d/icinga show-errors
Running configuration check...OK

Adjusting the SELinux settings

RHEL and derived distributions like Fedora and CentOS are shipped with activated SELinux (Security Enhanced Linux) running in "enforcing" mode. This may lead to "Internal Server Error" messages when you try to invoke the Icinga-CGIs.
Check if SELinux runs in enforcing mode
 #> getenforce
Set SELinux in "permissive" mode
 #> setenforce 0
To make this change permanent you have to adjust this setting in /etc/selinux/config and restart the system.
Instead of deactivating SELinux or setting it into permissive mode you can use the following commands to run the CGIs in enforcing/targeted mode. The semanage command will automatically add entries to /etc/selinux/targeted/contexts/files/file_contexts.local.

semanage fcontext -a -t httpd_sys_script_exec_t '/usr/local/icinga/sbin(/.*)?'
semanage fcontext -a -t httpd_sys_content_t '/usr/local/icinga/share(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/usr/local/icinga/var(/.*)?'
Once you have defined the necessary contexts you have to apply the settings:

# restorecon -R /usr/local/icinga/sbin
# restorecon -R /usr/local/icinga/share
# restorecon -R /usr/local/icinga/var

Start ICINGA
[root@zabbix init.d]# /etc/init.d/icinga start
Running configuration check...OK
Starting icinga: Starting icinga done.
Login to classic web interface
# Open a browser

You are done with the Icinga-Core and Classic Web Interface,
**  we are still at icinga server  **
Adding hosts

In your main configuration file which is usually /usr/local/icinga/etc/icinga.cfg you should add a line with no spaces at the beginning:
cfg_file=/usr/local/icinga/etc/conf.d/hosts.cfg                                                       
Now,
[root@zabbix objects]# pwd
/usr/local/icinga/etc/objects
#vim /usr/local/icinga/etc/objects/hosts.cfg
# HOST DEFINITION ###################################

# HOST DEFINITION
# Define a host for the local machine
define host{
use                     linux-server            ; Name of host template to use
; This host definition will inherit all variables that are defined
; in (or inherited by) the linux-server-client host template definition.
host_name               sonybiz
alias                   sonybiz
address                 5.9.19.37
contact_groups admins
}
define host{
use                     linux-server            ; Name of host template to use
; This host definition will inherit all variables that are defined
; in (or inherited by) the linux-server-client host template definition.
host_name              Edxorg
alias                   Edxorg
address                5.9.119.34
contact_groups admins
}
# HOST GROUP DEFINITION
# Define an optional hostgroup for Linux machines
define hostgroup{
hostgroup_name   linux-server-clients ; The name of the hostgroup
alias            linux-server-clients ; Long name of the group
members        sonybiz,Edxorg   ; Comma separated list of hosts that belong to this group
}
# SERVICE DEFINITIONS
# Define a service to "ping" the local machine
define service{
use                            generic-service         ; Name of service template to use
;        host_name                      sonybiz   < =uncomment it if you have host without group
hostgroup_name                        linux-server-clients
service_description             PING
check_command                                    check_ping!100.0,20%!500.0,60%
}
#This means that a warning is sent if the latency(RTA) is >100ms or 20% packet loss. An error will be sent if latency is >500ms of 60% packet loss.you could increase the latency (RTA) warning to 150ms to get less messages.
# Define a service to check the disk space of the root partition
# on the local machine.  Warning if < 20% free, critical if
# < 10% free space on partition.
define service{
use                            generic-service         ; Name of service template to use
;        host_name                      Mantraideas        <=use this if you have host without group
hostgroup_name                  linux-server-clients
service_description             Root Partition
check_command                                    check_local_disk!20%!10%!/
}
# Define a service to check the number of currently logged in
# users on the local machine.  Warning if > 20 users, critical
# if > 50 users.
# Define a service to check the load on the local machine.
define service{
use                             generic-service         ; Name of service template to use
;        host_name                      machine12
hostgroup_name                  linux-server-clients
service_description             Current Load
check_command                                    check_local_load!5.0,4.0,3.0!10.0,6.0,4.0
}
# Define a service to check the swap usage the local machine.
# Critical if less than 10% of swap is free, warning if less than 20% is free
define service{
use                             generic-service         ; Name of service template to use
;        host_name                       localhost
hostgroup_name                  linux-server-clients
service_description             Swap Usage
check_command                                    check_local_swap!20!10
}
# Define a service to check HTTP on the local machine.
# Disable notifications for this service by default, as not all users may have HTTP enabled.
define service{
use                             generic-service         ; Name of service template to use
;        host_name                       localhost
hostgroup_name                  linux-server-clients       
service_description             HTTP
check_command                                    check_http
notifications_enabled                  1
}
###Check your config file if it is correct or not ####
/usr/local/icinga/bin/icinga -v /usr/local/icinga/etc/icinga.cfg 
At Client Side
Do
install below packages necessary:-
nagios-plugins-mailq
nagios-plugins-disk
nagios-plugins-load
nagios-plugins-procs
nagios-plugins-nrpe    #for check_nrpe on localside
For Ubuntu
$ sudo apt-get install nagios-nrpe-server nagios-plugins 
/etc/init.d/nagios-nrpe-server restart
 
edit /etc/nagios/nrpe.cfg and make changes like 
allowed_hosts=127.0.0.1, 192.168.1.100
 
 
command[check_users]=/usr/lib/nagios/plugins/check_users -w 5 -c 10
command[check_load]=/usr/lib/nagios/plugins/check_load -w 15,10,5 -c 30,25,20
command[check_hda1]=/usr/lib/nagios/plugins/check_disk -w 20% -c 10% -p /dev/hda1
command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z
command[check_total_procs]=/usr/lib/nagios/plugins/check_procs -w 150 -c 200 
command[check_mailq]=/usr/lib/nagios/plugins/check_mailq -w 300 -c 600 
 

/etc/init.d/nagios-nrpe-server restart
For Centos
 #yum install nagios-nrpe -y
# vim  /etc/nagios/nrpe.cfg
 ;;add below line
allowed_hosts=199.50.155.195     <=this is your icinga server ip
dont_blame_nrpe=0  ;;check this
save-exit
#service nrpe start
#chkconfig nrpe on
Allow port 5666 
# iptables -I INPUT -p tcp -m tcp --dport 5666 -j ACCEPT
# service iptables save
ICINGA HTTP WARNING: HTTP/1.1 403 Forbidden ERROR
#touch /var/www/html/index.php
#/etc/init.d/icinga restart
That’s it !! 
alias icistat='/usr/local/icinga/bin/icinga -v /usr/local/icinga/etc/icinga.cfg'
 
  



========================================================================
check mailq EXIM
 ========================================================================
At client side:-

#rpm -qf utils.pm                                  //tofind the package name of file
#yum install nagios-plugins-perl
do this if you face the"utils.sh not found error". make dir's as needed

#ln -s /usr/lib64/nagios/plugins/utils.sh  /usr/local/nagios/libexec/utils.sh

OR

make changes in exim mailq script , change the line
. /usr/local/nagios/libexec/utils.sh  to  ->
/usr/lib64/nagios/plugins/utils.sh

#visudo

Comment out 

#Defaults    requiretty      <<<++= =

#add nrpe user like below line
root    ALL=(ALL)       ALL
nrpe ALL=NOPASSWD:/usr/sbin/exim                             

Save/exit
 ***************************************

copybelow script in file name  "check_eximmailqueue"
#ls -l  /usr/lib64/nagios/plugins/check_eximmailqueue
-rwxr-xr-x 1 root root   3285 Jul 27 06:25 check_eximmailqueue*
-rwxr-xr-x 1 root root 172880 Oct 17  2013 check_http*
-rwxr-xr-x 1 root root  40944 Oct 17  2013 check_load*
-rwxr-xr-x 1 root root  22256 Apr 30 21:28 check_nrpe*
-rwxr-xr-x 1 root root  36080 Oct 17  2013 check_users*
-rwxr-xr-x 1 root root  38696 Oct 17  2013 negate*
-rwxr-xr-x 1 root root  36104 Oct 17  2013 urlize*
-rw-r--r-- 1 root root   2091 Oct 17  2013 utils.pm
-rwxr-xr-x 1 root root   2728 Oct 17  2013 utils.sh*


cat /usr/lib64/nagios/plugins/check_eximmailqueue

#!/bin/sh
###############################################
#
# Nagios script to check Exim mail queue status
#
# Copyright 2007, 2008 Ian Yates
#
# NOTE: Depending on your config, the nagios user will probably be
#       needed to be added to the exim group for this script to function correctly
#
# See usage for command line switches
#

. /usr/local/nagios/libexec/utils.sh


VERSION="1.3"

EXIM=$(which exim)
SUDO=/usr/bin/sudo

FLAG_VERBOSE=FALSE
LEVEL_WARN=""
LEVEL_CRIT=""
RESULT=""
EXIT_STATUS=$STATE_OK


###############################################
#
## FUNCTIONS
#

## Print usage
usage() {
    echo " check_eximailqueue $VERSION - Nagios Exim mail queue check script"
    echo ""
    echo " Usage: check_eximailqueue -w <warning queue size> -c <critical queue size> [ -v ] [ -h ]"
    echo ""
    echo "         -w  Queue size at which a warning is triggered"
    echo "         -c  Queue size at which a critical is triggered"
    echo "         -v  Verbose output (ignored for now)"
    echo "         -h  Show this page"
    echo ""
}

## Process command line options
doopts() {
    if ( `test 0 -lt $#` )
    then
        while getopts w:c:vh myarg "$@"
        do
            case $myarg in
                h|\?)
                    usage
                    exit;;
                w)
                    LEVEL_WARN=$OPTARG;;
                c)
                    LEVEL_CRIT=$OPTARG;;
                v)
                    FLAG_VERBOSE=TRUE;;
                *)    # Default
                    usage
                    exit;;
            esac
        done
    else
        usage
        exit
    fi
}


# Write output and return result
theend() {
    echo $RESULT
    exit $EXIT_STATUS
}


#
## END FUNCTIONS
#

#############################################
#
## MAIN
#


# Handle command line options
doopts $@

# Do the do
OUTPUT=`$SUDO -u root $EXIM -bpc`
if test -z "$OUTPUT" ; then
    RESULT="Mailqueue WARNING - query returned no output!"
    EXIT_STATUS=$STATE_WARNING
else
    if test "$OUTPUT" -lt "$LEVEL_WARN" ; then
        RESULT="Mailqueue OK - $OUTPUT messages on queue"
        EXIT_STATUS=$STATE_OK
    else
        if test "$OUTPUT" -ge "$LEVEL_CRIT" ; then
            RESULT="Mailqueue CRITICAL - $OUTPUT messages on queue"
            EXIT_STATUS=$STATE_CRITICAL
        else
            if test "$OUTPUT" -ge "$LEVEL_WARN" ; then
                RESULT="Mailqueue WARNING - $OUTPUT messages on queue"
                EXIT_STATUS=$STATE_WARNING
            fi
        fi
    fi
fi

# Quit and return information and exit status
theend


vim /etc/nagios/nrpe.cfg
#add below command
command[check_eximmailqueue]=/usr/lib64/nagios/plugins/check_eximmailqueue -w 200 -c 300

@@@@@@@@@@@@@@@

Server side check

[root@zabbix libexec]# ./check_nrpe -H nepalhpf.org.np -c check_eximmailqueue
Mailqueue OK - 2 messages on queue



[root@zabbix ~]# cd /usr/local/icinga/etc/objects/

#vim commands.cfg
define command{
        command_name            check_nrpe
        command_line            $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
}


#vim nrpe-clients.cfg
define service{
use                     generic-service
#host_name              weblink3
hostgroup_name  mailq
service_description     Check Mail Queue
check_command           check_nrpe!check_eximmailqueue
}
restart icinga..
========================================================
ZOMBIE Processess check
= = = = = = = = = = = = = =  = = = 
#client side
yum install nagios-plugins-procs

check/add the below line in /etc/nagios/nrpe.cfg

command[check_zombie_procs]=/usr/lib64/nagios/plugins/check_procs -w 5 -c 10 -s Z


#monitoring server side
[root@zabbix ~]# cd /usr/local/icinga/etc/objects/

#vim commands.cfg
define command{
        command_name            check_nrpe
        command_line            $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
}
# vim nrpe-clients.cfg

define host{
        use linux-server
        host_name     nepalhpf
        alias         nepalhpf.org.np
        address nepalhpf.org.np
}
define service{
use generic-service
host_name nepalhpf
service_description Zombieprocs
check_command  check_nrpe!check_zombie_procs
}

                                                                                                                                                                  
LSYNCD process check with icinga
= = = = = = = =  = = = = = = = = = = = = = = = = = = 
@Client

#yum install -y nagios-plugins-procs   vim /etc/nagios/nrpe.cfg
add ..
command[check_lsyncd]=/usr/lib64/nagios/plugins/check_procs -c 1:5 -C lsyncd

 root@ns14 [/etc/nagios]# ls -l  /usr/lib64/nagios/plugins/
total 204
drwxrwxr-x. 2 root root   4096 Jul 10 19:16 ./
drwxr-xr-x. 3 root root   4096 Jul  4 21:53 ../
-rwxr-xr-x. 1 root root 118736 Oct 17  2013 check_procs*                 This file should exist or yum install nagios-plugins (add epel repository)
-rwxr-xr-x. 1 root root  38696 Oct 17  2013 negate*
-rwxr-xr-x. 1 root root  36104 Oct 17  2013 urlize*
-rwxr-xr-x. 1 root root   2728 Oct 17  2013 utils.sh*


# /usr/lib64/nagios/plugins/check_procs -c 1:5 -C lsyncd                 #testing locally
PROCS OK: 1 process with command name 'lsyncd'


 @Icinga Server    

vim /usr/local/icinga/etc/objects/nrpe-client-objects.cfg

define hostgroup{
hostgroup_name   lsyncserver; The name of the hostgroup
        alias       Lsyncd_Check
        members  web01,ns14
}


define service{
use     generic-service
hostgroup_name lsyncserver
service_description Lsyncd Process Check
check_command check_nrpe!check_lsyncd
}


==== = = = = == = = ==  =
@client 
 
/usr/local/nagios/libexec/check_procs -c 1:30 -C nginx
 
wherein:  -c 1:30 <– refers to the Critical range for number of Nginx processes. If there process count is below 1 and above 30 this will send me a Critical notice.  If you wan to add a Warning level you can use        "     -w 1:25    " - adjust the number of processes for you needs.  -C nginx <– this will check for the command name (nginx)

another example : - 

check_procs -c 1:1 -a /usr/local/bin/mysecurebackupserver
http://linuxsysadminblog.com/2009/02/nagios-how-to-check-if-remote-process-is-running/
@server

define service {
use                            generic-service         ; Name of service template to use
host_name                      HOST/IPADDRESS
service_description            CHECK_NGINX
check_period                   24x7
max_check_attempts             3
normal_check_interval          5
retry_check_interval           3
contact_groups                 Admins
notification_interval          480
notification_period            24x7
notification_options           w,u,c,r
check_command                  check_nrpe!check_nginx
notifications_enabled          1
}

= = = = = = =  = = = = = = = =  = =
checking from command line on server

./check_http -H 5.9.240.236 -c check_load


http://198.50.155.195/icinga/
icingaadmin
1Lumbini2#

http://kedar.nitty-witty.com/blog/10-steps-mysql-monitoring-nagios-installation-configuration
https://wiki.icinga.org/display/howtos/Service+Monitoring