Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
Gentoo Directory Server Installation Script
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks
View previous topic :: View next topic  
Author Message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Thu Jan 09, 2020 8:30 pm    Post subject: Gentoo Directory Server Installation Script Reply with quote

Hi Guys
Just today I finished porting over to Gentoo an older script of mine for Debian which will install and configure a full Directory Server including:


Code:

Bind Dns
Openldap
Kerberos
Kerberised NFS
Samba and
NTP



It will use "ip" "ifconfig" "sipcalc" and "hostname" to FIRST extract and variable-ize all your network info and then install and configure:

Code:

1.DNS BIND name server with forward and reverse lookup zones all reflecting your network configuration of course.

2. OPENLDAP server.

It will start the server with the stock slapd.conf file and then will switch to OLC functional mode.
It will create the config monitor and mdb databases and change the ROOTPW, import the schemas, change the domain, create a DIT and issue SSL certificates ALL of-course again reflecting your network and while ONLY using the OLC way with .ldif files.
The OUs People,Group and sudoers will be created together with a group "ldapusers" with gid=10000

3.KERBEROS KDC and KADMIN servers will configured,the db initialized to reflect YOUR realm and principals will be added for host/FQDN and nfs/FQDN together with their KEYS.

You will be prompted to give the passwords for the principals "root/admin"@REALM" and "root@REALM"

4.The NFS SERVER will ask you to choose a directory which it will then share with security sec=krb5p

5.A SAMBA SERVER will be installed and configured to share two directories.One open to guests and read-only and another "private" to be accessible only by a specific group.

6.Finally NTPd time synchronization daemon will be installed.



The script works both for machines using SYSTEMD and/or OPENRC.
And will create 4 files in

/etc/portage/package.use

directory.
Code:

echo "net-nds/openldap kerberos sha2 sasl -minimal samba" > /etc/portage/package.use/openldap
echo "app-crypt/mit-krb5  openldap" > /etc/portage/package.use/mit-krb5
echo "net-fs/nfs-utils kerberos ldap nfsv4" > /etc/portage/package.use/nfs-utils
echo "net-libs/libtirpc kerberos" > /etc/portage/package.use/libtirpc

This presupposes that your
/etc/portage/package.use
IS A DIRECTORY.
IF your package.use is a file then I will need to later add some code to cover this eventuality.

Without much further ado this is the script:


Code:

#!/bin/bash

##########  WRITTEN by alamahant on 9 January 2020 #############


[ ! -f /etc/hosts.bak ] && cp -p /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp -p /etc/hostname /etc/hostname.bak


#if ! equery l '*' | grep sipcalc >> /dev/null;then emerge -aq sipcalc;fi
#if ! equery l '*' | grep net-tools >> /dev/null;then emerge -aq net-tools;fi
#if ! equery l '*' | grep gentoolkit >> /dev/null;then emerge -aq app-portage/gentoolkit;fi

emerge -DNaq sipcalc net-tools gentoolkit

clear
staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

echo "EXTRACTING NETWORK INFO AND NOMENCLATURE..."
###NETWORK INFO AND NOMENCLATURE
#myIP=$(hostname -i)
#myIP=$(ip -o addr show up primary scope global | while read -r num dev fam addr rest; do echo ${addr%/*}; done)
myIP=$(ip route get 8.8.8.8| grep src| sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
#myFQDN=$(hostname)

setfqdn () {
clear
echo "DO YOU WISH TO SET YOUR FQDN? PLEASE PRESS "y" TO CONFIRM OR IF YOU HAVE ALREADY SET IT PRESS ANY OTHER KEY TO SKIP";read line
[ $line != "y" ] && return
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.<domain>.<dom>";read line
echo "DO YOU WISH YOUR FQDN TO BE ${line}? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
echo $line > /etc/hostname
pidof /sbin/init >> /dev/null && [ -f /etc/conf.d/hostname ] && echo "hostname="$line"" > /etc/conf.d/hostname && echo 'rc_before="net.lo"' >> /etc/conf.d/hostname
rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $line
EOF

pidof /sbin/init >> /dev/null && hostname -F /etc/hostname >> /dev/null
pidof /lib/systemd/systemd >> /dev/null && hostnamectl set-hostname $line

} ###Closing setfqdn


setfqdn
myFQDN=$(hostname)

myNETMASK=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $4 }')
#myDOMAIN=$(hostname -d) || myDOMAIN=$(dnsdomainname) || echo "THE SCRIPT ENCOUNTERED AN ERROR AND WILL EXIT.PLEASE FIX THE "hostname" COMMAND BECAUSE IT IS NOT FUNCTIONING PROPERLY"
myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
myMACHINE=$(echo $myFQDN | awk -F. '{ print $1 }')
myINADDR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $3"."$2"."$1 }')
mySERIAL=$(date '+%Y%m%d'01)
myPTR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $4 }')
myNETWORK=$(sipcalc $(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }') | grep "Network address" | awk '{ print $4 }')
myCIDR=$(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F/ '{ print $2 }')
myDNS=$(ip route | grep default | awk '{ print $3 }')
myREALM=$(echo ${myDOMAIN^^})

c1=$(echo $myDOMAIN | awk -F. '{ print $1 }')
c2=$(echo $myDOMAIN | awk -F. '{ print $2 }')
c1=$(echo "${c1^}")
c2=$(echo "${c2^}")
c3=$(echo $c1 $c2)

#####DIRECTORIES
myDNSDIR="/var/bind"
myLDAPCONFDIR="/etc/openldap"
myLDAPDATADIR="/var/lib/openldap-data"
myKRB5DIR="/var/lib/krb5kdc"
###DAEMON NOMENCLATURE
myDNSSVCNAME="named"
myDNSPACKNAME="bind"
myKDCSVCNAME="mit-krb5kdc"
myKADMINSVCNAME="mit-krb5kadmind"




dnsinstall () {
clear
echo "PART 1: DNS BIND. PLEASE PRESS ANY KEY TO CONTINUE";read line

pidof /lib/systemd/systemd >> /dev/null && systemctl stop $myDNSSVCNAME
pidof /sbin/init >> /dev/null && rc-service $myDNSSVCNAME stop
echo "REMOVING BIND AND PURGING ALL PREVIEWS CONFIGURATION..."
[ -d $myDNSDIR ] && rm  $myDNSDIR/*lan 
[ -d $myDNSDIR ] && rm  $myDNSDIR/*db
cp /etc/resolv.conf.bak /etc/resolv.conf
echo "INSTALLING AND CONFIGURING BIND..."
emerge -DNaq $myDNSPACKNAME
clear
[ ! -f /etc/bind/named.conf.bak ] && mv /etc/bind/named.conf /etc/bind/named.conf.bak
[ -f /etc/bind/named.conf ] && rm /etc/bind/named.conf
cat >> $myDNSDIR/$myDOMAIN.lan << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
         3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
        IN  A       $myIP

        IN  MX 10   $myFQDN.

$myMACHINE     IN  A       $myIP
EOF

cat >> $myDNSDIR/$myINADDR.db << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
        3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
   IN  PTR    $myDOMAIN.
        IN  A       $myNETMASK



$myPTR     IN  PTR       $myFQDN.
EOF

cat >> /etc/bind/named.conf << EOF


acl "xfer" {
   127.0.0.0/8; $myNETWORK/$myCIDR;

};


acl "trusted" {
   127.0.0.0/8;
   $myNETWORK/$myCIDR;
};

options {
   directory "$myDNSDIR";
   pid-file "/run/named/named.pid";

   //bindkeys-file "/etc/bind/bind.keys";

   listen-on-v6 { none; };
   //listen-on { 127.0.0.1; };
   listen-on port 53 { any; };
   allow-query {
      trusted;
   };

   allow-query-cache {
      /* Use the cache for the "trusted" ACL. */
      trusted;
   };

   allow-recursion {
      /* Only trusted addresses are allowed to use recursion. */
      trusted;
   };

   allow-transfer {
      /* Zone tranfers are denied by default. */
      xfer;
   };

   allow-update {
      /* Don't allow updates, e.g. via nsupdate. */
      none;
   };


   forwarders { $myDNS; };

   dnssec-enable yes;
   dnssec-validation auto;


};

logging {
   channel default_log {
      file "/var/log/named/named.log" versions 5 size 50M;
      print-time yes;
      print-severity yes;
      print-category yes;
   };

   category default { default_log; };
   category general { default_log; };
};


include "/etc/bind/rndc.key";
controls {
   inet 127.0.0.1 port 953 allow { 127.0.0.1/32; ::1/128; } keys { "rndc-key"; };
};

zone "." in {
   type hint;
   file "$myDNSDIR/named.cache";
};

zone "localhost" IN {
   type master;
   file "pri/localhost.zone";
   notify no;
};


zone "${myDOMAIN}" IN {
                type master;
                file "$myDOMAIN.lan";
                allow-update { none; };
        };
zone "${myINADDR}.in-addr.arpa" IN {
                type master;
                file "$myINADDR.db";
                allow-update { none; };
        };

EOF
#######################################

sed -i '/OPTIONS=/d' /etc/conf.d/named
echo 'OPTIONS="-4"' >> /etc/conf.d/named
if pidof /lib/systemd/systemd >> /dev/null
then
sed -i 's/ExecStart=\/usr\/sbin\/named -f -u named/ExecStart=\/usr\/sbin\/named -f -4 -u named/g' /lib/systemd/system/named.service
systemctl daemon-reload
fi
chown root:named /etc/bind/named.conf
chown root:named $myDNSDIR/*lan
chown root:named $myDNSDIR/*db
rm /etc/hosts
cat >> /etc/hosts << EOF
127.0.0.1  localhost
EOF


[ ! -d /var/log/named ] && mkdir /var/log/named
[ ! -f /var/log/named/named.log ] && touch /var/log/named/named.log
chown named. /var/log/named/named.log >> /dev/null
rndc-confgen -a
pidof /lib/systemd/systemd >> /dev/null && systemctl enable $myDNSSVCNAME && systemctl restart $myDNSSVCNAME
pidof /sbin/init >> /dev/null && rc-update add $myDNSSVCNAME default && rc-service $myDNSSVCNAME restart
sed -i '/nameserver/d' /etc/resolv.conf
sed -i '/search/d' /etc/resolv.conf
echo "search  $myDOMAIN" >> /etc/resolv.conf
echo "nameserver 127.0.0.1" >> /etc/resolv.conf
clear
echo "DNS CONFIGURATION COMPLETED.PLEASE REMEMBER TO SET YOUR INTERFACES TO USE THE LOCAL SERVER 127.0.0.1 AS THE PRIMARY DNS SERVER"
echo "THIS IS ABSOLUTELY ESSENTIAL AND YOU SHOULD MODIFY YOUR NETWORK MANAGER OR NETWORK SCRIPTS TO DO SO BEFORE REBOOTING"
echo "OTHERWISE YOU WILL TEMPORARILY LOOSE NETWORK CONNECTIVITY AFTER A REBOOT."
echo "YOU MAY WISH TO TEST YOUR BIND DNS NAME SERVER BY ISSUING:"
echo "ping $HOSTNAME"
echo "ping $(hostname -d)"
echo "ping -c 2 google.com"
echo "PRESS ANY KEY TO CONTINUE";read line
}    ###closing dnsinstall ()


openldapinstall () {
clear
echo "PART 2: OPENLDAP SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line

clear
pidof /lib/systemd/systemd >> /dev/null && systemctl stop slapd >> /dev/null
pidof /sbin/init >> /dev/null && rc-service slapd stop >> /dev/null
echo "REMOVING PREVIOUS LDAP CONFIG..."
rm -rf $myLDAPDATADIR/*mdb >> /dev/null
rm -rf $myLDAPCONFDIR/slap.conf >> /dev/null
rm -rf $myLDAPCONFDIR/slapd.d/* >> /dev/null
rm -rf $myLDAPCONFDIR/ssl/* >> /dev/null
rm -rf $myLDAPCONFDIR/ldifs/* >> /dev/null

echo "net-nds/openldap kerberos sha2 sasl -minimal samba" > /etc/portage/package.use/openldap
[ -f /etc/conf.d/slapd.bak ] && cp  /etc/conf.d/slapd.bak /etc/conf.d/slapd



 
emerge -DNaq net-nds/openldap

[ ! -f $myLDAPDATADIR/DB_CONFIG.example ] && cat >> $myLDAPDATADIR/DB_CONFIG.example << EOF


# Example DB_CONFIG file for use with slapd(8) BDB/HDB databases.
#
# See the Oracle Berkeley DB documentation
#   <http://www.oracle.com/technology/documentation/berkeley-db/db/ref/env/db_config.html>
# for detail description of DB_CONFIG syntax and semantics.
#
# Hints can also be found in the OpenLDAP Software FAQ
#   <http://www.openldap.org/faq/index.cgi?file=2>
# in particular:
#   <http://www.openldap.org/faq/index.cgi?file=1075>

# Note: most DB_CONFIG settings will take effect only upon rebuilding
# the DB environment.

# one 0.25 GB cache
set_cachesize 0 268435456 1

# Data Directory
#set_data_dir db

# Transaction Log settings
set_lg_regionmax 262144
set_lg_bsize 2097152
#set_lg_dir logs

# Note: special DB_CONFIG flags are no longer needed for "quick"
# slapadd(8) or slapindex(8) access (see their -q option).

EOF


###GET LDAP BASEDN FROM DOMAIN
echo "RECONFIGURING OPENLDAP SERVER..."

getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)


cp $myLDAPCONFDIR/DB_CONFIG.example $myLDAPCONFDIR/DB_CONFIG >> /dev/null && chown ldap. $myLDAPCONFDIR/DB_CONFIG
cp $myLDAPDATADIR/DB_CONFIG.example $myLDAPDATADIR/DB_CONFIG >> /dev/null && chown ldap. $myLDAPDATADIR/DB_CONFIG

[ ! -f /etc/conf.d/slapd.bak ] && cp -p /etc/conf.d/slapd /etc/conf.d/slapd.bak
[ -f $myLDAPCONFDIR/slapd.conf ] && rm $myLDAPCONFDIR/slapd.conf

cat >> $myLDAPCONFDIR/slapd.conf << EOF
include      $myLDAPCONFDIR/schema/core.schema
pidfile      /run/openldap/slapd.pid
argsfile   /run/openldap/slapd.args

modulepath   /usr/lib64/openldap/openldap
moduleload   back_passwd.so
moduleload   back_monitor.so
moduleload   back_mdb.so
moduleload   back_ldap.so
#moduleload   pw-kerberos.so
moduleload      pw-sha2.so

database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database monitor
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database        mdb
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

suffix      "dc=my-domain,dc=com"
maxsize         10485760
checkpoint   32   30
rootdn      "cn=Manager,dc=my-domain,dc=com"
rootpw      secret
directory   $myLDAPDATADIR

index   objectClass   eq
index   uid             pres,eq
index   mail            pres,sub,eq
index   cn              pres,sub,eq
index   sn              pres,sub,eq
index   dc              eq

EOF
chown root:ldap $myLDAPCONFDIR/slapd.conf

pidof /lib/systemd/systemd >> /dev/null && systemctl enable --now slapd && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-service slapd restart && rc-update add slapd default
chown -R ldap. $myLDAPDATADIR

rm /etc/conf.d/slapd >> /dev/null

cat >> /etc/conf.d/slapd << "EOF"
INSTANCE="openldap${SVCNAME#slapd}"
OPTS_CONF="-F /etc/${INSTANCE}/slapd.d"
OPTS="${OPTS_CONF} -h 'ldaps:// ldap:// ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock'"
#rc_need="!net net.lo"
EOF

[ ! -d $myLDAPCONFDIR/slad.d ] && mkdir $myLDAPCONFDIR/slapd.d
slaptest -f $myLDAPCONFDIR/slapd.conf  -F $myLDAPCONFDIR/slapd.d/ >> /dev/null
chown -R ldap. $myLDAPCONFDIR/slapd.d
chown -R ldap. $myLDAPDATADIR
pidof /lib/systemd/systemd >> /dev/null && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-service slapd restart


echo "CREATING SSL CERTIFICATES FOR USE WITH YOUR OPENLDAP SERVER..."
cd /etc/ssl/private
openssl genrsa -aes128 -out server.key 2048
openssl rsa -in server.key -out server.key

clear

echo "PLEASE REMEMBER TO ENTER YOUR FQDN  ${myFQDN} WHEN PROMPTED FOR 'Common Name' PRESS ANY KEY TO CONTINUE";read line
openssl req -new -days 3650 -key server.key -out server.csr
openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650
[ ! -d $myLDAPCONFDIR/ssl ] && mkdir $myLDAPCONFDIR/ssl

cp /etc/ssl/private/server* $myLDAPCONFDIR/ssl/
cp /etc/ssl/certs/ca-certificates.crt $myLDAPCONFDIR/ssl/
chown -R ldap. $myLDAPCONFDIR/ssl

[ ! -d $myLDAPCONFDIR/ldifs ] && mkdir $myLDAPCONFDIR/ldifs
cd $myLDAPCONFDIR/ldifs

clear
echo "YOU WILL BE PROMPTED FOR THE OPENLDAP ADMINISTRATIVE ACCOUNT "cn=Manager,${myDN}"  PASSWORD."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line
myPASS=$(echo $(slappasswd))

cat >> chrootpw.ldif << EOF
dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: $myPASS
EOF

ldapadd -Y EXTERNAL -H ldapi:/// -f chrootpw.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/inetorgperson.ldif

cat >> chdomain.ldif << EOF
dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth"
  read by dn.base="cn=Manager,${myDN}" read by * none

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: $myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=Manager,$myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: $myPASS

dn: olcDatabase={2}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by
  dn="cn=Manager,${myDN}" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=Manager,${myDN}" write by * read
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f chdomain.ldif

cat >> basedomain.ldif << EOF
dn: $myDN
objectClass: top
objectClass: dcObject
objectclass: organization
o: $c3
dc: $c1

dn: cn=Manager,$myDN
objectClass: organizationalRole
cn: Manager
description: Directory Manager

dn: ou=People,$myDN
objectClass: organizationalUnit
ou: People

dn: ou=Group,$myDN
objectClass: organizationalUnit
ou: Group

dn: ou=sudoers,$myDN
objectClass: organizationalUnit
ou: sudoers

dn: cn=ldapusers,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber: 10000
cn: ldapusers     
EOF

ldapadd -x -D "cn=Manager,${myDN}" -W -f basedomain.ldif
sleep 3

cat >> addgroup.lfif << EOF
dn: cn=,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber:
EOF


cat >> adduser.ldif << EOF
dn: uid=,ou=People,dc=,dc=
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn:
sn:
givenName:
userPassword:
loginShell: /bin/bash
uidNumber:
gidNumber: 10000
homeDirectory: /home/

dn: cn=,ou=Group,dc=,dc=
objectClass: posixGroup
cn:
gidNumber: 10000
memberUid:
EOF


cat >> mod_ssl.ldif << EOF
dn: cn=config
changetype: modify
add: olcTLSCACertificateFile
olcTLSCACertificateFile: $myLDAPCONFDIR/ssl/ca-certificates.crt
-
replace: olcTLSCertificateFile
olcTLSCertificateFile: $myLDAPCONFDIR/ssl/server.crt
-
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: $myLDAPCONFDIR/ssl/server.key
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f mod_ssl.ldif

rm $myLDAPCONFDIR/ldap.conf >> /dev/null
cat >> $myLDAPCONFDIR/ldap.conf << EOF
BASE   $myDN
URI    ldap://$myFQDN ldaps://$myFQDN ldapi:///

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# TLS certificates (needed for GnuTLS)
TLS_CACERT      /etc/ssl/certs/ca-certificates.crt
TLS_REQCERT allow
EOF

chown ldap. $myLDAPCONFDIR/ldap.conf

pidof /lib/systemd/systemd >> /dev/null && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-service slapd restart

clear
echo "PART 2: OPENLDAP SERVER COMPLETED."
echo "YOU CAN NOW TEST THE FUNCTIONALITY OF YOUR OPENLDAP SERVER BY ISSUING:"
echo "slapcat"
echo "ldapsearch -x -b $myDN -H ldap://$myFQDN/"
echo "ldapsearch -x -D cn=Manager,$myDN -b $myDN -H ldaps://$myFQDN/ -W"
echo "ldapsearch -x -b $myDN -H ldapi:///"
echo "etc etc etc"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line

}   ###closing openldapinstal ()


krb5install () {
clear
echo "PART 3: KERBEROS.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS KERBEROS CONFIGURATION..."


echo "app-crypt/mit-krb5  openldap" > /etc/portage/package.use/mit-krb5
pidof /lib/systemd/systemd >> /dev/null && systemctl stop $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init >> /dev/null && rc-service $myKDCSVCNAME stop && rc-service $myKADMINSVCNAME stop

rm -rf $myKRB5DIR/* >> /dev/null

emerge -DNaq mit-krb5
echo "RECONFIGURING KERBEROS..."

[ ! -e /etc/krb5.conf.bak ] && cp /etc/krb5.conf /etc/krb5.conf.bak
rm /etc/krb5.conf >> /dev/null
rm /etc/krb5.keytab >> /dev/null


cat >> /etc/krb5.conf << EOF
[libdefaults]
   default_realm = $myREALM
   kdc_timesync = 1
   ccache_type = 4
   forwardable = true
   proxiable = true
   dns_lookup_realm = false
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = true
    rdns = false
   pkinit_anchors = /etc/ssl/certs/ca-certificates.crt
    default_ccache_name = KEYRING:persistent:%{uid}

   fcc-mit-ticketflags = true

[realms]
   $myREALM = {
      kdc = $myFQDN
      admin_server = $myFQDN
   }
[domain_realm]
   .$myDOMAIN = $myREALM
   $myDOMAIN = $myREALM

EOF

cat >> $myKRB5DIR/kdc.conf << EOF
[kdcdefaults]
    kdc_ports = 750,88

[realms]
    $myREALM = {
        database_name = $myKRB5DIR/principal
        admin_keytab = FILE:$myKRB5DIR/kadm5.keytab
        acl_file = $myKRB5DIR/kadm5.acl
        key_stash_file = $myKRB5DIR/stash
        kdc_ports = 750,88
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        master_key_type = des3-hmac-sha1
        #supported_enctypes = aes256-cts:normal aes128-cts:normal
        default_principal_flags = +preauth
    }

EOF

echo "*/admin@${myREALM} *" > $myKRB5DIR/kadm5.acl
echo "YOU WILL BE PROMPTED FOR KERBEROS DB ROOT PASSWD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kdb5_util create -s -r ${myREALM}
pidof /lib/systemd/systemd >> /dev/null && systemctl enable $myKDCSVCNAME $myKADMINSVCNAME  && systemctl restart $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init >> /dev/null && rc-update add $myKDCSVCNAME default && rc-update add  $myKADMINSVCNAME default && rc-service $myKDCSVCNAME restart && rc-service $myKADMINSVCNAME restart
kadmin.local ank -randkey host/${myFQDN} >> /dev/nul
kadmin.local ktadd host/${myFQDN} >> /dev/null
echo "YOU WILL BE PROMPTED FOR KERBEROS ADMIN USER root/admin PASSWORD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kadmin.local ank root/admin
kadmin.local ank root
clear
echo "PART 3: KERBEROS COMPLETED.YOU MAY NOW TEST YOUR KERBEROS SERVER BY ISSUING:"
echo "kinit root/admin"
echo "kadmin.local addprinc -pw <password> <principal-name>"
echo "kadmin.local ank -randkey host/<fqdn>"
echo "kadmin.local  ktadd  service/<fqdn>"
echo "kadmin.local listprincs"
echo "etc etc etc"
PLEASE PRESS ANY KEY TO CONTINUE";read line

} ###Closing krb5installl


nfsinstall () {
clear
echo "PART 4: KERBERISED NFS-SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS NFS CONFIGURATION..."

pidof /lib/systemd/systemd >> /dev/null && systemctl stop nfs-server rpcbind
pidof /sbin/init >> /dev/null && rc-service nfs stop && rc-service rpcbind stop
rm -rf /srv/nfs
echo "net-fs/nfs-utils kerberos ldap nfsv4" > /etc/portage/package.use/nfs-utils
echo "net-libs/libtirpc kerberos" > /etc/portage/package.use/libtirpc
 
emerge -DNaq nfs-utils
echo "RECONFIGURING NFS-SERVER..."

###########################
nfsdir () {
echo 'NFS SERVER WILL SHARE A PRIVATE DIRECTORY WITH KERBEROS SECURITY sec=krb5p UNDER "/srv/nfs".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "NFS SERVER WILL SHARE "/srv/nfs/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && nfsdir
export nfsDIR=${private}
}  ####Closing nfsdir
nfsdir

##########################

sed -i '/srv/d' /etc/exports
mkdir -p /srv/nfs/$nfsDIR >> /dev/null && chmod -R 777 /srv/nfs >> /dev/null
[ ! -f /etc/idmapd.conf.bak ] && mv  /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf

################################
cat >> /etc/idmapd.conf << EOF
[General]

Verbosity = 0
#Pipefs-Directory = /run/rpc_pipefs
# set your own domain here, if it differs from FQDN minus hostname
Domain = $myDOMAIN

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup

EOF
echo "/srv/nfs *(rw,sec=krb5p,fsid=0,insecure)" >> /etc/exports
echo "/srv/nfs/$nfsDIR *(rw,sec=krb5p,nohide,insecure)" >> /etc/exports
[ ! -f /etc/conf.d/nfs.bak ] && cp -p /etc/conf.d/nfs /etc/conf.d/nfs.bak
sed -i '/NFS_NEEDED_SERVICES=/d' /etc/conf.d/nfs
echo "NFS_NEEDED_SERVICES="rpc.idmapd rpc.gssd rpc.svcgssd"" >> /etc/conf.d/nfs
pidof /lib/systemd/systemd >> /dev/null && systemctl enable --now rpcbind nfs-server && systemctl restart rpcbind nfs-server
if pidof /sbin/init >> /dev/null
then
rc-update add rpcbind default
rc-update add nfs default
rc-update add nfsclient default
rpc.idmapd
rpc.svcgssd
rc-service nfs restart
rpc.gssd
rc-service nfsclient restart
fi
exportfs -avr
kadmin.local ank -randkey nfs/${myFQDN} >> /dev/null
kadmin.local ktadd nfs/${myFQDN} >> /dev/null
clear
echo "PART 4: KERBERISED NFS-SERVER COMPLETED"
echo "AFTER REBOOTING YOUR MACHINE YOU CAN MOUNT /srv/nfs/$nfsDIR BY ISSUING:"
echo "kinit"
echo "systemctl start nfs-client.target"
echo "mount -t nfs4 -o sec=krb5p ${myFQDN}:/$nfsDIR /mnt"
echo "PLEASE REMEMBER TO CREATE PRINCIPALS FOR YOUR USERS IN KERBEROS."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line


}  ###Closing nfsinstall
###########################

##########################
sambainstall () {
clear
echo "PART 5: SAMBA SERVER CONFIGURATION.............."
emerge -DNaq samba
echo "REMOVING PREVIOUS SAMBA CONFIGURATION..."

[ ! -d /var/lib/samba.bak ] && cp -pa /var/lib/samba /var/lib/samba.bak
rm -rf /var/lib/samba
cp -pa /var/lib/samba.bak /var/lib/samba


if ! cat /etc/group | grep smbprivate >> /dev/null;then groupadd -g 3000 smbprivate;fi

sharedir () {
echo 'SAMBA SERVER WILL SHARE A READ-ONLY OPEN-TO-ALL DIRECTORY UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read dir
echo "SAMBA SERVER WILL SHARE "/srv/samba/$dir" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbshare=${dir}
echo 'SAMBA SERVER WILL SHARE A PRIVATE DIRECTORY TO BE USED ONLY BY THE GROUP "smbprivate" UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "SAMBA SERVER WILL SHARE "/srv/samba/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbprivate=${private}
}  ####Closing sharedir
sharedir

myIFACE=$(ip a  | grep $myIP | awk '{ print $2 }')
myHOSTS=$(echo $myNETWORK | awk -F. '{ print $1"."$2"."$3"." }')

[ -d /srv/samba ] && rm -rf /srv/samba
[ -f /etc/samba/smb.conf ] && rm /etc/samba/smb.conf
mkdir -p /srv/samba/$smbshare
mkdir -p /srv/samba/$smbprivate
chmod -R 777 /srv/samba

cat >> /etc/samba/smb.conf << EOF
#======================= Global Settings =====================================
[global]

   workgroup = MYGROUP

   server string = Samba Server

   server role = standalone server

   hosts allow =  $myHOSTS 127.

   guest account = nobody

#   log file = /var/log/samba/log.%m

   max log size = 50

   passdb backend = tdbsam

;   include = /etc/samba/smb.conf.%m

   interfaces = $myIFACE 127.0.0.1/24

;   logon path = \\%L\Profiles\%U

;   wins support = yes

;   wins server = w.x.y.z

;   wins proxy = yes

   dns proxy = no

;  add user script = /usr/sbin/useradd %u
;  add group script = /usr/sbin/groupadd %g
;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
;  delete user script = /usr/sbin/userdel %u
;  delete user from group script = /usr/sbin/deluser %u %g
;  delete group script = /usr/sbin/groupdel %g

map to guest = Bad User
server min protocol = SMB3
smb encrypt = desired
unix charset = UTF-8
dos charset = CP932

load printers = no
  printing = bsd
  printcap name = /dev/null
  disable spoolss = yes
  show add printer wizard = no

#============================ Share Definitions ==============================
[homes]
   comment = Home Directories
   browseable = no
   writable = no
   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
; [netlogon]
;   comment = Network Logon Service
;   path = /var/lib/samba/netlogon
;   guest ok = yes
;   writable = no
;   share modes = no


# Un-comment the following to provide a specific roving profile share
# the default is to use the user's home directory
;[Profiles]
;    path = /var/lib/samba/profiles
;    browseable = no
;    guest ok = yes


# NOTE: If you have a BSD-style print system there is no need to
# specifically define each individual printer
[printers]
   comment = All Printers
   path = /var/spool/samba
   browseable = no
# Set public = yes to allow user 'guest account' to print
   guest ok = no
   writable = no
   printable = yes

# This one is useful for people to share files
;[tmp]
;   comment = Temporary file space
;   path = /tmp
;   read only = no
;   public = yes

# A publicly accessible directory, but read only, except for people in
# the "staff" group
;[public]
;   comment = Public Stuff
;   path = /home/samba
;   public = yes
;   writable = no
;   printable = no
;   write list = @staff

# Other examples.
#
# A private printer, usable only by fred. Spool data will be placed in fred's
# home directory. Note that fred must have write access to the spool directory,
# wherever it is.
;[fredsprn]
;   comment = Fred's Printer
;   valid users = fred
;   path = /homes/fred
;   printer = freds_printer
;   public = no
;   writable = no
;   printable = yes

# A private directory, usable only by fred. Note that fred requires write
# access to the directory.
;[fredsdir]
;   comment = Fred's Service
;   path = /usr/somewhere/private
;   valid users = fred
;   public = no
;   writable = yes
;   printable = no

# a service which has a different directory for each machine that connects
# this allows you to tailor configurations to incoming machines. You could
# also use the %U option to tailor it by user name.
# The %m gets replaced with the machine name that is connecting.
;[pchome]
;  comment = PC Directories
;  path = /usr/pc/%m
;  public = no
;  writable = yes

# A publicly accessible directory, read/write to all users. Note that all files
# created in the directory by users will be owned by the default user, so
# any user with access can delete any other user's files. Obviously this
# directory must be writable by the default user. Another user could of course
# be specified, in which case all files would be owned by that user instead.
;[public]
;   path = /usr/somewhere/else/public
;   public = yes
;   only guest = yes
;   writable = yes
;   printable = no

# The following two entries demonstrate how to share a directory so that two
# users can place files there that will be owned by the specific users. In this
# setup, the directory should be writable by both users and should have the
# sticky bit set on it to prevent abuse. Obviously this could be extended to
# as many users as required.
;[myshare]
;   comment = Mary's and Fred's stuff
;   path = /usr/somewhere/shared
;   valid users = mary fred
;   public = no
;   writable = yes
;   printable = no
;   create mask = 0765

[$smbprivate]
path = /srv/samba/$smbprivate
guest ok = no
valid users = root @smbprivate
writable = yes
write list = root @smbprivate
create mask = 0664
force create mode = 0644
directory mask = 2775
force directory mode = 2775

[$smbshare]
path = /srv/samba/$smbshare
guest ok = yes
guest only = yes
read only = yes
create mode = 0777
directory mode = 0777


EOF
if pidof /lib/systemd/systemd >> /dev/null
then
systemctl enable --now smbd nmbd
systemctl restart smbd nmbd
systemctl status smbd nmbd
sleep 3
fi

if pidof /sbin/init >> /dev/null
then
rc-update add samba default
rc-service samba restart
sleep 3
fi


clear
echo "SAMBA CONFIGURATION COMPLETED.PLEASE REMEMBER TO ADD USERS TO THE "smbprivate" GROUP WITH  gid 3000 TO ENABLE THEM TO ACCESS THE $smbprivate DIRECTORY"
echo "MAKE SURE TO ADD THIS GROUP TO ALL CLIENT MACHINES THAT NEED ACCESS TO THE $smbprivate DIRECTORY"
echo "PLEASE USE smbpasswd -a TO ADD USERS TO SAMBA"
echo "PRESS ANY KEY TO CONTINUE";read line

}   ###Closing sambainstall

################################################

##############################
ntpinstall () {
clear
echo "INSTALLING NTP TIME SERVER..."
if ! equery l '*' | grep net-misc/ntp >> /dev/null;then emerge -DNaq net-misc/ntp;fi
if pidof /lib/systemd/systemd >> /dev/null;then systemctl enable --now ntpd && systemctl restart ntpd;fi
if pidof /sbin/init >> /dev/null
then
rc-update add ntpd default
rc-service ntpd restart
fi
ntpq -p
hwclock --systohc
sleep 3
clear
echo "NTP TIME SERVER INSTALLATION COMPLETE.PLEASE PRESS ANY KEY TO CONTINUE";read line
}  ############Closing ntpinstall()
#####################################


dnsinstall
openldapinstall
krb5install
nfsinstall
sambainstall
ntpinstall



The script contains 6 FUNCTIONS

dnsinstall
openldapinstall
krb5install
nfsinstall
sambainstall
ntpinstall

which are all currently uncommented meaning It will install and configure the whole thing.

In the beginning it will INSIST that you first configure STATIC IP for your machine and reboot.
Then it will PROMPT you to set your FQDN if you havent already done so.
From there it will flawlessly proceed to do its thing.

ADDENDUM: ADD LDAP USERS SCRIPT
As an extra bonus to compliment the Directory Server here are two scripts that automate adding users to the Openldap data base together with their respective Kerberos principals.
One is interactive for a single user each time.
The other adds users in bulk from a file:
Here they are:
Code:

#!/bin/bash

################## WRITTEN BY ALAMAHANT on 09/01/2020 ###########################


if [ ! -f /etc/profile.d/ldapuser.sh ]
then
echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
fi
clear
source /etc/profile.d/ldapuser.sh

[ -f ldapuser.ldif ] && rm ldapuser.ldif


echo "ADDING USER WITH UID" $uidserial

myFQDN=$(hostname)
myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
myREALM=$(echo ${myDOMAIN^^})
getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)

addldapuser () {
[ -f ldapuser.ldif ] && rm ldapuser.ldif
echo "first name";read givenName
echo "last name";read sn
echo "password";read passwd
echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
[ ! $line == "y" ] && return
myPASS=$(slappasswd -s $passwd)

cat > ldapuser.ldif << EOF
dn: uid=$givenName.$sn,ou=People,$myDN
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn: $givenName $sn
sn: $sn
givenName: $givenName
userPassword: $myPASS
loginShell: /bin/bash
uidNumber: $uidserial
gidNumber: 10000
homeDirectory: /home/$givenName.$sn

EOF

if ldapadd -x -D cn=Manager,$myDN -W -f ldapuser.ldif
then
let "uidserial=uidserial+1"
sed -i '/export/d' /etc/profile.d/ldapuser.sh
echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
echo "ADDED LDAP USER" $givenName.$sn
echo "HERE ARE THE DETAILS:"
echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
echo ""

if kadmin.local listprincs | grep  ${givenName}.${sn} >> /dev/null
then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
fi

else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
fi

} ####Closing addldapuser

addldapuser

......the interactive and

Code:

 #!/bin/bash

################## WRITTEN BY ALAMAHANT on 09/01/2020 ###########################
if [ ! -f /etc/profile.d/ldapuser.sh ]
then
echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
fi


source /etc/profile.d/ldapuser.sh


myFQDN=$(hostname)
myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
myREALM=$(echo ${myDOMAIN^^})
getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)

addldapuser () {
echo "ADDING USER WITH UID" $uidserial
[ -f ldapuser.ldif ] && rm ldapuser.ldif
#echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
#[ ! $line == "y" ] && return
myPASS=$(slappasswd -s $passwd)

cat > ldapuser.ldif << EOF
dn: uid=$givenName.$sn,ou=People,$myDN
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn: $givenName $sn
sn: $sn
givenName: $givenName
userPassword: $myPASS
loginShell: /bin/bash
uidNumber: $uidserial
gidNumber: 10000
homeDirectory: /home/$givenName.$sn

EOF

if ldapadd -x -D cn=Manager,$myDN -w $adminpasswd  -f ldapuser.ldif
then
let "uidserial=uidserial+1"
sed -i '/export/d' /etc/profile.d/ldapuser.sh
echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
echo "ADDED LDAP USER" $givenName.$sn
#echo "HERE ARE THE DETAILS:"
#echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
echo ""

if kadmin.local listprincs | grep  ${givenName}.${sn} >> /dev/null
then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
echo ""
fi

else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
fi

} ####Closing addldapuser


echo "PLEASE PROVIDE THE ABSOLUTE PATH OF THE FILE CONTAINING THE USERS TO BE ADDED TO THE OPENLDAP DATABASE"
echo "THE FILE SHOULD CONTAIN ONE USER PER LINE IN THE FORMAT:"
echo "firstname surname password"; read file
[ ! -f $file ] && echo "NO SUSCH FILE.EXITING......" && exit
echo "PLEASE PROVIDE THE PASSWORD FOR THE ADMINISTRATIVE ACCOUNT cn=Manager,$myDN"; read adminpasswd

clear
while read -r line
do
givenName=$(echo $line | awk '{ print $1 }')
sn=$(echo $line | awk '{ print $2 }')
passwd=$(echo $line | awk '{ print $3 }')
addldapuser
done < $file


.....the one adding users from a file.

Shortly I will post Directory Server Client configuration scripts for Gentoo,Debian and Redhat enabling them to authenticate and login users from the Gentoo Directory Server.

ADDENDUM: DIRECTORY CLIENT INSTALLATION SCRIPT
As promised here is a script that will turn a Gentoo machine into the Directory Servers Client.
It will first prompt you to enter the IP of the Server.
It DOES need ROOT SSH ACCESS TO THE SERVER WITH PASSWORD.
It will then
Code:


Create ssh keys

Copy them to the Server

Probe the Server for the domain-name

Prompt the user to enter a <name> to use with the Server domain.

After thus configuring FQDN ...........

Copy the /etc/krb5.conf and /etc/openldap/ldap.conf FROM the Server TO the Client.

It will install openldap mit-krb5 sssd and pam_krb5 and nfs-utils with the appropriate USE flags

It will configure the right sssd.conf, nsswitch.conf and system-auth files to enable Network Authentication.

Finally it will create principals for host and nfs in Kerberos database and

Modify sshd_config to set "GSSAPIAuthentication yes" so as to enable ssh-ing locally as a remote user from the Server's Openldap DB.


This is it:
Code:

#!/bin/bash

#################### WRITTEN BY ALAMAHANT ON FRIDAY 10 JANUARY 2020  ######################
[ ! -f /etc/nsswitch.conf.bak ] && cp  /etc/nsswitch.conf /etc/nsswitch.conf.bak
[ ! -f /etc/resolv.conf.bak ] && cp /etc/resolv.conf /etc/resolv.conf.bak
[ ! -f /etc/hosts.bak ] && cp /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp  /etc/hostname /etc/hostname.bak
[ -f /etc/krb5.keytab ] && rm /etc/krb5.keytab


echo "sys-auth/sssd  nfsv4 samba sudo autofs ssh" > /etc/portage/package.use/sssd
echo "net-misc/openssh kerberos" > /etc/portage/package.use/mit-krb5
echo  "net-fs/nfs-utils kerberos ldap nfsv4" > /etc/portage/package.use/nfs-utils
echo "net-nds/openldap kerberos sha2 sasl minimal samba" > /etc/portage/package.use/openldap
echo "net-libs/libtirpc kerberos" > /etc/portage/package.use/libtirpc
echo "dev-libs/cyrus-sasl  kerberos" > /etc/portage/package.use/cyrus-sasl

clear

emerge -DNaq sssd openssh nfs-utils openldap mit-krb5  pam_krb5
clear

pidof /lib/systemd/systemd >> /dev/null && systemctl enable sshd && systemctl restart sshd
pidof /sbin/init >> /dev/null && rc-update add sshd default && rc-service sshd restart
pidof /lib/systemd/systemd >> /dev/null && systemctl enable sssd
pidof /sbin/init >> /dev/null && rc-update add sssd default

clear
staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

myIP=$(ip route get 8.8.8.8| grep src| sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
if [ ! -f /root/.ssh/id_rsa.pub ]
then
echo "GENERATING SSH KEYS...."
ssh-keygen -t rsa
fi

echo "YOU NEED TO HAVE ROOT SSH ACCESS WITH PASSWORD TO THE SSO MACHINE"
echo "PLEASE ENTER THE IP ADDRESS OF THE SSO MACHINE";read server

if ! ssh-copy-id root@$server
then echo "EITHER WRONG IP ADDRESS OR HOST SSHD DAEMON NOT RUNNING OR ROOT SSH ACCESS WITH PASSWORD NOT ALLOWED.EXITING"
exit
fi

serverFQDN=$(ssh root@$server hostname)
myDOMAIN=$(echo $serverFQDN | awk -F. '{ print $2"."$3 }')

setfqdn () {
clear
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.${myDOMAIN}";read machine
echo "DO YOU WISH YOUR FQDN TO BE ${machine}.${myDOMAIN} ? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
myFQDN=$machine.$myDOMAIN
echo $myFQDN > /etc/hostname
pidof /sbin/init >> /dev/null && [ -f /etc/conf.d/hostname ] && echo "hostname="${myFQDN}"" > /etc/conf.d/hostname && echo 'rc_before="net.lo"' >> /etc/conf.d/hostname
rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $myFQDN
EOF

pidof /sbin/init >> /dev/null && hostname -F /etc/hostname >> /dev/null
pidof /lib/systemd/systemd >> /dev/null && hostnamectl set-hostname $myFQDN
export myFQDN=$myFQDN
} ###Closing setfqdn


setfqdn
echo $machine $myIP | ssh root@$server xargs  /etc/bind/dns-record

ssh root@$server << EOF
pidof /lib/systemd/systemd >> /dev/null && systemctl reload named
pidof /sbin/init >> /dev/null && rc-service named reload
EOF


[ ! -f /etc/krb5.conf.bak ] && mv /etc/krb5.conf /etc/krb5.conf.bak
scp  root@$server:/etc/krb5.conf /etc/krb5.conf
[ ! -f /etc/openldap/ldap.conf.bak ] && mv /etc/openldap/ldap.conf /etc/openldap/ldap.conf.bak
scp  root@$server:/etc/openldap/ldap.conf /etc/openldap/

getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)
myREALM=$(echo ${myDOMAIN^^})

[ ! -d /etc/openldap/certs ] && mkdir /etc/openldap/certs
[ ! -f /etc/openldap/certs/ca-certificates.crt ] && cp /etc/ssl/certs/ca-certificates.crt  /etc/openldap/certs/
chown -R ldap. /etc/openldap/certs
[ -f /etc/sssd/sssd.conf ] && rm /etc/sssd/sssd.conf
cat >> /etc/sssd/sssd.conf << EOF
[domain/default]

autofs_provider = ldap
cache_credentials = True
krb5_kpasswd = $serverFQDN
ldap_search_base = $myDN
krb5_server = $serverFQDN
id_provider = ldap
auth_provider = krb5
chpass_provider = krb5
krb5_store_password_if_offline = True
ldap_uri = ldap://$serverFQDN/
krb5_realm = $myREALM
ldap_id_use_start_tls = True
ldap_tls_cacertdir = /etc/openldap/certs
ldap_tls_reqcert = allow
[sssd]
services = nss, pam, autofs

domains = default
[nss]
homedir_substring = /home

[pam]

[sudo]

[autofs]

[ssh]

[pac]

[ifp]

[secrets]

[session_recording]
EOF

chmod 600 /etc/sssd/sssd.conf

rm /etc/nsswitch.conf
cp -p /etc/nsswitch.conf.bak /etc/nsswitch.conf
sed -i '/passwd/ s/$/ sss/g' /etc/nsswitch.conf
sed -i '/shadow/ s/$/ sss/g' /etc/nsswitch.conf
sed -i '/group/ s/$/ sss/g' /etc/nsswitch.conf

if ! grep automount /etc/nsswitch.conf >> /dev/null
then echo "automount:  files sss" >> /etc/nsswitch.conf
else sed -i '/automount/ s/$/ sss/g' /etc/nsswitch.conf
fi

if ! grep sudoers /etc/nsswitch.conf >> /dev/null
then echo "sudoers:  files sss" >> /etc/nsswitch.conf
else sed -i '/sudoers/ s/$/ sss/g' /etc/nsswitch.conf
fi

[ ! -f /etc/pam.d/system-auth.bak ] && mv /etc/pam.d/system-auth /etc/pam.d/system-auth.bak
rm /etc/pam.d/system-auth
cat >> /etc/pam.d/system-auth << EOF
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        sufficient    pam_sss.so use_first_pass                                         #
auth        required      pam_deny.so
 
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so                         #
account     required      pam_permit.so
 
password    requisite     pam_cracklib.so try_first_pass retry=3
password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok                                            #
password    required      pam_deny.so
 
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0077
session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so       
EOF
sed -i '/GSSAPIAuthentication/d' /etc/ssh/sshd_config
echo "GSSAPIAuthentication yes" >> /etc/ssh/sshd_config

pidof /lib/systemd/systemd >> /dev/null && systemctl restart sshd
pidof /sbin/init >> /dev/null && rc-service sshd restart

rm /etc/hosts
cat >> /etc/hosts << EOF
127.0.0.1   localhost
EOF

rm /etc/resolv.conf
cat >> /etc/resolv.conf << EOF
search   $myDOMAIN
nameserver $server
EOF

echo "YOU WILL BE PROMPTED FOR THE KERBEROS root/admin or root PASSWORD SO THAT PRINCIPALS FOR host/$myFQDN and nfs/$myFQDN MAY BE ISSUED"
kadmin ank -randkey host/$myFQDN
kadmin ank -randkey nfs/$myFQDN
kadmin ktadd host/$myFQDN
kadmin ktadd nfs/$myFQDN

[ -f /etc/conf.d/nfs.bak ] && cp /etc/conf.d/nfs /etc/conf.d/nfs.bak
sed -i '/NFS_NEEDED_SERVICES=/d' /etc/conf.d/nfs
echo "NFS_NEEDED_SERVICES="rpc.idmapd rpc.gssd rpc.svcgssd"" >> /etc/conf.d/nfs

[ -f /etc/idmapd.conf.bak ] && cp /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf
cat >> /etc/idmapd.conf << EOF
[General]
domain = $myDOMAIN
[Mapping]

Nobody-User = nobody
Nobody-Group = nobody
EOF

pidof /lib/systemd/systemd >> /dev/null && systemctl enable --now rpcbind nfs-client.target >> /dev/null

if pidof /sbin/init >> /dev/null
then
rc-update add rpcbind default
rc-update add nfsclient default
fi


echo "CLIENT CONFIGURATION COMPLETED.IT IS ABSOLUTELY ESSENTIAL THOUGH THAT YOU MODIFY YOUR INTERFACE TO USE THE DIRECTORY SERVER'S DNS @IP ADDRESS:${server} .THEN PLEASE REBOOT YOUR MACHINE AND LOGIN OR SSH TO YOUR MACHINE USING A REMOTE USERNAME.FURTHERMORE YOU CAN USE THE getent passwd COMMAND TO PROBE FOR USERS ON THE  REMOTE SERVER"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read key
[/code]

FINALLY here is a little script that add A and PTR records to the BIND DNS server.
Please place it in the server's

/etc/bind

directory because it is invoked by the Client Installation script to add records of Itself to the Server.

Of course you can also run it yourself whenever you need to add a host to BIND.

Code:

#!/bin/bash

### Written by Alamahant on 10/01/2020.This simple script will add A and PTR records to BIND

###Use the script thus "sudo bash dns-record <machine-name>  <IP>".

[ -z $1 ] || [ -z $2 ] && echo "USAGE dns-record <HOST-NAME> <IP-ADDRESS>" && exit
myCIDR=$(echo $2 | awk -F. '{ print $4 }')
myDOMAIN=$(hostname -d)
mySVCDIR="/var/bind"
mySVCNAME="named"
if ! $(cat $mySVCDIR/*lan | grep $1 >> /dev/null)  && ! $(cat $mySVCDIR/*lan | grep $2 >> /dev/null) 
then
echo "$1    IN A      $2" >> $mySVCDIR/*lan
echo "$myCIDR    IN PTR      $1.$myDOMAIN" >> $mySVCDIR/*db
pidof /lib/systemd/systemd >> /dev/null && systemctl reload $mySVCNAME
pidof /sbin/init >> /dev/null && service $mySVCNAME reload
echo "Host $1 with IP $2 added to Bind"
elif $(cat $mySVCDIR/*lan | grep $1 >> /dev/null)
then
echo "Host already exists"
else echo "IP is taken"
fi


These scripts were written with great effort and care and I feel enthusiastic about having done so.
I wish to give back something to the community from which I receive so much guidance and inspiration.

Thank you Guys
Enjoy
and I am looking forward to your valuable feedback and insights.
Try them first in a VM and when confident in any machine you wish.

A NOTE ON MOUNTING KERBERIZED NFS SHARES WHEN USING OPENRC:
Whereas when using systemd a simple
Code:

kinit
systemctl start nfs-client.target
mount -t nfs4 -o sec=krb5p servers-FQDN:/nfs-share /mount/point

would suffice
when in Openrc here is how to do it.
Code:

rc-service rpcbind start/restart
rpc.idmapd
rpc.svcgssd 
rc-service nfs start/restart
rpc.gssd
rc-service nfsclient start/restart
kinit
....etc

If you are testing the share from within the Server then use the WHOLE above stanza.
If you are trying to mount the share from a client then omit the "rpc.svcgssd" and "start/restart nfs" lines.


EDIT:For an UPDATED VERSION of this script together with CLIENT INSTALLATION SCRIPTS FOR DEBIAN AND CENTOS please refer here
https://forums.gentoo.org/viewtopic-p-8409512.html#8409512

As It seemed impossible to further edit this thread for some kind of obscure reason....
Maybe disk quota or db backend limits.

Best

Andreas
:D :) :lol:


Last edited by alamahant on Wed Jan 06, 2021 1:47 pm; edited 17 times in total
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Tue Jan 14, 2020 6:43 pm    Post subject: Gentoo Directory Server Installation Script-B Reply with quote

Hi Guys

It seems that I had reached my quota of disk space or db entry limit for my post
https://forums.gentoo.org/viewtopic-t-1106708.html
and I couldn't edit or add updates to it.

Therefore may i be allowed to post this thread which contains an updated version of my script that also contains the "ldap.user.sh" "bulkusers.sh" and "dns-record" in-built IN the script.
So you do NOT need to manually create these files.
You will find them ready-to-use in the following directories:
Code:

ldapuser.sh in /etc/openldap/ldifs
bulkusers.sh in /etc/openldap/ldifs
dns-record in /etc/bind

So keeping my fingers crossed that I will be able to post this...............

Code:


#!/bin/bash
##########  WRITTEN by alamahant on 9 January 2020 #############

[ ! -f /etc/resolv.conf.bak ] && cp -p /etc/resolv.conf /etc/resolv.conf.bak
[ ! -f /etc/hosts.bak ] && cp -p /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp -p /etc/hostname /etc/hostname.bak

#if ! equery l '*' | grep sipcalc >> /dev/null;then emerge -aq sipcalc;fi
#if ! equery l '*' | grep net-tools >> /dev/null;then emerge -aq net-tools;fi
#if ! equery l '*' | grep gentoolkit >> /dev/null;then emerge -aq app-portage/gentoolkit;fi

emerge -DNaq sipcalc net-tools gentoolkit

clear

staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

echo "EXTRACTING NETWORK INFO AND NOMENCLATURE..."
###NETWORK INFO AND NOMENCLATURE
#myIP=$(hostname -i)
#myIP=$(ip -o addr show up primary scope global | while read -r num dev fam addr rest; do echo ${addr%/*}; done)
myIP=$(ip route get 8.8.8.8| grep src| sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
#myFQDN=$(hostname)

setfqdn () {
clear
echo "DO YOU WISH TO SET YOUR FQDN? PLEASE PRESS "y" TO CONFIRM OR IF YOU HAVE ALREADY SET IT PRESS ANY OTHER KEY TO SKIP";read line
[ $line != "y" ] && return
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.<domain>.<dom>";read line
echo "DO YOU WISH YOUR FQDN TO BE ${line}? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
echo $line > /etc/hostname&
pidof /sbin/init >> /dev/null && [ -f /etc/conf.d/hostname ] && echo "hostname="$line"" > /etc/conf.d/hostname && echo 'rc_before="net.lo"' >> /etc/conf.d/hostname
rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $line
EOF

pidof /sbin/init >> /dev/null && hostname -F /etc/hostname >> /dev/null
pidof /lib/systemd/systemd >> /dev/null && hostnamectl set-hostname $line

} ###Closing setfqdn


setfqdn
myFQDN=$(hostname)

myNETMASK=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $4 }')
#myDOMAIN=$(hostname -d) || myDOMAIN=$(dnsdomainname) || echo "THE SCRIPT ENCOUNTERED AN ERROR AND WILL EXIT.PLEASE FIX THE "hostname" COMMAND BECAUSE IT IS NOT FUNCTIONING PROPERLY"
myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
myMACHINE=$(echo $myFQDN | awk -F. '{ print $1 }')
myINADDR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $3"."$2"."$1 }')
mySERIAL=$(date '+%Y%m%d'01)
myPTR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $4 }')
myNETWORK=$(sipcalc $(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }') | grep "Network address" | awk '{ print $4 }')
myCIDR=$(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F/ '{ print $2 }')
myDNS=$(ip route | grep default | awk '{ print $3 }')
myREALM=$(echo ${myDOMAIN^^})

c1=$(echo $myDOMAIN | awk -F. '{ print $1 }')
c2=$(echo $myDOMAIN | awk -F. '{ print $2 }')
c1=$(echo "${c1^}")
c2=$(echo "${c2^}")
c3=$(echo $c1 $c2)

#####DIRECTORIES
myDNSDIR="/var/bind"
myLDAPCONFDIR="/etc/openldap"
myLDAPDATADIR="/var/lib/openldap-data"
myKRB5DIR="/var/lib/krb5kdc"
###DAEMON NOMENCLATURE
myDNSSVCNAME="named"
myDNSPACKNAME="bind"
myKDCSVCNAME="mit-krb5kdc"
myKADMINSVCNAME="mit-krb5kadmind"




dnsinstall () {
clear
echo "PART 1: DNS BIND. PLEASE PRESS ANY KEY TO CONTINUE";read line
pidof /lib/systemd/systemd >> /dev/null && systemctl stop $myDNSSVCNAME
pidof /sbin/init >> /dev/null && rc-service $myDNSSVCNAME stop
echo "REMOVING BIND AND PURGING ALL PREVIEWS CONFIGURATION..."
[ -d $myDNSDIR ] && rm  $myDNSDIR/*lan 
[ -d $myDNSDIR ] && rm  $myDNSDIR/*db
cp /etc/resolv.conf.bak /etc/resolv.conf
echo "INSTALLING AND CONFIGURING BIND..."

emerge -DNaq $myDNSPACKNAME

clear
[ ! -f /etc/bind/named.conf.bak ] && mv /etc/bind/named.conf /etc/bind/named.conf.bak
[ -f /etc/bind/named.conf ] && rm /etc/bind/named.conf
cat >> $myDNSDIR/$myDOMAIN.lan << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
         3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
        IN  A       $myIP

        IN  MX 10   $myFQDN.

$myMACHINE     IN  A       $myIP
EOF

cat >> $myDNSDIR/$myINADDR.db << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
        3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
   IN  PTR    $myDOMAIN.
        IN  A       $myNETMASK



$myPTR     IN  PTR       $myFQDN.
EOF

cat >> /etc/bind/named.conf << EOF


acl "xfer" {
   127.0.0.0/8; $myNETWORK/$myCIDR;

};


acl "trusted" {
   127.0.0.0/8;
   $myNETWORK/$myCIDR;
};

options {
   directory "$myDNSDIR";
   pid-file "/run/named/named.pid";

   //bindkeys-file "/etc/bind/bind.keys";

   listen-on-v6 { none; };
   //listen-on { 127.0.0.1; };
   listen-on port 53 { any; };
   allow-query {
      trusted;
   };

   allow-query-cache {
      /* Use the cache for the "trusted" ACL. */
      trusted;
   };

   allow-recursion {
      /* Only trusted addresses are allowed to use recursion. */
      trusted;
   };

   allow-transfer {
      /* Zone tranfers are denied by default. */
      xfer;
   };

   allow-update {
      /* Don't allow updates, e.g. via nsupdate. */
      none;
   };


   forwarders { $myDNS; };

   dnssec-enable yes;
   dnssec-validation auto;


};

logging {
   channel default_log {
      file "/var/log/named/named.log" versions 5 size 50M;
      print-time yes;
      print-severity yes;
      print-category yes;
   };

   category default { default_log; };
   category general { default_log; };
};


include "/etc/bind/rndc.key";
controls {
   inet 127.0.0.1 port 953 allow { 127.0.0.1/32; ::1/128; } keys { "rndc-key"; };
};

zone "." in {
   type hint;
   file "$myDNSDIR/named.cache";
};

zone "localhost" IN {
   type master;
   file "pri/localhost.zone";
   notify no;
};


zone "${myDOMAIN}" IN {
                type master;
                file "$myDOMAIN.lan";
                allow-update { none; };
        };
zone "${myINADDR}.in-addr.arpa" IN {
                type master;
                file "$myINADDR.db";
                allow-update { none; };
        };

EOF
#######################################

sed -i '/OPTIONS=/d' /etc/conf.d/named
echo 'OPTIONS="-4"' >> /etc/conf.d/named
if pidof /lib/systemd/systemd >> /dev/null
then
sed -i 's/ExecStart=\/usr\/sbin\/named -f -u named/ExecStart=\/usr\/sbin\/named -f -4 -u named/g' /lib/systemd/system/named.service
systemctl daemon-reload
fi
chown root:named /etc/bind/named.conf
chown root:named $myDNSDIR/*lan
chown root:named $myDNSDIR/*db
rm /etc/hosts
cat >> /etc/hosts << EOF
127.0.0.1  localhost
EOF


[ ! -d /var/log/named ] && mkdir /var/log/named
[ ! -f /var/log/named/named.log ] && touch /var/log/named/named.log
chown named. /var/log/named/named.log
pidof /lib/systemd/systemd >> /dev/null && systemctl enable $myDNSSVCNAME && systemctl restart $myDNSSVCNAME
pidof /sbin/init >> /dev/null && rc-update add $myDNSSVCNAME default && rc-service $myDNSSVCNAME restart
sed -i '/nameserver/d' /etc/resolv.conf
sed -i '/search/d' /etc/resolv.conf
echo "search  $myDOMAIN" >> /etc/resolv.conf
echo "nameserver 127.0.0.1" >> /etc/resolv.conf
clear
echo "DNS CONFIGURATION COMPLETED.PLEASE REMEMBER TO SET YOUR INTERFACES TO USE THE LOCAL SERVER 127.0.0.1 AS THE PRIMARY DNS SERVER"
echo "PRESS ANY KEY TO CONTUNUE";read line
}    ###closing dnsinstall ()


openldapinstall () {
clear
echo "PART 2: OPENLDAP SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line
clear
pidof /lib/systemd/systemd >> /dev/null && systemctl stop slapd >> /dev/null
pidof /sbin/init >> /dev/null && rc-service slapd stop >> /dev/null
echo "REMOVING PREVIOUS LDAP CONFIG..."
rm -rf $myLDAPDATADIR/*mdb >> /dev/null
rm -rf $myLDAPCONFDIR/slap.conf >> /dev/null
rm -rf $myLDAPCONFDIR/slapd.d/* >> /dev/null
rm -rf $myLDAPCONFDIR/ssl/* >> /dev/null
rm -rf $myLDAPCONFDIR/ldifs/* >> /dev/null
[ -f /etc/profile.d/ldapuser.sh ] && rm /etc/profile.d/ldapuser.sh
echo "net-nds/openldap kerberos sha2 sasl -minimal samba" > /etc/portage/package.use/openldap
[ -f /etc/conf.d/slapd.bak ] && cp  /etc/conf.d/slapd.bak /etc/conf.d/slapd

 
emerge -DNaq net-nds/openldap

###GET LDAP BASEDN FROM DOMAIN
echo "RECONFIGURING OPENLDAP SERVER..."

getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)


cp $myLDAPCONFDIR/DB_CONFIG.example $myLDAPCONFDIR/DB_CONFIG >> /dev/null && chown ldap. $myLDAPCONFDIR/DB_CONFIG
cp $myLDAPDATADIR/DB_CONFIG.example $myLDAPDATADIR/DB_CONFIG >> /dev/null && chown ldap. $myLDAPDATADIR/DB_CONFIG

[ ! -f /etc/conf.d/slapd.bak ] && cp -p /etc/conf.d/slapd /etc/conf.d/slapd.bak
[ -f $myLDAPCONFDIR/slapd.conf ] && rm $myLDAPCONFDIR/slapd.conf

cat >> $myLDAPCONFDIR/slapd.conf << EOF
include      $myLDAPCONFDIR/schema/core.schema
pidfile      /run/openldap/slapd.pid
argsfile   /run/openldap/slapd.args

modulepath   /usr/lib64/openldap/openldap
moduleload   back_passwd.so
moduleload   back_monitor.so
moduleload   back_mdb.so
moduleload   back_ldap.so
#moduleload   pw-kerberos.so
moduleload      pw-sha2.so

database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database monitor
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database        mdb
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

suffix      "dc=my-domain,dc=com"
maxsize         10485760
checkpoint   32   30
rootdn      "cn=Manager,dc=my-domain,dc=com"
rootpw      secret
directory   $myLDAPDATADIR

index   objectClass   eq
index   uid             pres,eq
index   mail            pres,sub,eq
index   cn              pres,sub,eq
index   sn              pres,sub,eq
index   dc              eq

EOF
chown root:ldap $myLDAPCONFDIR/slapd.conf

pidof /lib/systemd/systemd >> /dev/null && systemctl enable slapd && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-service slapd start
chown -R ldap. $myLDAPDATADIR

rm /etc/conf.d/slapd >> /dev/null

cat >> /etc/conf.d/slapd << "EOF"
INSTANCE="openldap${SVCNAME#slapd}"
OPTS_CONF="-F /etc/${INSTANCE}/slapd.d"
OPTS="${OPTS_CONF} -h 'ldaps:// ldap:// ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock'"
#rc_need="!net net.lo"
EOF

[ ! -d $myLDAPCONFDIR/slad.d ] && mkdir $myLDAPCONFDIR/slapd.d
slaptest -f $myLDAPCONFDIR/slapd.conf  -F $myLDAPCONFDIR/slapd.d/ >> /dev/null
chown -R ldap. $myLDAPCONFDIR/slapd.d
chown -R ldap. $myLDAPDATADIR
pidof /lib/systemd/systemd >> /dev/null && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-update add slapd default && rc-service slapd restart


echo "CREATING SSL CERTIFICATES FOR USE WITH YOUR OPENLDAP SERVER..."
cd /etc/ssl/private
openssl genrsa -aes128 -out server.key 2048
openssl rsa -in server.key -out server.key

clear

echo "PLEASE REMEMBER TO ENTER YOUR FQDN  ${myFQDN} WHEN PROMPTED FOR 'Common Name' PRESS ANY KEY TO CONTINUE";read line
openssl req -new -days 3650 -key server.key -out server.csr
openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650
[ ! -d $myLDAPCONFDIR/ssl ] && mkdir $myLDAPCONFDIR/ssl

cp /etc/ssl/private/server* $myLDAPCONFDIR/ssl/
cp /etc/ssl/certs/ca-certificates.crt $myLDAPCONFDIR/ssl/
chown -R ldap. $myLDAPCONFDIR/ssl

[ ! -d $myLDAPCONFDIR/ldifs ] && mkdir $myLDAPCONFDIR/ldifs
cd $myLDAPCONFDIR/ldifs

clear
echo "YOU WILL BE PROMPTED FOR THE OPENLDAP ADMINISTRATIVE ACCOUNT "cn=Manager,${myDN}"  PASSWORD."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line
myPASS=$(echo $(slappasswd))

cat >> chrootpw.ldif << EOF
dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: $myPASS
EOF

ldapadd -Y EXTERNAL -H ldapi:/// -f chrootpw.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/inetorgperson.ldif

cat >> chdomain.ldif << EOF
dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth"
  read by dn.base="cn=Manager,${myDN}" read by * none

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: $myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=Manager,$myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: $myPASS

dn: olcDatabase={2}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by
  dn="cn=Manager,${myDN}" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=Manager,${myDN}" write by * read
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f chdomain.ldif

cat >> basedomain.ldif << EOF
dn: $myDN
objectClass: top
objectClass: dcObject
objectclass: organization
o: $c3
dc: $c1

dn: cn=Manager,$myDN
objectClass: organizationalRole
cn: Manager
description: Directory Manager

dn: ou=People,$myDN
objectClass: organizationalUnit
ou: People

dn: ou=Group,$myDN
objectClass: organizationalUnit
ou: Group

dn: ou=sudoers,$myDN
objectClass: organizationalUnit
ou: sudoers

dn: cn=ldapusers,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber: 10000
cn: ldapusers     
EOF

ldapadd -x -D "cn=Manager,${myDN}" -W -f basedomain.ldif


cat >> addgroup.lfif << EOF
dn: cn=,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber:
EOF


cat >> adduser.ldif << EOF
dn: uid=,ou=People,dc=,dc=
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn:
sn:
givenName:
userPassword:
loginShell: /bin/bash
uidNumber:
gidNumber: 10000
homeDirectory: /home/

dn: cn=,ou=Group,dc=,dc=
objectClass: posixGroup
cn:
gidNumber: 10000
memberUid:
EOF

##############################################

[ -f $myDNSDIR/dns-record ] && rm $myDNSDIR/dns-record
cat >> $myDNSDIR/dns-record << "EOF"
#!/bin/bash
###Written by alamahant on 24/12/19.This simple script will add A and PTR records to BIND
###Use the script thus "sudo bash dns-record <machine-name>  <IP>".
#[ -z $1 ] || [ -z $2 ] && echo "USAGE dns-record <HOST-NAME> <IP-ADDRESS>" && exit
#myCIDR=$(echo $2 | awk -F. '{ print $4 }')
#myDOMAIN=$(hostname -d)
#mySVCDIR="/var/bind"
#mySVCNAME="named"
#if ! $(cat $mySVCDIR/*lan | grep $1 >> /dev/null)  && ! $(cat $mySVCDIR/*lan | grep $2 >> /dev/null) 
#then
#echo "$1    IN A      $2" >> $mySVCDIR/*lan
#echo "$myCIDR    IN PTR      $1.$myDOMAIN" >> $mySVCDIR/*db
#pidof /lib/systemd/systemd >> /dev/null && systemctl reload $mySVCNAME
#pidof /sbin/init >> /dev/null && service $mySVCNAME reload
#echo "Host $1 with IP $2 added to Bind"
#elif $(cat $mySVCDIR/*lan | grep $1 >> /dev/null)
#then
#echo "Host already exists"
#else echo "IP is taken"
#fi
EOF
sed -i 's/^#//g' $myDNSDIR/dns-record
chmod +x $myDNSDIR/dns-record
#########################################################

####################################################
cat >> ldapuser.sh << "EOF"
##!/bin/bash
#
################### WRITTEN BY ALAMAHANT on 09/01/2020 ###########################
#
#
#if [ ! -f /etc/profile.d/ldapuser.sh ]
#then
#echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
#echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
#fi
#clear
#source /etc/profile.d/ldapuser.sh
#
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
#
#
#echo "ADDING USER WITH UID" $uidserial
#
#myFQDN=$(hostname)
#myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
#myREALM=$(echo ${myDOMAIN^^})
#getdn () {
#for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
#do
#dc=$(echo $myDOMAIN | cut -d "." -f $i)
#if [ $i -eq 1 ]
#then dn="dc="$dc
#
#else dn=$dn,"dc="$dc
#fi
#done
#echo  $dn
#}  ###Closing getdn ()
#
#myDN=$(getdn)
#
#addldapuser () {
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
#echo "first name";read givenName
#echo "last name";read sn
#echo "password";read passwd
#echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
#[ ! $line == "y" ] && return
#myPASS=$(slappasswd -s $passwd)
#
#cat > ldapuser.ldif << EOF
#dn: uid=$givenName.$sn,ou=People,$myDN
#objectClass: inetOrgPerson
#objectClass: posixAccount
#objectClass: shadowAccount
#cn: $givenName $sn
#sn: $sn
#givenName: $givenName
#userPassword: $myPASS
#loginShell: /bin/bash
#uidNumber: $uidserial
#gidNumber: 10000
#homeDirectory: /home/$givenName.$sn
#
#EOF
#
#if ldapadd -x -D cn=Manager,$myDN -W -f ldapuser.ldif
#then
#let "uidserial=uidserial+1"
#sed -i '/export/d' /etc/profile.d/ldapuser.sh
#echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
#echo "ADDED LDAP USER" $givenName.$sn
#echo "HERE ARE THE DETAILS:"
#echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
#echo ""
#
#if kadmin.local listprincs | grep  ${givenName}.${sn} >> /dev/null
#then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
#else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
#echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
#fi
#
#else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
#fi
#
#} ####Closing addldapuser
#
#addldapuser
#
EOF
sed -i 's/^#//g' ldapuser.sh
chmod +x ldapuser.sh
##################################################################

####################################################################
cat >> bulkusers.sh << "EOF"
##!/bin/bash
#
################### WRITTEN BY ALAMAHANT on 09/01/2020 ###########################
#if [ ! -f /etc/profile.d/ldapuser.sh ]
#then
#echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
#echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
#fi
#
#
#source /etc/profile.d/ldapuser.sh
#
#
#myFQDN=$(hostname)
#myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
#myREALM=$(echo ${myDOMAIN^^})
#getdn () {
#for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
#do
#dc=$(echo $myDOMAIN | cut -d "." -f $i)
#if [ $i -eq 1 ]
#then dn="dc="$dc
#
#else dn=$dn,"dc="$dc
#fi
#done
#echo  $dn
#}  ###Closing getdn ()
#
#myDN=$(getdn)
#
#addldapuser () {
#echo "ADDING USER WITH UID" $uidserial
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
##echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
##[ ! $line == "y" ] && return
#myPASS=$(slappasswd -s $passwd)
#
#cat > ldapuser.ldif << EOF
#dn: uid=$givenName.$sn,ou=People,$myDN
#objectClass: inetOrgPerson
#objectClass: posixAccount
#objectClass: shadowAccount
#cn: $givenName $sn
#sn: $sn
#givenName: $givenName
#userPassword: $myPASS
#loginShell: /bin/bash
#uidNumber: $uidserial
#gidNumber: 10000
#homeDirectory: /home/$givenName.$sn
#
#EOF
#
#if ldapadd -x -D cn=Manager,$myDN -w $adminpasswd  -f ldapuser.ldif
#then
#let "uidserial=uidserial+1"
#sed -i '/export/d' /etc/profile.d/ldapuser.sh
#echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
#echo "ADDED LDAP USER" $givenName.$sn
##echo "HERE ARE THE DETAILS:"
##echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
#echo ""
#
#if kadmin.local listprincs | grep  ${givenName}.${sn} >> /dev/null
#then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
#else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
#echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
#echo ""
#fi
#
#else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
#fi
#
#} ####Closing addldapuser
#
#
#echo "PLEASE PROVIDE THE ABSOLUTE PATH OF THE FILE CONTAINING THE USERS TO BE ADDED TO THE OPENLDAP DATABASE"
#echo "THE FILE SHOULD CONTAIN ONE USER PER LINE IN THE FORMAT:"
#echo "firstname surname password"; read file
#[ ! -f $file ] && echo "NO SUSCH FILE.EXITING......" && exit
#echo "PLEASE PROVIDE THE PASSWORD FOR THE ADMINISTRATIVE ACCOUNT cn=Manager,$myDN"; read adminpasswd
#
#clear
#while read -r line
#do
#givenName=$(echo $line | awk '{ print $1 }')
#sn=$(echo $line | awk '{ print $2 }')
#passwd=$(echo $line | awk '{ print $3 }')
#addldapuser
#done < $file
#
EOF
sed -i 's/^#//g' bulkusers.sh
chmod +x bulkusers.sh
#################################################################


cat >> mod_ssl.ldif << EOF
dn: cn=config
changetype: modify
add: olcTLSCACertificateFile
olcTLSCACertificateFile: $myLDAPCONFDIR/ssl/ca-certificates.crt
-
replace: olcTLSCertificateFile
olcTLSCertificateFile: $myLDAPCONFDIR/ssl/server.crt
-
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: $myLDAPCONFDIR/ssl/server.key
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f mod_ssl.ldif

sleep 3

rm $myLDAPCONFDIR/ldap.conf >> /dev/null
cat >> $myLDAPCONFDIR/ldap.conf << EOF
BASE   $myDN
URI    ldap://$myFQDN ldaps://$myFQDN ldapi:///

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# TLS certificates (needed for GnuTLS)
TLS_CACERT      /etc/ssl/certs/ca-certificates.crt
TLS_REQCERT allow
EOF

chown ldap. $myLDAPCONFDIR/ldap.conf

pidof /lib/systemd/systemd >> /dev/null && systemctl restart slapd
pidof /sbin/init >> /dev/null && rc-service slapd restart

clear
echo "PART 2: OPENLDAP SERVER COMPLETED."
echo "YOU CAN NOW TEST THE FUNCTIONALITY OF YOUR OPENLDAP SERVER BY ISSUING:"
echo "slapcat"
echo "ldapsearch -x -b $myDN -H ldap://$myFQDN/"
echo "ldapsearch -x -D cn=Manager,$myDN -b $myDN -H ldaps://$myFQDN/ -W"
echo "ldapsearch -x -b $myDN -H ldapi:///"
echo "etc etc etc"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line

}   ###closing openldapinstal ()


krb5install () {
clear
echo "PART 3: KERBEROS.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS KERBEROS CONFIGURATION..."

echo "app-crypt/mit-krb5  openldap" > /etc/portage/package.use/mit-krb5
pidof /lib/systemd/systemd >> /dev/null && systemctl stop $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init >> /dev/null && rc-service $myKDCSVCNAME stop && rc-service $myKADMINSVCNAME stop

rm -rf $myKRB5DIR/* >> /dev/null

emerge -DNaq mit-krb5
echo "RECONFIGURING KERBEROS..."

[ ! -e /etc/krb5.conf.bak ] && cp /etc/krb5.conf /etc/krb5.conf.bak
rm /etc/krb5.conf >> /dev/null
rm /etc/krb5.keytab >> /dev/null


cat >> /etc/krb5.conf << EOF
[libdefaults]
   default_realm = $myREALM
   kdc_timesync = 1
   ccache_type = 4
   forwardable = true
   proxiable = true
   dns_lookup_realm = false
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = true
    rdns = false
   pkinit_anchors = /etc/ssl/certs/ca-certificates.crt
    default_ccache_name = KEYRING:persistent:%{uid}

   fcc-mit-ticketflags = true

[realms]
   $myREALM = {
      kdc = $myFQDN
      admin_server = $myFQDN
   }
[domain_realm]
   .$myDOMAIN = $myREALM
   $myDOMAIN = $myREALM

EOF

cat >> $myKRB5DIR/kdc.conf << EOF
[kdcdefaults]
    kdc_ports = 750,88

[realms]
    $myREALM = {
        database_name = $myKRB5DIR/principal
        admin_keytab = FILE:$myKRB5DIR/kadm5.keytab
        acl_file = $myKRB5DIR/kadm5.acl
        key_stash_file = $myKRB5DIR/stash
        kdc_ports = 750,88
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        master_key_type = des3-hmac-sha1
        #supported_enctypes = aes256-cts:normal aes128-cts:normal
        default_principal_flags = +preauth
    }

EOF

echo "*/admin@${myREALM} *" > $myKRB5DIR/kadm5.acl
echo "YOU WILL BE PROMPTED FOR KERBEROS DB ROOT PASSWD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kdb5_util create -s -r ${myREALM}
pidof /lib/systemd/systemd >> /dev/null && systemctl enable $myKDCSVCNAME $myKADMINSVCNAME  && systemctl restart $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init >> /dev/null && rc-update add $myKDCSVCNAME default && rc-update add  $myKADMINSVCNAME default && rc-service $myKDCSVCNAME restart && rc-service $myKADMINSVCNAME restart
kadmin.local ank -randkey host/${myFQDN} >> /dev/nul
kadmin.local ktadd host/${myFQDN} >> /dev/null
echo "YOU WILL BE PROMPTED FOR KERBEROS ADMIN USER root/admin PASSWORD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kadmin.local ank root/admin
kadmin.local ank root
clear
echo "PART 3: KERBEROS COMPLETED"
echo "YOU MAY USE THE KRB5KDC AND KADMIN SERVERS TO MANAGE YOUR REALM"
echo "SOME USEFUL COMMANDS:"
echo "kadmin.local ank -pw <passwd> <principal>"
echo "kadmin.local ank -randkey host/FQDN"
echo "kadmin.local ktadd service/FQDN"
echo "kadmin.local listprincs"
echo "kadmin.local delprinc <principal>"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read key
} ###Closing krb5installl


nfsinstall () {
clear
echo "PART 4: KERBERISED NFS-SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS NFS CONFIGURATION..."
pidof /lib/systemd/systemd >> /dev/null && systemctl stop nfs-server rpcbind
pidof /sbin/init >> /dev/null && rc-service nfs stop && rc-service rpcbind stop
rm -rf /srv/nfs
echo "net-fs/nfs-utils kerberos ldap nfsv4" > /etc/portage/package.use/nfs-utils
echo "net-libs/libtirpc kerberos" > /etc/portage/package.use/libtirpc
 
emerge -DNaq nfs-utils
echo "RECONFIGURING NFS-SERVER..."

###########################
nfsdir () {
echo 'NFS SERVER WILL SHARE A PRIVATE DIRECTORY WITH KERBEROS SECURITY sec=krb5p UNDER "/srv/nfs".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "NFS SERVER WILL SHARE "/srv/nfs/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && nfsdir
export nfsDIR=${private}
}  ####Closing nfsdir
nfsdir

##########################

sed -i '/srv/d' /etc/exports
mkdir -p /srv/nfs/$nfsDIR >> /dev/null && chmod -R 777 /srv/nfs >> /dev/null
[ ! -f /etc/idmapd.conf.bak ] && mv  /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf

################################
cat >> /etc/idmapd.conf << EOF
[General]

Verbosity = 0
#Pipefs-Directory = /run/rpc_pipefs
# set your own domain here, if it differs from FQDN minus hostname
Domain = $myDOMAIN

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup

EOF
echo "/srv/nfs *(rw,sec=krb5p,fsid=0,insecure)" >> /etc/exports
echo "/srv/nfs/$nfsDIR *(rw,sec=krb5p,nohide,insecure)" >> /etc/exports
[ ! -f /etc/conf.d/nfs.bak ] && cp -p /etc/conf.d/nfs /etc/conf.d/nfs.bak
sed -i '/NFS_NEEDED_SERVICES=/d' /etc/conf.d/nfs
echo "NFS_NEEDED_SERVICES="rpc.idmapd rpc.gssd rpc.svcgssd"" >> /etc/conf.d/nfs
pidof /lib/systemd/systemd >> /dev/null && systemctl enable --now rpcbind nfs-server && systemctl restart rpcbind nfs-server
if pidof /sbin/init >> /dev/null
then
rc-update add rpcbind default
rc-update add nfs default
rc-update add nfsclient default
rpc.idmapd
rpc.svcgssd
rc-service nfs restart
rpc.gssd
rc-service nfsclient restart
fi
exportfs -avr
kadmin.local ank -randkey nfs/${myFQDN} >> /dev/null
kadmin.local ktadd nfs/${myFQDN} >> /dev/null
clear
echo "PART 4: KERBERISED NFS-SERVER COMPLETED"
echo "AFTER REBOOTING YOUR MACHINE YOU CAN MOUNT /srv/nfs/$nfsDIR BY ISSUING:"
echo "kinit"
echo "systemctl start nfs-client.target"
echo "mount -t nfs4 -o sec=krb5p ${myFQDN}:/$nfsDIR /mnt"
echo "PLEASE REMEMBER TO CREATE PRINCIPALS FOR YOUR USERS IN KERBEROS."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line


}  ###Closing nfsinstall
###########################

##########################
sambainstall () {
clear
echo "PART 5: SAMBA SERVER CONFIGURATION.............."
emerge -DNaq samba
echo "REMOVING PREVIOUS SAMBA CONFIGURATION..."

[ ! -d /var/lib/samba.bak ] && cp -pa /var/lib/samba /var/lib/samba.bak
rm -rf /var/lib/samba
cp -pa /var/lib/samba.bak /var/lib/samba


if ! cat /etc/group | grep smbprivate >> /dev/null;then groupadd -g 3000 smbprivate;fi

sharedir () {
echo 'SAMBA SERVER WILL SHARE A READ-ONLY OPEN-TO ALL DIRECTORY UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read dir
echo "SAMBA SERVER WILL SHARE "/srv/samba/$dir" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbshare=${dir}
echo 'SAMBA SERVER WILL SHARE A PRIVATE DIRECTORY TO BE USED ONLY BY THE GROUP "smbprivate" UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "SAMBA SERVER WILL SHARE "/srv/samba/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbprivate=${private}
}  ####Closing sharedir
sharedir

myIFACE=$(ip a  | grep $myIP | awk '{ print $2 }')
myHOSTS=$(echo $myNETWORK | awk -F. '{ print $1"."$2"."$3"." }')

[ -d /srv/samba ] && rm -rf /srv/samba
[ -f /etc/samba/smb.conf ] && rm /etc/samba/smb.conf
mkdir -p /srv/samba/$smbshare
mkdir -p /srv/samba/$smbprivate
chmod -R 777 /srv/samba

cat >> /etc/samba/smb.conf << EOF
#======================= Global Settings =====================================
[global]

   workgroup = MYGROUP

   server string = Samba Server

   server role = standalone server

   hosts allow =  $myHOSTS 127.

   guest account = nobody

#   log file = /var/log/samba/log.%m

   max log size = 50

   passdb backend = tdbsam

;   include = /etc/samba/smb.conf.%m

   interfaces = $myIFACE 127.0.0.1/24

;   logon path = \\%L\Profiles\%U

;   wins support = yes

;   wins server = w.x.y.z

;   wins proxy = yes

   dns proxy = no

;  add user script = /usr/sbin/useradd %u
;  add group script = /usr/sbin/groupadd %g
;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
;  delete user script = /usr/sbin/userdel %u
;  delete user from group script = /usr/sbin/deluser %u %g
;  delete group script = /usr/sbin/groupdel %g

map to guest = Bad User
server min protocol = SMB3
smb encrypt = desired
unix charset = UTF-8
dos charset = CP932

load printers = no
  printing = bsd
  printcap name = /dev/null
  disable spoolss = yes
  show add printer wizard = no

#============================ Share Definitions ==============================
[homes]
   comment = Home Directories
   browseable = no
   writable = no
   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
; [netlogon]
;   comment = Network Logon Service
;   path = /var/lib/samba/netlogon
;   guest ok = yes
;   writable = no
;   share modes = no


# Un-comment the following to provide a specific roving profile share
# the default is to use the user's home directory
;[Profiles]
;    path = /var/lib/samba/profiles
;    browseable = no
;    guest ok = yes


# NOTE: If you have a BSD-style print system there is no need to
# specifically define each individual printer
[printers]
   comment = All Printers
   path = /var/spool/samba
   browseable = no
# Set public = yes to allow user 'guest account' to print
   guest ok = no
   writable = no
   printable = yes

# This one is useful for people to share files
;[tmp]
;   comment = Temporary file space
;   path = /tmp
;   read only = no
;   public = yes

# A publicly accessible directory, but read only, except for people in
# the "staff" group
;[public]
;   comment = Public Stuff
;   path = /home/samba
;   public = yes
;   writable = no
;   printable = no
;   write list = @staff

# Other examples.
#
# A private printer, usable only by fred. Spool data will be placed in fred's
# home directory. Note that fred must have write access to the spool directory,
# wherever it is.
;[fredsprn]
;   comment = Fred's Printer
;   valid users = fred
;   path = /homes/fred
;   printer = freds_printer
;   public = no
;   writable = no
;   printable = yes

# A private directory, usable only by fred. Note that fred requires write
# access to the directory.
;[fredsdir]
;   comment = Fred's Service
;   path = /usr/somewhere/private
;   valid users = fred
;   public = no
;   writable = yes
;   printable = no

# a service which has a different directory for each machine that connects
# this allows you to tailor configurations to incoming machines. You could
# also use the %U option to tailor it by user name.
# The %m gets replaced with the machine name that is connecting.
;[pchome]
;  comment = PC Directories
;  path = /usr/pc/%m
;  public = no
;  writable = yes

# A publicly accessible directory, read/write to all users. Note that all files
# created in the directory by users will be owned by the default user, so
# any user with access can delete any other user's files. Obviously this
# directory must be writable by the default user. Another user could of course
# be specified, in which case all files would be owned by that user instead.
;[public]
;   path = /usr/somewhere/else/public
;   public = yes
;   only guest = yes
;   writable = yes
;   printable = no

# The following two entries demonstrate how to share a directory so that two
# users can place files there that will be owned by the specific users. In this
# setup, the directory should be writable by both users and should have the
# sticky bit set on it to prevent abuse. Obviously this could be extended to
# as many users as required.
;[myshare]
;   comment = Mary's and Fred's stuff
;   path = /usr/somewhere/shared
;   valid users = mary fred
;   public = no
;   writable = yes
;   printable = no
;   create mask = 0765

[$smbprivate]
path = /srv/samba/$smbprivate
guest ok = no
valid users = root @smbprivate
writable = yes
write list = root @smbprivate
create mask = 0664
force create mode = 0644
directory mask = 2775
force directory mode = 2775

[$smbshare]
path = /srv/samba/$smbshare
guest ok = yes
guest only = yes
read only = yes
create mode = 0777
directory mode = 0777


EOF
if pidof /lib/systemd/systemd >> /dev/null
then
systemctl enable --now smbd nmbd
systemctl restart smbd nmbd
sleep 3
fi

if pidof /sbin/init >> /dev/null
then
rc-update add samba default
rc-service samba restart
sleep 3
fi


clear
echo "SAMBA CONFIGURATION COMPLETED.PLEASE REMEMBER TO ADD USERS TO THE "smbprivate" GROUP WITH  gid 3000 TO ENABLE THEM TO ACCESS THE $smbprivate DIRECTORY"
echo "MAKE SURE TO ADD THIS GROUP TO ALL CLIENT MACHINES THAT NEED ACCESS TO THE $smbprivate DIRECTORY"
echo "PLEASE USE smbpasswd -a TO ADD USERS TO SAMBA"
echo "PRESS ANY KEY TO CONTINUE";read line

}   ###Closing sambainstall

################################################

##############################
ntpinstall () {
clear
echo "INSTALLING NTP TIME SERVER..."
if ! equery l '*' | grep net-misc/ntp >> /dev/null;then emerge -DNaq net-misc/ntp;fi
if pidof /lib/systemd/systemd >> /dev/null;then systemctl enable --now ntpd && systemctl restart ntpd;fi
if pidof /sbin/init >> /dev/null
then
rc-update add ntpd default
rc-service ntpd restart
fi

hwclock --systohc
sleep 3
clear
echo "NTP TIME SERVER INSTALLATION COMPLETE.PLEASE PRESS ANY KEY TO CONTINUE";read line
}  ############Closing ntpinstall()
#####################################

#########apache2install

apache2install () {

clear
echo "CONFIGURING APACHE......"
echo "REMOVING PREVIOUS APACHE CONFIG AND RECONFIGURING APACHE.PRESS y TO CONTINUE ";read confirm

if [ $confirm != "y" ]
then echo "ABORTING....."
exit
fi

if pidof /lib/systemd/systemd >> /dev/null;then systemctl stop apache2 >> /dev/null;fi
if pidof /sbin/init >> /dev/null
then
rc-service apache2 stop >> /dev/null
fi
emerge -DNaq apache mod_auth_kerb

clear

[ ! -f /etc/conf.d/apache2.bak ] && mv /etc/conf.d/apache2 /etc/conf.d/apache2.bak >> /dev/null
[ -f /etc/apache2/krb5dir.info ] && krb5dir=$(cat /etc/apache2/krb5dir.info) && rm -rf /var/www/localhost/htdocs/$krb5dir
[ ! -f /etc/apache2/modules.d/11_mod_auth_kerb.conf.bak ] && mv /etc/apache2/modules.d/11_mod_auth_kerb.conf /etc/apache2/modules.d/11_mod_auth_kerb.conf.bak
[ ! -f /etc/apache2/vhosts.d/00_default_ssl_vhost.conf.bak ] && mv /etc/apache2/vhosts.d/00_default_ssl_vhost.conf /etc/apache2/vhosts.d/00_default_ssl_vhost.conf.bak
rm /etc/conf.d/apache2 >> /dev/null
rm /etc/apache2/vhosts.d/00_default_ssl_vhost.conf >> /dev/null
rm /etc/apache2/modules.d/11_mod_auth_kerb.conf >> /dev/null

echo "APACHE WILL SERVE A KERBEROS PROTECTED DIRECTORY FROM THE DEFAULT LOCATION OF /var/www/localhost/htdocs"
echo "PLEASE CHOOSE THE NAME OF THIS DIRECTORY ";read krb5dir
echo "APACHE WILL SHARE THE /var/www/localhost/htdocs/$krb5dir DIRECTORY.PLEASE PRESS y TO CONFIRM ";read confirm


if [ $confirm != "y" ]
then echo "ABORTING....."
exit
fi

mkdir /var/www/localhost/htdocs/$krb5dir

cat >> /var/www/localhost/htdocs/$krb5dir/index.html << EOF
Welcome to Kerberos-shared /var/www/localhost/htdocs/$krb5dir Directory

This page uses the Apache module  mod_auth_kerb to authenticate and allow access to only existing kerberos users.
You may wish to symlink files that you wish to share,create directories and html files and even have a whole "inner" private and secure site served from here.It uses the SSL certificates we created during ldap installation and as a result you will get an SSL warning from firefox when trying to access it.For testing pupropses its ok but in production you may wish to use some proper SSL certs i.e. Letsencrypt etc.
EOF

cat >> /etc/apache2/vhosts.d/00_default_ssl_vhost.conf << EOF
<IfDefine SSL>
<IfDefine SSL_DEFAULT_VHOST>
<IfModule ssl_module>

Listen 443

<VirtualHost _default_:443>
   ServerName $myDOMAIN
   Include /etc/apache2/vhosts.d/default_vhost.include
   ErrorLog /var/log/apache2/ssl_error_log

   <IfModule log_config_module>
      TransferLog /var/log/apache2/ssl_access_log
   </IfModule>

   SSLEngine on

   SSLProtocol ALL -SSLv2 -SSLv3

   SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128:AES256:HIGH:!RC4:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK

   SSLHonorCipherOrder On

   SSLCertificateFile /etc/ssl/private/server.crt

   SSLCertificateKeyFile /etc/ssl/private/server.key


   SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt

   <FilesMatch "\.(cgi|shtml|phtml|php)$">
      SSLOptions +StdEnvVars
   </FilesMatch>

   <Directory "/var/www/localhost/cgi-bin">
      SSLOptions +StdEnvVars
   </Directory>




   <IfModule log_config_module>
      CustomLog /var/log/apache2/ssl_request_log \
         "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
   </IfModule>


<Directory /var/www/localhost/htdocs/$krb5dir>
    SSLRequireSSL
    AuthType Kerberos
    AuthName "Kerberos Authentication"
    KrbAuthRealms $myREALM
    Krb5Keytab /etc/apache2/.HTTP.keytab
    KrbMethodNegotiate On
    KrbMethodK5Passwd On
    KrbServiceName HTTP/$myFQDN
    KrbSaveCredentials Off
    KrbVerifyKDC Off
    Require valid-user
</Directory>

</VirtualHost>
</IfModule>
</IfDefine>
</IfDefine>
EOF

cat >> /etc/conf.d/apache2 << EOF
APACHE2_OPTS="-D INFO -D SSL -D SSL_DEFAULT_VHOST -D LANGUAGE -D AUTH_KERB"
EOF

cat >> /etc/apache2/modules.d/11_mod_auth_kerb.conf << EOF
<IfDefine AUTH_KERB>
LoadModule auth_kerb_module modules/mod_auth_kerb.so
</IfDefine>
EOF

if kadmin.local listprincs | grep HTTP >> /dev/null
then princ=$(kadmin.local listprincs | grep HTTP)
kadmin.local delprinc $princ >> /dev/null
fi

kadmin.local addprinc -randkey HTTP/$myFQDN
kadmin.local ktadd -k /etc/apache2/.HTTP.keytab HTTP/$myFQDN >> /dev/null

echo "$krb5dir" > /etc/apache2/krb5dir.info

if pidof /lib/systemd/systemd >> /dev/null;then systemctl enable apache2 >> /dev/null && systemctl start apache2;fi
if pidof /sbin/init >> /dev/null
then
rc-service apache2 restart >> /dev/null
fi

clear

echo "APACHE CONFIGURATION COMPLETE.PLEASE OPEN A WEB BROWSER AND NAVIGATE TO https://$myDOMAIN/$krb5dir"
echo "AUTHENTICATING WITH AN EXISTING KERBEROS USER AND PASSWORD.OR YOU MAY WISH TO OPEN A NEW TERMINAL OR SSH SESSION AND ADD A USER NOW BY RUNNING  sudo kadmin.local ank -pw <password> <username> FURTHERMORE IF YOU ARE NOT ACCESSING THE WEB PAGE LOCALLY THEN PLEASE MAKE SURE THAT IT IS RESOLVABLE EITHER THROUGH A DNS ENTRY OR VIA AN ENTRY IN /etc/hosts.......PLEASE PRESS ANY KEY TO CONTINUE ";read key
}###closing apache2install()



dnsinstall
openldapinstall
krb5install
nfsinstall
sambainstall
ntpinstall
apache2install



ADDENDUM:CLIENT INSTALLATION SCRIPTS FOR DEBIAN AND CENTOS/REDHAT/FEDORA:
As promised here are some more installation scripts in case your client machine is not Gentoo.

First DEBIAN:
Code:

#!/bin/bash

#################### WRITTEN BY ALAMAHANT ON FRIDAY 10 JANUARY 2020  ######################

[ ! -f /etc/nsswitch.conf ] && cp  /usr/share/libc-bin/nsswitch.conf /etc/nsswitch.conf
[ ! -f /etc/nsswitch.conf.bak ] && cp  /etc/nsswitch.conf /etc/nsswitch.conf.bak
[ ! -f /etc/resolv.conf.bak ] && cp /etc/resolv.conf /etc/resolv.conf.bak
[ ! -f /etc/hosts.bak ] && cp /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp  /etc/hostname /etc/hostname.bak
[ -f /etc/krb5.conf ] && rm /etc/krb5.conf
[ -f /etc/krb5.keytab ] && rm /etc/krb5.keytab
[ ! -f /etc/pam.d/common-auth.bak ] && mv /etc/pam.d/common-auth /etc/pam.d/common-auth.bak
[ ! -f /etc/pam.d/common-password.bak ] && mv /etc/pam.d/common-password /etc/pam.d/common-password.bak
[ ! -f /etc/pam.d/common-account.bak ] && mv /etc/pam.d/common-account /etc/pam.d/common-account.bak
[ ! -f /etc/pam.d/common-session.bak ] && mv /etc/pam.d/common-session /etc/pam.d/common-session.bak
rm /etc/pam.d/common* >> /dev/null

clear

apt update && apt install sssd nfs-common ldap-utils krb5-admin-server libpam-krb5 libnss-sss libpam-sss

clear


systemctl enable sssd
 

clear
staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

myIP=$(ip route get 8.8.8.8 | grep src | sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
if [ ! -f /root/.ssh/id_rsa.pub ]
then
echo "GENERATING SSH KEYS...."
ssh-keygen -t rsa
fi

echo "YOU NEED TO HAVE ROOT SSH ACCESS WITH PASSWORD TO THE SSO MACHINE"
echo "PLEASE ENTER THE IP ADDRESS OF THE SSO MACHINE";read server

if ! ssh-copy-id root@$server
then echo "EITHER WRONG IP ADDRESS OR HOST SSHD DAEMON NOT RUNNING OR ROOT SSH ACCESS WITH PASSWORD NOT ALLOWED.EXITING"
exit
fi

serverFQDN=$(ssh root@$server hostname)
myDOMAIN=$(echo $serverFQDN | awk -F. '{ print $2"."$3 }')
myREALM=$(echo ${myDOMAIN^^})

setfqdn () {
clear
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.${myDOMAIN}";read machine
echo "DO YOU WISH YOUR FQDN TO BE ${machine}.${myDOMAIN} ? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
myFQDN=$machine.$myDOMAIN
echo $myFQDN > /etc/hostname

rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $myFQDN
EOF

hostname -F /etc/hostname
hostnamectl set-hostname $myFQDN

export myFQDN=$myFQDN

} ###Closing setfqdn


setfqdn
echo $machine $myIP | ssh root@$server xargs  /etc/bind/dns-record

ssh root@$server << EOF
systemctl reload named || rc-service named reload

EOF


scp  root@$server:/etc/krb5.conf /etc/krb5.conf

[ ! -f /etc/ldap/ldap.conf.bak ] && mv /etc/ldap/ldap.conf /etc/ldap/ldap.conf.bak
rm /etc/ldap/ldap.conf >> /dev/null
scp  root@$server:/etc/ldap/ldap.conf /etc/ldap/

getdn () {
end=$(echo $myDOMAIN | awk -F. '{ print NF; end}')
for i in {1,$end}
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)
myREALM=$(echo ${myDOMAIN^^})






[ ! -f /etc/sssd/sssd.conf.bak ] && cp -p  /etc/sssd/sssd.conf /etc/sssd/sssd.conf.bak

[ -f /etc/sssd/sssd.conf ] && rm /etc/sssd/sssd.conf
cat >> /etc/sssd/sssd.conf << EOF
[domain/default]

autofs_provider = ldap
cache_credentials = True
krb5_kpasswd = $serverFQDN
ldap_search_base = $myDN
krb5_server = $serverFQDN
id_provider = ldap
auth_provider = krb5
chpass_provider = krb5
krb5_store_password_if_offline = True
ldap_uri = ldap://$serverFQDN/
krb5_realm = $myREALM
ldap_id_use_start_tls = True
ldap_tls_cacertdir = /etc/ldap/sasl2
ldap_tls_reqcert = allow
[sssd]
services = nss, pam, autofs

domains = default
[nss]
homedir_substring = /home

[pam]

[sudo]

[autofs]

[ssh]

[pac]

[ifp]

[secrets]

[session_recording]
EOF

chmod 600 /etc/sssd/sssd.conf

[ ! -d /etc/ldap/sasl2 ] && mkdir /etc/ldap/sasl2
cp /etc/ssl/certs/ca-certificates.crt /etc/ldap/sasl2/

rm /etc/nsswitch.conf
cp -p /etc/nsswitch.conf.bak /etc/nsswitch.conf
sed -i '/passwd/ s/$/ sss/g' /etc/nsswitch.conf
sed -i '/shadow/ s/$/ sss/g' /etc/nsswitch.conf
sed -i '/group/ s/$/ sss/g' /etc/nsswitch.conf

if ! grep automount /etc/nsswitch.conf >> /dev/null
then echo "automount:  files sss" >> /etc/nsswitch.conf
else sed -i '/automount/ s/$/ sss/g' /etc/nsswitch.conf
fi

if ! grep sudoers /etc/nsswitch.conf >> /dev/null
then echo "sudoers:  files sss" >> /etc/nsswitch.conf
else sed -i '/sudoers/ s/$/ sss/g' /etc/nsswitch.conf
fi


cat >> /etc/pam.d/common-auth << EOF
auth    [success=2 default=ignore]                      pam_sss.so
auth    [success=1 default=ignore]      pam_unix.so nullok_secure try_first_pass
auth    requisite                       pam_deny.so
auth    required                        pam_permit.so
EOF

cat >> /etc/pam.d/common-account << EOF
account [success=1 new_authtok_reqd=done default=ignore]  pam_unix.so
account requisite                       pam_deny.so
account required                        pam_permit.so
session optional      pam_mkhomedir.so skel=/etc/skel umask=0077
account [default=bad success=ok user_unknown=ignore]    pam_sss.so
EOF

cat >> /etc/pam.d/common-password << EOF
password        sufficient                      pam_sss.so
password        [success=1 default=ignore]      pam_unix.so obscure try_first_pass sha512
password        requisite                       pam_deny.so
password        required                        pam_permit.so
EOF

cat >> /etc/pam.d/common-session << EOF
session [default=1]   pam_permit.so
session requisite     pam_deny.so
session required      pam_permit.so
session optional      pam_mkhomedir.so skel=/etc/skel umask=0077
session optional      pam_sss.so
session required      pam_unix.so
EOF


sed -i '/GSSAPIAuthentication/d' /etc/ssh/sshd_config
echo "GSSAPIAuthentication yes" >> /etc/ssh/sshd_config

systemctl restart sshd


rm /etc/hosts >> /dev/null
cat >> /etc/hosts << EOF
127.0.0.1   localhost
EOF

rm /etc/resolv.conf >> /dev/null
cat >> /etc/resolv.conf << EOF
search   $myDOMAIN
nameserver $server
EOF

echo "YOU WILL BE PROMPTED FOR THE KERBEROS root/admin or root PASSWORD SO THAT PRINCIPALS FOR host/$myFQDN and nfs/$myFQDN MAY BE ISSUED"
kadmin ank -randkey host/$myFQDN
kadmin ank -randkey nfs/$myFQDN
kadmin ktadd host/$myFQDN
kadmin ktadd nfs/$myFQDN



[ -f /etc/idmapd.conf.bak ] && cp /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf
cat >> /etc/idmapd.conf << EOF
[General]
domain = $myDOMAIN
[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup
EOF

systemctl enable --now rpcbind nfs-client.target >> /dev/null
systemctl restart rpcbind nfs-client.target >> /dev/null





echo "CLIENT CONFIGURATION COMPLETED.IT IS ABSOLUTELY ESSENTIAL THOUGH THAT YOU MODIFY YOUR INTERFACE TO USE THE DIRECTORY SERVER'S DNS @IP ADDRESS:${server} .THEN PLEASE REBOOT YOUR MACHINE AND LOGIN OR SSH TO YOUR MACHINE USING A REMOTE USERNAME.FURTHERMORE YOU CAN USE THE getent passwd COMMAND TO PROBE FOR USERS ON THE  REMOTE SERVER"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read key



For REDHAT/CENTOS/FEDORA:
Code:

#!/bin/bash

#################### WRITTEN BY ALAMAHANT ON FRIDAY 10 JANUARY 2020  ######################

[ ! -f /etc/resolv.conf.bak ] && cp /etc/resolv.conf /etc/resolv.conf.bak
[ ! -f /etc/hosts.bak ] && cp /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp  /etc/hostname /etc/hostname.bak
[ -f /etc/krb5.conf ] && rm /etc/krb5.conf
[ -f /etc/krb5.keytab ] && rm /etc/krb5.keytab

clear
yum -y update && yum install sssd nfs-utils openldap-clients krb5-workstation pam_krb5 policycoreutils policycoreutils-python ###checkmodule?
clear
systemctl enable sshd && systemctl restart sshd

systemctl enable sssd
 

clear
staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

myIP=$(ip route get 8.8.8.8| grep src | sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
if [ ! -f /root/.ssh/id_rsa.pub ]
then
echo "GENERATING SSH KEYS...."
ssh-keygen -t rsa
fi

echo "YOU NEED TO HAVE ROOT SSH ACCESS WITH PASSWORD TO THE SSO MACHINE"
echo "PLEASE ENTER THE IP ADDRESS OF THE SSO MACHINE";read server

if ! ssh-copy-id root@$server
then echo "EITHER WRONG IP ADDRESS OR HOST SSHD DAEMON NOT RUNNING OR ROOT SSH ACCESS WITH PASSWORD NOT ALLOWED.EXITING"
exit
fi

serverFQDN=$(ssh root@$server hostname)
myDOMAIN=$(echo $serverFQDN | awk -F. '{ print $2"."$3 }')
myREALM=$(echo ${myDOMAIN^^})
setfqdn () {
clear
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.${myDOMAIN}";read machine
echo "DO YOU WISH YOUR FQDN TO BE ${machine}.${myDOMAIN} ? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
myFQDN=$machine.$myDOMAIN
echo $myFQDN > /etc/hostname

rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $myFQDN
EOF

hostname -F /etc/hostname
hostnamectl set-hostname $myFQDN
export myFQDN=$myFQDN
} ###Closing setfqdn


setfqdn
echo $machine $myIP | ssh root@$server xargs  /etc/bind/dns-record

ssh root@$server << EOF
systemctl reload named || rc-service named reload

EOF


[ ! -f /etc/krb5.conf.bak ] && mv /etc/krb5.conf /etc/krb5.conf.bak
scp  root@$server:/etc/krb5.conf /etc/krb5.conf
[ ! -f /etc/openldap/ldap.conf.bak ] && mv /etc/openldap/ldap.conf /etc/openldap/ldap.conf.bak
scp  root@$server:/etc/openldap/ldap.conf /etc/openldap/

getdn () {
end=$(echo $myDOMAIN | awk -F. '{ print NF; end}')
for i in {1,$end}
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)
myREALM=$(echo ${myDOMAIN^^})

authconfig --enableldap --ldapserver=$serverFQDN --ldapbasedn=$myDN  --enableldapstarttls --enablekrb5 --krb5kdc=$serverFQDN --krb5adminserver=$serverFQDN --krb5realm=$myREALM --enablemkhomedir --update


sed -i '/ldap_tls_cacertdir/a ldap_tls_reqcert = allow' /etc/sssd/sssd.conf

[ ! -f /etc/sssd/sssd.conf.bak ] && mcp -p  /etc/sssd/sssd.conf /etc/sssd/sssd.conf.bak


chmod 600 /etc/sssd/sssd.conf
cp /etc/pki/tls/certs/ca-bundle.crt /etc/openldap/cacerts/
chown ldap. /etc/openldap/cacerts/*

sed -i '/GSSAPIAuthentication yes/d' /etc/ssh/sshd_config
echo "GSSAPIAuthentication yes" >> /etc/ssh/sshd_config

systemctl restart sshd


rm /etc/hosts
cat >> /etc/hosts << EOF
127.0.0.1   localhost
EOF

rm /etc/resolv.conf
cat >> /etc/resolv.conf << EOF
search   $myDOMAIN
nameserver $server
EOF

echo "YOU WILL BE PROMPTED FOR THE KERBEROS root/admin or root PASSWORD SO THAT PRINCIPALS FOR host/$myFQDN and nfs/$myFQDN MAY BE ISSUED"
kadmin ank -randkey host/$myFQDN
kadmin ank -randkey nfs/$myFQDN
kadmin ktadd host/$myFQDN
kadmin ktadd nfs/$myFQDN



[ -f /etc/idmapd.conf.bak ] && cp /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf
cat >> /etc/idmapd.conf << EOF
[General]
domain = $myDOMAIN
[Mapping]

Nobody-User = nfsnobody
Nobody-Group = nfsnobody
EOF

systemctl enable --now rpcbind nfs nfs-client.target >> /dev/null
systemctl restart rpcbind nfs nfs-client.target >> /dev/null


echo "CONFIGURING SELINUX TO ALLOW CREATION OF REMOTE USERS HOME DIRECTORIES....."

rm mkhomedir.te

cat >> mkhomedir.te << EOF
module mkhomedir 1.0;

require {
        type unconfined_t;
        type oddjob_mkhomedir_exec_t;
        class file entrypoint;
}

#============= unconfined_t ==============
allow unconfined_t oddjob_mkhomedir_exec_t:file entrypoint;
EOF

checkmodule -m -M -o mkhomedir.mod mkhomedir.te
semodule_package --outfile mkhomedir.pp --module mkhomedir.mod
semodule -i mkhomedir.pp


echo "CLIENT CONFIGURATION COMPLETED.IT IS ABSOLUTELY ESSENTIAL THOUGH THAT YOU MODIFY YOUR INTERFACE TO USE  THE DIRECTORY SERVER'S DNS @IP ADDRESS:${server} .THEN PLEASE REBOOT YOUR MACHINE AND LOGIN OR SSH TO YOUR MACHINE USING A REMOTE USERNAME.FURTHERMORE YOU CAN USE THE getent passwd COMMAND TO PROBE FOR USERS ON THE  REMOTE SERVER"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read key


:D :) :lol:


Last edited by alamahant on Sun Mar 29, 2020 9:38 pm; edited 20 times in total
Back to top
View user's profile Send private message
Hu
Administrator
Administrator


Joined: 06 Mar 2007
Posts: 22754

PostPosted: Wed Jan 15, 2020 1:53 am    Post subject: Re: Gentoo Directory Server Installation Script-B Reply with quote

alamahant wrote:
It seems that I had reached my quota of disk space or db entry limit for my post
Individual posts have a length limit, and threads have a maximum advisable length, but this one does not appear to be close to that limit.
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Wed Jan 15, 2020 2:06 am    Post subject: Reply with quote

My Dear Hu
I kept getting "posting error" however much I tried to append some code to the main script...
Thankssssssssss for the edit. :D
Yes how foolish of me.
I should have appended the rest in a comment rather than opening a new thread.
Thanks again........

:D
Back to top
View user's profile Send private message
ali3nx
l33t
l33t


Joined: 21 Sep 2003
Posts: 732
Location: Winnipeg, Canada

PostPosted: Tue Jan 28, 2020 4:06 am    Post subject: Reply with quote

Just wow. I'm completely impressed.

Github or gitlab repo as well as a gentoo ebuild or package for the intended purpose could be a great home for this.

Again bravo friend. those scripts are a text manipulation artwork 8O
_________________
Compiling Gentoo since version 1.4
Thousands of Gentoo Installs Completed
Emerged on every continent but Antarctica
Compile long and Prosper!
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Tue Jan 28, 2020 5:36 pm    Post subject: Reply with quote

Thanks a lot ali3nx.
Such a great encouragement from you..
Thanks again!

:D :) :)
Back to top
View user's profile Send private message
ali3nx
l33t
l33t


Joined: 21 Sep 2003
Posts: 732
Location: Winnipeg, Canada

PostPosted: Wed Jan 29, 2020 12:40 am    Post subject: Reply with quote

alamahant wrote:
Thanks a lot ali3nx.
Such a great encouragement from you..
Thanks again!

:D :) :)


Your welcome. when i get some free time in the near future i'll be sacrificing a systemd qemu gentoo vm to try this out.

learning ldap has been on my gentoo bucket list for too many years and this is more than adequate motivation
_________________
Compiling Gentoo since version 1.4
Thousands of Gentoo Installs Completed
Emerged on every continent but Antarctica
Compile long and Prosper!
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Sun Mar 15, 2020 11:42 pm    Post subject: Reply with quote

Hi Guys,
I have added a new function in the script.
It will install and configure a kerberos-shared Apache directory.
It uses Apache module "mod_auth_kerb".
It will ask the user for the name of the directory which will then serve from default(/var/www/localhost/htdocs) location as a sub directory of the default ssl virtual host.
It uses the SSL certs created during the openldap installation.
Only existing kerberos users will be allowed access after authenticating via username and password.

A NOTE ON ~amd USERS:
Although mod_auth_kerb was until recently working fine in ~amd ,lately for some obscure reason Apache cant load the module.
Maybe a future update will solve the issue.
"Stable" users however should face no problem whatsoever.....

Have Fun

:D :D :)
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Sat Mar 28, 2020 9:41 am    Post subject: Reply with quote

I have rectified some minor errors in the script including suppressing some unneeded output on the screen.
This way it looks neater.
:)


Code:



#!/bin/bash
##########  WRITTEN by alamahant on 9 January 2020 #############

[ ! -f /etc/resolv.conf.bak ] && cp -p /etc/resolv.conf /etc/resolv.conf.bak
[ ! -f /etc/hosts.bak ] && cp -p /etc/hosts /etc/hosts.bak
[ ! -f /etc/conf.d/hostname.bak ] && [ -f /etc/conf.d/hostname ] && cp -p /etc/conf.d/hostname /etc/conf.d/hostname.bak
[ ! -f /etc/hostname.bak ] && cp -p /etc/hostname /etc/hostname.bak

#if ! equery l '*' | grep sipcalc > /dev/null 2>&1;then emerge -aq sipcalc;fi
#if ! equery l '*' | grep net-tools > /dev/null 2>&1;then emerge -aq net-tools;fi
#if ! equery l '*' | grep gentoolkit > /dev/null 2>&1;then emerge -aq app-portage/gentoolkit;fi

emerge -DNaq sipcalc net-tools gentoolkit

clear
staticip () {
echo "IT IS ESSENTIAL TO CONFIGURE STATIC IP FOR YOUR MACHINE BEFORE PROCEEDING WITH THIS SCRIPT."
echo "IF YOUR MACHINE IS ALREADY CONFIGURED TO USE STATIC IP THEN PLEASE PRESS "y" TO CONTINUE"
echo "OTHERWISE PLEASE PRESS ANY OTHER KEY TO EXIT THE SCRIPT,CONFIGURE STATIC IP AND REBOOT YOUR MACHINE.";read line
[ ! $line == "y" ] && exit
}

staticip

echo "EXTRACTING NETWORK INFO AND NOMENCLATURE..."
###NETWORK INFO AND NOMENCLATURE
#myIP=$(hostname -i)
#myIP=$(ip -o addr show up primary scope global | while read -r num dev fam addr rest; do echo ${addr%/*}; done)
myIP=$(ip route get 8.8.8.8| grep src| sed 's/.*src \(.*\)$/\1/g' | awk '{ print $1 }')
#myFQDN=$(hostname)

setfqdn () {
clear
echo "DO YOU WISH TO SET YOUR FQDN? PLEASE PRESS "y" TO CONFIRM OR IF YOU HAVE ALREADY SET IT PRESS ANY OTHER KEY TO SKIP";read line
[ $line != "y" ] && return
echo "PLEASE SET YOUR FQDN IN THE FORMAT <machine-name>.<domain>.<dom>";read line
echo "DO YOU WISH YOUR FQDN TO BE ${line}? PLEASE ENTER 'y' TO CONFIRM";read confirm
[ $confirm != "y" ] && exit
echo $line > /etc/hostname&
pidof /sbin/init > /dev/null 2>&1 && [ -f /etc/conf.d/hostname ] && echo "hostname="$line"" > /etc/conf.d/hostname && echo 'rc_before="net.lo"' >> /etc/conf.d/hostname
rm /etc/hosts

cat >> /etc/hosts << EOF
127.0.0.1  localhost
$myIP   $line
EOF

pidof /sbin/init > /dev/null 2>&1 && hostname -F /etc/hostname > /dev/null 2>&1
pidof /lib/systemd/systemd > /dev/null 2>&1 && hostnamectl set-hostname $line

} ###Closing setfqdn


setfqdn
myFQDN=$(hostname)

myNETMASK=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $4 }')
#myDOMAIN=$(hostname -d) || myDOMAIN=$(dnsdomainname) || echo "THE SCRIPT ENCOUNTERED AN ERROR AND WILL EXIT.PLEASE FIX THE "hostname" COMMAND BECAUSE IT IS NOT FUNCTIONING PROPERLY"
myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
myMACHINE=$(echo $myFQDN | awk -F. '{ print $1 }')
myINADDR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $3"."$2"."$1 }')
mySERIAL=$(date '+%Y%m%d'01)
myPTR=$(ifconfig  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F. '{ print $4 }')
myNETWORK=$(sipcalc $(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }') | grep "Network address" | awk '{ print $4 }')
myCIDR=$(ip a  | grep $(echo $myIP | awk '{ print $1 }') | awk '{ print $2 }' | awk -F/ '{ print $2 }')
myDNS=$(ip route | grep default | awk '{ print $3 }')
myREALM=$(echo ${myDOMAIN^^})

c1=$(echo $myDOMAIN | awk -F. '{ print $1 }')
c2=$(echo $myDOMAIN | awk -F. '{ print $2 }')
c1=$(echo "${c1^}")
c2=$(echo "${c2^}")
c3=$(echo $c1 $c2)

#####DIRECTORIES
myDNSDIR="/var/bind"
myLDAPCONFDIR="/etc/openldap"
myLDAPDATADIR="/var/lib/openldap-data"
myKRB5DIR="/var/lib/krb5kdc"
###DAEMON NOMENCLATURE
myDNSSVCNAME="named"
myDNSPACKNAME="bind"
myKDCSVCNAME="mit-krb5kdc"
myKADMINSVCNAME="mit-krb5kadmind"




dnsinstall () {
clear
echo "PART 1: DNS BIND. PLEASE PRESS ANY KEY TO CONTINUE";read line
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl stop $myDNSSVCNAME
pidof /sbin/init > /dev/null 2>&1 && rc-service $myDNSSVCNAME stop
echo "REMOVING BIND AND PURGING ALL PREVIEWS CONFIGURATION..."
[ -d $myDNSDIR ] && rm  $myDNSDIR/*lan 
[ -d $myDNSDIR ] && rm  $myDNSDIR/*db
cp /etc/resolv.conf.bak /etc/resolv.conf
echo "INSTALLING AND CONFIGURING BIND..."
emerge -DNaq $myDNSPACKNAME
clear
[ ! -f /etc/bind/named.conf.bak ] && mv /etc/bind/named.conf /etc/bind/named.conf.bak
[ -f /etc/bind/named.conf ] && rm /etc/bind/named.conf
cat >> $myDNSDIR/$myDOMAIN.lan << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
         3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
        IN  A       $myIP

        IN  MX 10   $myFQDN.

$myMACHINE     IN  A       $myIP
EOF

cat >> $myDNSDIR/$myINADDR.db << EOF
\$TTL 86400
@   IN  SOA    $myFQDN. root.$myDOMAIN. (
        $mySERIAL            ;Serial
        3600        ;Refresh
        1800        ;Retry
        604800      ;Expire
        86400       ;Minimum TTL
)

        IN  NS     $myFQDN.
   IN  PTR    $myDOMAIN.
        IN  A       $myNETMASK



$myPTR     IN  PTR       $myFQDN.
EOF

cat >> /etc/bind/named.conf << EOF


acl "xfer" {
   127.0.0.0/8; $myNETWORK/$myCIDR;

};


acl "trusted" {
   127.0.0.0/8;
   $myNETWORK/$myCIDR;
};

options {
   directory "$myDNSDIR";
   pid-file "/run/named/named.pid";

   //bindkeys-file "/etc/bind/bind.keys";

   listen-on-v6 { none; };
   //listen-on { 127.0.0.1; };
   listen-on port 53 { any; };
   allow-query {
      trusted;
   };

   allow-query-cache {
      /* Use the cache for the "trusted" ACL. */
      trusted;
   };

   allow-recursion {
      /* Only trusted addresses are allowed to use recursion. */
      trusted;
   };

   allow-transfer {
      /* Zone tranfers are denied by default. */
      xfer;
   };

   allow-update {
      /* Don't allow updates, e.g. via nsupdate. */
      none;
   };


   forwarders { $myDNS; };

   dnssec-enable yes;
   dnssec-validation no;


};

logging {
   channel default_log {
      file "/var/log/named/named.log" versions 5 size 50M;
      print-time yes;
      print-severity yes;
      print-category yes;
   };

   category default { default_log; };
   category general { default_log; };
};


include "/etc/bind/rndc.key";
controls {
   inet 127.0.0.1 port 953 allow { 127.0.0.1/32; ::1/128; } keys { "rndc-key"; };
};

zone "." in {
   type hint;
   file "$myDNSDIR/named.cache";
};

zone "localhost" IN {
   type master;
   file "pri/localhost.zone";
   notify no;
};


zone "${myDOMAIN}" IN {
                type master;
                file "$myDOMAIN.lan";
                allow-update { none; };
        };
zone "${myINADDR}.in-addr.arpa" IN {
                type master;
                file "$myINADDR.db";
                allow-update { none; };
        };

EOF
#######################################

sed -i '/OPTIONS=/d' /etc/conf.d/named
echo 'OPTIONS="-4"' >> /etc/conf.d/named
if pidof /lib/systemd/systemd > /dev/null 2>&1
then
#sed -i 's/ExecStart=\/usr\/sbin\/named -f -u named/ExecStart=\/usr\/sbin\/named -f -4 -u named/g' /etc/systemd/system/named.service
sed -i 's/ExecStart=\/usr\/sbin\/named -f -u named/ExecStart=\/usr\/sbin\/named -f -4 -u named/g' /lib/systemd/system/named.service
systemctl daemon-reload
fi
chown root:named /etc/bind/named.conf
chown root:named $myDNSDIR/*lan
chown root:named $myDNSDIR/*db
rm /etc/hosts
cat >> /etc/hosts << EOF
127.0.0.1  localhost
EOF


[ ! -d /var/log/named ] && mkdir /var/log/named
[ ! -f /var/log/named/named.log ] && touch /var/log/named/named.log
chown named. /var/log/named/named.log
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl enable $myDNSSVCNAME && systemctl restart $myDNSSVCNAME
pidof /sbin/init > /dev/null 2>&1 && rc-update add $myDNSSVCNAME default && rc-service $myDNSSVCNAME restart
sed -i '/nameserver/d' /etc/resolv.conf
sed -i '/search/d' /etc/resolv.conf
echo "search  $myDOMAIN" >> /etc/resolv.conf
echo "nameserver 127.0.0.1" >> /etc/resolv.conf
clear
echo "DNS CONFIGURATION COMPLETED.PLEASE REMEMBER TO SET YOUR INTERFACES TO USE THE LOCAL SERVER 127.0.0.1 AS THE PRIMARY DNS SERVER"
echo "PRESS ANY KEY TO CONTUNUE";read line
}    ###closing dnsinstall ()


openldapinstall () {
clear
echo "PART 2: OPENLDAP SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line
clear
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl stop slapd > /dev/null 2>&1
pidof /sbin/init > /dev/null 2>&1 && rc-service slapd stop > /dev/null 2>&1
echo "REMOVING PREVIOUS LDAP CONFIG..."
rm -rf $myLDAPDATADIR/*mdb > /dev/null 2>&1
rm -rf $myLDAPCONFDIR/slap.conf > /dev/null 2>&1
rm -rf $myLDAPCONFDIR/slapd.d/* > /dev/null 2>&1
rm -rf $myLDAPCONFDIR/ssl/* > /dev/null 2>&1
rm -rf $myLDAPCONFDIR/ldifs/* > /dev/null 2>&1
[ -f /etc/profile.d/ldapuser.sh ] && rm /etc/profile.d/ldapuser.sh
echo "net-nds/openldap kerberos sha2 sasl -minimal samba" > /etc/portage/package.use/openldap
[ -f /etc/conf.d/slapd.bak ] && cp  /etc/conf.d/slapd.bak /etc/conf.d/slapd




 
emerge -DNaq net-nds/openldap

[ ! -f $myLDAPDATADIR/DB_CONFIG.example ] && cat >> $myLDAPDATADIR/DB_CONFIG.example << EOF

#
# Example DB_CONFIG file for use with slapd(8) BDB/HDB databases.
#
# See the Oracle Berkeley DB documentation
#   <http://www.oracle.com/technology/documentation/berkeley-db/db/ref/env/db_config.html>
# for detail description of DB_CONFIG syntax and semantics.
#
# Hints can also be found in the OpenLDAP Software FAQ
#   <http://www.openldap.org/faq/index.cgi?file=2>
# in particular:
#   <http://www.openldap.org/faq/index.cgi?file=1075>

# Note: most DB_CONFIG settings will take effect only upon rebuilding
# the DB environment.

# one 0.25 GB cache
set_cachesize 0 268435456 1

# Data Directory
#set_data_dir db

# Transaction Log settings
set_lg_regionmax 262144
set_lg_bsize 2097152
#set_lg_dir logs

# Note: special DB_CONFIG flags are no longer needed for "quick"
# slapadd(8) or slapindex(8) access (see their -q option).

EOF

###GET LDAP BASEDN FROM DOMAIN
echo "RECONFIGURING OPENLDAP SERVER..."

getdn () {
for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
do
dc=$(echo $myDOMAIN | cut -d "." -f $i)
if [ $i -eq 1 ]
then dn="dc="$dc

else dn=$dn,"dc="$dc
fi
done
echo  $dn
}  ###Closing getdn ()

myDN=$(getdn)


cp $myLDAPCONFDIR/DB_CONFIG.example $myLDAPCONFDIR/DB_CONFIG > /dev/null 2>&1 && chown ldap. $myLDAPCONFDIR/DB_CONFIG
cp $myLDAPDATADIR/DB_CONFIG.example $myLDAPDATADIR/DB_CONFIG > /dev/null 2>&1 && chown ldap. $myLDAPDATADIR/DB_CONFIG

[ ! -f /etc/conf.d/slapd.bak ] && cp -p /etc/conf.d/slapd /etc/conf.d/slapd.bak
[ -f $myLDAPCONFDIR/slapd.conf ] && rm $myLDAPCONFDIR/slapd.conf

cat >> $myLDAPCONFDIR/slapd.conf << EOF
include      $myLDAPCONFDIR/schema/core.schema
pidfile      /run/openldap/slapd.pid
argsfile   /run/openldap/slapd.args

modulepath   /usr/lib64/openldap/openldap
moduleload   back_passwd.so
moduleload   back_monitor.so
moduleload   back_mdb.so
moduleload   back_ldap.so
#moduleload   pw-kerberos.so
moduleload      pw-sha2.so

database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database monitor
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

database        mdb
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

suffix      "dc=my-domain,dc=com"
maxsize         10485760
checkpoint   32   30
rootdn      "cn=Manager,dc=my-domain,dc=com"
rootpw      secret
directory   $myLDAPDATADIR

index   objectClass   eq
index   uid             pres,eq
index   mail            pres,sub,eq
index   cn              pres,sub,eq
index   sn              pres,sub,eq
index   dc              eq

EOF
chown root:ldap $myLDAPCONFDIR/slapd.conf

pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl enable slapd && systemctl restart slapd
pidof /sbin/init > /dev/null 2>&1 && rc-service slapd start
chown -R ldap. $myLDAPDATADIR

rm /etc/conf.d/slapd > /dev/null 2>&1

cat >> /etc/conf.d/slapd << "EOF"
INSTANCE="openldap${SVCNAME#slapd}"
OPTS_CONF="-F /etc/${INSTANCE}/slapd.d"
OPTS="${OPTS_CONF} -h 'ldaps:// ldap:// ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock'"
#rc_need="!net net.lo"
EOF

[ ! -d $myLDAPCONFDIR/slad.d ] && mkdir $myLDAPCONFDIR/slapd.d
slaptest -f $myLDAPCONFDIR/slapd.conf  -F $myLDAPCONFDIR/slapd.d/ > /dev/null 2>&1
chown -R ldap. $myLDAPCONFDIR/slapd.d
chown -R ldap. $myLDAPDATADIR
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl restart slapd
pidof /sbin/init > /dev/null 2>&1 && rc-update add slapd default && rc-service slapd restart


echo "CREATING SSL CERTIFICATES FOR USE WITH YOUR OPENLDAP SERVER..."
cd /etc/ssl/private
openssl genrsa -aes128 -out server.key 2048
openssl rsa -in server.key -out server.key

clear

echo "PLEASE REMEMBER TO ENTER YOUR FQDN  ${myFQDN} WHEN PROMPTED FOR 'Common Name' PRESS ANY KEY TO CONTINUE";read line
openssl req -new -days 3650 -key server.key -out server.csr
openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650
[ ! -d $myLDAPCONFDIR/ssl ] && mkdir $myLDAPCONFDIR/ssl

cp /etc/ssl/private/server* $myLDAPCONFDIR/ssl/
cp /etc/ssl/certs/ca-certificates.crt $myLDAPCONFDIR/ssl/
chown -R ldap. $myLDAPCONFDIR/ssl

[ ! -d $myLDAPCONFDIR/ldifs ] && mkdir $myLDAPCONFDIR/ldifs
cd $myLDAPCONFDIR/ldifs

clear
echo "YOU WILL BE PROMPTED FOR THE OPENLDAP ADMINISTRATIVE ACCOUNT "cn=Manager,${myDN}"  PASSWORD."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line
myPASS=$(echo $(slappasswd))

cat >> chrootpw.ldif << EOF
dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: $myPASS
EOF

ldapadd -Y EXTERNAL -H ldapi:/// -f chrootpw.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f $myLDAPCONFDIR/schema/inetorgperson.ldif

cat >> chdomain.ldif << EOF
dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth"
  read by dn.base="cn=Manager,${myDN}" read by * none

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: $myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=Manager,$myDN

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: $myPASS

dn: olcDatabase={2}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by
  dn="cn=Manager,${myDN}" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=Manager,${myDN}" write by * read
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f chdomain.ldif

cat >> basedomain.ldif << EOF
dn: $myDN
objectClass: top
objectClass: dcObject
objectclass: organization
o: $c3
dc: $c1

dn: cn=Manager,$myDN
objectClass: organizationalRole
cn: Manager
description: Directory Manager

dn: ou=People,$myDN
objectClass: organizationalUnit
ou: People

dn: ou=Group,$myDN
objectClass: organizationalUnit
ou: Group

dn: ou=sudoers,$myDN
objectClass: organizationalUnit
ou: sudoers

dn: cn=ldapusers,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber: 10000
cn: ldapusers     
EOF

ldapadd -x -D "cn=Manager,${myDN}" -W -f basedomain.ldif


cat >> addgroup.lfif << EOF
dn: cn=,ou=Group,$myDN
objectClass: top
objectClass: posixGroup
gidNumber:
EOF


cat >> adduser.ldif << EOF
dn: uid=,ou=People,dc=,dc=
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn:
sn:
givenName:
userPassword:
loginShell: /bin/bash
uidNumber:
gidNumber: 10000
homeDirectory: /home/

dn: cn=,ou=Group,dc=,dc=
objectClass: posixGroup
cn:
gidNumber: 10000
memberUid:
EOF

##############################################

[ -f $myDNSDIR/dns-record ] && rm $myDNSDIR/dns-record
cat >> $myDNSDIR/dns-record << "EOF"
#!/bin/bash
###Written by alamahant on 24/12/19.This simple script will add A and PTR records to BIND
###Use the script thus "sudo bash dns-record <machine-name>  <IP>".
#[ -z $1 ] || [ -z $2 ] && echo "USAGE dns-record <HOST-NAME> <IP-ADDRESS>" && exit
#myCIDR=$(echo $2 | awk -F. '{ print $4 }')
#myDOMAIN=$(hostname -d)
#mySVCDIR="/var/bind"
#mySVCNAME="named"
#if ! $(cat $mySVCDIR/*lan | grep $1 > /dev/null 2>&1)  && ! $(cat $mySVCDIR/*lan | grep $2 > /dev/null 2>&1) 
#then
#echo "$1    IN A      $2" >> $mySVCDIR/*lan
#echo "$myCIDR    IN PTR      $1.$myDOMAIN" >> $mySVCDIR/*db
#pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl reload $mySVCNAME
#pidof /sbin/init > /dev/null 2>&1 && service $mySVCNAME reload
#echo "Host $1 with IP $2 added to Bind"
#elif $(cat $mySVCDIR/*lan | grep $1 > /dev/null 2>&1)
#then
#echo "Host already exists"
#else echo "IP is taken"
#fi
EOF
sed -i 's/^#//g' $myDNSDIR/dns-record
chmod +x $myDNSDIR/dns-record
#########################################################

####################################################
cat >> ldapuser.sh << "EOF"
##!/bin/bash
#
################### WRITTEN BY ALAMAHANT on 09/01/2020 ###########################
#
#
#if [ ! -f /etc/profile.d/ldapuser.sh ]
#then
#echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
#echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
#fi
#clear
#source /etc/profile.d/ldapuser.sh
#
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
#
#
#echo "ADDING USER WITH UID" $uidserial
#
#myFQDN=$(hostname)
#myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
#myREALM=$(echo ${myDOMAIN^^})
#getdn () {
#for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
#do
#dc=$(echo $myDOMAIN | cut -d "." -f $i)
#if [ $i -eq 1 ]
#then dn="dc="$dc
#
#else dn=$dn,"dc="$dc
#fi
#done
#echo  $dn
#}  ###Closing getdn ()
#
#myDN=$(getdn)
#
#addldapuser () {
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
#echo "first name";read givenName
#echo "last name";read sn
#echo "password";read passwd
#echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
#[ ! $line == "y" ] && return
#myPASS=$(slappasswd -s $passwd)
#
#cat > ldapuser.ldif << EOF
#dn: uid=$givenName.$sn,ou=People,$myDN
#objectClass: inetOrgPerson
#objectClass: posixAccount
#objectClass: shadowAccount
#cn: $givenName $sn
#sn: $sn
#givenName: $givenName
#userPassword: $myPASS
#loginShell: /bin/bash
#uidNumber: $uidserial
#gidNumber: 10000
#homeDirectory: /home/$givenName.$sn
#
#EOF
#
#if ldapadd -x -D cn=Manager,$myDN -W -f ldapuser.ldif
#then
#let "uidserial=uidserial+1"
#sed -i '/export/d' /etc/profile.d/ldapuser.sh
#echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
#echo "ADDED LDAP USER" $givenName.$sn
#echo "HERE ARE THE DETAILS:"
#echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
#echo ""
#
#if kadmin.local listprincs | grep  ${givenName}.${sn} > /dev/null 2>&1
#then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
#else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
#echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
#fi
#
#else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
#fi
#
#} ####Closing addldapuser
#
#addldapuser
#
EOF
sed -i 's/^#//g' ldapuser.sh
chmod +x ldapuser.sh
##################################################################

####################################################################
cat >> bulkusers.sh << "EOF"
##!/bin/bash
#
################### WRITTEN BY ALAMAHANT on 09/01/2020 ###########################
#if [ ! -f /etc/profile.d/ldapuser.sh ]
#then
#echo "#/bin/bash" > /etc/profile.d/ldapuser.sh
#echo "export uidserial=10001" >> /etc/profile.d/ldapuser.sh
#fi
#
#
#source /etc/profile.d/ldapuser.sh
#
#
#myFQDN=$(hostname)
#myDOMAIN=$(echo $myFQDN | awk -F. '{ print $2"."$3 }')
#myREALM=$(echo ${myDOMAIN^^})
#getdn () {
#for ((i=1; i<=$(echo $myDOMAIN | awk -F. '{ print NF; end}'); i++))
#do
#dc=$(echo $myDOMAIN | cut -d "." -f $i)
#if [ $i -eq 1 ]
#then dn="dc="$dc
#
#else dn=$dn,"dc="$dc
#fi
#done
#echo  $dn
#}  ###Closing getdn ()
#
#myDN=$(getdn)
#
#addldapuser () {
#echo "ADDING USER WITH UID" $uidserial
#[ -f ldapuser.ldif ] && rm ldapuser.ldif
##echo "PEASE PRESS "y" TO CONFIRM ADDITION OF USER";read line
##[ ! $line == "y" ] && return
#myPASS=$(slappasswd -s $passwd)
#
#cat > ldapuser.ldif << EOF
#dn: uid=$givenName.$sn,ou=People,$myDN
#objectClass: inetOrgPerson
#objectClass: posixAccount
#objectClass: shadowAccount
#cn: $givenName $sn
#sn: $sn
#givenName: $givenName
#userPassword: $myPASS
#loginShell: /bin/bash
#uidNumber: $uidserial
#gidNumber: 10000
#homeDirectory: /home/$givenName.$sn
#
#EOF
#
#if ldapadd -x -D cn=Manager,$myDN -w $adminpasswd  -f ldapuser.ldif
#then
#let "uidserial=uidserial+1"
#sed -i '/export/d' /etc/profile.d/ldapuser.sh
#echo "export uidserial=${uidserial}" >> /etc/profile.d/ldapuser.sh && source /etc/profile.d/ldapuser.sh
#echo "ADDED LDAP USER" $givenName.$sn
##echo "HERE ARE THE DETAILS:"
##echo -e "$(slapcat -s uid=$givenName.$sn,ou=People,$myDN)\n"
#echo ""
#
#if kadmin.local listprincs | grep  ${givenName}.${sn} > /dev/null 2>&1
#then echo "KERBEROS PRINCIPAL "$givenName.$sn@$myREALM" ALREADY EXISTS IN THE KERBEROS DATABASE"
#else kadmin.local ank -pw ${passwd} ${givenName}.${sn}
#echo "ADDED KERBEROS PRINCIPAL" $givenName.$sn@$myREALM
#echo ""
#fi
#
#else echo "USER ALREADY EXISTS OR LDAP SERVER MISCONFIGURATION ERROR" && exit
#fi
#
#} ####Closing addldapuser
#
#
#echo "PLEASE PROVIDE THE ABSOLUTE PATH OF THE FILE CONTAINING THE USERS TO BE ADDED TO THE OPENLDAP DATABASE"
#echo "THE FILE SHOULD CONTAIN ONE USER PER LINE IN THE FORMAT:"
#echo "firstname surname password"; read file
#[ ! -f $file ] && echo "NO SUSCH FILE.EXITING......" && exit
#echo "PLEASE PROVIDE THE PASSWORD FOR THE ADMINISTRATIVE ACCOUNT cn=Manager,$myDN"; read adminpasswd
#
#clear
#while read -r line
#do
#givenName=$(echo $line | awk '{ print $1 }')
#sn=$(echo $line | awk '{ print $2 }')
#passwd=$(echo $line | awk '{ print $3 }')
#addldapuser
#done < $file
#
EOF
sed -i 's/^#//g' bulkusers.sh
chmod +x bulkusers.sh
#################################################################


cat >> mod_ssl.ldif << EOF
dn: cn=config
changetype: modify
add: olcTLSCACertificateFile
olcTLSCACertificateFile: $myLDAPCONFDIR/ssl/ca-certificates.crt
-
replace: olcTLSCertificateFile
olcTLSCertificateFile: $myLDAPCONFDIR/ssl/server.crt
-
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: $myLDAPCONFDIR/ssl/server.key
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f mod_ssl.ldif

sleep 3

rm $myLDAPCONFDIR/ldap.conf > /dev/null 2>&1
cat >> $myLDAPCONFDIR/ldap.conf << EOF
BASE   $myDN
URI    ldap://$myFQDN ldaps://$myFQDN ldapi:///

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# TLS certificates (needed for GnuTLS)
TLS_CACERT      /etc/ssl/certs/ca-certificates.crt
TLS_REQCERT allow
EOF

chown ldap. $myLDAPCONFDIR/ldap.conf

pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl restart slapd
pidof /sbin/init > /dev/null 2>&1 && rc-service slapd restart

clear
echo "PART 2: OPENLDAP SERVER COMPLETED."
echo "YOU CAN NOW TEST THE FUNCTIONALITY OF YOUR OPENLDAP SERVER BY ISSUING:"
echo "slapcat"
echo "ldapsearch -x -b $myDN -H ldap://$myFQDN/"
echo "ldapsearch -x -D cn=Manager,$myDN -b $myDN -H ldaps://$myFQDN/ -W"
echo "ldapsearch -x -b $myDN -H ldapi:///"
echo "etc etc etc"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line

}   ###closing openldapinstal ()


krb5install () {
clear
echo "PART 3: KERBEROS.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS KERBEROS CONFIGURATION..."

echo "app-crypt/mit-krb5  openldap" > /etc/portage/package.use/mit-krb5
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl stop $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init > /dev/null 2>&1 && rc-service $myKDCSVCNAME stop && rc-service $myKADMINSVCNAME stop

rm -rf $myKRB5DIR/* > /dev/null 2>&1

emerge -DNaq mit-krb5
echo "RECONFIGURING KERBEROS..."

[ ! -e /etc/krb5.conf.bak ] && cp /etc/krb5.conf /etc/krb5.conf.bak
rm /etc/krb5.conf > /dev/null 2>&1
rm /etc/krb5.keytab > /dev/null 2>&1


cat >> /etc/krb5.conf << EOF
[libdefaults]
   default_realm = $myREALM
   kdc_timesync = 1
   ccache_type = 4
   forwardable = true
   proxiable = true
   dns_lookup_realm = false
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = true
    rdns = false
   pkinit_anchors = /etc/ssl/certs/ca-certificates.crt
    default_ccache_name = KEYRING:persistent:%{uid}

   fcc-mit-ticketflags = true

[realms]
   $myREALM = {
      kdc = $myFQDN
      admin_server = $myFQDN
   }
[domain_realm]
   .$myDOMAIN = $myREALM
   $myDOMAIN = $myREALM

EOF

cat >> $myKRB5DIR/kdc.conf << EOF
[kdcdefaults]
    kdc_ports = 750,88

[realms]
    $myREALM = {
        database_name = $myKRB5DIR/principal
        admin_keytab = FILE:$myKRB5DIR/kadm5.keytab
        acl_file = $myKRB5DIR/kadm5.acl
        key_stash_file = $myKRB5DIR/stash
        kdc_ports = 750,88
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        master_key_type = des3-hmac-sha1
        #supported_enctypes = aes256-cts:normal aes128-cts:normal
        default_principal_flags = +preauth
    }

EOF

echo "*/admin@${myREALM} *" > $myKRB5DIR/kadm5.acl
echo "YOU WILL BE PROMPTED FOR KERBEROS DB ROOT PASSWD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kdb5_util create -s -r ${myREALM}
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl enable $myKDCSVCNAME $myKADMINSVCNAME  && systemctl restart $myKDCSVCNAME $myKADMINSVCNAME
pidof /sbin/init > /dev/null 2>&1 && rc-update add $myKDCSVCNAME default && rc-update add  $myKADMINSVCNAME default && rc-service $myKDCSVCNAME restart && rc-service $myKADMINSVCNAME restart
kadmin.local ank -randkey host/${myFQDN} >> /dev/nul
kadmin.local ktadd host/${myFQDN} > /dev/null 2>&1
echo "YOU WILL BE PROMPTED FOR KERBEROS ADMIN USER root/admin PASSWORD.PLEASE PRESS ANY KEY TO CONTINUE";read line
kadmin.local ank root/admin
kadmin.local ank root
clear
echo "PART 3: KERBEROS COMPLETED"
echo "YOU MAY USE THE KRB5KDC AND KADMIN SERVERS TO MANAGE YOUR REALM"
echo "SOME USEFUL COMMANDS:"
echo "kadmin.local ank -pw <passwd> <principal>"
echo "kadmin.local ank -randkey host/FQDN"
echo "kadmin.local ktadd service/FQDN"
echo "kadmin.local listprincs"
echo "kadmin.local delprinc <principal>"
echo "PLEASE PRESS ANY KEY TO CONTINUE";read key
} ###Closing krb5installl


nfsinstall () {
clear
echo "PART 4: KERBERISED NFS-SERVER.PLEASE PRESS ANY KEY TO CONTINUE";read line
echo "REMOVING PREVIOUS NFS CONFIGURATION..."
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl stop nfs-server rpcbind
pidof /sbin/init > /dev/null 2>&1 && rc-service nfs stop && rc-service rpcbind stop
rm -rf /srv/nfs
echo "net-fs/nfs-utils kerberos ldap nfsv4" > /etc/portage/package.use/nfs-utils
echo "net-libs/libtirpc kerberos" > /etc/portage/package.use/libtirpc
 
emerge -DNaq nfs-utils
echo "RECONFIGURING NFS-SERVER..."

###########################
nfsdir () {
echo 'NFS SERVER WILL SHARE A PRIVATE DIRECTORY WITH KERBEROS SECURITY sec=krb5p UNDER "/srv/nfs".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "NFS SERVER WILL SHARE "/srv/nfs/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && nfsdir
export nfsDIR=${private}
}  ####Closing nfsdir
nfsdir

##########################

sed -i '/srv/d' /etc/exports
mkdir -p /srv/nfs/$nfsDIR > /dev/null 2>&1 && chmod -R 777 /srv/nfs > /dev/null 2>&1
[ ! -f /etc/idmapd.conf.bak ] && mv  /etc/idmapd.conf /etc/idmapd.conf.bak
rm /etc/idmapd.conf

################################
cat >> /etc/idmapd.conf << EOF
[General]

Verbosity = 0
#Pipefs-Directory = /run/rpc_pipefs
# set your own domain here, if it differs from FQDN minus hostname
Domain = $myDOMAIN

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup

EOF
echo "/srv/nfs *(rw,sec=krb5p,fsid=0,insecure)" >> /etc/exports
echo "/srv/nfs/$nfsDIR *(rw,sec=krb5p,nohide,insecure)" >> /etc/exports
[ ! -f /etc/conf.d/nfs.bak ] && cp -p /etc/conf.d/nfs /etc/conf.d/nfs.bak
sed -i '/NFS_NEEDED_SERVICES=/d' /etc/conf.d/nfs
echo "NFS_NEEDED_SERVICES="rpc.idmapd rpc.gssd rpc.svcgssd"" >> /etc/conf.d/nfs
pidof /lib/systemd/systemd > /dev/null 2>&1 && systemctl enable --now rpcbind nfs-server && systemctl restart rpcbind nfs-server
if pidof /sbin/init > /dev/null 2>&1
then
rc-update add rpcbind default
rc-update add nfs default
rc-update add nfsclient default
rpc.idmapd
rpc.svcgssd
rc-service nfs restart
rpc.gssd
rc-service nfsclient restart
fi
exportfs -avr
kadmin.local ank -randkey nfs/${myFQDN} > /dev/null 2>&1
kadmin.local ktadd nfs/${myFQDN} > /dev/null 2>&1
clear
echo "PART 4: KERBERISED NFS-SERVER COMPLETED"
echo "AFTER REBOOTING YOUR MACHINE YOU CAN MOUNT /srv/nfs/$nfsDIR BY ISSUING:"
echo "kinit"
echo "systemctl start nfs-client.target"
echo "mount -t nfs4 -o sec=krb5p ${myFQDN}:/$nfsDIR /mnt"
echo "PLEASE REMEMBER TO CREATE PRINCIPALS FOR YOUR USERS IN KERBEROS."
echo "PLEASE PRESS ANY KEY TO CONTINUE";read line


}  ###Closing nfsinstall
###########################

##########################
sambainstall () {
clear
echo "PART 5: SAMBA SERVER CONFIGURATION.............."
emerge -DNaq samba
echo "REMOVING PREVIOUS SAMBA CONFIGURATION..."
if ! cat /etc/group | grep smbprivate > /dev/null 2>&1;then groupadd -g 3000 smbprivate;fi

sharedir () {
echo 'SAMBA SERVER WILL SHARE A READ-ONLY OPEN-TO ALL DIRECTORY UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read dir
echo "SAMBA SERVER WILL SHARE "/srv/samba/$dir" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbshare=${dir}
echo 'SAMBA SERVER WILL SHARE A PRIVATE DIRECTORY TO BE USED ONLY BY THE GROUP "smbprivate" UNDER "/srv/samba".PLEASE CHOOSE THE DESIRED NAME FOR THIS DIRECTORY';read private
echo "SAMBA SERVER WILL SHARE "/srv/samba/$private" PLEASE PRESS "y" TO CONFIRM";read line
[ ! $line == "y" ] && sharedir
export smbprivate=${private}
}  ####Closing sharedir
sharedir

myIFACE=$(ip a  | grep $myIP | awk '{ print $2 }')
myHOSTS=$(echo $myNETWORK | awk -F. '{ print $1"."$2"."$3"." }')

[ -d /srv/samba ] && rm -rf /srv/samba
[ -f /etc/samba/smb.conf ] && rm /etc/samba/smb.conf
mkdir -p /srv/samba/$smbshare
mkdir -p /srv/samba/$smbprivate
chmod -R 777 /srv/samba

cat >> /etc/samba/smb.conf << EOF
#======================= Global Settings =====================================
[global]

   workgroup = MYGROUP

   server string = Samba Server

   server role = standalone server

   hosts allow =  $myHOSTS 127.

   guest account = nobody

#   log file = /var/log/samba/log.%m

   max log size = 50

   passdb backend = tdbsam

;   include = /etc/samba/smb.conf.%m

   interfaces = $myIFACE 127.0.0.1/24

;   logon path = \\%L\Profiles\%U

;   wins support = yes

;   wins server = w.x.y.z

;   wins proxy = yes

   dns proxy = no

;  add user script = /usr/sbin/useradd %u
;  add group script = /usr/sbin/groupadd %g
;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
;  delete user script = /usr/sbin/userdel %u
;  delete user from group script = /usr/sbin/deluser %u %g
;  delete group script = /usr/sbin/groupdel %g

map to guest = Bad User
server min protocol = SMB3
smb encrypt = desired
unix charset = UTF-8
dos charset = CP932

load printers = no
  printing = bsd
  printcap name = /dev/null
  disable spoolss = yes
  show add printer wizard = no

#============================ Share Definitions ==============================
[homes]
   comment = Home Directories
   browseable = no
   writable = no
   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
; [netlogon]
;   comment = Network Logon Service
;   path = /var/lib/samba/netlogon
;   guest ok = yes
;   writable = no
;   share modes = no


# Un-comment the following to provide a specific roving profile share
# the default is to use the user's home directory
;[Profiles]
;    path = /var/lib/samba/profiles
;    browseable = no
;    guest ok = yes


# NOTE: If you have a BSD-style print system there is no need to
# specifically define each individual printer
[printers]
   comment = All Printers
   path = /var/spool/samba
   browseable = no
# Set public = yes to allow user 'guest account' to print
   guest ok = no
   writable = no
   printable = yes

# This one is useful for people to share files
;[tmp]
;   comment = Temporary file space
;   path = /tmp
;   read only = no
;   public = yes

# A publicly accessible directory, but read only, except for people in
# the "staff" group
;[public]
;   comment = Public Stuff
;   path = /home/samba
;   public = yes
;   writable = no
;   printable = no
;   write list = @staff

# Other examples.
#
# A private printer, usable only by fred. Spool data will be placed in fred's
# home directory. Note that fred must have write access to the spool directory,
# wherever it is.
;[fredsprn]
;   comment = Fred's Printer
;   valid users = fred
;   path = /homes/fred
;   printer = freds_printer
;   public = no
;   writable = no
;   printable = yes

# A private directory, usable only by fred. Note that fred requires write
# access to the directory.
;[fredsdir]
;   comment = Fred's Service
;   path = /usr/somewhere/private
;   valid users = fred
;   public = no
;   writable = yes
;   printable = no

# a service which has a different directory for each machine that connects
# this allows you to tailor configurations to incoming machines. You could
# also use the %U option to tailor it by user name.
# The %m gets replaced with the machine name that is connecting.
;[pchome]
;  comment = PC Directories
;  path = /usr/pc/%m
;  public = no
;  writable = yes

# A publicly accessible directory, read/write to all users. Note that all files
# created in the directory by users will be owned by the default user, so
# any user with access can delete any other user's files. Obviously this
# directory must be writable by the default user. Another user could of course
# be specified, in which case all files would be owned by that user instead.
;[public]
;   path = /usr/somewhere/else/public
;   public = yes
;   only guest = yes
;   writable = yes
;   printable = no

# The following two entries demonstrate how to share a directory so that two
# users can place files there that will be owned by the specific users. In this
# setup, the directory should be writable by both users and should have the
# sticky bit set on it to prevent abuse. Obviously this could be extended to
# as many users as required.
;[myshare]
;   comment = Mary's and Fred's stuff
;   path = /usr/somewhere/shared
;   valid users = mary fred
;   public = no
;   writable = yes
;   printable = no
;   create mask = 0765

[$smbprivate]
path = /srv/samba/$smbprivate
guest ok = no
valid users = root @smbprivate
writable = yes
write list = root @smbprivate
create mask = 0664
force create mode = 0644
directory mask = 2775
force directory mode = 2775

[$smbshare]
path = /srv/samba/$smbshare
guest ok = yes
guest only = yes
read only = yes
create mode = 0777
directory mode = 0777


EOF
if pidof /lib/systemd/systemd > /dev/null 2>&1
then
systemctl enable --now smbd nmbd
systemctl restart smbd nmbd
sleep 3
fi

if pidof /sbin/init > /dev/null 2>&1
then
rc-update add samba default
rc-service samba restart
sleep 3
fi


clear
echo "SAMBA CONFIGURATION COMPLETED.PLEASE REMEMBER TO ADD USERS TO THE "smbprivate" GROUP WITH  gid 3000 TO ENABLE THEM TO ACCESS THE $smbprivate DIRECTORY"
echo "MAKE SURE TO ADD THIS GROUP TO ALL CLIENT MACHINES THAT NEED ACCESS TO THE $smbprivate DIRECTORY"
echo "PLEASE USE smbpasswd -a TO ADD USERS TO SAMBA"
echo "PRESS ANY KEY TO CONTINUE";read line

}   ###Closing sambainstall

################################################

##############################
ntpinstall () {
clear
echo "INSTALLING NTP TIME SERVER..."
if ! equery l '*' | grep net-misc/ntp > /dev/null 2>&1;then emerge -DNaq net-misc/ntp;fi
if pidof /lib/systemd/systemd > /dev/null 2>&1;then systemctl enable --now ntpd && systemctl restart ntpd;fi
if pidof /sbin/init > /dev/null 2>&1
then
rc-update add ntpd default
rc-service ntpd restart
fi

hwclock --systohc
sleep 3
clear
echo "NTP TIME SERVER INSTALLATION COMPLETE.PLEASE PRESS ANY KEY TO CONTINUE";read line
}  ############Closing ntpinstall()
#####################################

apache2install () {

clear
echo "CONFIGURING APACHE......"
echo "REMOVING PREVIOUS APACHE CONFIG AND RECONFIGURING APACHE.PRESS y TO CONTINUE ";read confirm

if [ ! $confirm == "y" ]
then echo "ABORTING....."
exit
fi

if pidof /lib/systemd/systemd > /dev/null 2>&1;then systemctl stop apache2 > /dev/null 2>&1;fi
if pidof /sbin/init > /dev/null 2>&1
then
rc-service apache2 stop > /dev/null 2>&1
fi
emerge -DNaq apache mod_auth_kerb

clear

[ ! -f /etc/conf.d/apache2.bak ] && mv /etc/conf.d/apache2 /etc/conf.d/apache2.bak > /dev/null 2>&1
[ -f /etc/apache2/krb5dir.info ] && krb5dir=$(cat /etc/apache2/krb5dir.info) && rm -rf /var/www/localhost/htdocs/$krb5dir
[ ! -f /etc/apache2/modules.d/11_mod_auth_kerb.conf.bak ] && mv /etc/apache2/modules.d/11_mod_auth_kerb.conf /etc/apache2/modules.d/11_mod_auth_kerb.conf.bak
[ ! -f /etc/apache2/vhosts.d/00_default_ssl_vhost.conf.bak ] && mv /etc/apache2/vhosts.d/00_default_ssl_vhost.conf /etc/apache2/vhosts.d/00_default_ssl_vhost.conf.bak
rm /etc/conf.d/apache2 > /dev/null 2>&1
rm /etc/apache2/vhosts.d/00_default_ssl_vhost.conf > /dev/null 2>&1
rm /etc/apache2/modules.d/11_mod_auth_kerb.conf > /dev/null 2>&1

echo "APACHE WILL SERVE A KERBEROS PROTECTED DIRECTORY FROM THE DEFAULT LOCATION OF /var/www/localhost/htdocs"
echo "PLEASE CHOOSE THE NAME OF THIS DIRECTORY ";read krb5dir
echo "APACHE WILL SHARE THE /var/www/localhost/htdocs/$krb5dir DIRECTORY.PLEASE PRESS y TO CONFIRM ";read confirm


if [ $confirm != "y" ]
then echo "ABORTING....."
exit
fi

mkdir /var/www/localhost/htdocs/$krb5dir

cat >> /var/www/localhost/htdocs/$krb5dir/index.html << EOF
Welcome to Kerberos-shared /var/www/localhost/htdocs/$krb5dir Directory

This page uses the Apache module  mod_auth_kerb to authenticate and allow access to only existing kerberos users.
You may wish to symlink files that you wish to share,create directories and html files and even have a whole "inner" private and secure site served from here.It uses the SSL certificates we created during ldap installation and as a result you will get an SSL warning from firefox when trying to access it.For testing pupropses its ok but in production you may wish to use some proper SSL certs i.e. Letsencrypt etc.
EOF

cat >> /etc/apache2/vhosts.d/00_default_ssl_vhost.conf << EOF
<IfDefine SSL>
<IfDefine SSL_DEFAULT_VHOST>
<IfModule ssl_module>

Listen 443

<VirtualHost _default_:443>
   ServerName $myDOMAIN
   Include /etc/apache2/vhosts.d/default_vhost.include
   ErrorLog /var/log/apache2/ssl_error_log

   <IfModule log_config_module>
      TransferLog /var/log/apache2/ssl_access_log
   </IfModule>

   SSLEngine on

   SSLProtocol ALL -SSLv2 -SSLv3

   SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128:AES256:HIGH:!RC4:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK

   SSLHonorCipherOrder On

   SSLCertificateFile /etc/ssl/private/server.crt

   SSLCertificateKeyFile /etc/ssl/private/server.key


   SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt

   <FilesMatch "\.(cgi|shtml|phtml|php)$">
      SSLOptions +StdEnvVars
   </FilesMatch>

   <Directory "/var/www/localhost/cgi-bin">
      SSLOptions +StdEnvVars
   </Directory>




   <IfModule log_config_module>
      CustomLog /var/log/apache2/ssl_request_log \
         "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
   </IfModule>


<Directory /var/www/localhost/htdocs/$krb5dir>
    SSLRequireSSL
    AuthType Kerberos
    AuthName "Kerberos Authentication"
    KrbAuthRealms $myREALM
    Krb5Keytab /etc/apache2/.HTTP.keytab
    KrbMethodNegotiate On
    KrbMethodK5Passwd On
    KrbServiceName HTTP/$myFQDN
    KrbSaveCredentials Off
    KrbVerifyKDC Off
    Require valid-user
</Directory>

</VirtualHost>
</IfModule>
</IfDefine>
</IfDefine>
EOF

cat >> /etc/conf.d/apache2 << EOF
APACHE2_OPTS="-D INFO -D SSL -D SSL_DEFAULT_VHOST -D LANGUAGE -D AUTH_KERB"
EOF

cat >> /etc/apache2/modules.d/11_mod_auth_kerb.conf << EOF
<IfDefine AUTH_KERB>
LoadModule auth_kerb_module modules/mod_auth_kerb.so
</IfDefine>
EOF

if kadmin.local listprincs | grep HTTP > /dev/null 2>&1
then princ=$(kadmin.local listprincs | grep HTTP)
kadmin.local delprinc $princ > /dev/null 2>&1
fi

kadmin.local addprinc -randkey HTTP/$myFQDN
kadmin.local ktadd -k /etc/apache2/.HTTP.keytab HTTP/$myFQDN > /dev/null 2>&1

echo "$krb5dir" > /etc/apache2/krb5dir.info

if pidof /lib/systemd/systemd > /dev/null 2>&1;then systemctl enable apache2 > /dev/null 2>&1 && systemctl start apache2;fi
if pidof /sbin/init > /dev/null 2>&1
then
rc-service apache2 restart > /dev/null 2>&1
fi

clear

echo "APACHE CONFIGURATION COMPLETE.PLEASE OPEN A WEB BROWSER AND NAVIGATE TO https://$myDOMAIN/$krb5dir"
echo "AUTHENTICATING WITH AN EXISTING KERBEROS USER AND PASSWORD.OR YOU MAY WISH TO OPEN A NEW TERMINAL OR SSH SESSION AND ADD A USER NOW BY RUNNING  sudo kadmin.local ank -pw <password> <username> FURTHERMORE IF YOU ARE NOT ACCESSING THE WEB PAGE LOCALLY THEN PLEASE MAKE SURE THAT IT IS RESOLVABLE EITHER THROUGH A DNS ENTRY OR VIA AN ENTRY IN /etc/hosts.......PLEASE PRESS ANY KEY TO CONTINUE ";read key
}


dnsinstall
openldapinstall
krb5install
nfsinstall
sambainstall
ntpinstall
apache2install



Last edited by alamahant on Sat Apr 04, 2020 12:10 pm; edited 6 times in total
Back to top
View user's profile Send private message
Ant P.
Watchman
Watchman


Joined: 18 Apr 2009
Posts: 6920

PostPosted: Sat Mar 28, 2020 10:37 pm    Post subject: Reply with quote

Forum threads are generally a poor way of implementing version control.
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Sun Mar 29, 2020 1:22 am    Post subject: Reply with quote

Understood............
:)
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Wed Jan 06, 2021 2:05 pm    Post subject: Reply with quote

I was amazed to find today that the client script still works.
There was a minor mistake that i corrected.
I know @Ant P. advised me otherwise so i will move the whole scri[ts to github where i will update them to work with the new pam password quality modules.
Anyhow i am happy that i revisited my old scripts...
_________________
:)
Back to top
View user's profile Send private message
pjp
Administrator
Administrator


Joined: 16 Apr 2002
Posts: 20499

PostPosted: Wed Jan 06, 2021 8:43 pm    Post subject: Reply with quote

alamahant,

Some day I'll get around to adapting this.

I see a possible error when you use 'pidof /sbin/init' to determine if something should execute. (Ref: March 2020 post/script)

pidof should return a list of PIDs, which you discard. However, the test seems to fail by not matching /sbin/init exactly.

For demonstration, I'm not discarding the PIDs:
Code:
$ pidof crond && echo "running" || echo "not running"
5103
running
$ pidof /sbin/init && echo "running" || echo "not running"
not running
$ pidof init && echo "running" || echo "not running"
1
running


Maybe whether to match against init or /sbin/init depends on the system?
Code:
$ ps -p1 -o uid,pid,ppid,comm=
  UID   PID  PPID
    0     1     0 init

_________________
Quis separabit? Quo animo?
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Wed Jan 06, 2021 9:51 pm    Post subject: Reply with quote

@pip
Thanks a lot for your valuable insight.
I guess I was trying to make the script applicable both to systemd and openrc Gentoos
I think now a more appropriate way to express this would be
Code:

[ -f /lib/systemd/systemd ] && systemctl.............
[ ! -f /lib/systemd/systemd ] && rc-service .................

I love bash's these kind of short-circuit conditionals...
Thankssss a lot mate!!
_________________
:)
Back to top
View user's profile Send private message
Hu
Administrator
Administrator


Joined: 06 Mar 2007
Posts: 22754

PostPosted: Wed Jan 06, 2021 9:54 pm    Post subject: Reply with quote

Testing for the presence of systemd files is not right either, though. It's legal to have both systemd and sysvinit installed on the same system, and pick one at boot via an init= parameter.
Back to top
View user's profile Send private message
alamahant
Advocate
Advocate


Joined: 23 Mar 2019
Posts: 3918

PostPosted: Wed Jan 06, 2021 9:57 pm    Post subject: Reply with quote

Yes @Hu
You are so right.
In fact when playing around I did install such a dual init system that I have forgotten to update for ages.
I think it will be now difficult when consolekit is discontinued..
_________________
:)
Back to top
View user's profile Send private message
pjp
Administrator
Administrator


Joined: 16 Apr 2002
Posts: 20499

PostPosted: Wed Jan 06, 2021 10:13 pm    Post subject: Reply with quote

For lack of a better solution, this seems to work:
Code:
$ pidof /sbin/init init && echo "running" || echo "not running"
1
running
But I very much dislike references to commands of significance unless they are intended to be used. I even do things like last |grep 'em bo' instead of having random references to 'reboot' causing unintended side effects.
_________________
Quis separabit? Quo animo?
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum