Home | Linuxmon.comhttps://linuxmon.com/2024-03-29T14:34:24+00:00HomeGeoip and Nginx How to block visitors by country2018-04-05T17:03:04+00:002024-03-29T13:31:50+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/geoip-and-nginx/<p>Operating system: Ubuntu 16.04</p>
<p>First we need to know nginx has support Geoip:</p>
<pre>$ nginx -V<br/>nginx version: nginx/1.10.3 (Ubuntu)<br/>built with OpenSSL 1.0.2g 1 Mar 2016<br/>TLS SNI support enabled<br/>configure arguments: --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2' <br/>--with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf <br/>--http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid <br/>--http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy <br/>--http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module <br/>--with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module <br/><strong>--with-http_geoip_module</strong> --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module <br/>--with-http_sub_module --with-http_xslt_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads</pre>
<p>yes, we have.</p>
<p>Install geoip packages:</p>
<pre>$ sudo apt-get install geoip-database</pre>
<p>place for database is:</p>
<p>/usr/share/GeoIP</p>
<p>GeoIP.dat - > for IPv4</p>
<p>GeoIPv6.dat - > for IPv4 and IPv6</p>
<p>Go to nginx config:</p>
<pre>$ cd /etc/nginx</pre>
<p>in section http add follow rows:</p>
<pre>http{
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {<br/> default no;<br/> US yes; # enable USA IPs<br/> CA yes; # enable Canada IPs<br/>}
geo $exclusions {<br/> default 0;<br/> 10.0.1.126 1; # here comes allowed IP that is in blocked country list<br/> 10.0.0.0/24 1;<br/> 172.68.58.75 1;<br/> 10.0.0.7 1;
}
# Rest of config<br/><br/><span>#..... <br/>}</span></pre>
<p></p>
<p>save it and go to virtual server (dir sites-enabled)</p>
<p>add follow in section server</p>
<pre>server {
#.... some config
location / {<br/> if ($allow_visit = yes) {<br/> set $exclusions 1;<br/> }<br/> if ($exclusions = "0") {<br/> return 403;<br/> }
#...
# rest of config
}</pre>
<p>almost done</p>
<p>restart nginx</p>
<pre>sudo /etc/init.d/nginx reload<br/>[ ok ] Reloading nginx configuration (via systemctl): nginx.service.</pre>
<p>You can check availability your site from any place with online services.</p>
<p></p>
<p></p>Protect your web site with Fail2Ban!2017-05-23T12:07:46+00:002024-03-29T14:34:24+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/protect-site-fail2ban-ubuntu/<p><span><img alt="" height="124" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/fail2ban.jpg/fail2ban-124x124.jpg" width="124"/></span></p>
<p><span>from <a href="https://en.wikipedia.org/wiki/Fail2ban">WiKi</a>:</span></p>
<p><span>Fail2Ban operates by monitoring </span><a class="mw-redirect" href="https://en.wikipedia.org/wiki/Computer_data_logging" title="Computer data logging">log files</a><span> (e.g. </span><tt>/var/log/auth.log</tt><span>, </span><tt>/var/log/apache/access.log</tt><span>, etc.) for selected entries and running scripts based on them. Most commonly this is used to block selected </span><a href="https://en.wikipedia.org/wiki/IP_address" title="IP address">IP addresses</a><span> that may belong to </span><a href="https://en.wikipedia.org/wiki/Host_(network)" title="Host (network)">hosts</a><span> that are trying to breach the system's security. It can ban any host IP address that makes too many login attempts or performs any other unwanted action within a time frame defined by the administrator. Fail2Ban is typically set up to unban a blocked host within a certain period, so as to not "lock out" any genuine connections that may have been temporarily misconfigured. However, an unban time of several minutes is usually enough to stop a network connection being </span><a href="https://en.wikipedia.org/wiki/Denial-of-service_attack" title="Denial-of-service attack">flooded</a><span> by malicious connections, as well as reducing the likelihood of a successful </span><a href="https://en.wikipedia.org/wiki/Dictionary_attack" title="Dictionary attack">dictionary attack</a><span>.</span></p>
<p></p>
<h2>Install and Configure fail2ban on Ubuntu server</h2>
<p>Warning! all actions required root privileges!</p>
<p></p>
<div class="video-container"><iframe allowfullscreen="allowfullscreen" height="315" src="https://www.youtube.com/embed/haq_bHROWBE" width="560"></iframe></div>
<div></div>
<p>Update system:</p>
<pre>$sudo apt-get update<br/>$Install fail2ban<br/>$sudo apt-get install fail2ban</pre>
<p>go to /etc/fail2ban</p>
<pre>$cd /etc/fail2ban/</pre>
<p>need copy jail.conf to jail.local</p>
<pre>$sudo cp jail.conf jail.local</pre>
<p>it will be main config file for fail2ban</p>
<p>For first time fail2ban is ready to protect your server by default:</p>
<p>on port tcp 22 (ssh) </p>
<p>in file /etc/fail2ban/jail.local:</p>
<pre>[ssh]<br/>enabled = true<br/>port = ssh<br/>filter = sshd<br/>logpath = /var/log/auth.log<br/>maxretry = 6</pre>
<p>it means</p>
<p>listening log file /var/log/auth.log and fail2ban will look for errors attempts like this:</p>
<pre>May 14 20:43:12 exim auth worker: PASSV: pam_unix(dovecot:auth): authentication failure; logname= uid=0 euid=0 tty=dovecot ruser=test@lnxmon.com rhost=45.58.99.<hidden></pre>
<p>and after 6 attempts will be blocked by iptables</p>
<pre>filter = sshd</pre>
<p>it means:</p>
<p>used filter sshd</p>
<p>go to /etc/fail2ban/filter.d/</p>
<p>file sshd.conf is a filter</p>
<pre>find block reg exp in file:</pre>
<pre>failregex = ^%(__prefix_line)s(?:error: PAM: )?[aA]uthentication (?:failure|error) for .* from <HOST>( via \S+)?\s*$<br/> ^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from <HOST>\s*$<br/> ^%(__prefix_line)sFailed \S+ for .*? from <HOST>(?: port \d*)?(?: ssh\d*)?(: (ruser .*|(\S+ ID \S+ \(serial \d+\) CA )?\S+ %(__md5hex)s(, client user ".*", client host ".*")?))?\s*$<br/> ^%(__prefix_line)sROOT LOGIN REFUSED.* FROM <HOST>\s*$<br/> ^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>\s*$<br/> ^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers\s*$<br/> ^%(__prefix_line)sUser .+ from <HOST> not allowed because listed in DenyUsers\s*$<br/> ^%(__prefix_line)sUser .+ from <HOST> not allowed because not in any group\s*$<br/> ^%(__prefix_line)srefused connect from \S+ \(<HOST>\)\s*$<br/> ^%(__prefix_line)sReceived disconnect from <HOST>: 3: \S+: Auth fail$<br/> ^%(__prefix_line)sUser .+ from <HOST> not allowed because a group is listed in DenyGroups\s*$<br/> ^%(__prefix_line)sUser .+ from <HOST> not allowed because none of user's groups are listed in AllowGroups\s*$<br/> ^(?P<__prefix>%(__prefix_line)s)User .+ not allowed because account is locked<SKIPLINES>(?P=__prefix)(?:error: )?Received disconnect from <HOST>: 11: .+ \[preauth\]$<br/> ^(?P<__prefix>%(__prefix_line)s)Disconnecting: Too many authentication failures for .+? \[preauth\]<SKIPLINES>(?P=__prefix)(?:error: )?Connection closed by <HOST> \[preauth\]$<br/> ^(?P<__prefix>%(__prefix_line)s)Connection from <HOST> port \d+(?: on \S+ port \d+)?<SKIPLINES>(?P=__prefix)Disconnecting: Too many authentication failures for .+? \[preauth\]$<br/> ^%(__prefix_line)spam_unix\(sshd:auth\):\s+authentication failure;\s*logname=\S*\s*uid=\d*\s*euid=\d*\s*tty=\S*\s*ruser=\S*\s*rhost=<HOST>\s.*$</pre>
<p>these are all reg exp wich willl be catch in log file /var/log/auth.log</p>
<p>You can add yourself filtters and reg exp</p>
<p>For wordpress site you can create filter:</p>
<p>$sudo touch /etc/fail2ban/filter.d/wp-auth.conf</p>
<p>and copy and paster to it:</p>
<pre># WordPress brute force auth filter: /etc/fail2ban/filter.d/wp-auth.conf:<br/>#<br/># Block IPs trying to auth wp wordpress<br/>#<br/># Matches e.g.<br/># pay attention in this raw:<br/># 12.34.33.22 - [07/Jun/2014:11:15:29] "POST /wp/wp-login.php HTTP/1.0" 200 4523<br/># 12.34.33.22 - [07/Jun/2014:11:15:29] "GET /wp-content HTTP/1.0" 200 4523</pre>
<pre><br/># fail2ban will scan log file and will be find like this and block ip address<br/><br/>[Definition]<br/><strong>failregex = ^<HOST> .* "GET \/(wp-login.php|xmlrpc.php)</strong><br/><br/>ignoreregex =</pre>
<p>fail2ban looking for regexp in log file:</p>
<pre>^<HOST> .* "GET \/(wp-login.php|xmlrpc.php)</pre>
<p>and create jail for it:</p>
<p>go to file /etc/fail2ban/jail.local and put it to the bottom of file:</p>
<pre>[wp-auth]<br/>enabled = true<br/>filter = wp-auth<br/>action = iptables-multiport[name=NoAuthFailures, port="http,https"]<br/>logpath = /var/www/mezzanine/logs/ssl_access.log # pls change to your log file<br/>bantime = 86400<br/>maxretry = 3</pre>
<p>after 3 attempts fail2ban will block ip address for 86400 secconds (24hs)</p>
<p>If you would like to enter in admin panel only from your IP address, add in section [DEFAULT] in file /etc/fail2ban/jail.local</p>
<pre>[DEFAULT]<br/>ignoreip = 127.0.0.1/8 <your ip_address> </pre>
<p># with no symbols '<>' </p>
<p>and save it</p>
<p>fail2ban will be ignore your ip ddresses </p>
<p>If you use your own filters you can check it by command:</p>
<pre>$fail2ban-regex ssl_access.log /etc/fail2ban/filter.d/wp-auth.conf<br/>Running tests<br/>=============<br/>Use failregex file : /etc/fail2ban/filter.d/wp-auth.conf<br/>Use log file : ssl_access.log<br/>Results<br/>=======<br/>Failregex: 5540 total<br/>|- #) [# of hits] regular expression<br/>| 1) [4686] ^<HOST> .* "GET \/(wp-login.php|xmlrpc.php)<br/>| 2) [854] ^<HOST> .* "GET \/(wp-content)<br/>`-<br/><br/>Ignoreregex: 0 total<br/><br/>Date template hits:<br/>|- [# of hits] date format<br/>| [19758] Day/MONTH/Year:Hour:Minute:Second<br/>`-<br/><br/>Lines: 19758 lines, 0 ignored, 5540 matched, 14218 missed<br/>Missed line(s):: too many to print. Use --print-all-missed to print all 14218 lines<br/><br/><br/></pre>
<p>all filters work fine.</p>
<p>After that you should restart fail2ban</p>
<pre>$sudo service fail2ban restart</pre>
<p>All detailed info you can see at </p>
<p>/var/log/fail2ban.log</p>
<p>Who banned or unbanned:</p>
<pre>.....<br/>2017-05-21 06:48:30,205 fail2ban.server : INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.8.11<br/>2017-05-22 01:42:51,534 fail2ban.actions: WARNING [wp-auth] Ban 60.241.112.205<br/><strong>2017-05-22 01:42:53,597 fail2ban.actions: INFO [wp-auth] 60.241.112.<hidden>. already banned</strong><br/><strong>2017-05-22 01:42:56,601 fail2ban.actions: INFO [wp-auth] 60.241.112.<hidden>. already banned</strong><br/><strong>2017-05-23 01:42:52,254 fail2ban.actions: WARNING [wp-auth] Unban 60.241.112.205</strong><br/>2017-05-23 09:37:02,946 fail2ban.actions: WARNING [wp-auth] Ban 185.119.81.24<br/>2017-05-23 10:07:06,785 fail2ban.server : INFO Stopping all jails<br/>2017-05-23 10:07:07,541 fail2ban.actions: WARNING [wp-auth] Unban 185.119.81.24<br/>.....</pre>
<p>also you can see status iptables:</p>
<pre>$sudo iptables -S<br/>-P INPUT ACCEPT<br/>-P FORWARD ACCEPT<br/>-P OUTPUT ACCEPT<br/>-N fail2ban-NoAuthFailures<br/>-N fail2ban-ssh<br/>-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-NoAuthFailures<br/>-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh<br/>-A FORWARD -i tun0 -j ACCEPT<br/>-A FORWARD -o tun0 -j ACCEPT<br/>-A FORWARD -o eth0 -j ACCEPT<br/>-A FORWARD -i eth0 -j ACCEPT<br/>-A fail2ban-NoAuthFailures -j RETURN<br/>-A fail2ban-ssh -j RETURN</pre>
<p>nobody banned yet )</p>
<p>Links:</p>
<p><a href="https://www.fail2ban.org/wiki/index.php/Main_Page">https://www.fail2ban.org/wiki/index.php/Main_Page</a></p>
<p></p>
<p></p>Install Mail Server Exim4 on Ubuntu Server 16.042017-04-17T18:45:13+00:002024-03-28T12:45:17+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/install-exim-on-ubuntu-server/<p><a href="https://linuxmon.com/install-exim-on-ubuntu-server/"><strong><img alt="" height="100" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/exim_logo.png/exim_logo-137x100.png" width="137"/></strong></a></p>
<h3><strong>Overview</strong></h3>
<p><a href="http://exim.org/" target="_blank">Exim</a> is MTA - SMTP Mail server</p>
<p>is opensource package.</p>
<h3><strong>Install</strong></h3>
<p>we will install exim with MySQL support (mail boxes, multidomain, etc.)</p>
<p>Today we will install Exim v4 on Ubuntu server 16.04</p>
<p>before we need update upgrade all necessary packages:</p>
<pre>$sudo apt-get update -y && apt-get upgrade -y && apt-get dist-upgrade -y</pre>
<p>Install dovecot as imap/pop3 services:</p>
<pre><code class="plain">$apt-get </code><code class="functions">install</code><span> </span><code class="plain">dovecot-common dovecot-imapd dovecot-pop3d</code></pre>
<p></p>
<p>Create system user with uid = 1150, username = vmail, in group = mail:</p>
<pre>$sudo useradd -r -u 1150 -g mail -d /var/vmail -s /sbin/nologin -c 'Virtual Mailbox' vmail</pre>
<p>create dir for store mails and get permissions vmail user:</p>
<pre>$sudo mkdir var/mail<br/>$sudo chwon vmail:mail /var/mail<br/>$sudo chmod 0770 /var/mail</pre>
<p>Now create Database for exim:</p>
<pre>$sudo apt-get install mysql-server</pre>
<p>in during installation MySQL server, provide password for root (root in this case mysql server's user) not root user Operating system Ubuntu server</p>
<pre>$mysqladmin -u root -p create exim_db<br/>
$Enter password: (Enter password)<br/>
$mysql -u root -p <br/>
mysql><span>GRANT ALL PRIVILEGES ON exim_db.* TO exim_user@localhost IDENTIFIED BY 'password';</span> <br/>
mysql>Ctrl+D</pre>
<p>we created database and user for it.</p>
<p>in this case user is - exim_user </p>
<p>password - "password" (you can change it and remember, we will use in exim's config file later)</p>
<p></p>
<p>Create self-signed certificate</p>
<pre><strong>$sudo openssl req -new -x509 -days 3650 -nodes -out /etc/ssl/certs/mail.pem -keyout /etc/ssl/certs/mail.pem</strong></pre>
<p></p>
<h3><strong>Configuration Dovecot</strong></h3>
<p><strong>$cat /etc/dovecot/dovecot.conf</strong></p>
<p></p>
<pre><strong>#change domain name!!!</strong><br/>auth_default_realm = domain.com<br/>auth_verbose = yes<br/>$for temp files<br/>base_dir = /var/run/dovecot/<br/>disable_plaintext_auth = no<br/>first_valid_gid = 8<br/>first_valid_uid = 118<br/>login_greeting = Dovecot ready<br/>log_path = /var/log/dovecot.log<br/>login_log_format_elements = user=<%u> method=%m rip=%r lip=%l %c<br/>mail_access_groups = mail<br/>mail_debug = yes<br/>mail_location = maildir:/var/mail/%d/%n<br/>passdb {<br/> args = /etc/dovecot/dovecot-sql.conf<br/> driver = sql<br/>}<br/>protocols = pop3 imap<br/>service auth {<br/> unix_listener auth-master {<br/> mode = 0600<br/> user = Debian-exim<br/> }<br/> user = root<br/>}<br/>service imap-login {<br/> chroot = login<br/> inet_listener imap {<br/> address = *<br/> port = 143<br/> }<br/> process_limit = 3<br/> process_min_avail = 3<br/> service_count = 1<br/> user = dovecot<br/> vsz_limit = 64 M<br/>}<br/>service pop3-login {<br/> chroot = login<br/> inet_listener pop3 {<br/> address = *<br/> port = 110<br/> }<br/> process_limit = 3<br/> process_min_avail = 3<br/> service_count = 1<br/> user = dovecot<br/> vsz_limit = 64 M<br/>}<br/>ssl = yes<br/>ssl_cert = </etc/ssl/certs/mail.pem<br/>ssl_key = </etc/ssl/certs/mail.pem<br/>userdb {<br/> args = /etc/dovecot/dovecot-sql.conf<br/> driver = sql<br/>}<br/>verbose_proctitle = yes<br/> <br/>#protocol imap {<br/># imap_client_workarounds = delay-newmail tb-extra-mailbox-sep<br/>#}<br/> <br/>protocol pop3 {<br/> pop3_client_workarounds = outlook-no-nuls oe-ns-eoh<br/> pop3_uidl_format = %08Xu%08Xv<br/>}<br/>protocol lda {<br/> auth_socket_path = /var/run/dovecot/auth-master<br/> postmaster_address = support@nixtalk.com<br/>}<br/><br/>## Dovecot configuration file<br/><br/># If you're in a hurry, see http://wiki2.dovecot.org/QuickConfiguration<br/><br/># "doveconf -n" command gives a clean output of the changed settings. Use it<br/># instead of copy&pasting files when posting to the Dovecot mailing list.<br/><br/># '#' character and everything after it is treated as comments. Extra spaces<br/># and tabs are ignored. If you want to use either of these explicitly, put the<br/># value inside quotes, eg.: key = "# char and trailing whitespace "<br/><br/># Default values are shown for each setting, it's not required to uncomment<br/># those. These are exceptions to this though: No sections (e.g. namespace {})<br/># or plugin settings are added by default, they're listed only as examples.<br/># Paths are also just examples with the real defaults being based on configure<br/># options. The paths listed here are for configure --prefix=/usr<br/># --sysconfdir=/etc --localstatedir=/var<br/><br/># Enable installed protocols<br/>!include_try /usr/share/dovecot/protocols.d/*.protocol<br/><br/># A comma separated list of IPs or hosts where to listen in for connections. <br/># "*" listens in all IPv4 interfaces, "::" listens in all IPv6 interfaces.<br/># If you want to specify non-default ports or anything more complex,<br/># edit conf.d/master.conf.<br/>#listen = *, ::<br/><br/># Base directory where to store runtime data.<br/>#base_dir = /var/run/dovecot/<br/><br/># Name of this instance. Used to prefix all Dovecot processes in ps output.<br/>#instance_name = dovecot<br/><br/># Greeting message for clients.<br/>#login_greeting = Dovecot ready.<br/><br/># Space separated list of trusted network ranges. Connections from these<br/># IPs are allowed to override their IP addresses and ports (for logging and<br/># for authentication checks). disable_plaintext_auth is also ignored for<br/># these networks. Typically you'd specify your IMAP proxy servers here.<br/>#login_trusted_networks =<br/><br/># Sepace separated list of login access check sockets (e.g. tcpwrap)<br/>#login_access_sockets = <br/><br/># Show more verbose process titles (in ps). Currently shows user name and<br/># IP address. Useful for seeing who are actually using the IMAP processes<br/># (eg. shared mailboxes or if same uid is used for multiple accounts).<br/>#verbose_proctitle = no<br/><br/># Should all processes be killed when Dovecot master process shuts down.<br/># Setting this to "no" means that Dovecot can be upgraded without<br/># forcing existing client connections to close (although that could also be<br/># a problem if the upgrade is e.g. because of a security fix).<br/>#shutdown_clients = yes<br/><br/># If non-zero, run mail commands via this many connections to doveadm server,<br/># instead of running them directly in the same process.<br/>#doveadm_worker_count = 0<br/># UNIX socket or host:port used for connecting to doveadm server<br/>#doveadm_socket_path = doveadm-server<br/><br/># Space separated list of environment variables that are preserved on Dovecot<br/># startup and passed down to all of its child processes. You can also give<br/># key=value pairs to always set specific settings.<br/>#import_environment = TZ<br/><br/>##<br/>## Dictionary server settings<br/>##<br/><br/># Dictionary can be used to store key=value lists. This is used by several<br/># plugins. The dictionary can be accessed either directly or though a<br/># dictionary server. The following dict block maps dictionary names to URIs<br/># when the server is used. These can then be referenced using URIs in format<br/># "proxy::<name>".<br/><br/>dict {<br/> #quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext<br/> #expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext<br/>}<br/><br/># Most of the actual configuration gets included below. The filenames are<br/># first sorted by their ASCII value and parsed in that order. The 00-prefixes<br/># in filenames are intended to make it easier to understand the ordering.<br/>!include conf.d/*.conf<br/><br/># A config file can also tried to be included without giving an error if<br/># it's not found:<br/>!include_try local.conf<br/><br/>
</pre>
<p><strong>$ sudo cat dovecot-sql.conf (access has only root )</strong></p>
<pre># This file is opened as root, so it should be owned by root and mode 0600.
#
# http://wiki2.dovecot.org/AuthDatabase/SQL
#
# For the sql passdb module, you'll need a database with a table that
# contains fields for at least the username and password. If you want to
# use the user@domain syntax, you might want to have a separate domain
# field as well.
#
# If your users all have the same uig/gid, and have predictable home
# directories, you can use the static userdb module to generate the home
# dir based on the username and domain. In this case, you won't need fields
# for home, uid, or gid in the database.
#
# If you prefer to use the sql userdb module, you'll want to add fields
# for home, uid, and gid. Here is an example table:
#
# CREATE TABLE users (
# username VARCHAR(128) NOT NULL,
# domain VARCHAR(128) NOT NULL,
# password VARCHAR(64) NOT NULL,
# home VARCHAR(255) NOT NULL,
# uid INTEGER NOT NULL,
# gid INTEGER NOT NULL,
# active CHAR(1) DEFAULT 'Y' NOT NULL
# );
# Database driver: mysql, pgsql, sqlite
driver = mysql<br/><br/><strong>#here you should put ip address server and credentials for MySQL server</strong>
<strong>connect=host=10.10.10.10 dbname=exim_db user=exim_user password=password</strong>
default_pass_scheme=PLAIN
password_query=select password from accounts where login='%n' and domain='%d'
user_query=select uid, gid from accounts where login='%n' and domain='%d'
# Database connection string. This is driver-specific setting.
#
# HA / round-robin load-balancing is supported by giving multiple host
# settings, like: host=sql1.host.org host=sql2.host.org
#
# pgsql:
# For available options, see the PostgreSQL documention for the
# PQconnectdb function of libpq.
# Use maxconns=n (default 5) to change how many connections Dovecot can
# create to pgsql.
#
# mysql:
# Basic options emulate PostgreSQL option names:
# host, port, user, password, dbname
#
# But also adds some new settings:
# client_flags - See MySQL manual
# ssl_ca, ssl_ca_path - Set either one or both to enable SSL
# ssl_cert, ssl_key - For sending client-side certificates to server
# ssl_cipher - Set minimum allowed cipher security (default: HIGH)
# option_file - Read options from the given file instead of
# the default my.cnf location
# option_group - Read options from the given group (default: client)
#
# You can connect to UNIX sockets by using host: host=/var/run/mysql.sock
# Note that currently you can't use spaces in parameters.
#
# sqlite:
# The path to the database file.
#
# Examples:
# connect = host=192.168.1.1 dbname=users
# connect = host=sql.example.com dbname=virtual user=virtual password=blarg
# connect = /etc/dovecot/authdb.sqlite
#
#connect =
# Default password scheme.
#
# List of supported schemes is in
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
#
#default_pass_scheme = MD5
# passdb query to retrieve the password. It can return fields:
# password - The user's password. This field must be returned.
# user - user@domain from the database. Needed with case-insensitive lookups.
# username and domain - An alternative way to represent the "user" field.
#
# The "user" field is often necessary with case-insensitive lookups to avoid
# e.g. "name" and "nAme" logins creating two different mail directories. If
# your user and domain names are in separate fields, you can return "username"
# and "domain" fields instead of "user".
#
# The query can also return other fields which have a special meaning, see
# http://wiki2.dovecot.org/PasswordDatabase/ExtraFields
#
# Commonly used available substitutions (see http://wiki2.dovecot.org/Variables
# for full list):
# %u = entire user@domain
# %n = user part of user@domain
# %d = domain part of user@domain
#
# Note that these can be used only as input to SQL query. If the query outputs
# any of these substitutions, they're not touched. Otherwise it would be
# difficult to have eg. usernames containing '%' characters.
#
# Example:
# password_query = SELECT userid AS user, pw AS password \
# FROM users WHERE userid = '%u' AND active = 'Y'
#
#password_query = \
# SELECT username, domain, password \
# FROM users WHERE username = '%n' AND domain = '%d'
# userdb query to retrieve the user information. It can return fields:
# uid - System UID (overrides mail_uid setting)
# gid - System GID (overrides mail_gid setting)
# home - Home directory
# mail - Mail location (overrides mail_location setting)
#
# None of these are strictly required. If you use a single UID and GID, and
# home or mail directory fits to a template string, you could use userdb static
# instead. For a list of all fields that can be returned, see
# http://wiki2.dovecot.org/UserDatabase/ExtraFields
#
# Examples:
# user_query = SELECT home, uid, gid FROM users WHERE userid = '%u'
# user_query = SELECT dir AS home, user AS uid, group AS gid FROM users where userid = '%u'
# user_query = SELECT home, 501 AS uid, 501 AS gid FROM users WHERE userid = '%u'
#
#user_query = \
# SELECT home, uid, gid \
# FROM users WHERE username = '%n' AND domain = '%d'
# If you wish to avoid two SQL lookups (passdb + userdb), you can use
# userdb prefetch instead of userdb sql in dovecot.conf. In that case you'll
# also have to return userdb fields in password_query prefixed with "userdb_"
# string. For example:
#password_query = \
# SELECT userid AS user, password, \
# home AS userdb_home, uid AS userdb_uid, gid AS userdb_gid \
# FROM users WHERE userid = '%u'
# Query to get a list of all usernames.
#iterate_query = SELECT username AS user FROM users
</pre>
<p>$sudo systemctl restart dovecot.service</p>
<h3><strong>Configuration EXIM</strong></h3>
<p>Lets restore schema of database exim_db:</p>
<p></p>
<pre><strong># cat exim_db.sql</strong>
-- MySQL dump 10.13 Distrib 5.7.17, for Linux (x86_64)
--
-- Host: localhost Database: exim_db
-- ------------------------------------------------------
-- Server version 5.7.17-0ubuntu0.16.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `accounts`
--
DROP TABLE IF EXISTS `accounts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accounts` (
`login` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
`password` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
`uid` int(11) NOT NULL DEFAULT '118',
`gid` int(11) NOT NULL DEFAULT '8',
`domain` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT 'nixtalk.com',
`quota` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '250M',
`status` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`login`,`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `accounts`
--
LOCK TABLES `accounts` WRITE;
/*!40000 ALTER TABLE `accounts` DISABLE KEYS */;
INSERT INTO `accounts` VALUES ('admin','password',118,8,'domain.com','250M',1);
/*!40000 ALTER TABLE `accounts` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `aliases`
--
DROP TABLE IF EXISTS `aliases`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `aliases` (
`address` varchar(128) COLLATE utf8_bin DEFAULT NULL,
`goto` varchar(128) COLLATE utf8_bin DEFAULT NULL,
`domain` varchar(128) COLLATE utf8_bin DEFAULT 'nixtalk.com'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `aliases`
--
LOCK TABLES `aliases` WRITE;
/*!40000 ALTER TABLE `aliases` DISABLE KEYS */;
/*!40000 ALTER TABLE `aliases` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `blacklist`
--
DROP TABLE IF EXISTS `blacklist`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `blacklist` (
`senders` varchar(128) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `blacklist`
--
LOCK TABLES `blacklist` WRITE;
/*!40000 ALTER TABLE `blacklist` DISABLE KEYS */;
/*!40000 ALTER TABLE `blacklist` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `domains`
--
DROP TABLE IF EXISTS `domains`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `domains` (
`domain` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
`status` int(11) NOT NULL DEFAULT '1',
`relay` varchar(45) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `domains`
--
LOCK TABLES `domains` WRITE;
/*!40000 ALTER TABLE `domains` DISABLE KEYS */;
INSERT INTO `domains` VALUES ('domain.com',1,'l');
/*!40000 ALTER TABLE `domains` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `whitelist`
--
DROP TABLE IF EXISTS `whitelist`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `whitelist` (
`senders` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'support@nixtalk.com'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `whitelist`
--
LOCK TABLES `whitelist` WRITE;
/*!40000 ALTER TABLE `whitelist` DISABLE KEYS */;
/*!40000 ALTER TABLE `whitelist` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-04-17 16:36:13
</pre>
<p>save it in file exim_db.sql (use copy/paste)</p>
<p>and restore in your database:</p>
<pre>$mysql -u root -p exim_db < exim_db.sql</pre>
<p>Add some stuff:</p>
<pre>$mysql -u root -p<br/>mysql>use exim_db;<br/>#add user mail box admin1@domain.com<br/>mysql>INSERT into exim_db.accounts (login, password, uid, gid, domain, quota, status) VALUES('admin1', 'password', 119, 8, 'domain.com', '250M', '1');<br/>#add domain, current - domain.com, you can add any domains<br/>mysql>INSERT into exim_db.domains (domain, status, relay) VALUES('domain.com', 1, 'l');<br/>Ctrl+D</pre>
<p></p>
<p>$cat /etc/exim4/exim4.conf.template</p>
<pre><strong>#your domain name, change it!</strong><br/>primary_hostname = domain.com
<strong># databasename and credentials</strong>
hide mysql_servers = 10.10.10.10/exim_db/exim_user/password
<strong>#local_domains is all domains in your mail server, in our case we have only one domain - domain.com</strong><br/>domainlist local_domains = ${lookup mysql{select domain from domains where domain='${domain}' AND relay='l'}}
<strong>#domains you can send mails (this server you can use as smart host for another mail server)</strong><br/>domainlist relay_to_domains = ${lookup mysql{select domain from domains where domain='${domain}' AND relay = 'r'}}
<strong># IP addresses from you can accept mails</strong><br/>hostlist relay_from_hosts = localhost : 127.0.0.1 :4.34.146.111
<br/><strong>#white list (we use mysql)</strong>
hostlist cool_senders = ${lookup mysql{SELECT ipaddr FROM whiteipaddr WHERE ipaddr='${quote_mysql:$sender_host_address}' LIMIT 1}}
<strong>#black list (we use file)</strong>
domainlist rbl_blacklist = lsearch;/etc/exim4/rblblacklist
acl_smtp_connect = acl_check_connect
acl_smtp_helo = acl_check_helo
acl_smtp_rcpt = acl_check_rcpt
acl_smtp_data = acl_check_data
#disable_ipv6 = true
<strong>#you should create self-signed certificate</strong>
tls_certificate = /etc/ssl/certs/mail.pem
tls_privatekey = /etc/ssl/certs/mail.pem
<strong>#port smtp</strong>
daemon_smtp_ports = 25: 465
tls_on_connect_ports = 465
tls_advertise_hosts = *
qualify_domain = domain.com
qualify_recipient = domain.com
allow_domain_literals = false
exim_user = Debian-exim
exim_group = Debian-exim
never_users = root
host_lookup = * : !+relay_from_hosts
rfc1413_hosts = *
rfc1413_query_timeout = 0s
ignore_bounce_errors_after = 2h
timeout_frozen_after = 14d
return_size_limit = 10K
split_spool_directory = true
syslog_timestamp = no
smtp_accept_max = 100
smtp_accept_max_per_connection = 50
smtp_accept_max_per_host = 20
smtp_accept_queue_per_connection = 30
remote_max_parallel = 15
av_scanner = clamd:/var/run/clamav/clamd.ctl
<strong>#spamassassin, you will install it later</strong><br/>spamd_address = 127.0.0.1 783
smtp_banner = $smtp_active_hostname ESMTP
#dns_again_means_nonexist = !+local_domains : !+relay_to_domains
dns_again_means_nonexist = *.in-addr.arpa
# Enable HELO verification in ACLs for all hosts
helo_try_verify_hosts = *: !+local_domains : !+relay_from_hosts
<strong>#structure of log file</strong>
log_selector = \
+all_parents \
+lost_incoming_connection \
+received_sender \
+received_recipients \
+smtp_confirmation \
+smtp_syntax_error \
+smtp_connection \
+smtp_protocol_error \
-queue_run
######### ACL ########
begin acl
acl_check_connect:
<strong># deny get mail from dynamic ip addresses</strong>
deny message = "Dynamic hosts is forbidden!"
condition = ${if match{$sender_host_name}\
{webcam|dsl|dial|dhcp|\.cable\.|static|dynamic|ppp} {yes}{no}}
<strong>#except white listed senders</strong><br/># !hosts = +cool_senders
!hosts = ${lookup mysql{SELECT ipaddr FROM whiteipaddr WHERE ipaddr='${quote_mysql:$sender_host_address}' LIMIT 1}}
accept
########################
acl_check_helo:
<strong># deny all senders who put own IP in HELO.</strong>
deny message = "The use of IP is forbidden in HELO!"
hosts = !+relay_from_hosts
log_message = The use of IP is forbidden in HELO!
condition = ${if eq{$sender_helo_name}\
{$sender_host_address}{true}{false}}
accept
########################
acl_check_rcpt:
accept hosts = :
<strong>#deny symbols in local part of email</strong><br/>deny domains = +local_domains
local_parts = ^[.] : ^.*[@%!/|]
deny domains = !+local_domains
local_parts = ^[./|] : ^.*[@%!] : ^.*/\\.\\./
<strong>#deny local part 'spam'</strong><br/>deny domains = !+local_domains : !+relay_to_domains
local_parts = spam
#deny message = Rejected because $sender_fullhost is blacklisted locally
# log_message = Rejected because $sender_fullhost is blacklisted locally
# senders = /etc/exim4/rblblacklist
deny message = Rejected because $sender or $sender_helo_name in BL db
senders=${lookup mysql{SELECT senders FROM blacklist \
WHERE senders='${quote_mysql:$sender_address}' \
OR senders='*@${quote_mysql:$sender_address_domain}' LIMIT 1}}
################ WARN!!! ###############
<strong># accept emails from IP addresses in relay domains.</strong>
accept hosts = +relay_from_hosts
accept authenticated = *
<br/><strong># deny relay except relay_to_domains</strong>
deny message = relay not permitted to another domain
log_message = relay not permitted to another domain
domains = !+relay_to_domains: !+local_domains
hosts = !+relay_from_hosts
deny
message = Reverse DNS lookup failed for host $sender_host_address.
log_message = Reverse DNS lookup failed for host $sender_host_address
!verify = reverse_host_lookup
deny
message = Message was delivered by ratware
log_message = remote host used our name in HELO/EHLO greeting.
condition = ${if match_domain{$sender_helo_name}\
{$primary_hostname:+local_domains:+relay_to_domains}\
{true}{false}}
<strong># deny numbers in HELO except localhost</strong>
deny condition = ${if match{$sender_helo_name}{\N^\d+$\N}{yes}{no}}
log_message = There can not be only numbers in HELO
hosts = !127.0.0.1:!localhost:*
message = "There can not be only numbers in HELO!"
<strong># deny with no return address.</strong>
deny condition = ${if eq{$sender_address}{}{yes}{no}}
log_message = Your message have not return address
hosts = !+relay_from_hosts
message = "Your message have not return address"
<br/>deny message = HELO/EHLO required by SMTP RFC
log_message = HELO/EHLO required by SMTP RFC
hosts = !+relay_from_hosts
condition = ${if eq{$sender_helo_name}{}{yes}{no}}
accept senders=${lookup mysql{SELECT senders FROM whitelist \
WHERE senders='${quote_mysql:$sender_address}' \
OR senders='*@${quote_mysql:$sender_address_domain}' LIMIT 1}}
<strong>#check IP addresses in black list</strong>
deny message = rejected because $sender_host_address \
is in a black list at $dnslist_domain\n$dnslist_text
hosts = !+relay_from_hosts
!authenticated = *
log_message = found in $dnslist_domain
dnslists = bl.spamcop.net : \
cbl.abuseat.org : \
dnsbl.njabl.org : \
pbl.spamhaus.org : \
zen.spamhaus.org
# tor.ahbl.org : \
#require verify = sender
drop message = Rejected - Sender Verify Failed
log_message = Rejected - Sender Verify Failed
hosts = !+relay_from_hosts
!verify = sender/no_details/callout=2m,defer_ok
!condition = ${if eq{$sender_verify_failure}{}}
condition = ${if match_ip{$sender_host_address}{${lookup dnsdb{>: defer_never,a=$sender_helo_name}}}{no}{yes}}
#warn !verify = sender
# log_message = sender verify failed: $acl_verify_message
accept domains = +local_domains
endpass
message = $acl_verify_message
verify = recipient
accept domains = +relay_to_domains
endpass
message = "Unrouteable address!"
verify = recipient/callout=30s,defer_ok,use_postmaster
#require message = Can't verify sender
# verify = sender
accept
##### Data #####
acl_check_data:
deny malware = *
message = This message contains a virus ($malware_name).
#accept
# hosts = +relay_from_hosts
<strong># check spam by spamassassin</strong>
warn spam = Debian-exim:true
!hosts = +relay_from_hosts
add_header = X-Spam-Flag: YES\n\
X-Spam_score: $spam_score\n\
X-Spam_score_int: $spam_score_int\n\
X-Spam_bar: $spam_bar\n\
#X-Spam_report: $spam_report
<strong># China symbols</strong>
deny message = This is spam - denied
!senders = :
condition = ${if match{$message_body}{105[-_]*51[-_]*86|778[-_]*98[-_]*94}{yes}{no}}
#Extensions
deny message = contains $found_extension file (blacklisted).
!senders = :
demime = com:vbs:bat:pif:scr:exe:wsb:pdf.zip
#Check MIME
deny message = This message contains a MIME error ($demime_reason)
!senders = :
hosts = !+relay_from_hosts
demime = *
condition = ${if >{$demime_errorlevel}{2}{1}{0}}
#Messages with NUL- symbols
deny message = This message contains NUL characters
!senders = :
log_message = NUL characters!
condition = ${if >{$body_zerocount}{0}{1}{0}}
# Headers
deny message = Incorrect headers syntax
hosts = !+relay_from_hosts:*
!senders = :
!verify = header_syntax
accept
############ Routers #########
begin routers
<strong>#route mail to relay_to_domains (exim in this case as smart host)</strong>
mailenable_router:
driver = manualroute
domains = +relay_to_domains
transport = remote_smtp
route_list = * <strong>10.10.10.148</strong>
no_more
dnslookup:
driver = dnslookup
domains = !+local_domains
transport = remote_smtp
ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
no_more
system_aliases:
driver = redirect
allow_fail
allow_defer
data = ${lookup mysql{select goto from aliases where address='${quote_mysql:$local_part}' and domain='${quote_mysql:$domain}'}}
user = Debian-exim
group = mail
file_transport = address_file
pipe_transport = address_pipe
userforward:
driver = redirect
check_local_user
no_verify
no_expn
check_ancestor
file_transport = address_file
pipe_transport = address_pipe
reply_transport = address_reply
data = ${lookup mysql{select goto from aliases where address='${quote_mysql:$local_part}' and domain='${quote_mysql:$domain}'}}
localuser:
driver = accept
domains = ${lookup mysql{select domain from domains where domain='${domain}' AND relay='l'}}
local_parts = ${lookup mysql{select login from accounts where login='${local_part}' and domain='${domain}'}}
transport = local_delivery
cannot_route_message = Unknown user
##### Transport #####
begin transports
remote_smtp:
driver = smtp
hosts_avoid_tls = 4.28.131.119: 10.0.1.148
local_delivery:
driver = appendfile
maildir_format
maildir_tag = ,S=$message_size
directory = /var/mail/$domain/$local_part
create_directory
delivery_date_add
envelope_to_add
return_path_add
group = mail
mode = 0660
no_mode_fail_narrower
address_pipe:
driver = pipe
return_output
address_file:
driver = appendfile
delivery_date_add
envelope_to_add
return_path_add
address_reply:
driver = autoreply
begin retry
* * F,2h,15m; G,16h,1h,1.5; F,4d,6h
begin rewrite
begin authenticators
auth_plain:
driver = plaintext
server_set_id = $2
server_prompts = :
public_name = PLAIN
server_condition = ${lookup mysql{select login from accounts where login='${quote_mysql:${local_part:$2}}' and password='${quote_mysql:$3}'}{yes}{no}}
auth_login:
driver = plaintext
public_name = LOGIN
server_set_id = $1
server_prompts = Username:: : Password::
server_condition = ${lookup mysql{select login from accounts where login='${quote_mysql:${local_part:$1}}' and password='${quote_mysql:$2}'}{yes}{no}}
auth_cram_md5:
driver = cram_md5
public_name = CRAM-MD5
server_secret = ${lookup mysql{select password from accounts where login='${quote_mysql:${local_part:$1}}'}{$value}fail}
server_set_id = $1
</pre>
<p>try restart exim:</p>
<pre>$sudo systemctl restart exim4.service</pre>
<p>Tools for checking email delivery:</p>
<p>check routing</p>
<pre>$exim -v <a href="mailto:admin@domain.com">admin@domain.com</a></pre>
<p>check from fake IP address:</p>
<p><strong>$exim -bh <IP address></strong></p>
<p>test routing delivery mail:</p>
<p><strong>$exim -bt <a href="mailto:mail@domain.com">mail@domain.com</a><a href="mailto:mail@domain.com"></a></strong></p>
<p><strong></strong></p>
<p>See next</p>
<p><a href="https://linuxmon.com/spamassassin/">Install Spamassassin</a></p>
<p>---</p>
<p>links:</p>
<p><a href="http://exim.org/docs.html" target="_blank">Exim Documentation</a></p>
<p></p>Install OpenVPN server in Openvz container Ubuntu Server2017-04-04T19:49:41+00:002024-03-28T13:14:31+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/install-openvpn-server-in-openvz-container-ubuntu-server/<div><a href="https://linuxmon.com/installing-openvpn-server-in-openvz-container-ubuntu-server/" target="_blank"><img alt="openvpn" class="wp-image-383 alignleft" height="36" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/openvpn.png/openvpn-219x36.png" width="219"/></a></div>
<p> Today we are going to install OPENVPN Server in OpenVZ contaiter.</p>
<p>After create container for example 102, we need create tun/tap device in OpenVZ host :</p>
<pre>vzctl set 102 --devnodes net/tun:rw --save
vzctl set 102 --devices c:10:200:rw --save
vzctl set 102 --capability net_admin:on --save
vzctl exec 102 mkdir -p /dev/net
vzctl exec 102 mknod /dev/net/tun c 10 200</pre>
<!--more-->
<p>Then go to the container:</p>
<pre>vzctl enter 102</pre>
<p>installing Openvpn server: step 1:</p>
<pre>#apt-get update
#apt-get install openvpn
#mkdir /etc/openvpn/easy-rsa/
#cp -R /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa/
</pre>
<p>step 2: <span>Edit /etc/openvpn/easy-rsa/vars</span></p>
<pre>export KEY_COUNTRY="US"
<span class="anchor" id="line-2-4"></span>export KEY_PROVINCE="NY"
<span class="anchor" id="line-3-3"></span>export KEY_CITY="NY City"
export KEY_EMAIL="me@myhost.mydomain"</pre>
<p>step 3: <span>Setup the CA and create the first server certificate</span></p>
<pre>cd /etc/openvpn/easy-rsa/
sudo ln -s openssl-1.0.0.cnf openssl.cnf
source ./vars
./clean-all ##Deletes all keys
./build-dh
./pkitool --initca ## creates ca cert and key
./pkitool --server server ## creates a server cert and key
cd keys
openvpn --genkey --secret ta.key ## Build a TLS key
sudo cp server.crt server.key ca.crt dh1024.pem ta.key ../../</pre>
<p>Configuring server.conf</p>
<pre>local 10.184.211.130 # <local ip address>
port 1194
proto udp
dev tun
;dev tap
ca ca.crt
cert server.crt
key server.key
dh dh1024.pem
server 10.184.212.0 255.255.255.0 # range ip address for clients
#ifconfig-pool-persist ipp.txt
#push "redirect-gateway def1"
push "route 10.184.211.0 255.255.255.0"
push "route 10.0.1.0 255.255.255.0" # you can delete it
push "route 10.0.0.0 255.255.255.0"
push "dhcp-option DNS 10.184.211.131"
#push "dhcp-option DNS 208.67.220.220"
keepalive 5 30
comp-lzo
persist-key
persist-tun
status server-tcp.log
verb 3
</pre>
<p>Then try to start OpenVPN</p>
<pre>#/etc/init.d/openvpn start</pre>
<p> Next step we will create keys for clients:</p>
<pre>#source ./vars
#./build-key client1</pre>
<p>after answer some questions in dir keys we will see 3 files: client1.key client1.crt client1.csr Wen need 3 files:</p>
<pre>ca.crt, client1.key, client1.crt</pre>
<p>and copy to client's host <strong>Configuring client access to VPN server</strong> installing openvpn:</p>
<pre>$sudo apt-get update
$sudo apt-get install openvpn
$cd /etc/openvpn
$sudo vim openvpn.conf</pre>
<pre> client
dev tun
proto udp
remote 10.184.211.130 1194 #this is ip address Opnevpn server
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert mah.crt
key mah.key
comp-lzo
verb 3</pre>
<p>keys should be here in this directory: /etc/openvpn/ Trying start service</p>
<pre>$sudo /etc/init.d/openvpn start</pre>
<pre>$ifconfig
tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.184.212.6 P-t-P:10.184.212.5 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:234452 errors:0 dropped:231992 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:0 (0.0 B) TX bytes:349924494 (349.9 MB)</pre>
<p>interface tun0 is up , look's like good =============== links: <a href="https://help.ubuntu.com/community/OpenVPN">https://help.ubuntu.com/community/OpenVPN</a> #how to install OpenVPN in Ubuntu <a href="https://openvz.org/VPN_via_the_TUN/TAP_device">https://openvz.org/VPN_via_the_TUN/TAP_device</a> #VPN via the TUN/TAP device in OpenVZ container </p>Ubuntu bonding2017-04-04T19:46:11+00:002024-03-27T06:17:47+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/ubuntu-bonding/<p><a href="https://linuxmon.com/ubuntu-bonding/"><img alt="" height="116" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/bonding.png/bonding-207x116.png" width="207"/></a></p>
<p>If we need increase Bandwidth of the server we need to configure bond in ethernet card Bonding also calls port <strong>trunking</strong> this is combination someethernet card in one link with one IP address, for high- loaded systems:</p>
<ul>
<li>load balancing,</li>
<li>high-availability,</li>
<li>maximum throughput,</li>
<li>high-availability</li>
</ul>
<p>or combinations of these modes. We will setup in Ubunti 12.04 LTS</p>
<!--more-->
<p>Ubuntu 12.04.4 LTS <strong>Installation</strong> we need to install <strong>ifenslave-2.6</strong> ifenslave-2.6 used turn-off-turn-on slave ethernet cards in bond</p>
<pre>sudo apt-get install ifenslave-2.6</pre>
<p><b>Configuration ethernet cards</b> before configuring eth cards in bond, we need to check exist module bonding in core system and make autoload module:</p>
<pre class="brush: bash; gutter: true; first-line: 1">sudo vi /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored
loop
lp
rtc
bonding
</pre>
<p>stop networking: sudo /etc/init.d/networking stop</p>
<pre>sudo /etc/init.d/networking stop</pre>
<p>load module <strong>bonding</strong></p>
<pre>sudo modprobe bonding</pre>
<p>now we are ready to set up our ethernet cards:</p>
<pre>sudo vim /etc/network/interfaces</pre>
<p>for example, we have two eth card and we need bond its. eth0 and eth1 for bonding in mode ‘load balancing’.</p>
<pre class="brush: bash; gutter: true; first-line: 1">auto eth0
iface eth0 inet manual
bond-master bond0
auto eth1
iface eth1 inet manual
bond-master bond0
# bond0 is configured using static network information.
auto bond0
iface bond0 inet static
address 192.168.1.10
gateway 192.168.1.1
netmask 255.255.255.0
bond-mode balance-rr
bond-miimon 100
bond-slaves eth0 eth1</pre>
<p>start networking:</p>
<pre>sudo /etc/init.d/networking start</pre>
<p>verify ethernet card bond0:</p>
<pre>$cat /proc/net/bonding/bond0</pre>
<pre>Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)
Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0
Slave Interface: eth3
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:15:17:6a:65:f5
Slave queue ID: 0
Slave Interface: eth2
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:15:17:6a:65:f4
Slave queue ID: 0</pre>
<p>Everything are OK. --- Original <span style="text-decoration: underline;">here</span></p>Plugin for Nagios in Bash2017-04-04T19:42:46+00:002024-03-28T20:02:11+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/plugin-for-nagios-in-bash/<p><a href="https://linuxmon.com/plugin-for-nagios-in-bash/"><img alt="" height="37" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/nagios.png/nagios-157x37.png" width="157"/></a></p>
<p>Today we make simple plugin in Bash</p>
<p>We need to know that Nagios’ plugins should return code:</p>
<table border="0">
<tbody>
<tr>
<td><strong>Exit Code</strong></td>
<td><strong>Status</strong></td>
</tr>
<tr>
<td>0</td>
<td>OK</td>
</tr>
<tr>
<td>1</td>
<td>WARNING</td>
</tr>
<tr>
<td>2</td>
<td>CRITICAL</td>
</tr>
<tr>
<td>3</td>
<td>UNKNOWN</td>
</tr>
</tbody>
</table>
<p>For example, we need count of number something process in Linux</p>
<pre> #ps ax |grep collector | wc -l
33</pre>
<p><!--more--></p>
<p>we have 33 processes of ‘collector’ , we assume that is correct number of processes and if this value not much then plugin should return CRITICAL code</p>
<pre class="brush: bash; gutter: true; first-line: 1">#!/bin/bash
#do work#######
COUNT=`ps ax |grep collector | grep -v grep |grep -v check_collector| wc -l`
CNTSHOULDBE=$1
if
[ $COUNT -eq $CNTSHOULDBE ] ; then
echo "OK - $COUNT connections, should be $CNTSHOULDBE "
exit 0
elif
[ $COUNT -lt $CNTSHOULDBE ] ; then
echo "CRITICAL - $COUNT connections should be $CNTSHOULDBE "
exit 2
elif
[ $COUNT -ge $CNTSHOULDBE ] ; then
echo "CRITICAL - $COUNT connections should be $CNTSHOULDBE "
exit 2
else
echo "UNKNOWN - $COUNT connections"
exit 3
fi
</pre>
<p>argument for this plugin will be some number</p>
<p>save this code in</p>
<p><strong>/usr/local/nagios/libexec</strong></p>
<p>And make executable</p>
<p><strong>chmod +x check_collector</strong></p>
<p>We are ready to test</p>
<h2><b>Adding plugins in NRPE</b></h2>
<p>Add plugin in NRPE config file with argument for example</p>
<p><strong>command[check_collector]=/usr/local/nagios/libexec/check_collector 33</strong></p>
<p><b>33 - </b> in this case correct value for our system.</p>
<p>restart nrpe:</p>
<p><strong>#killall nrpe</strong></p>
<p><strong>#/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d</strong></p>
<p>go to the nagios host to set up for this plugin.</p>
<p>Add in config file :</p>
<pre>define service{
use generic-service ; Name of service template to use
host_name rec-1
service_description Check Collector
check_command check_nrpe!check_collector
}</pre>
<p>restart nagios:</p>
<p><strong>#server nagios restart</strong></p>
<p>in WEB interface nagios we should see:</p>
<p><a href="https://linuxmon.com/static/media/uploads/Blog/check_collector-300x7.png" target="_blank"><img alt="check_collector" class="aligncenter size-full wp-image-220" height="19" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/check_collector.png/check_collector-736x19.png" width="736"/></a></p>
<p>Setup plugin for Nagios done.</p>Install and setup Nagios. Part 12017-04-04T19:04:21+00:002024-03-29T12:01:15+00:00mahhttps://linuxmon.com/author/mah/https://linuxmon.com/nagios-part-1/<p><!--:en--></p>
<p><a href="https://linuxmon.com/nagios-part-1/"><img alt="nagios" class="alignnone size-full wp-image-22" height="37" src="https://linuxmon.com/static/media/uploads/Blog/.thumbnails/nagios.png/nagios-157x37.png" width="157"/></a></p>
<p><strong>Tasks</strong></p>
<p>1. Install Nagios</p>
<p>2. Setup and add hosts Nagios for monitoring</p>
<p>3. Install and setup NRPE</p>
<h5> </h5>
<h5>---------------------------</h5>
<p><strong>Nagios</strong> is an open source computer system monitoring, network monitoring and infrastructure monitoring software application. Nagios offers monitoring and alerting services for servers, switches, applications and services. It alerts the users when things go wrong and alerts them a second time when the problem has been resolved.<!--:--><!--:ru--></p>
<p> </p>
<h5><!--more--></h5>
<h5>---------------------------</h5>
<p>We will be install Nagios on server Ubuntu 12.04.2 LTS from repository</p>
<p><span>sudo apt-get udate</span></p>
<p><span>sudo apt-get install nagios3 nagios3-cgi</span></p>
<p>After input admin password <strong>nagiosadmin</strong> and after installation all depends we can log on by address:</p>
<p><span>http://192.168.0.1/nagios3</span></p>
<p>Input password nagiosadmin, then should be open website nagios</p>
<p></p>
<p>By default, nagios monitors localhost only, for monitoring any hosts, we need setup config file each host:</p>
<p>Go to the host by ssh consoleubder root to <strong>/etc/nagios3/conf.d</strong></p>
<p>We need explain about files in this directory:</p>
<p>contacts_nagios2.cfg - describes all contacts for notification, leave by default, and we can change email for notification</p>
<pre>define contact{
contact_name root
alias Root
service_notification_period 24x7
host_notification_period 24x7
service_notification_options w,u,c,r
host_notification_options d,r
service_notification_commands notify-service-by-email
host_notification_commands notify-host-by-email
email root@localhost
}</pre>
<p>generic-host_nagios2.cfg - General template for host</p>
<pre># Generic host definition template - This is NOT a real host, just a template!
define host{
name generic-host ; The name of this host template
notifications_enabled 1 ; Host notifications are enabled
event_handler_enabled 1 ; Host event handler is enabled
flap_detection_enabled 1 ; Flap detection is enabled
failure_prediction_enabled 1 ; Fail prediction is enabled
process_perf_data 1 ; Process performance data
retain_status_information 1 ; Retain status information across program restarts
retain_nonstatus_information 1 ; Retain non-status information across program restarts
check_command check-host-alive
max_check_attempts 10
notification_interval 0
notification_period 24x7
notification_options d,u,r
contact_groups admins
register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REA HOST, JUST A TEMPLATE!
}</pre>
<p>This template leave as is. Based on this file we will generate files for hosts</p>
<p>generic-service_nagios2.cfg - General template for services</p>
<p>Object Definitions, wich used in config files , <span style="text-decoration: underline;">here</span></p>
<p style="text-align: left;">------------------</p>
<p style="text-align: left;">In <a href="http://lnxmon.com/nagios-part-2/">second part</a> we'll add host to nagios for monitoring</p>
<p><!--:--></p>