OpenLDAP 搭建入门

Stella981
• 阅读 1112

系统环境:CentOS 7

slapd版本:2.4.44

简介

OpenLDAP是一款轻量级目录访问协议,基于X.500标准的,支持TCP/IP协议,用于实现账号集中管理的开源软件,提供一整套安全的账号统一管理机制,属于C/S架构。

OpenLDAP默认以Berkeley DB作为后端数据库,Berkeley DB数据库 是一类特殊的数据库,主要以散列的数据类型进行数据存储,主要用于搜索、浏览、更新查询操作,对于一次写入数据、多次查询和搜索有很好的效果。

整体目标

后端服务器数量日益增加,账号的数量也在不断增加,账号的统一管理变得尤为重要。结合堡垒机,主要针对服务器账号体系接入LDAP管理做如下主要工作:

ldap server主从的搭建,ldap主从考虑用同步复制(syncrepl)实现,大致为slave到master以拉的模式同步目录树,master负责读写,slave只读。另外主从都需接入负载均衡提供读服务;

服务器账号接入ldap,客户端可以ssh远程连接服务器用户名和密码登录;

ldap管理客户端的公钥,使客户端可以ssh服务器免密码登录;

ldap管理服务器用户的sudo权限

OpenLDAP 目录架构

分为两种:互联网命名组织架构、企业级命名组织架构

企业级命名组织架构

ou=People,dc=xxyd,dc=com

openldap相关缩写:

LDAP相关的缩写如下:

dn - distinguished name(区别名,主键)

o - organization(组织-公司)

ou - organization unit(组织单元-部门)

c - countryName(国家)

dc - domainComponent(域名)

sn - sure name(真实名称)

cn - common name(常用名称)

openldap组件:

OpenLDAP各组件的功能简介:

slapd:主LDAP服务器

slurpd:负责与复制LDAP服务器保持同步的服务器

对网络上的目录进行操作的客户机程序。下面这两个程序是一对儿:

ldapadd:打开一个到LDAP服务器的连接,绑定、修改或增加条目

ldapsearch:打开一个到LDAP服务器的连接,绑定并使用指定的参数进行搜索

对本地系统上的数据库进行操作的几个程序:

slapadd:将以LDAP目录交换格式(LDIF)指定的条目添加到LDAP数据库中

slapcat:打开LDAP数据库,并将对应的条目输出为LDIF格式.

安装服务端

yum -y install openldap openldap-servers openldap-clients openldap-devel compat-openldap

cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG

chown -R ldap.ldap /etc/openldap/

chown -R ldap.ldap /var/lib/ldap/

systemctl start slapd

vi /etc/openldap/ldap.conf
BASE    dc=xxyd,dc=com
URI    ldap://ldap.xxyd.com


slappasswd

cat /etc/openldap/slapd.conf 
include        /etc/openldap/schema/corba.schema
include        /etc/openldap/schema/core.schema
include        /etc/openldap/schema/cosine.schema
include        /etc/openldap/schema/duaconf.schema
include        /etc/openldap/schema/dyngroup.schema
include        /etc/openldap/schema/inetorgperson.schema
include        /etc/openldap/schema/java.schema
include        /etc/openldap/schema/misc.schema
include        /etc/openldap/schema/nis.schema
include        /etc/openldap/schema/openldap.schema
include        /etc/openldap/schema/ppolicy.schema
include        /etc/openldap/schema/collective.schema
allow bind_v2
pidfile        /var/run/openldap/slapd.pid
argsfile    /var/run/openldap/slapd.args
modulepath /usr/lib64/openldap
moduleload ppolicy.la
TLSCACertificatePath /etc/openldap/certs 
TLSCertificateFile "\"OpenLDAP Server\""
TLSCertificateKeyFile /etc/openldap/certs/password
access to attrs=shadowLastChange,userPassword
      by self write
      by * auth
access to *
      by * read
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" read
        by dn.exact="cn=admin,dc=xxyd,dc=com" read
        by * none
database    hdb
suffix        "dc=xxyd,dc=com"
checkpoint    1024 15
rootdn        "cn=admin,dc=xxyd,dc=com"
rootpw            {SSHA}M7S4/DHYIOGx7PsQJFU6kyh00YRCyjhn
directory    /var/lib/ldap
index objectClass                       eq,pres
index ou,cn,mail,surname,givenname      eq,pres,sub
index uidNumber,gidNumber,loginShell    eq,pres
index uid,memberUid                     eq,pres,sub
index nisMapName,nisMapEntry            eq,pres,sub
loglevel        4095 

rm -rf /etc/openldap/slapd.d/*

slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/

chown -R ldap.ldap /etc/openldap/slapd.d
chown -R ldap.ldap /var/lib/ldap/
systemctl restart slapd
systemctl status slapd

# 开机启动
systemctl enable slapd



TLSCACertificatePath /etc/openldap/certs 
TLSCertificateFile "\"OpenLDAP Server\""
TLSCertificateKeyFile /etc/openldap/certs/password 这三句如果出现启动不了可以干掉

安装客户端

Ubuntu client

apt-get install libpam-ldap nscd

##### The following extra packages will be installed:
##### auth-client-config ldap-auth-client ldap-auth-config libnss-ldap

安装后仍然要填写一些信息

LDAP server Uniform Resource Identifier

因为我用的同一台机器,所以我填的是 ldap://127.0.0.1:389,端口号选填
特别注意把它默认的ldapi:///换成ldap://
Distinguished name of the search base

就是你目录树的根,比如我的是 dc=chenjr,dc=cc
LDAP version to use: 3
Make local root Database admin: Yes
Does the LDAP database require login? No
LDAP account for root:

这个是装LDAP服务器时的创建的那个admin账号
我这里是 cn=admin,dc=xxyd,dc=com
LDAP root account password

# If you make a mistake and need to change a value, you can go through the menu again by issuing this command:

sudo dpkg-reconfigure ldap-auth-config

还需要编辑一些文件,首先是/etc/nsswitch.conf,它使得我们在linux下改变用户密码等属性的时候会反映到LDAP中。在以下三行中的compat前面都加上ldap。

passwd: ldap compat
group:  ldap compat
shadow: ldap compat

以上方式,ldap server不可用时,系统将不能登录,需改成:
passwd:        files [UNAVAIL=return] ldap
group:      files [UNAVAIL=return] ldap
shadow:     files [UNAVAIL=return] ldap

这样,ldap client本地用户不需要ldapserver验证,即使ldap server宕机也不影响本地用户登录系统。

然后需要更改PAM的配置,编辑/etc/pam.d/common-session,在末尾加上一行,这使得用户第一次登录的时候创建主目录

session required    pam_mkhomedir.so skel=/etc/skel umask=0022
然后,编辑/etc/pam.d/common-password,将以下这行中的use_authtok删掉,这是避免使用passwd命令时报错而无法更改密码

password    [success=1 user_unknown=ignore default=die] pam_ldap.so use_authtok try_first_pass
然后重启nscd服务

sudo /etc/init.d/nscd restart

CentOS client

yum -y install nss-pam-ldapd

vim /etc/nslcd.conf
uri ldap://ldap.xxyd.com
base dc=xxyd,dc=com
ssl no
tls_cacertdir /etc/openldap/cacerts

vim /etc/pam_ldap.conf
base dc=xxyd,dc=com
uri ldap://ldap.xxyd.com
ssl no
tls_cacertdir /etc/openldap/cacerts
pam_password md5

vi /etc/pam.d/system-auth
auth        sufficient    pam_ldap.so try_first_pass
account     [default=bad success=ok user_unknown=ignore] pam_ldap.so
password    sufficient    pam_ldap.so use_authtok
session     optional      pam_ldap.so

vi /etc/nsswitch.conf
passwd:     files       ldap
shadow:     files       ldap
group:      files       ldap

vi /etc/sysconfig/authconfig
USELDAPAUTH=yes
USELDAP=yes

systemctl restart  nslcd

切换用户:/bash-4.2$
需:
vi /etc/pam.d/system-auth  添加
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0022

OpenLDAP用户以及用户组的添加

两种方式:

一、通过migrationtools工具导入

二、自定义LDIF文件导入

通过migrationtools工具导入

migrationtools开源工具通过查找/etc/passwd、/etc/shadow、/etc/groups生成LDIF文件,并通过ldapadd命令更新数据库数据,完成用户添加。

此方式方便导入系统目前已存在的用户以及用户组

# 安装migrationtools工具
yum -y install migrationtools

vi /usr/share/migrationtools/migrate_common.ph
$DEFAULT_MAIL_DOMAIN = "xxyd.com";
$DEFAULT_BASE = "dc=xxyd,dc=com";
$EXTENDED_SCHEMA = 1;


# 通过migrationtools工具生成LDIF模板文件并生成系统用户及组LDIF
cd ~
/usr/share/migrationtools/migrate_base.pl > base.ldif
/usr/share/migrationtools/migrate_passwd.pl  /etc/passwd > passwd.ldif
/usr/share/migrationtools/migrate_group.pl  /etc/group > group.ldif

### sed -i 's/padl/xxyd/g' *.ldif

删除不必要的base.ldif信息(此处我只保留ou=Group、ou=Peopl相关项)

删除不需要的用户信息(group.ldif、passwd.ldif)

导入至OpenLDAP目录树中

ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f ~/base.ldif
ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f ~/passwd.ldif
ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f ~/group.ldif

自定义LDIF导入

自定义用户属性信息导入OpenLDAP。

OpenLDAP加密传输

默认情况下,OpenLDAP服务端与客户端之间使用明文进行验证、查询等一系列操作,由于在互联网上进行传输存在不安全因素,需要提供OpenLDAP服务端证书以及修改配置文件来支持加密传输

强烈建议在制作证书过程使用泛域名,这样满足多IDC机房的时候使用同一个证书进行部署。比如:证书匹配 *.domain.com,每个IDC使用各自的域名

idc1.domain.com

idc2.domain.com

idc3.domain.com

部署过程只需要一个证书即可满足所有IDC的需求,方便快捷。

客户端还可以配两个服务端地址,第一个服务端不可用自动连接第二个服务端。

自建CA

# 安装OpenSSL软件
yum -y install openssl-devel

# CA中心生成自身私钥
# 为保证CA机构私钥的安全,需要把私钥文件权限设置为600
cd /etc/pki/CA
 (umask 077;openssl genrsa -out private/cakey.pem 2048)
 
 # CA签发自身公钥
 openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3650
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:GD
Locality Name (eg, city) [Default City]:SZ
Organization Name (eg, company) [Default Company Ltd]:xxyd.com
Organizational Unit Name (eg, section) []:YW
Common Name (eg, your name or your server's hostname) []:ldap.xxyd.com
Email Address []:976972175@qq.com

touch serial index.txt
echo "01" > serial

# 查看根证书信息
openssl x509 -noout -text -in /etc/pki/CA/cacert.pem

OpenLDAP与CA集成

生成OpenLDAP服务端证书以及修改配置文件来支持SSL、TLS方式会话加密

# OpenLDAP服务端生成秘钥
mkdir /etc/openldap/ssl
cd /etc/openldap/ssl
(umask 077;openssl genrsa -out ldapkey.pem 1024)

# OpenLDAP服务端向CA申请证书签署请求
openssl req -new -key ldapkey.pem -out ldap.csr -days 3650
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:GD
Locality Name (eg, city) [Default City]:SZ
Organization Name (eg, company) [Default Company Ltd]:xxyd.com
Organizational Unit Name (eg, section) []:YW
Common Name (eg, your name or your server's hostname) []:ldap.xxyd.com
Email Address []:976972175@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

# CA核实并签发证书
 openssl ca -in ldap.csr -out ldapcert.pem -days 3650
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Apr 25 08:18:45 2018 GMT
            Not After : Apr 22 08:18:45 2028 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = GD
            organizationName          = xxyd.com
            organizationalUnitName    = YW
            commonName                = ldap.xxyd.com
            emailAddress              = 976972175@qq.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                C9:0D:16:5C:91:04:27:E9:96:F4:60:6A:B9:ED:70:16:08:0A:96:32
            X509v3 Authority Key Identifier: 
                keyid:CC:5A:C4:57:70:52:C0:67:D3:F3:BF:A6:3B:01:31:3C:7F:8D:07:66

Certificate is to be certified until Apr 22 08:18:45 2028 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

OpenLDAP TLS/SASL部署

cp /etc/pki/CA/cacert.pem /etc/openldap/ssl/
chown -R ldap.ldap /etc/openldap/ssl/*
chmod -R 0400 /etc/openldap/ssl/*

vi /etc/openldap/slapd.conf 
# TLSCACertificatePath /etc/openldap/certs
# TLSCertificateFile "\"OpenLDAP Server\""
# TLSCertificateKeyFile /etc/openldap/certs/password
TLSCACertificateFile /etc/openldap/ssl/cacert.pem
TLSCertificateFile /etc/openldap/ssl/ldapcert.pem
TLSCertificateKeyFile /etc/openldap/ssl/ldapkey.pem
TLSVerifyClient never

vi /etc/sysconfig/slapd
SLAPD_URLS="ldapi:/// ldap:/// ldaps:///"
SLAPD_LDAP=yes
SLAPD_LDAPI=yes
SLAPD_LDAPS=yes

rm -rf /etc/openldap/slapd.d/*
slaptest -u
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart
ss -lnp |grep 636

# 通过CA证书公钥验证OpenLDAP服务端证书的合法性
# openssl verify -CAfile /etc/pki/CA/cacert.pem /etc/openldap/ssl/ldapcert.pem 
/etc/openldap/ssl/ldapcert.pem: OK

# 确认当前套接字是否能通过CA的验证
# openssl s_client -connect ldap.xxyd.com:636 -showcerts -state -CAfile /etc/openldap/ssl/cacert.pem 
CONNECTED(00000003)
SSL_connect:before/connect initialization
SSL_connect:SSLv2/v3 write client hello A
SSL_connect:SSLv3 read server hello A
depth=1 C = CN, ST = GD, L = SZ, O = xxyd.com, OU = YW, CN = ldap.xxyd.com, emailAddress = 976972175@qq.com
verify return:1
depth=0 C = CN, ST = GD, O = xxyd.com, OU = YW, CN = ldap.xxyd.com, emailAddress = 976972175@qq.com
verify return:1
SSL_connect:SSLv3 read server certificate A
SSL_connect:SSLv3 read server key exchange A
SSL_connect:SSLv3 read server done A
SSL_connect:SSLv3 write client key exchange A
SSL_connect:SSLv3 write change cipher spec A
SSL_connect:SSLv3 write finished A
SSL_connect:SSLv3 flush data
SSL_connect:SSLv3 read finished A
---
Certificate chain
 0 s:/C=CN/ST=GD/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
   i:/C=CN/ST=GD/L=SZ/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
-----BEGIN CERTIFICATE-----
MIIDYTCCAkmgAwIBAgIBATANBgkqhkiG9w0BAQsFADB+MQswCQYDVQQGEwJDTjEL
MAkGA1UECAwCR0QxCzAJBgNVBAcMAlNaMRAwDgYDVQQKDAdubmsuY29tMQswCQYD
VQQLDAJZVzEVMBMGA1UEAwwMbGRhcC5ubmsuY29tMR8wHQYJKoZIhvcNAQkBFhA5
NzY5NzIxNzVAcXEuY29tMB4XDTE4MDQyNTA4MTg0NVoXDTI4MDQyMjA4MTg0NVow
cTELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAkdEMRAwDgYDVQQKDAdubmsuY29tMQsw
CQYDVQQLDAJZVzEVMBMGA1UEAwwMbGRhcC5ubmsuY29tMR8wHQYJKoZIhvcNAQkB
FhA5NzY5NzIxNzVAcXEuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDW
sexciew5xl6Yl324mBQ3EEMJvZYO+GJ7PWqoQg1qPVvfg5jUYs66ONOxmYTb+Kfw
oMuWicyptJofwAC8CRSdm0tzZI5JBgKrHfZMmjQh9rXF4rnmKWv6LhKupDfWT0aJ
DZZIdnrYJ8jFX5iU5SaO6C/gS+X6cuKf0yQJr6cb7QIDAQABo3sweTAJBgNVHRME
AjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0
ZTAdBgNVHQ4EFgQUyQ0WXJEEJ+mW9GBque1wFggKljIwHwYDVR0jBBgwFoAUzFrE
V3BSwGfT87+mOwExPH+NB2YwDQYJKoZIhvcNAQELBQADggEBAGwpTJzHMA7Xe1EI
0aicAF7zNnep7fAFTx6t6SJgD1Yio+uwE6xpLiDq9XT8bHmqmS4RK96eB/Il1ZT9
I0gk/7nOm9qU9tfjgvQVfL/tr1/L+gu9Q86tFUrgrR6aHI9U0VTtOug6j0/kMu5Y
xo4H6O5/blmV9lmRI65/FDJlaQCJHsWK6fJzBiqh2OtszVgInDEum/L3GVN+oL+L
SLLqWqvCv8QDkmvEpe7ht0/tb9C2foED1+lI+H9zQKM3lUI2Bp4SRp4nwpIyvnGc
uq/+EzijIeW+WagPMeNtH+9h20kmvbzCog+YGWXQOkozhXCuHCgzn6+qtPYaLuZT
WHlPkKA=
-----END CERTIFICATE-----
 1 s:/C=CN/ST=GD/L=SZ/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
   i:/C=CN/ST=GD/L=SZ/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
-----BEGIN CERTIFICATE-----
MIIDzzCCAregAwIBAgIJAJA1elZ+21+rMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV
BAYTAkNOMQswCQYDVQQIDAJHRDELMAkGA1UEBwwCU1oxEDAOBgNVBAoMB25uay5j
b20xCzAJBgNVBAsMAllXMRUwEwYDVQQDDAxsZGFwLm5uay5jb20xHzAdBgkqhkiG
9w0BCQEWEDk3Njk3MjE3NUBxcS5jb20wHhcNMTgwNDI1MDgwMTQ4WhcNMjgwNDIy
MDgwMTQ4WjB+MQswCQYDVQQGEwJDTjELMAkGA1UECAwCR0QxCzAJBgNVBAcMAlNa
MRAwDgYDVQQKDAdubmsuY29tMQswCQYDVQQLDAJZVzEVMBMGA1UEAwwMbGRhcC5u
bmsuY29tMR8wHQYJKoZIhvcNAQkBFhA5NzY5NzIxNzVAcXEuY29tMIIBIjANBgkq
hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtLLSFTcyLeQNeZMlddJ5v388TQJpUByN
bbq0cjdeWWg9OHqF6+JIA481B8lGlmZXpUmOsWbxMpgb4M98AQ9zM48SybbNTVMf
Is3GMz0YkXSGsqj6id3FkXs3wfPR6UpWhAQuuoHaovHEia9TVmK/ypK+OIY+F8qv
p3qmWDCmxNOAR6tyndxcp3hG2rrIWTUkVoZWoEpPzRsesKdVYJ/CzscFQc9x2jM8
RgQzX59Z3dM6XR2eT9byhzwPHIy7wiZBg3kesQ+3dIoRYsHWkqK5dzDA3W1Lj1pY
xGN+udRhXSK0o9HlXd457g6SqPpEFRxClAB8fGu+7BqyiCeFOvPbJQIDAQABo1Aw
TjAdBgNVHQ4EFgQUzFrEV3BSwGfT87+mOwExPH+NB2YwHwYDVR0jBBgwFoAUzFrE
V3BSwGfT87+mOwExPH+NB2YwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC
AQEAjPFE1jDbvRhTxjJ40eBssnr/E6h+baY4eDnU+dSiO7BhaA+DQY2ANdCi7scu
pfqceQ6UPpvjNZC8bQOqc1j57kXGCK6Na1k70cP7Tpdtp1ZA0kBe43aUi7quwsYP
b0boBwAmBFZ7C958Pgmv58r+GGTidd1RMJR111FT8hceC4WiMTrMTxCj1EFWm2c4
wv0uZIg0awGy8TS3nfSNb9t7YiFQYjlV/xUOBzobZZRl0e8FdQ7mO7qogoOmR8r/
2P5SJk6FjH0ENKb9igwlMDnlm1E78ZUjLbfvAfyPLSUE3kYoIFa9Xa0dyVV46IuW
u3tdbPBah5v6z3FkcbAldZHeGw==
-----END CERTIFICATE-----
---
Server certificate
subject=/C=CN/ST=GD/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
issuer=/C=CN/ST=GD/L=SZ/O=xxyd.com/OU=YW/CN=ldap.xxyd.com/emailAddress=976972175@qq.com
---
No client certificate CA names sent
Peer signing digest: SHA256
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 2213 bytes and written 415 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 55054DE6A2BDA0AB00F94966542DF551E357F9B3F07B5B6F1DD3567D0CBEE311
    Session-ID-ctx: 
    Master-Key: 1E1248619CC913A090967862C855CD9F43299DFE60A52D8BFBB515A8C6C01A74DD2E2E939C97B5414C1DA0A05FC16D2A
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1524647608
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

# OpenLDAP从服务器部署
拷贝 cacert.pem ldapcert.pem ldapkey.pem至/etc/openldap/ssl/

chown -R ldap.ldap /etc/openldap/ssl/*
chmod -R 0400 /etc/openldap/ssl/*
vi /etc/openldap/slapd.conf
# TLSCACertificatePath /etc/openldap/certs
# TLSCertificateFile "\"OpenLDAP Server\""
# TLSCertificateKeyFile /etc/openldap/certs/password
TLSCACertificateFile /etc/openldap/ssl/cacert.pem
TLSCertificateFile /etc/openldap/ssl/ldapcert.pem
TLSCertificateKeyFile /etc/openldap/ssl/ldapkey.pem
TLSVerifyClient never

vi /etc/sysconfig/slapd
SLAPD_URLS="ldapi:/// ldap:/// ldaps:///"
SLAPD_LDAP=yes
SLAPD_LDAPI=yes
SLAPD_LDAPS=yes

rm -rf /etc/openldap/slapd.d/*
slaptest -u
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart
ss -lnp |grep 636

客户端部署

剥离基础组件故障对于平台的影响

非常幸运OpenLDAP的客户端配置文件中支持 ==nss_initgroups_ignoreusers== 的配置。也就是说可以将角色用户( root、service、oracle、read_only等)忽略掉,不需要进行OpenLDAP请求,而直接在本地进行权限认证即可。个人账号及权限在OpenLDAP中维护,而角色账号是在服务器passwd&shadow中维护的。

Ubuntu客户端

# rsync -azP ldap.xxyd.com:/etc/pki/CA/cacert.pem /etc/ldap/ssl/

# vi /etc/ldap.conf
base dc=xxyd,dc=com
uri ldaps://ldap.xxyd.com
#ssl start_tls
#ssl no
ssl on
## nss_initgroups_ignoreusers set ignore local user
nss_initgroups_ignoreusers root,daemon,bin,sys,sync,mail,nobody,syslog,sshd


# vi /etc/ldap/ldap.conf
BASE    dc=xxyd,dc=com
URI    ldaps://ldap.xxyd.com
TLS_CACERT    /etc/ldap/ssl/cacert.pem
#TLS_CACERT     /etc/ssl/certs/ca-certificates.crt



/etc/init.d/nscd restart

CentOS客户端

rsync -azP ldap.xxyd.com:/etc/pki/CA/cacert.pem /etc/openldap/cacerts/

vi /etc/openldap/ldap.conf
URI ldaps://ldap.xxyd.com/
## nss_initgroups_ignoreusers set ignore local user
nss_initgroups_ignoreusers root,daemon,bin,operator,sync,mail,nobody,adm,sshd

vi /etc/pam_ldap.conf
# ssl start_tls
# ssl no
uri ldaps://ldap.xxyd.com/
ssl on

vi /etc/nslcd.conf
# ssl no
uri ldaps://ldap.xxyd.com/
ssl on
tls_cacertfile /etc/openldap/cacerts/cacert.pem


service nslcd restart

# 通过客户端测试SSL连接是否正常
# yum -y install openldap-clients
# ldapwhoami -v -x -Z
ldap_initialize( <DEFAULT> )
ldap_start_tls: Operations error (1)
    additional info: TLS already started
anonymous
Result: Success (0)

# LAP用户验证密码
# ldapwhoami -D "uid=test01,ou=People,dc=xxyd,dc=com" -W -H ldaps://ldap.xxyd.com -v
ldap_initialize( ldaps://ldap.xxyd.com:636/??base )
Enter LDAP Password: 
dn:uid=test01,ou=People,dc=xxyd,dc=com
Result: Success (0)

# 通过getent在客户端执行,查看能否获取账号信息
# getent passwd test01
test01:x:1001:1001:test01:/home/test01:/bin/bash

sudo权限控制

cp /usr/share/doc/sudo-1.8.6p7/schema.OpenLDAP /etc/openldap/schema/sudo.schema

vi /etc/openldap/slapd.conf
include        /etc/openldap/schema/sudo.schema

rm -rf /etc/openldap/slapd.d/*

slaptest -u
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/

service slapd restart


# 根据实际需求添加sudo项
# cat ~/sudoers.ldif
dn: ou=sudoers,dc=xxyd,dc=com
objectClass: top
objectClass: organizationalUnit
ou: sudoers

dn: cn=defaults,ou=sudoers,dc=xxyd,dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: requiretty
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoOption: env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS"
sudoOption: env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
sudoOption: env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
sudoOption: env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
sudoOption: env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
sudoOption: secure_path = /sbin:/bin:/usr/sbin:/usr/bin
sudoOrder: 1

dn: cn=%apps,ou=sudoers,dc=xxyd,dc=com
objectClass: top
objectClass: sudoRole
cn: %apps
sudoUser: %apps
sudoHost: ALL
sudoRunAsUser: %apps
sudoCommand: /bin/kill
sudoCommand: /usr/bin/nohup
sudoCommand: /usr/bin/vi
sudoCommand: /bin/cp
sudoCommand: /bin/mv
sudoCommand: /bin/ln
sudoCommand: /bin/mkdir
sudoOption: !authenticate
sudoOrder: 2

dn: cn=%www-data,ou=sudoers,dc=xxyd,dc=com
objectClass: top
objectClass: sudoRole
cn: %www-data
sudoUser: %www-data
sudoHost: ALL
sudoRunAsUser: %www-data
sudoCommand: /bin/kill
sudoCommand: /usr/bin/nohup
sudoCommand: /usr/bin/vi
sudoCommand: /bin/cp
sudoCommand: /bin/mv
sudoCommand: /bin/ln
sudoCommand: /bin/mkdir
sudoCommand: /usr/bin/rsync
sudoOption: !authenticate
sudoOrder: 3


# ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f ~/sudoers.ldif
Enter LDAP Password: 
adding new entry "ou=sudoers,dc=xxyd,dc=com"

adding new entry "cn=defaults,ou=sudoers,dc=xxyd,dc=com"

adding new entry "cn=%apps,ou=sudoers,dc=xxyd,dc=com"

adding new entry "cn=%www-data,ou=sudoers,dc=xxyd,dc=com"

## 为test01用户添加附加组
# cat add_apps.ldif 
dn: cn=apps,ou=Group,dc=xxyd,dc=com
objectClass: posixGroup
objectClass: top
cn: apps
userPassword: {crypt}x
gidNumber: 1500
memberUid: test01

dn: uid=apps,ou=People,dc=xxyd,dc=com
uid: apps
cn: apps
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 1500
gidNumber: 1500
homeDirectory: /home/apps

# ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f add_apps.ldif 
Enter LDAP Password: 
adding new entry "cn=apps,ou=Group,dc=xxyd,dc=com"

adding new entry "uid=apps,ou=People,dc=xxyd,dc=com"

客户端

centos 客户端

authconfig --enableldap --enableldapauth --enablemkhomedir --enableforcelegacy --disablesssd --disablesssdauth --disableldaptls --enablelocauthorize --ldapserver=ldap.xxyd.com --ldapbasedn="dc=xxyd,dc=com" --enableshadow --update


vi /etc/nsswitch.conf
sudoers:  ldap files

vi /etc/sudo-ldap.conf 
uri ldaps://ldap.xxyd.com/
base dc=xxyd,dc=com
SUDOERS_BASE ou=sudoers,dc=xxyd,dc=com

vi /etc/pam_ldap.conf
uri ldaps://ldap.xxyd.com/

service nslcd restart

Ubuntu客户端

# export SUDO_FORCE_REMOVE=yes
# apt-get install sudo-ldap
# ls -lh /etc/sudo-ldap.conf
lrwxrwxrwx 1 root root 14 Apr 28 01:22 /etc/sudo-ldap.conf -> ldap/ldap.conf

# vi /etc/ldap/ldap.conf 
SUDOERS_BASE ou=sudoers,dc=xxyd,dc=com

# echo "sudoers:    ldap files" >> /etc/nsswitch.conf
# service nscd restart

# 测试
# su - test01
$ sudo -l
匹配此主机上 test01 的默认条目:
    requiretty, !visiblepw, always_set_home, env_reset, env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS",
    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT
    LC_MESSAGES", env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS
    _XKB_CHARSET XAUTHORITY", secure_path = /sbin:/bin:/usr/sbin:/usr/bin, !visiblepw, always_set_home, env_reset, env_keep="COLORS
    DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE",
    env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER
    LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY", secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

用户 test01 可以在该主机上运行以下命令:
    (%apps) NOPASSWD: /bin/kill, /usr/bin/nohup, /usr/bin/vi, /bin/cp, /bin/mv, /bin/ln, /bin/mkdir


#备注:Ubuntu和CentOS命令路径部分有区别,如vi

密码策略

vi /etc/openldap/slapd.conf
include         /etc/openldap/schema/ppolicy.schema
moduleload ppolicy.la
overlay ppolicy
#密码加密算法,不加这一行密码将明文显示
password-hash {SSHA}
#Add和Modify中传递的密码明文保存数据库中必须进行Hash加密
ppolicy_hash_cleartext
ppolicy_use_lockout
#默认密码控制策略
ppolicy_default "cn=default,ou=policies,dc=xxyd,dc=com"

rm -rf /etc/openldap/slapd.d/*
# slaptest -u
config file testing succeeded
# slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
config file testing succeeded
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart

#参考/root/openldap-2.4.44/servers/slapd/schema/ppolicy.ldif


#定义默认密码策略
# cat policy.ldif 
dn: ou=policies, dc=xxyd,dc=com
objectClass: top
objectClass: organizationalUnit
ou: Policies

dn: cn=default, ou=policies, dc=xxyd,dc=com
objectClass: top
objectClass: person
objectClass: pwdPolicy
cn: default
pwdAttribute: userPassword
pwdLockoutDuration: 15
pwdInHistory: 6
pwdCheckQuality: 2
pwdExpireWarning: 1296000
pwdMaxAge: 15552000
pwdMinLength: 8
pwdGraceAuthNLimit: 3
pwdAllowUserChange: TRUE
pwdMustChange: TRUE
pwdMaxFailure: 3
pwdFailureCountInterval: 86400
pwdSafeModify: TRUE
pwdLockout: TRUE
sn: dummy value


#密码策略注解
pwdLockout  是否开启账户锁定功能
pwdMaxFailure 密码最大失败次数,超过后账号被锁定
pwdLockoutDuration 帐户保持锁定的时间(秒为单位),默认为0表示无法访问账户
pwdInHistory  历史密码维护列表中密码的数量
pwdCheckQuality 检查密码质量,0不检查,1、2检查
pwdExpireWarning 密码过期提醒,单位秒
pwdMaxAge 密码有效期,单位秒
pwdMinLength 密码最小长度
pwdGraceAuthNLimit 密码过期后宽限期
pwdAllowUserChange 是否允许用户更改自己的密码
pwdLockout 超过pwdMaxFailure定义的无效密码尝试次数时是否锁定账户
pwdMustChange 用户在帐户锁定后由管理员重置帐户后是否必须更改密码
pwdMaxFailure 允许的最大连续失败密码尝试次数
pwdFailureCountInterval 密码失败次数复位时间
pwdSafeModify 用户在密码修改操作期间是否必须发送当前密码

# ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f policy.ldif 
Enter LDAP Password: 
adding new entry "ou=policies, dc=xxyd, dc=com"

adding new entry "cn=default, ou=policies, dc=xxyd, dc=com"

# 定义用户遵守指定密码策略
# cat test02.ldif 
dn: cn=test02,ou=Group,dc=xxyd,dc=com
objectClass: posixGroup
objectClass: top
cn: test02
userPassword: {crypt}x
gidNumber: 1002

dn: uid=test02,ou=People,dc=xxyd,dc=com
uid: test02
cn: test02
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
userPassword: {crypt}$6$Yu95/zTK$g/nCoExrQwlf80a8Gc0VxMNzkJWa7icUVinFWwEjPBad/KhCNDs81hUVCYA7vV/dJdw7.zSBu2Yz.F0gVJH0a/
shadowLastChange: 17638
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 1002
gidNumber: 1002
homeDirectory: /home/test02
pwdPolicySubentry: cn=default,ou=policies,dc=xxyd,dc=com

定义用户登录修改密码

为了增强用户密码安全性,一般需要用户更改初始密码

方式有两种:用户登录后通过passwd命令更改、用户登录系统是提示更改初始密码否则无法登录

推进第二种

为了定义密码控制策略,将pwdReset属性和值添加至用户的属性中,否则不生效

# cat << EOF |ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W
dn: uid=test02,ou=People,dc=xxyd,dc=com
changetype: modify
replace: pwdReset
pwdReset: TRUE
EOF

#查看定义用户的策略信息
# pwdReset属于隐藏属性,默认ldapsearch无法获取隐藏属性,通过“+”号可获取查询包含的隐藏属性
# ldapsearch -x -LLL uid=test02 +
dn: uid=test02,ou=People,dc=xxyd,dc=com
pwdPolicySubentry: cn=default,ou=policies,dc=xxyd,dc=com
structuralObjectClass: account
entryUUID: 0fc49c74-dd83-1037-8006-65040a056c63
creatorsName: cn=admin,dc=xxyd,dc=com
createTimestamp: 20180426095056Z
pwdChangedTime: 20180426095747Z
pwdHistory: 20180426095747Z#1.3.6.1.4.1.1466.115.121.1.40#105#{crypt}$6$Yu95/z
 TK$g/nCoExrQwlf80a8Gc0VxMNzkJWa7icUVinFWwEjPBad/KhCNDs81hUVCYA7vV/dJdw7.zSBu2
 Yz.F0gVJH0a/
pwdReset: TRUE
entryCSN: 20180426095747.741644Z#000000#000#000000
modifiersName: uid=test02,ou=People,dc=xxyd,dc=com
modifyTimestamp: 20180426095747Z
entryDN: uid=test02,ou=People,dc=xxyd,dc=com
subschemaSubentry: cn=Subschema
hasSubordinates: FALSE

客户端配置

CentOS 客户端

vi /etc/pam_ldap.conf
bind_policy soft
pam_password md5
pam_lookup_policy yes
pam_password clear_remove_old

service nslcd restart

# ssh test02@10.1.101.116
test02@10.1.101.116's password: 
You are required to change your LDAP password immediately.
Creating directory '/home/test02'.
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user test02.
Enter login(LDAP) password: 
New password: 
Retype new password: 
LDAP password information changed for test02
passwd: all authentication tokens updated successfully.

Ubuntu 客户端

vi /etc/pam_ldap.conf
bind_policy soft
pam_password md5
pam_lookup_policy yes
pam_password clear_remove_old

service nscd restart

密码审计控制

# cat << EOF | ldapadd -Y EXTERNAL -H ldapi:///
dn: cn=module{0},cn=config
changetype: modify
add: olcModuleLoad
olcModuleLoad: {1}auditlog

dn: olcOverlay=auditlog,olcDatabase={2}hdb,cn=config
changetype: add
objectClass: olcOverlayConfig
objectClass: olcAuditLogConfig
olcOverlay: auditlog
olcAuditlogFile: /var/log/slapd/auditlog.log
EOF

mkdir /var/log/slapd
chown -R ldap.ldap /var/log/slapd
service slapd restart

日志

vi /etc/openldap/slapd.conf
loglevel 0x80 0x1
logfile         /var/log/slapd/slapd.log

rm -rf /etc/openldap/slapd.d/*
slaptest -u
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart

mkdir /var/log/slapd/
chown -R ldap.ldap /var/log/slapd/

# vi /etc/logrotate.d/ldap 
/var/log/slapd/slapd.log {
    prerotate
        /usr/bin/chattr -a /var/log/slapd/slapd.log
    endscript
    compress
    delaycompress
    notifempty
    rotate 100
    size 10M
    postrotate
        /usr/bin/chattr +a /var/log/slapd/slapd.log
    endscript
}

vi /etc/rsyslog.conf
local4.*            /var/log/slapd/slapd.log

service rsyslog restart

ssh public key

服务端

yum -y install openssh-ldap

cp /usr/share/doc/openssh-ldap-7.4p1/openssh-lpk-openldap.schema /etc/openldap/schema/

rm -rf /etc/openldap/slapd.d/*
slaptest -u
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart

# 添加测试账户
# cat test03.ldif 
dn: cn=test03,ou=Group,dc=xxyd,dc=com
objectClass: posixGroup
objectClass: top
cn: test03
userPassword: {crypt}x
gidNumber: 1003

dn: uid=test03,ou=People,dc=xxyd,dc=com
uid: test03
cn: test03
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
objectClass: ldapPublicKey
userPassword: {crypt}$6$Yu95/zTK$g/nCoExrQwlf80a8Gc0VxMNzkJWa7icUVinFWwEjPBad/KhCNDs81hUVCYA7vV/dJdw7.zSBu2Yz.F0gVJH0a/
shadowLastChange: 17638
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 1003
gidNumber: 1003
homeDirectory: /home/test03
pwdPolicySubentry: cn=default,ou=policies,dc=xxyd,dc=com
sshPublicKey: ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIBZpJc0dfiPsHlfPNEJBUqhCGZX2wGabxklz09ptnriLoCh9AeYj39suHPptTZDAGiOn8JxrdYK4SubEby9WdQ/t2kVE60Bytw+Jyc2YjEhVb1iJinMd1sdck7O3YBDJoCt0WTf7USAQE7e1oH54kDCPQcPozid7AjbrF2mzxnFpQ== rsa-key-20101209

# ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f test03.ldif
Enter LDAP Password: 
adding new entry "cn=test03,ou=Group,dc=xxyd,dc=com"

adding new entry "uid=test03,ou=People,dc=xxyd,dc=com"

客户端

CentOS client

yum -y install openssh-ldap

# vi /etc/ssh/ldap.conf 
URI ldaps://ldap.xxyd.com/
BASE dc=xxyd,dc=com
ssl on

# vi /etc/ssh/sshd_config
AuthorizedKeysCommand /usr/libexec/openssh/ssh-ldap-wrapper
AuthorizedKeysCommandRunAs nobody

# vi /usr/libexec/openssh/ssh-ldap-wrapper
#!/bin/bash
# get configuration from /etc/ldap.conf
for x in $(sed -n 's/^\([a-zA-Z_]*\) \(.*\)$/\1="\2"/p' /etc/ldap.conf); do 
    eval $x; 
done

# local user do not search ldap
USER=$1
for user in `echo $nss_initgroups_ignoreusers|sed 's/,/ /g'`; do
    exit ;
done

exec /usr/libexec/openssh/ssh-ldap-helper -s "$1"


# service sshd restart

# grep test03 /var/log/secure
Apr 27 15:15:37 new sshd[31926]: Accepted publickey for test03 from xx.xx.xx.xx port 6658 ssh2
Apr 27 15:15:37 new sshd[31926]: pam_unix(sshd:session): session opened for user test03 by (uid=0)

Ubuntu client

# 升级OpenSSH (6.2以上版本)

## 搭建telnet server
# apt-get install openbsd-inetd telnetd
# vi /etc/inetd.conf
telnet stream tcp nowait root /usr/sbin/tcpd /usr/sbin/in.telnetd 

# vi /etc/securetty 
# Telnet
pts/0
pts/1
pts/2

# 限制telnet登录ip,只允许指定ip段(信任ip段)登录
# vi /etc/hosts.deny
in.telnetd:ALL EXCEPT 192.168.0.0/24

service openbsd-inetd restart

# telnet 登录服务器升级OpenSSh版本
telnet x.x.x.x

cp /etc/init.d/ssh /root/ssh.old
cp -r /etc/ssh /root/
cp /etc/pam.d/sshd /root/
grep sshd /etc/passwd | head -1 | awk -F: '{print $1,$3,$4,$6,$7}' > /root/ssh_user

# 卸载openssh 旧版本,卸载之前必须确认可用telnet登录,以下步骤telnet登录服务器操作
apt-get -y purge openssh-client openssh-server

apt-get -y install zlib1g-dev libssl-dev libpam0g-dev make

## 安装openssh 7.2
wget https://openbsd.hk/pub/OpenBSD/OpenSSH/portable/openssh-7.2p2.tar.gz

useradd -u `awk '{print $2}' /root/ssh_user` -g `awk '{print $3}' /root/ssh_user` -d `awk '{print $4}' /root/ssh_user` -s `awk '{print $5}' /root/ssh_user` sshd

tar zxvf openssh-7.2p2.tar.gz
cd openssh-7.2p2/

./configure --prefix=/usr --sysconfdir=/etc/ssh --with-zlib --with-md5-passwords --with-pam --with-tcp-wrappers

make &&make install

# ssh -V
OpenSSH_7.2p2, OpenSSL 1.0.1 14 Mar 2012




# cat > /etc/ssh/sshd_config << EOF
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes
AuthorizedKeysCommand /etc/ssh/ldap-keys.sh
AuthorizedKeysCommandUser nobody
EOF

# cat > /etc/ssh/ssh_config <<EOF
Host *
    SendEnv LANG LC_*
    HashKnownHosts yes
    #GSSAPIAuthentication yes
    #GSSAPIDelegateCredentials no
EOF

### 7.2 不支持GSSAPI参数
/etc/ssh/ssh_config line 4: Unsupported option "gssapiauthentication"
/etc/ssh/ssh_config line 5: Unsupported option "gssapidelegatecredentials"
###

cat > /etc/pam.d/sshd << EOF
@include common-auth
account    required     pam_nologin.so
@include common-account
@include common-session
session    optional     pam_motd.so # [1]
session    optional     pam_mail.so standard noenv # [1]
session    required     pam_limits.so
session    required     pam_env.so # [1]
session    required     pam_env.so user_readenv=1 envfile=/etc/default/locale
@include common-password
EOF


apt-get -y install ldap-utils

vi /etc/ssh/ldap-keys.sh
#!/bin/bash
# get configuration from /etc/ldap.conf
for x in $(sed -n 's/^\([a-zA-Z_]*\) \(.*\)$/\1="\2"/p' /etc/ldap.conf); do 
    eval $x;
done

# local user do not search ldap
for USER in `echo $nss_initgroups_ignoreusers|sed 's/,/ /g'`; do
    if [ $USER == $1 ];then
    exit
    fi
done
 
OPTIONS=
case "$ssl" in
    start_tls) 
        case "$tls_checkpeer" in
            no) OPTIONS+="-Z";;
            *) OPTIONS+="-ZZ";;
        esac;;
esac
 
# ldap user search ldap sshPublicKey
ldapsearch $OPTIONS -H ${uri} -w "${bindpw}" -D "${binddn}" -b "${base}" '(&(objectClass=posixAccount)(uid='"$1"'))' 'sshPublicKey' \
    | sed -n '/^ /{H;d};/sshPublicKey:/x;$g;s/\n *//g;s/sshPublicKey: //gp'

chmod +x /etc/ssh/ldap-keys.sh

# 拷贝旧的ssh启动脚本
cp /root/ssh.old /etc/init.d/ssh 

# service ssh start

#开机启动
update-rc.d ssh defaults

# ssh 升级完成之后卸载telnet服务,还原配置
apt-get purge openbsd-inetd telnetd
sed -i '/Telnet/d' /etc/securetty
sed -i '/pts\//d' /etc/securetty
sed -i '/in.telnetd/d' /etc/hosts.deny

参考链接:
https://www.linuxidc.com/Linux/2011-10/45739.htm
https://marc.waeckerlin.org/computer/blog/ssh_and_ldap

主机控制策略

http://ju.outofmemory.cn/entry/146609

服务端

# vi /etc/openldap/schema/ldapns.schema
# $
# : ldapns.schema,v 1.3 2009-10-01 19:17:20 tedcheng Exp $
# LDAP Name Service Additional Schema
# http://www.iana.org/assignments/gssapi-service-names
#
# Not part of the distribution: this is a workaround!
#
attributetype ( 1.3.6.1.4.1.5322.17.2.1 NAME 'authorizedService'
          DESC 'IANA GSS-API authorized service name'
          EQUALITY caseIgnoreMatch
          SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )
attributetype ( 1.3.6.1.4.1.5322.17.2.2 NAME 'loginStatus'
          DESC 'Currently logged in sessions for a user'
          EQUALITY caseIgnoreMatch
          SUBSTR caseIgnoreSubstringsMatch
          ORDERING caseIgnoreOrderingMatch
          SYNTAX OMsDirectoryString )
objectclass ( 1.3.6.1.4.1.5322.17.1.1 NAME 'authorizedServiceObject'
          DESC 'Auxiliary object class for adding authorizedService attribute'
          SUP top
          AUXILIARY
          MAY authorizedService )
objectclass ( 1.3.6.1.4.1.5322.17.1.2 NAME 'hostObject'
          DESC 'Auxiliary object class for adding host attribute'
          SUP top
          AUXILIARY
          MAY host )
objectclass ( 1.3.6.1.4.1.5322.17.1.3 NAME 'loginStatusObject'
          DESC 'Auxiliary object class for login status attribute'
          SUP top
          AUXILIARY
          MAY loginStatus )

# vi /etc/openldap/slapd.conf
include         /etc/openldap/schema/ldapns.schema

rm -rf /etc/openldap/slapd.d/*
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart

cat <<EOF | ldapadd -x -D cn=admin,dc=xxyd,dc=com -W -H ldap://ldap.xxyd.com/
dn: ou=APP,ou=People,dc=xxyd,dc=com
ou: APP
objectClass: top
objectClass: organizationalUnit
EOF

cat <<EOF | ldapadd -x -D cn=admin,dc=xxyd,dc=com -W -H ldap://ldap.xxyd.com/
dn: ou=DB,ou=People,dc=xxyd,dc=com
ou: DB
objectClass: top
objectClass: organizationalUnit
EOF

规划:

ou=APP 应用运维人员账户根路径;

ou=DB 数据库管理员账户根路径

Ubuntu客户端

# echo "pam_check_host_attr yes" >> /etc/pam_ldap.conf
# vi /etc/ldap.conf
nss_base_passwd ou=APP,ou=People,dc=xxyd,dc=com
nss_base_shadow ou=APP,ou=People,dc=xxyd,dc=com
nss_base_group ou=APP,ou=People,dc=xxyd,dc=com

## 注明:应用服务器设置ou=APP,ou=People,dc=xxyd,dc=com
##       数据库服务器设置ou=DB,ou=People,dc=xxyd,dc=com
##       同时登陆应用和数据库服务器设置ou=People,dc=xxyd,dc=com
## /etc/ldap.conf配置文件注意不要有多余的空格分隔符,否则ldap-keys.sh脚本会报语法错误

# service nscd restart

CentOS 客户端

测试,应用运维人员只能登录应用服务器,数据库管理员只能登录数据库服务器

数据同步

主从同步

主服务器同步策略配置

编辑OpenLDAP主配置文件

vi /etc/ldap/slapd.conf

moduleload syncprov.la
index entryCSN,entryUUID eq
overlay syncprov
syncprov-checkpoint 100 10
syncprov-sessionlog 100

重新生成数据库文件,使其配置生效

service slapd stop
rm -rf /etc/openldap/slapd.d/*
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart
ss -lnp |grep slapd

从服务器配置

编辑OpenLDAP主配置文件

vi /etc/openldap/slapd.conf

moduleload syncprov.la
index entryCSN,entryUUID eq
syncrepl rid=002
    provider=ldap://10.1.31.128:389/
    type=refreshOnly
    retry="60 10 600 +"
    interval=00:00:00:10
    searchbase="dc=xxyd,dc=com"
    scope=sub
    schemachecking=off
    bindmethod=simple
    binddn="cn=admin,dc=xxyd,dc=com"
    attrs="*,+"
    credentials=PASSWD

# Refer updates to the master
updatedn "cn=admin,xxyd,dc=com"
updateref  ldap://10.1.31.243

重新生成数据库文件,使其配置生效

service slapd stop
rm -rf /etc/openldap/slapd.d/*
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d/
service slapd restart
ss -lnp |grep slapd

导入数据条目

主服务器上导出数据条目:

ldapsearch -x -b 'dc=com,dc=cn' > ldapbackup.ldif

传输备份数据到备服务器上并导入

ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f ldapbackup.ldif

比对主备服务器数据条目是否一致

ldapsearch -x -LLL  |wc -l

重新生成数据库文件,使其配置生效

service slapd stop
rm -rf /etc/ldap/slapd.d/
slaptest -f /etc/ldap/slapd.conf -F /etc/ldap/slapd.d/
chown -R openldap.openldap /etc/ldap/slapd.d/
service slapd restart
ss -lnp |grep slapd

主从同步验证

主服务器上添加条目

ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f group.test02.ldif

ldapadd -x -D "cn=admin,dc=xxyd,dc=com" -W -f passwd.test02.ldif 

查看从服务器上是否存在新添加的条目

ldapsearch -x -LLL uid=test02

查看同步日志

/var/log/syslog

多主同步(N-Way Multimaster)

服务器同步策略配置

多主模式,多台服务器配置一致,只需更改ip/域名即可

编辑OpenLDAP配置文件

# vi /etc/openldap/slapd.conf
moduleload syncprov.la
index entryUUID,entryCSN eq
overlay syncprov
syncprov-checkpoint 100 10
syncprov-sessionlog 100
serverID 1 ldaps://ldap01.xxyd.com
serverID 2 ldaps://ldap02.xxyd.com

syncrepl rid=001
    provider=ldaps://ldap01.xxyd.com
    binddn="cn=admin,dc=xxyd,dc=com"
    bindmethod=simple
    credentials=PASSWD
    searchbase="dc=xxyd,dc=com"
    type=refreshAndPersist
    retry="5 5 300 5"
    timeout=1
syncrepl rid=002
    provider=ldaps://ldap02.xxyd.com
    binddn="cn=admin,dc=xxyd,dc=com"
    bindmethod=simple
    credentials=PASSWD
    searchbase="dc=xxyd,dc=com"
    type=refreshAndPersist
    retry="5 5 300 5"
    timeout=1
mirrormode TRUE

## 填写本机监听地址
# vi /etc/sysconfig/slapd
SLAPD_URLS="ldapi:/// ldaps://ldap01.xxyd.com"


rm -rf /etc/openldap/slapd.d/*
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d/
chown -R ldap.ldap /etc/openldap/slapd.d
systemctl restart slapd

同步数据测试

在一台主服务器上添加或删除数据,会立即同步到另一台主服务器上即测试成功。

高可用

方案一、

客户端连接两台openldap服务器(主从或主主模式或多主模式)

第一台不可用时会自动连接到第二台

vi /etc/ldap.conf

uri ldaps://ldap01.xxyd.com ldaps://ldap02.xxyd.com

重启服务

service nscd restart

方案二

两台openldap服务器使用主从或主主模式

结合keepalived配置VIP实现故障切换

客户端连接域名:uri ldaps://ldap.xxyd.com,ldap.xxyd.com域名指向VIP

自助修改密码

https://www.ilanni.com/?p=13822

数据备份

ldapsearch -x -b 'dc=xxyd,dc=com' > backupldap_$(date +%Y%m%d-%H%M).ldif

参考链接:

http://chuansong.me/n/317694151860 https://blog.csdn.net/m1213642578/article/details/52578360 http://www.zytrax.com/books/ldap/ch6/ppolicy.html http://blog.163.com/excellent_2008/blog/static/30760156201392362414238/ https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap http://briteming.blogspot.com/2017/11/setting-up-openldap-server-with-openssh.html https://www.cnblogs.com/moonson/archive/2008/11/20/1337775.html

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这