Pages

Monday 19 April 2021

Password Less authencation configure in Linux System

In this post, we are going to configure Password-less access to a Linux machine. below are the overview for the same,   

1. Create stander user in Machine 

2. Generate SSH RSA key for the user.

3. Convert RSA key to .pem file 

4. Change the sshd_config file. and restart sshd service. 


Create stander user in Machine add user in wheel group

[root@servera ~]# useradd admin
[root@servera ~]# passwd admin
Changing password for user admin.
New password:
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:
passwd: all authentication tokens updated successfully.
[root@servera ~]#
[root@servera ~]# usermod –aG wheel admin
[root@servera ~]# id admin
uid=1001(admin) gid=1001(admin) groups=1001(admin),10(wheel)
[root@servera ~]#

Generate SSH RSA key for the admin user.

[root@servera ~]# su - admin
[admin@servera ~]$ ls
[admin@servera ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/admin/.ssh/id_rsa): admin
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in admin.
Your public key has been saved in admin.pub.
The key fingerprint is:
SHA256:10tJj+1jaXiqiyQDZRWmVlntK6G4iDvwyO13c31EkB8 admin@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|        =+...    |
|       =.  o.E   |
|      =    .+ .  |
|     +    .o.B   |
|    .  .S...*.o  |
|.    .. .....= . |
|.+.. .o.. ..+ B  |
|..+....* o . * . |
|  o+. . + ooo    |
+----[SHA256]-----+
[admin@servera ~]$ ls
admin  admin.pub
[admin@servera ~]$ cat admin > admin.pem
[admin@servera ~]$ ls
admin  admin.pem  admin.pub
[admin@servera ~]$

NOTE: Copy above admin.pem file to another system. 

Create .ssh Folder with below permission
[admin@servera ~]$ mkdir .ssh
[admin@servera ~]$ chmod 700 .ssh
[admin@servera ~]$ ls -la
total 28
drwx------. 3 admin admin  142 Apr  6 11:07 .
drwxr-xr-x. 4 root  root    35 Apr  6 11:00 ..
-rw-------. 1 admin admin 1675 Apr  6 11:02 admin
-r--------. 1 admin admin 1675 Apr  6 11:03 admin.pem
-rw-r--r--. 1 admin admin  409 Apr  6 11:02 admin.pub
-rw-------. 1 admin admin  468 Apr  6 11:19 .bash_history
-rw-r--r--. 1 admin admin   18 Oct 30  2018 .bash_logout
-rw-r--r--. 1 admin admin  193 Oct 30  2018 .bash_profile
-rw-r--r--. 1 admin admin  231 Oct 30  2018 .bashrc
drwx------. 2 admin admin   48 Apr  6 11:12 .ssh
[admin@servera ~]$
[admin@servera ~]$ cat admin.pub > .ssh/authorized_keys
[admin@servera ~]$ chmod 600 .ssh/authorized_keys

Logout from admin user and change setting in sudores no passwd from wheel groups member 

[root@servera ~]# cat /etc/sudoers

## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
...
...
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS
## Allows people in group wheel to run all commands
#%wheel ALL=(ALL)       ALL
## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL
## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom
## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
[root@servera ~]#

Change below in /etc/ssh/sshd_config file and restart sshd service 

[root@servera ~]# cat /etc/ssh/sshd_config
#       $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $
# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/bin:/usr/bin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.
# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
# Ciphers and keying
#RekeyLimit default none
# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
RSAAuthentication yes
PubkeyAuthentication yes
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      .ssh/authorized_keys
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication no
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes
# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none
# no default banner path
#Banner none
# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server
[root@servera ~]#
[root@servera ~]# systemctl restart sshd 

Now Try to ssh login with another system via pem key 

[root@serverb ~]# chmod 400 admin.pem 
[root@serverb ~]# ssh -i admin.pem admin@servera
[root@servera ~]#


Wednesday 6 November 2019

Install Web Client (7/7)

Install Web Client (7/7)

Configure horde database

[root@mailserver emc]# mysql -u root -p
Enter password: redhat
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 7431
Server version: 5.5.44-MariaDB MariaDB Server

Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>create user horde@localhost identified by "redhat";
Query OK, 0 rows affected (0.18 sec)

MariaDB [(none)]> grant all privileges on horde.* to horde@localhost;
Query OK, 0 rows affected (0.03 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]>\q


[root@mailserver etc]# pear channel-discover pear.horde.org
Adding Channel "pear.horde.org" succeeded
Discovery of channel "pear.horde.org" succeeded

[root@mailserver html]# pear install horde/horde_role
downloading Horde_Role-1.0.1.tgz ...
Starting to download Horde_Role-1.0.1.tgz (10,977 bytes)
.....done: 10,977 bytes
install ok: channel://pear.horde.org/Horde_Role-1.0.1
horde/Horde_Role has post-install scripts:
/usr/share/pear/PEAR/Installer/Role/Horde/Role.php
Horde_Role: Use "pear run-scripts horde/Horde_Role" to finish setup.
DO NOT RUN SCRIPTS FROM UNTRUSTED SOURCES

[root@mailserver html]# pear run-scripts horde/Horde_Role
Including external post-installation script "/usr/share/pear/PEAR/Installer/Role/Horde/Role.php" - any errors are in this script
Inclusion succeeded
running post-install script "Horde_Role_postinstall->init()"
init succeeded
Filesystem location for the base Horde application :
* Enter an answer for #1: (Filesystem location for the base Horde application)
Filesystem location for the base Horde application : /var/www/html/webmail
Configuration successfully saved to PEAR config.
Install scripts complete

[root@mailserver html]# mkdir /var/www/html/webmail

[root@mailserver html]# pear install -a -B horde/webmail
WARNING: "pear/Console_Getopt" is deprecated in favor of "pear/Console_GetoptPlus"
Unknown remote channel: phpseclib.sourceforge.net
WARNING: "pear/Net_Sieve" is deprecated in favor of "horde/Horde_ManageSieve"
Failed to download pear/Text_LanguageDetect within preferred state "stable", latest release is version 0.3.0, stability "alpha", use "channel://pear.php.net/Text_LanguageDetect-0.3.0" to install
Failed to download pecl/sasl within preferred state "stable", latest release is version 0.1.0, stability "alpha", use "channel://pecl.php.net/sasl-0.1.0" to install
Failed to download pecl/idn within preferred state "stable", latest release is version 0.2.0, stability "beta", use "channel://pecl.php.net/idn-0.2.0" to install
Failed to download pecl/ssh2 within preferred state "stable", latest release is version 0.12, stability "beta", use "channel://pecl.php.net/ssh2-0.12" to install
WARNING: "pear/HTTP_Request" is deprecated in favor of "pear/HTTP_Request2"
WARNING: "pear/DB" is deprecated in favor of "pear/MDB2"
Failed to download pear/SOAP within preferred state "stable", latest release is version 0.13.0, stability "beta", use "channel://pear.php.net/SOAP-0.13.0" to install
Failed to download pear/Console_Color2 within preferred state "stable", latest release is version 0.1.2, stability "alpha", use "channel://pear.php.net/Console_Color2-0.1.2" to install
Failed to download pecl/msgpack within preferred state "stable", latest release is version 2.0.0, stability "beta", use "channel://pecl.php.net/msgpack-2.0.0" to install
WARNING: "pear/HTTP_Request" is deprecated in favor of "pear/HTTP_Request2"

....

....

Output Omitted. 

....

....

install ok: channel://pear.horde.org/gollem-3.0.6
install ok: channel://pear.horde.org/imp-6.2.11
install ok: channel://pear.horde.org/ingo-3.2.7
install ok: channel://pear.horde.org/kronolith-4.2.11
install ok: channel://pear.horde.org/mnemo-4.2.8
install ok: channel://pear.horde.org/nag-4.2.6
install ok: channel://pear.horde.org/trean-1.1.3
install ok: channel://pear.horde.org/turba-4.2.11
install ok: channel://pear.horde.org/webmail-5.2.11
[root@mailserver html]# ls
webmail


[root@mailserver html]# ls webmail/
admin content imp ingo js lib login.php nag rpc services static test.php timeobjects turba
config gollem index.php install kronolith locale mnemo rampage.php rpc.php signup.php templates themes trean util

[root@mailserver html]# getenforce
Disabled

[root@mailserver html]# yum install php-pdo
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: linux.mirrors.es.net
* epel: mirrors.cat.pdx.edu
* extras: linux.mirrors.es.net
* updates: mirrors.unifiedlayer.co.in
Package php-pdo-5.4.16-36.el7_1.x86_64 already installed and latest version
Nothing to do
[root@mailserver html]# webmail-install

Installing Horde Groupware Webmail Edition

Configuring database settings

What database backend should we use?
(false) [None]
(mysql) MySQL / PDO
(mysqli) MySQL (mysqli)
(oci8) Oracle
(pgsql) PostgreSQL
(sqlite) SQLite

Type your choice []: mysql

Username to connect to the database as* [] horde
Password to connect with
How should we connect to the database?
(unix) UNIX Sockets
(tcp) TCP/IP

Type your choice [unix]: tcp

Database server/host* [] localhost

Port the DB is running on, if non-standard [3306]

Database name to use* [] horde

Internally used charset* [utf-8]
Use SSL to connect to the server?
(1) Yes
(0) No

Type your choice [0]: 0

Certification Authority to use for SSL connections []
Split reads to a different server?
(false) Disabled
(true) Enabled

Type your choice [false]:

Writing main configuration file... done.

Creating and updating database tables... done.

Configuring administrator settings

Specify an existing mail user who you want to give administrator
permissions (optional):

Writing main configuration file... done.

Thank you for using Horde Groupware Webmail Edition!


Configure Amavishd service (6/7)

Configure Amavishd service (6/7)

Installation amavisd-new service by yum command.

[root@mailserver ~]# yum --enablerepo=epel -y install amavisd-new clamav-server clamav-server-systemd

[root@mailserver ~]# cp /usr/share/doc/clamav-server-0.98.7/clamd.sysconfig /etc/sysconfig/clamd.amavisd

[root@mailserver ~]# vim /etc/sysconfig/clamd.amavisd
[root@mailserver ~]# cat /etc/sysconfig/clamd.amavisd
CLAMD_CONFIGFILE=/etc/clamd.d/amavisd.conf
CLAMD_SOCKET=/var/run/clamd.amavised/clamd.sock
#CLAMD_OPTIONS=
[root@mailserver ~]#


[root@mailserver ~]# vim /usr/lib/systemd/system/clamd\@.service
[root@mailserver ~]# cat /usr/lib/systemd/system/clamd\@.service
[Unit]
Description = clamd scanner (%i) daemon
After = syslog.target nss-lookup.target network.target

[Service]
Type = simple
ExecStart = /usr/sbin/clamd -c /etc/clamd.d/%i.conf --nofork=yes
Restart = on-failure
PrivateTmp = true

[Install]
WantedBy=multi-user.target
[root@mailserver ~]#


[root@mailserver ~]# systemctl start clamd@amavisd
[root@mailserver ~]# systemctl enable clamd@amavisd
ln -s '/usr/lib/systemd/system/clamd@.service' '/etc/systemd/system/multi-user.target.wants/clamd@amavisd.service'
[root@mailserver ~]# systemctl status clamd@amavisd
clamd@amavisd.service - clamd scanner (amavisd) daemon
Loaded: loaded (/usr/lib/systemd/system/clamd@.service; enabled)
Active: active (running) since Mon 2015-11-23 18:08:35 IST; 19s ago
Main PID: 2915 (clamd)
CGroup: /system.slice/system-clamd.slice/clamd@amavisd.service
└─2915 /usr/sbin/clamd -c /etc/clamd.d/amavisd.conf --nofork=yes

Nov 23 18:08:43 mailserver.example.com clamd[2915]: Algorithmic detection enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: Portable Executable support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: ELF support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: Mail files support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: OLE2 support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: PDF support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: SWF support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: HTML support enabled.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: Self checking every 600 seconds.
Nov 23 18:08:43 mailserver.example.com clamd[2915]: Self checking every 600 seconds.
[root@mailserver ~]# 

#Modify /etc/amavised/amavised.conf file same as below.

[root@mailserver ~]# vim /etc/amavisd/amavisd.conf
[root@mailserver ~]# cat /etc/amavisd/amavisd.conf
use strict;

# a minimalistic configuration file for amavisd-new with all necessary settings
#
# see amavisd.conf-default for a list of all variables with their defaults;
# for more details see documentation in INSTALL, README_FILES/*
# and at http://www.ijs.si/software/amavisd/amavisd-new-docs.html


# COMMONLY ADJUSTED SETTINGS:

# @bypass_virus_checks_maps = (1); # controls running of anti-virus code
# @bypass_spam_checks_maps = (1); # controls running of anti-spam code
# $bypass_decode_parts = 1; # controls running of decoders&dearchivers

$max_servers = 2; # num of pre-forked children (2..30 is common), -m
$daemon_user = 'amavis'; # (no default; customary: vscan or amavis), -u
$daemon_group = 'amavis'; # (no default; customary: vscan or amavis), -g

$mydomain = 'example.com'; # a convenient default for other settings

$MYHOME = '/var/spool/amavisd'; # a convenient default for other settings, -H
$TEMPBASE = "$MYHOME/tmp"; # working directory, needs to exist, -T
$ENV{TMPDIR} = $TEMPBASE; # environment variable TMPDIR, used by SA, etc.

....

....

Output omitted

....

....




# OTHER MORE COMMON SETTINGS (defaults may suffice):

# $myhostname = 'host.example.co.in'; # must be a fully-qualified domain name!
$myhostname = 'mailserver.example.com'; # must be a fully-qualified domain name!

$notify_method = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[127.0.0.1]:10025'; # set to undef with milter!

$final_virus_destiny = D_DISCARD;
$final_banned_destiny = D_BOUNCE;
$final_spam_destiny = D_DISCARD; #!!! D_DISCARD / D_REJECT
$final_bad_header_destiny = D_BOUNCE;
# $bad_header_quarantine_method = undef;

# $os_fingerprint_method = 'p0f:*:2345'; # to query p0f-analyzer.pl

## hierarchy by which a final setting is chosen:
## policy bank (based on port or IP address) -> *_by_ccat
## *_by_ccat (based on mail contents) -> *_maps
## *_maps (based on recipient address) -> final configuration value


....

....

Output omitted

....

....

# Potentially useful when all other scanners fail and it is desirable
# to let mail continue to flow with no virus checking (when uncommented).
# ['always-clean', sub {0}],

);


1; # insure a defined return value
[root@mailserver ~]#

Configure amavisd service in postfix service main.cf file.

[root@mailserver ~]# vim /etc/postfix/main.cf
[root@mailserver ~]# cat /etc/postfix/main.cf
...
#
# amavisd configure
content_filter=smtp-amavis:[127.0.0.1]:10024


Configure amavisd service in postfix service master.cf file.

[root@mailserver ~]# vim /etc/postfix/master.cf
[root@mailserver ~]# cat /etc/postfix/master.cf
...
#
#
#add below configretion for amavish service
smtp-amavis unix - - n - 2 smtp
-o smtp_data_done_timeout=1200
-o smtp_send_xforward_command=yes
-o disable_dns_lookups=yes
127.0.0.1:10025 inet n - n - - smtpd
-o content_filter=
-o local_recipient_maps=
-o relay_recipient_maps=
-o smtpd_restriction_classes=
-o smtpd_client_restrictions=
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o strict_rfc821_envelopes=yes
-o smtpd_error_sleep_time=0
-o smtpd_soft_error_limit=1001
-o smtpd_hard_error_limit=1000
[root@mailserver ~]#




Configure Dovecot service (5/7)

Configure Dovecot service (5/7)

Installation of dovecot

[root@mailserver ~]# yum install dovecot dovecot-mysql dovecot-pigeonhole


[root@mailserver ~]# vim /etc/dovecot/dovecot.conf
[root@mailserver ~]# cat /etc/dovecot/dovecot.conf
## Dovecot configuration file

# If you're in a hurry, see http://wiki2.dovecot.org/QuickConfiguration

# "doveconf -n" command gives a clean output of the changed settings. Use it
# instead of copy&pasting files when posting to the Dovecot mailing list.

# '#' character and everything after it is treated as comments. Extra spaces
# and tabs are ignored. If you want to use either of these explicitly, put the
# value inside quotes, eg.: key = "# char and trailing whitespace "

# Most (but not all) settings can be overridden by different protocols and/or
# source/destination IPs by placing the settings inside sections, for example:
# protocol imap { }, local 127.0.0.1 { }, remote 10.0.0.0/8 { }

# Default values are shown for each setting, it's not required to uncomment
# those. These are exceptions to this though: No sections (e.g. namespace {})
# or plugin settings are added by default, they're listed only as examples.
# Paths are also just examples with the real defaults being based on configure
# options. The paths listed here are for configure --prefix=/usr
# --sysconfdir=/etc --localstatedir=/var

# Protocols we want to be serving.
protocols = imap pop3 lmtp

# A comma separated list of IPs or hosts where to listen in for connections.
# "*" listens in all IPv4 interfaces, "::" listens in all IPv6 interfaces.

....
Output obmitted
....

# in filenames are intended to make it easier to understand the ordering.
!include conf.d/*.conf

# A config file can also tried to be included without giving an error if
# it's not found:
!include_try local.conf
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/10-auth.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/10-auth.conf
##
## Authentication processes
##

# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
# See also ssl=required setting.
disable_plaintext_auth = yes
#disable_plaintext_auth = no

# Authentication cache size (e.g. 10M). 0 means it's disabled. Note that
# bsdauth, PAM and vpopmail require cache_key to be set for caching to be used.
#auth_cache_size = 0
# Time to live for cached data. After TTL expires the cached record is no
# longer used, *except* if the main database lookup returns internal failure.
# We also try to handle password changes automatically: If user's previous
....
Output Obmiited
....

# Take the username from client's SSL certificate, using
# X509_NAME_get_text_by_NID() which returns the subject's DN's
# CommonName.
#auth_ssl_username_from_cert = no

# Space separated list of wanted authentication mechanisms:
# plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey
# gss-spnego
# NOTE: See also disable_plaintext_auth setting.
auth_mechanisms = plain login

##
## Password and user databases
##

#
# Password database is used to verify user's password (and nothing more).
# You can have multiple passdbs and userdbs. This is useful if you want to
# allow both system users (/etc/passwd) and virtual users to login without
# duplicating the system users into virtual database.
#
# <doc/wiki/PasswordDatabase.txt>
#
# User database specifies where mails are located and what user/group IDs
# own them. For single-UID configuration use "static" userdb.
#
# <doc/wiki/UserDatabase.txt>

#!include auth-deny.conf.ext
#!include auth-master.conf.ext

#!include auth-system.conf.ext
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext
[root@mailserver ~]#



[root@mailserver ~]# vim /etc/dovecot/conf.d/10-mail.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/10-mail.conf
##
## Mailbox locations and namespaces
##

# Location for users' mailboxes. The default is empty, which means that Dovecot
# tries to find the mailboxes automatically. This won't work if the user
# doesn't yet have any mail, so you should explicitly tell Dovecot the full
# location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
# isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
# %u - username
# %n - user part in user@domain, same as %u if there's no domain
# %d - domain part in user@domain, empty if there's no domain
# %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
# mail_location = maildir:~/Maildir
# mail_location = mbox:~/mail:INBOX=/var/mail/%u
# mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
# <doc/wiki/MailLocation.txt>
#
#mail_location =
mail_location = maildir:/var/spool/mail/%d/%n

# If you need to set multiple mailbox locations or want to change default
# namespace settings, you can do it by defining namespace sections.
#
# You can have private, shared and public namespaces. Private namespaces
# are for user's personal mails. Shared namespaces are for accessing other
# users' mailboxes that have been shared. Public namespaces are for shared
# mailboxes that are managed by sysadmin. If you create any shared or public
# namespaces you'll typically want to enable ACL plugin also, otherwise all

....
Output Obmitted
....


# Group to enable temporarily for privileged operations. Currently this is
# used only with INBOX when either its initial creation or dotlocking fails.
# Typically this is set to "mail" to give access to /var/mail.
mail_privileged_group = mail

# Grant access to these supplementary groups for mail processes. Typically
# these are used to set up access to shared mailboxes. Note that it may be
# dangerous to set these if users can create symlinks (e.g. if "mail" group is
# set here, ln -s /var/mail ~/mail/var could allow a user to delete others'
# mailboxes, or ln -s /secret/shared/box ~/mail/mybox would allow reading it).
mail_access_groups = mail

# Allow full filesystem access to clients. There's no access checks other than
# what the operating system does for the active UID/GID. It works with both
# maildir and mboxes, allowing you to prefix mailboxes names with eg. /path/
# or ~user/.
#mail_full_filesystem_access = no

# Dictionary for key=value mailbox attributes. Currently used by URLAUTH, but
# soon intended to be used by METADATA as well.
#mail_attribute_dict =

##
## Mail processes
##

# Don't use mmap() at all. This is required if you store indexes to shared
# filesystems (NFS or clustered filesystem).
#mmap_disable = no
mmap_disable = yes

# Rely on O_EXCL to work when creating dotlock files. NFS supports O_EXCL
# since version 3, so this should be safe to use nowadays by default.
#dotlock_use_excl = yes

# When to use fsync() or fdatasync() calls:
# optimized (default): Whenever necessary to avoid losing important data
# always: Useful with e.g. NFS when write()s are delayed
# never: Never use it (best performance, but crashes can lose data)
#mail_fsync = optimized

# Mail storage exists in NFS. Set this to yes to make Dovecot flush NFS caches
# whenever needed. If you're using only a single mail server this isn't needed.
#mail_nfs_storage = no
# Mail index files also exist in NFS. Setting this to yes requires
# mmap_disable=yes and fsync_disable=no.
#mail_nfs_index = no

# Locking method for index files. Alternatives are fcntl, flock and dotlock.
# Dotlocking uses some tricks which may create more disk I/O than other locking
# methods. NFS users: flock doesn't work, remember to change mmap_disable.
#lock_method = fcntl

# Directory in which LDA/LMTP temporarily stores incoming mails >128 kB.
#mail_temp_dir = /tmp

# Valid UID range for users, defaults to 500 and above. This is mostly
# to make sure that users can't log in as daemons or other system users.
# Note that denying root logins is hardcoded to dovecot binary and can't
# be done even if first_valid_uid is set to 0.
#first_valid_uid = 500
first_valid_uid = 8
#last_valid_uid = 0

# Valid GID range for users, defaults to non-root/wheel. Users having
# non-valid GID as primary group ID aren't allowed to log in. If user
# belongs to supplementary groups with non-valid GIDs, those groups are
# not set.
#first_valid_gid = 1
first_valid_gid = 12
#last_valid_gid = 0

# Maximum allowed length for mail keyword name. It's only forced when trying
# to create new keywords.
#mail_max_keyword_length = 50

....
Output Obmitted
....


#mail_attachment_fs = sis posix

# Hash format to use in attachment filenames. You can add any text and
# variables: %{md4}, %{md5}, %{sha1}, %{sha256}, %{sha512}, %{size}.
# Variables can be truncated, e.g. %{sha256:80} returns only first 80 bits
#mail_attachment_hash = %{sha1}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/10-master.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/10-master.conf
#default_process_limit = 100
#default_client_limit = 1000

# Default VSZ (virtual memory size) limit for service processes. This is mainly
# intended to catch and kill processes that leak memory before they eat up
# everything.
#default_vsz_limit = 256M

# Login user is internally used by login processes. This is the most untrusted
# user in Dovecot system. It shouldn't have access to anything at all.
#default_login_user = dovenull

....
Output Obmitted
....

service auth {
# auth_socket_path points to this userdb socket by default. It's typically
# used by dovecot-lda, doveadm, possibly imap process, etc. Users that have
# full permissions to this socket are able to get a list of all usernames and
# get the results of everyone's userdb lookups.
#
# The default 0666 mode allows anyone to connect to the socket, but the
# userdb lookups will succeed only if the userdb returns an "uid" field that
# matches the caller process's UID. Also if caller's uid or gid matches the
# socket's uid or gid the lookup succeeds. Anything else causes a failure.
#
# To give the caller full permissions to lookup all users, set the mode to
# something else than 0666 and Dovecot lets the kernel enforce the
# permissions (e.g. 0777 allows everyone full permissions).
unix_listener auth-userdb {
mode = 0600
user = mail
group = mail
}

# Postfix smtp-auth
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}

# Auth process is run as this user.
#user = $default_internal_user
}

service auth-worker {
# Auth worker process is run as root by default, so that it can access
# /etc/shadow. If this isn't necessary, the user should be changed to
# $default_internal_user.
#user = root
}

service dict {
# If dict proxy is used, mail processes should have access to its socket.
# For example: mode=0660, group=vmail and global mail_access_groups=vmail
unix_listener dict {
#mode = 0600
#user =
#group =
}
}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/10-ssl.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/10-ssl.conf
##
## SSL settings
##

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
# disable plain pop3 and imap, allowed are only pop3+TLS, pop3s, imap+TLS and imaps
# plain imap and pop3 are still allowed for local connections
#ssl = required
ssl = yes

# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
#ssl_cert = </etc/pki/dovecot/certs/dovecot.pem
#ssl_key = </etc/pki/dovecot/private/dovecot.pem
ssl_cert = </etc/pki/tls/certs/mailserver.example.com.crt
ssl_key = </etc/pki/tls/certs/mailserver.example.com.key

# If key file is password protected, give the password here. Alternatively
# give it when starting dovecot with -p parameter. Since this file is often
# world-readable, you may want to place this setting instead to a different
# root owned 0600 file by using ssl_key_password = <path.
#ssl_key_password =

# PEM encoded trusted certificate authority. Set this only if you intend to use
# ssl_verify_client_cert=yes. The file should contain the CA certificate(s)
# followed by the matching CRL(s). (e.g. ssl_ca = </etc/pki/dovecot/certs/ca.pem)
#ssl_ca =

# Require that CRL check succeeds for client certificates.
#ssl_require_crl = yes

....
Output Obmitted
....

# Prefer the server's order of ciphers over client's.
#ssl_prefer_server_ciphers = no

# SSL crypto device to use, for valid values run "openssl engine"
#ssl_crypto_device =
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/15-lda.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/15-lda.conf
##
## LDA specific settings (also used by LMTP)
##

# Address to use when sending rejection mails.
# Default is postmaster@<your domain>. %d expands to recipient domain.
postmaster_address = postmaster@example.com

# Hostname to use in various parts of sent mails (e.g. in Message-Id) and
# in LMTP replies. Default is the system's real hostname@domain.
hostname = mailserver.example.com

# If user is over quota, return with temporary failure instead of
# bouncing the mail.
#quota_full_tempfail = no

# Binary to use for sending mails.
#sendmail_path = /usr/sbin/sendmail

# If non-empty, send mails via this SMTP host[:port] instead of sendmail.
#submission_host =

# Subject: header to use for rejection mails. You can use the same variables
# as for rejection_reason below.
#rejection_subject = Rejected: %s

# Human readable error message for rejection mails. You can use variables:
# %n = CRLF, %r = reason, %s = original subject, %t = recipient
#rejection_reason = Your message to <%t> was automatically rejected:%n%r

# Delimiter character between local-part and detail in email address.
#recipient_delimiter = +

# Header where the original recipient address (SMTP's RCPT TO: address) is taken
# from if not available elsewhere. With dovecot-lda -a parameter overrides this.
# A commonly used header for this is X-Original-To.
#lda_original_recipient_header =

# Should saving a mail to a nonexistent mailbox automatically create it?
#lda_mailbox_autocreate = no
lda_mailbox_autocreate = yes

# Should automatically created mailboxes be also automatically subscribed?
#lda_mailbox_autosubscribe = no
lda_mailbox_autosubscribe = yes

protocol lda {
# Space separated list of plugins to load (default is global mail_plugins).
#mail_plugins = $mail_plugins
mail_plugins = sieve
}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/20-pop3.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/20-pop3.conf
##
## POP3 specific settings
##

# Don't try to set mails non-recent or seen with POP3 sessions. This is
# mostly intended to reduce disk I/O. With maildir it doesn't move files
# from new/ to cur/, with mbox it doesn't write Status-header.
#pop3_no_flag_updates = no

# Support LAST command which exists in old POP3 specs, but has been removed
# from new ones. Some clients still wish to use this though. Enabling this
# makes RSET command clear all \Seen flags from messages.
#pop3_enable_last = no

....
Output Obmitted
....

# If you want UIDL compatibility with other POP3 servers, use:
# UW's ipop3d : %08Xv%08Xu
# Courier : %f or %v-%u (both might be used simultaneosly)
# Cyrus (<= 2.1.3) : %u
# Cyrus (>= 2.1.4) : %v.%u
# Dovecot v0.99.x : %v.%u
# tpop3d : %Mf
#
# Note that Outlook 2003 seems to have problems with %v.%u format which was
# Dovecot's default, so if you're building a new server it would be a good
# idea to change this. %08Xu%08Xv should be pretty fail-safe.
#
pop3_uidl_format = %08Xu%08Xv

# Permanently save UIDLs sent to POP3 clients, so pop3_uidl_format changes
# won't change those UIDLs. Currently this works only with Maildir.
#pop3_save_uidl = no

# What to do about duplicate UIDLs if they exist?
# allow: Show duplicates to clients.
# rename: Append a temporary -2, -3, etc. counter after the UIDL.
#pop3_uidl_duplicates = allow

# This option changes POP3 behavior so that it's not possible to actually
# delete mails via POP3, only hide them from future POP3 sessions. The mails
# will still be counted towards user's quota until actually deleted via IMAP.
# Use e.g. "$POP3Deleted" as the value (it will be visible as IMAP keyword).
# Make sure you can legally archive mails before enabling this setting.
#pop3_deleted_flag =

# POP3 logout format string:
# %i - total number of bytes read from client
# %o - total number of bytes sent to client
# %t - number of TOP commands
# %p - number of bytes sent to client as a result of TOP command
# %r - number of RETR commands
# %b - number of bytes sent to client as a result of RETR command
# %d - number of deleted messages
# %m - number of messages (before deletion)
# %s - mailbox size in bytes (before deletion)
# %u - old/new UIDL hash. may help finding out if UIDLs changed unexpectedly
#pop3_logout_format = top=%t/%p, retr=%r/%b, del=%d/%m, size=%s

# Workarounds for various client bugs:
# outlook-no-nuls:
# Outlook and Outlook Express hang if mails contain NUL characters.
# This setting replaces them with 0x80 character.
# oe-ns-eoh:
# Outlook Express and Netscape Mail breaks if end of headers-line is
# missing. This option simply sends it if it's missing.
# The list is space-separated.
pop3_client_workarounds = outlook-no-nuls oe-ns-eoh

protocol pop3 {
# Space separated list of plugins to load (default is global mail_plugins).
#mail_plugins = $mail_plugins

# Maximum number of POP3 connections allowed for a user from each IP address.
# NOTE: The username is compared case-sensitively.
#mail_max_userip_connections = 10
}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/20-managesieve.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/20-managesieve.conf
##
## ManageSieve specific settings
##

# Uncomment to enable managesieve protocol:
protocols = $protocols sieve

# Service definitions

#service managesieve-login {
#inet_listener sieve {
# port = 4190
#}

#inet_listener sieve_deprecated {
# port = 2000
#}

# Number of connections to handle before starting a new process. Typically
# the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
# is faster. <doc/wiki/LoginProcess.txt>
#service_count = 1

# Number of processes to always keep waiting for more connections.
#process_min_avail = 0

# If you set service_count=0, you probably need to grow this.
#vsz_limit = 64M
#}

....
Output Obmitted
....

# The maximum number of compile errors that are returned to the client upon
# script upload or script verification.
#managesieve_max_compile_errors = 5

# Refer to 90-sieve.conf for script quota configuration and configuration of
# Sieve execution limits.
}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/conf.d/90-sieve.conf
[root@mailserver ~]# cat /etc/dovecot/conf.d/90-sieve.conf
##
## Settings for the Sieve interpreter
##

# Do not forget to enable the Sieve plugin in 15-lda.conf and 20-lmtp.conf
# by adding it to the respective mail_plugins= settings.

plugin {
# The path to the user's main active script. If ManageSieve is used, this the
# location of the symbolic link controlled by ManageSieve.
#sieve = ~/.dovecot.sieve
sieve = /home/vmail/%Ld/%Ln.sieve/.dovecot.sieve

# The default Sieve script when the user has none. This is a path to a global
# sieve script file, which gets executed ONLY if user's private Sieve script
# doesn't exist. Be sure to pre-compile this script manually using the sievec
# command line tool.
# --> See sieve_before fore executing scripts before the user's personal
# script.
#sieve_default = /var/lib/dovecot/sieve/default.sieve

# Directory for :personal include scripts for the include extension. This
# is also where the ManageSieve service stores the user's scripts.
#sieve_dir = ~/sieve
sieve_dir = /home/vmail/%Ld/%Ln.sieve/

# Directory for :global include scripts for the include extension.
#sieve_global_dir =

# Path to a script file or a directory containing script files that need to be
# executed before the user's script. If the path points to a directory, all
# the Sieve scripts contained therein (with the proper .sieve extension) are
# executed. The order of execution within a directory is determined by the
# file names, using a normal 8bit per-character comparison. Multiple script
# file or directory paths can be specified by appending an increasing number.
#sieve_before =
#sieve_before2 =
#sieve_before3 = (etc...)

# Identical to sieve_before, only the specified scripts are executed after the
# user's script (only when keep is still in effect!). Multiple script file or
# directory paths can be specified by appending an increasing number.
#sieve_after =
#sieve_after2 =
#sieve_after2 = (etc...)

# Which Sieve language extensions are available to users. By default, all
# supported extensions are available, except for deprecated extensions or
# those that are still under development. Some system administrators may want
# to disable certain Sieve extensions or enable those that are not available
# by default. This setting can use '+' and '-' to specify differences relative
# to the default. For example `sieve_extensions = +imapflags' will enable the
# deprecated imapflags extension in addition to all extensions were already
# enabled by default.
sieve_extensions = +notify +imapflags

# Which Sieve language extensions are ONLY available in global scripts. This
# can be used to restrict the use of certain Sieve extensions to administrator
# control, for instance when these extensions can cause security concerns.
# This setting has higher precedence than the `sieve_extensions' setting
# (above), meaning that the extensions enabled with this setting are never
# available to the user's personal script no matter what is specified for the
# `sieve_extensions' setting. The syntax of this setting is similar to the
# `sieve_extensions' setting, with the difference that extensions are
# enabled or disabled for exclusive use in global scripts. Currently, no
# extensions are marked as such by default.
#sieve_global_extensions =

....
Output Obmitted
....

# The maximum amount of disk storage a single user's scripts may occupy. If
# set to 0, no limit on the used amount of disk storage is enforced.
# (Currently only relevant for ManageSieve)
#sieve_quota_max_storage = 0
}
[root@mailserver ~]#


[root@mailserver ~]# vim /etc/dovecot/dovecot-sql.conf.ext
[root@mailserver ~]# cat /etc/dovecot/dovecot-sql.conf.ext
driver = mysql

connect = host=localhost dbname=vmaildb user=vmailuser password=redhat@123

user_query = SELECT CONCAT("/home/vmail/", domain) AS home, 8 AS uid, 12 AS gid, 'maildir:/var/spool/mail/%d/%n' AS mail, CONCAT("dirsize:storage=", quota) AS quota FROM mailbox WHERE username = '%u' AND active = '1'

password_query = SELECT username AS user, password, CONCAT("/var/spool/mail/", domain) AS userdb_home, 8 AS userdb_uid, 12 AS userdb_gid FROM mailbox WHERE username = '%u' AND active='1'

iterate_query = SELECT username AS user FROM mailbox WHERE active='1'
[root@mailserver ~]#


[root@mailserver ~]# chmod 0600 /etc/dovecot/dovecot-sql.conf.ext

[root@mailserver ~]# systemctl restart dovecot