OpenLDAP+SSL+SSSD 实现Linux登录集中认证

核能气质少年 提交于 2020-03-24 14:37:36

3 月,跳不动了?>>>

第一部分 OpenLDAP之sldap数据库安装

1、yum安装

yum install -y openldap openldap-servers openssh-ldap openldap-clients migrationtools

2、配置ssl域名证书,实现ldap的TLS加密通信

    通过域名 master.ldap.conf.top(主LDAP)和 slave.ldap.conf.top(从LDAP)域名访问LDAP数据库

a) 创建文件 /etc/pki/CA/openssl.cnf 内容如下

HOME            = .
RANDFILE        = $ENV::HOME/.rnd
oid_section     = new_oids
[ new_oids ]
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
[ ca ]
default_ca  = CA_default        # The default ca section
[ CA_default ]
dir     = /etc/pki/CA       # Where everything is kept
certs       = $dir/certs        # Where the issued certs are kept
crl_dir     = $dir/crl      # Where the issued crl are kept
database    = $dir/index.txt    # database index file.
                   # several ctificates with same subject.
new_certs_dir   = $dir/newcerts     # default place for new certs.
certificate = $dir/certs/ca.crt     # The CA certificate
serial      = $dir/serial       # The current serial number
crlnumber   = $dir/crlnumber    # the current crl number
                   # must be commented out to leave a V1 CRL
crl     = $dir/crl/crl.pem      # The current CRL
private_key = $dir/private/ca.key   # The private key
RANDFILE    = $dir/private/.rand    # private random number file
x509_extensions = usr_cert      # The extentions to add to the cert
name_opt    = ca_default        # Subject Name options
cert_opt    = ca_default        # Certificate field options
default_days    = 3650          # how long to certify for
default_crl_days= 30            # how long before next CRL
default_md  = sha256        # use public key default MD
preserve    = no            # keep passed DN ordering
policy      = policy_dn
[ policy_match ]
countryName     = match
stateOrProvinceName = match
organizationName    = match
organizationalUnitName  = optional
commonName      = supplied
emailAddress        = optional
[ policy_anything ]
countryName     = optional
stateOrProvinceName = optional
localityName        = optional
organizationName    = optional
organizationalUnitName  = optional
commonName      = supplied
emailAddress        = optional
[ policy_dn ]
countryName             = supplied              # required parameter, any value allowed
stateOrProvinceName     = optional
localityName            = optional
organizationName        = match                 # required, and must match root certificate
organizationalUnitName  = optional
commonName              = supplied              # required parameter, any value allowed
emailAddress            = optional              # email in DN is deprecated, use subjectAltName
[ req ]
default_bits        = 2048
default_md      = sha256
encrypt_key             = no
prompt                  = yes
default_keyfile     = client.key
distinguished_name  = req_distinguished_name
x509_extensions = v3_ca # The extentions to add to the self signed cert
string_mask = utf8only
[ req_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default     = CN
countryName_min         = 2
countryName_max         = 2
stateOrProvinceName     = State or Province Name (full name)
stateOrProvinceName_default = Beijing
localityName            = Locality Name (eg, city)
localityName_default        = Beijing
0.organizationName      = Organization Name (eg, company)
0.organizationName_default  = Beijing Century Fortunet Network Technology Co.,Ltd.
organizationalUnitName      = Organizational Unit Name (eg, section)
organizationalUnitName_default  = IT Operation Management
commonName          = Common Name (eg, your name or your server\'s hostname)
commonName_max          = 64
emailAddress            = Email Address
emailAddress_max        = 64
emailAddress_default        = admin@conf.top
[ req_attributes ]
challengePassword       = A challenge password
challengePassword_min       = 4
challengePassword_max       = 20
unstructuredName        = An optional company name
[ usr_cert ]
basicConstraints    = CA:FALSE
nsComment       = "CONFCA Generated Certificate"
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid,issuer
[ v3_req ]
basicConstraints    = CA:FALSE
keyUsage        = digitalSignature, keyEncipherment
extendedKeyUsage        = serverAuth, clientAuth
subjectKeyIdentifier    = hash
subjectAltName      = @alt_names
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
keyUsage        = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign
extendedKeyUsage        = serverAuth, clientAuth, codeSigning, timeStamping, emailProtection, msEFS, 1.3.6.1.4.1.311.10.3.11, 1.3.6.1.4.1.311.20.2.2
basicConstraints = CA:true
[ X509_ca ]
basicConstraints        = CA:TRUE
nsCertType              = sslCA                 # restrict the usage
keyUsage                = keyCertSign, cRLSign  # restrict the usage
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid:always,issuer:always
[ X509_server ]
basicConstraints        = CA:FALSE
nsCertType              = server                # restrict the usage
keyUsage                = digitalSignature, keyEncipherment
extendedKeyUsage        = serverAuth            # restrict the usage
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid,issuer
[ X509_client ]
basicConstraints        = CA:FALSE
nsCertType              = client                # restrict the usage
keyUsage                = digitalSignature      # restrict the usage
extendedKeyUsage        = clientAuth            # restrict the usage
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid,issuer
[ crl_ext ]
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
basicConstraints=CA:FALSE
nsComment           = "CONFCA Generated Certificate"
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
[ tsa ]
default_tsa = tsa_config1   # the default TSA section
[ tsa_config1 ]
dir     = ./demoCA      # TSA root directory
serial      = $dir/tsaserial    # The current serial number (mandatory)
crypto_device   = builtin       # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem  # The TSA signing certificate
                   # (optional)
certs       = $dir/cacert.pem   # Certificate chain to include in reply
                   # (optional)
signer_key  = $dir/private/tsakey.pem # The TSA private key (optional)
default_policy  = tsa_policy1       # Policy if request did not specify it
                   # (optional)
other_policies  = tsa_policy2, tsa_policy3  # acceptable policies (optional)
digests     = md5, sha1     # Acceptable message digests (mandatory)
accuracy    = secs:1, millisecs:500, microsecs:100  # (optional)
clock_precision_digits  = 0 # number of digits after dot. (optional)
ordering        = yes   # Is ordering defined for timestamps?
               # (optional, default: no)
tsa_name        = yes   # Must the TSA name be included in the reply?
               # (optional, default: no)
ess_cert_id_chain   = no    # Must the ESS cert id chain be included?
               # (optional, default: no)
[ alt_names ]
DNS.1 = conf.top
DNS.2 = *.conf.top
DNS.3 = ***.conf.top
DNS.4 = *.***.conf.top
DNS.5 = ldap.conf.top
DNS.6 = *.ldap.conf.top

b) 创建CA证书

# 创建工作目录

cd /etc/pki/CA/ && umask 0077 && mkdir -p /etc/pki/CA/{private,certs,crl,csr,newcerts,private} && touch index.txt && echo '00'>serial

# 创建CA证书的私钥

openssl genrsa -out private/ca.key 2048

# 创建CA证书的公钥,其他配置可以默认,出现 Common Name (eg, your name or your server's hostname) []:
# 的时候一定不能默认了,CA证书这里就输入CONFCA

openssl req -days 177121 -new -sha256 -x509 -key private/ca.key -out certs/ca.crt -config openssl.cnf

c) 创建域名证书

## 创建key

openssl genrsa -out private/conf.top.key 2048  

## 生成csr文件,同样遇到输入 Common Name  的时候不能默认,这里输入conf.top

openssl req -new -sha256 -key private/conf.top.key -out csr/conf.top.csr -extensions v3_req -config openssl.cnf

## 签名证书

openssl ca -days 30659 -in csr/conf.top.csr -out certs/conf.top.crt -extensions v3_req -config openssl.cnf

d) 将生成好的CA证书和服务器端域名证书拷贝到openldap目录

cp /etc/pki/CA/certs/ca.crt /etc/openldap/certs/ca.crt                  # CA证书
cp /etc/pki/CA/certs/conf.top.crt /etc/openldap/certs/conf.top.crt      # 服务器证书
cp /etc/pki/CA/private/conf.top.key /etc/openldap/certs/conf.top.key    # 服务器私钥

# 设置目录安全

chown -R root:ldap /etc/openldap/certs
chmod -R 750 /etc/openldap/certs

3、 配置OpenLDAP schema模板
a) 拷贝ssh的schema模板(路径可能不同,根据openssh-ldap和sudo版本号找对应路径)

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

b) 拷贝sudo的schema模板

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

c) 自定义权限控制模板

    创建schema模板文件

touch /etc/openldap/schema/my.schema

    my.schema自定义模板(objectclass=MyAccount)说明:

active: 账号状态 0-禁用  1-启用 (必须)
access:访问权限控制 (必须) 可以有多个值,添加用户的时候必须添加此字段值为ssh
         此字段设计为增加多个值例如web 、***,使用ldap客户端时用search_filter进行权限控制
gauthcode: 谷歌Token (可选) 用于配合google-authenticator(Google Authenticator PAM module)谷歌Token验证模块使用
另外增加一些常用字段:
sn (姓) givenName (名) displayName (姓名) mobile (手机号) mail (邮件) photo (照片)

    /etc/openldap/schema/my.schema 文件内容

attributetype ( 1.3.6.1.4.1.30000.500.1.1.1 NAME 'active'
   DESC 'MANDATORY: Account active stauts 0-disable 1-enable'
   EQUALITY integerMatch
       SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
attributetype ( 1.3.6.1.4.1.30000.500.1.1.2 NAME 'access'
   DESC 'MANDATORY: Access Control'
   EQUALITY caseExactIA5Match
       SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
attributetype ( 1.3.6.1.4.1.30000.500.1.1.3 NAME 'gauthcode'
       DESC 'MANDATORY: Google authenticator'
       EQUALITY caseExactIA5Match
       SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
objectclass ( 1.3.6.1.4.1.30000.500.1.2.0 NAME 'MyAccount' SUP top AUXILIARY
   DESC 'MANDATORY: conf user account'
   MUST ( active )
   MAY ( access $ gauthcode $ sn $ givenName $ displayName $ mobile $ mail $ photo)
   )

4、创建slapd配置文件

    使用slappasswd命令,输入密码后生成管理员密码串,将密码替换到下一步中的rootpw

slappasswd

    创建配置文件/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
include     /etc/openldap/schema/sudo.schema
include     /etc/openldap/schema/openssh-lpk-openldap.schema
include     /etc/openldap/schema/my.schema
allow bind_v2
disallow bind_anon
require authc
pidfile    /var/run/openldap/slapd.pid
argsfile   /var/run/openldap/slapd.args
# 主从同步模块
#moduleload syncprov.la
# 证书路径
TLSCACertificatePath /etc/openldap/certs/ca.crt
TLSCertificateFile /etc/openldap/certs/conf.top.crt
TLSCertificateKeyFile /etc/openldap/certs/conf.top.key
TLSCiphersuite TLSv1.2+RSA:!EXPORT:!NULL
TLSVerifyClient never
# ACL权限控制
database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by * none
database monitor
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read
        by dn.exact="cn=root,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_admin,ou=ldap,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by * none
database    bdb
access to attrs=gauthcode
        by anonymous auth
        by dn.exact="uid=ldap_write,ou=ldap,dc=conf,dc=top" write
        by dn.exact="uid=ldap_admin,ou=ldap,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by * none
access to attrs=userPassword
        by anonymous auth
        by dn.exact="uid=ldap_read,ou=ldap,dc=conf,dc=top" none
        by dn.exact="uid=ldap_write,ou=ldap,dc=conf,dc=top" write
        by dn.exact="uid=ldap_admin,ou=ldap,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by self write
        by * none
access to attrs=shadowLastChange
        by anonymous auth
        by self write
        by dn.exact="uid=ldap_read,ou=ldap,dc=conf,dc=top" read
        by dn.exact="uid=ldap_write,ou=ldap,dc=conf,dc=top" write
        by dn.exact="uid=ldap_admin,ou=ldap,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by * none
access to *
        by anonymous auth
        by dn.exact="uid=ldap_read,ou=ldap,dc=conf,dc=top" read
        by dn.exact="uid=ldap_write,ou=ldap,dc=conf,dc=top" write
        by dn.exact="uid=ldap_admin,ou=ldap,dc=conf,dc=top" manage
        by dn.exact="uid=ldap_sync,ou=ldap,dc=conf,dc=top" read
        by * none
# 其他配置
suffix      "dc=conf,dc=top"
checkpoint  1024 15
rootdn      "cn=root,dc=conf,dc=top"
rootpw      <用slappasswd命令生成的密码>
# 当做从库的时候,需要配置为readonly属性
#readonly    on
directory   /var/lib/ldap
lastmod     on
index objectClass                          eq,pres
index ou,cn,mail,sn,givenName              eq,pres,sub
index uidNumber,gidNumber,loginShell       eq,pres
index uid,memberUid,mobile                 eq,pres,sub
index nisMapName,nisMapEntry               eq,pres,sub
index sudoUser                             eq
index displayName               pres,sub,eq
index default                   sub
index entryCSN,entryUUID        eq  
# 配置同步
#overlay syncprov
#syncprov-checkpoint 100 10  
#syncprov-sessionlog 100
#serverID      21       #服务器标识,主从配置不相同
#syncrepl      rid=101  #主从配置相同
#              provider=ldaps://master.ldap.conf.top
#              binddn="uid=ldap_sync,ou=ldap,dc=conf,dc=top"
#              bindmethod=simple
#              starttls=yes
#              tls_cacert=/etc/openldap/certs/ca.crt
#              tls_reqcert=never
#              credentials="<ldap_sync用户的密码>"
#              searchbase="dc=conf,dc=top"
#              schemachecking=off
#              type=refreshAndPersist
#              retry="60 +"
#mirrormode on
# 日志级别 0:关闭日志
loglevel 0

    修改sldap默认启动配置文件 /etc/sysconfig/ldap ,关闭ldap://只启用ldaps://

SLAPD_LDAP=yes
SLAPD_LDAPI=yes
SLAPD_LDAPS=no

    拷贝DB_CONFIG配置文件

cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
chmod 600 /var/lib/ldap/DB_CONFIG
chown -R ldap:ldap /var/lib/ldap
chmod 700 /var/lib/ldap

    初始化sldap系统配置的脚本 /etc/openldap/init.sh(更改sladp.conf配置后执行该脚本)

#!/bin/bash
/etc/init.d/slapd stop
rm -rf /etc/openldap/slapd.d/*
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d || exit 1
chmod 700 /etc/openldap/slapd.d
chown -R ldap:ldap /etc/openldap/slapd.d
chown root:ldap /etc/openldap/slapd.conf
chmod 750 /etc/openldap/slapd.conf
/etc/init.d/slapd start

    先启动sldap服务,然后执行init.sh

/etc/init.d/sldap start
sh /etc/openldap/init.sh

5、创建用户和组并导入到ldap数据库

    a) 规划和用户ID 和组ID,比如组ID:20000-29999,用户id: 30000+
    计划创建3个组:运维confops、开发confdev、测试confqa,创建用户admin属于运维组。

    b) 然后创建用户列表 user.txt,格式和Linux系统/etc/passwd相同, 如下

admin:x:30001:20001::/home/admin:/bin/bash

    c) 创建组列表文件 group.txt,格式和/etc/group相同,如下

confops:x:20001:admin
confdev:x:20002:
confqa:x:20003:

    d) 创建密码文本shadow.txt, 格式和/etc/shadow相同

admin:$6$2Zdjcxvz$p/dHCZQUTn9dmSZdv2abCyd/oPRhskr3z4MNCCAYOn1LLYS3Q6DXw.VVXFt3CWger2SLwYWYS/a64yHNOuS3I/:16968:0:99999:7:::

使用migrationtools工具将导出的用户组密码等文本转为ldap能读取的ldif文件

    e) 导入环境变量

export LDAP_BASEDN="dc=conf,dc=top"
export LDAP_DEFAULT_MAIL_DOMAIN="conf.top"

    f) 生成ldif数据库文件

/usr/share/migrationtools/migrate_base.pl > base.ldif
/usr/share/migrationtools/migrate_passwd.pl user.txt > user.ldif
/usr/share/migrationtools/migrate_group.pl group.txt > group.ldif
/usr/share/migrationtools/migrate_passwd.pl shadow.txt > shadow.ldif

    g) 本地/etc/hosts文件添加域名解析,如果sldap服务部署在其他服务器,这里该为对应服务器IP

127.0.0.1 master.ldap.conf.top

    h) 使用ldapadd工具将ldif文件导入到数据库,输入sldap的rootdn管理员密码

ldapadd -H "ldaps://master.ldap.conf.top" -D "cn=root,dc=conf,dc=top" -W -x -f base.ldif
ldapadd -H "ldaps://master.ldap.conf.top" -D "cn=root,dc=conf,dc=top" -W -x -f user.ldif
ldapadd -H "ldaps://master.ldap.conf.top" -D "cn=root,dc=conf,dc=top" -W -x -f group.ldif
#ldapadd -H "ldaps://master.ldap.conf.top" -D "cn=root,dc=conf,dc=top" -W -x -f shadow.ldif #可忽略

# 验证导入的数据,可以查询到从passwd导出的用户

ldapsearch -H "ldaps://master.ldap.conf.top" -D "cn=root,dc=conf,dc=top" -W -x -b -L -W -b "ou=People,dc=conf,dc=top"

6、创建LDAP系统账号ldap_admin, ldap_read, ldap_sync, ldap_write

    使用slappasswd命令生成4个ldap账号的密码并替换以下内容中userPassword字段,然后创建文件ldap.ldif,内容如下:

dn: ou=ldap,dc=conf,dc=top
objectClass: top
objectClass: organizationalUnit
ou: ldap
description:: TERBUOezu+e7n+i0puWPtw==

dn: uid=ldap_read,ou=ldap,dc=conf,dc=top
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
sn: ldap_read
displayName: ldap_read
uid: ldap_read
homeDirectory: /home/ldap_read
loginShell: /sbin/nologin
cn: ldap_read
uidNumber: 58
gidNumber: 55
userPassword: {SSHA}fr03Kp4NIYfNXQDrO4a+J0yYRVZmZ3M2UGVoQ2lJMzk=

dn: uid=ldap_write,ou=ldap,dc=conf,dc=top
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
sn: ldap_write
displayName: ldap_write
uid: ldap_write
homeDirectory: /home/ldap_write
loginShell: /sbin/nologin
cn: ldap_write
uidNumber: 57
gidNumber: 55
userPassword: {SSHA}TahVHL4g/451wuljaM/bRbPQnz9Ba2YxVmNCZi9vNEo=

dn: uid=ldap_admin,ou=ldap,dc=conf,dc=top
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
sn: ldap_admin
displayName: ldap_admin
uid: ldap_admin
homeDirectory: /home/ldap_admin
loginShell: /sbin/nologin
cn: ldap_admin
uidNumber: 56
gidNumber: 55
userPassword: {SSHA}IgT0ZyVL4YyEr4LPsti59tCB0wVMT25tdWpDemhidjQ=

dn: uid=ldap_sync,ou=ldap,dc=conf,dc=top
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
givenName: ldap_sync
sn: ldap_sync
displayName: ldap_sync
uid: ldap_sync
homeDirectory: /home/ldap_sync
loginShell: /sbin/nologin
cn: ldap_sync
uidNumber: 59
gidNumber: 55
userPassword: {SSHA}reRN6H+hsiVdIRSFCfg9E6wwP9lQdkUzc1pCeUJROC8=

    导入ldap.ldif账号

ldapadd -D "cn=root,dc=conf,dc=top" -W -x -f ldap.ldif

7、创建Sudo模板,手动替换以下内容中的域名,保存为sudo.ldif

    模板中confops组和admin用户可以免密码sudo

    confdev和confqa组只允许sudo某些命令

    zabbix用户可以删除或者按照此模板给任意用户特定的sudo权限

dn: ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: organizationalUnit
description: SUDO Configuration Subtree
ou: SUDOers

dn: cn=defaults,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: visiblepw
sudoOption: always_set_home
sudoOption: env_reset

dn: cn=root,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: root
sudoUser: root
sudoHost: ALL
sudoRunAsUser: ALL
sudoCommand: ALL
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset

dn: cn=%wheel,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: %wheel
sudoUser: %wheel
sudoHost: ALL
sudoRunAsUser: ALL
sudoCommand: ALL
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoOption: requiretty

dn: cn=%confops,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: %confops
sudoUser: %confops
sudoHost: ALL
sudoRunAsUser: ALL
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoCommand: ALL
sudoCommand: !/bin/passwd

dn: cn=%confdev,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: %confdev
sudoUser: %confdev
sudoHost: ALL
sudoRunAsUser: ALL
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoCommand: /sbin/service
sudoCommand: !/bin/passwd
sudoCommand: /etc/init.d/tomcat
sudoCommand: /bin/kill
sudoCommand: /usr/bin/pkill
sudoCommand: /usr/bin/killall
sudoCommand: /etc/init.d/confservice
sudoCommand: /bin/su - app -s /bin/bash
sudoCommand: /bin/su - tomcat -s /bin/bash

dn: cn=%confqa,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: %confqa
sudoUser: %confqa
sudoHost: ALL
sudoRunAsUser: ALL
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoCommand: /sbin/service
sudoCommand: !/bin/passwd
sudoCommand: /etc/init.d/confservice
sudoCommand: /bin/kill
sudoCommand: /usr/bin/pkill
sudoCommand: /usr/bin/killall
sudoCommand: /bin/su - app -s /bin/bash
sudoCommand: /bin/su - tomcat -s /bin/bash
sudoCommand: /etc/init.d/tomcat

dn: cn=zabbix,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: zabbix
sudoHost: ALL
sudoUser: zabbix
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoRunAsUser: root
sudoCommand: !/bin/passwd
sudoCommand: /etc/init.d/tomcat
sudoCommand: /etc/init.d/confservice
sudoCommand: /usr/bin/nmap
sudoCommand: /usr/local/zabbix-ztc/bin/sudo-*

dn: cn=admin,ou=SUDOers,dc=conf,dc=top
objectClass: top
objectClass: sudoRole
cn: admin
sudoHost: ALL
sudoRunAsUser: ALL
sudoOption: !authenticate
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: env_reset
sudoCommand: ALL
sudoCommand: !/bin/passwd
sudoUser: admin

    导入用户和组后,默认应该是没有我们自定义的my.schema模板(objectclass=MyAccount)

    需要通过LDAP 客户端(推荐用Windows下的LDAP Admin软件),连接ldap数据库后,将用户增加:

    objectClass: MyAccount 和 objectClass: ldapPublicKey

    需要填入sshPublicKey (用户ssh公钥)、 active (1启用,0禁用) 、 access (值为ssh, 授权用户ssh登录)

第二部分 OpenLDAP客户端sssd安装配置

1、yum安装sssd-ldap客户端

yum install authconfig sssd-ldap -y

2、使用authconfig配置启用sssd

authconfig \
--passalgo=sha512 \
--enablesssd \
--enablesssdauth \
--enablelocauthorize \
--ldapserver=ldaps://master.ldap.conf.top \
--disableldaptls \
--ldapbasedn="dc=conf,dc=top" \
--enablerfc2307bis \
--enablemkhomedir \
--enablecachecreds \
--enableldaptls \
--enablemkhomedir \
--disableldap \
--disableldapauth \
--disablefingerprint \
--disablesmartcard \
--disablekrb5 \
--update

3、配置sssd.conf

    将第一部分创建的CA证书 /etc/pki/CA/certs/ca.crt 拷贝到 /etc/openldap/certs/ca.crt

    说明:
    enumerate=False 禁止getent命令遍历ldap中的用户和组,改为True可以执行getent passwd或getent group命令列出ldap中的用户或组
    ldap_user_search_filter 登录权限控制,active必须为1时才能登录
    ldap_access_filter 访问权限控制,此处每台服务器(客户端)上的配置IP要替换为本机IP
    例如: (|(host=*)(host=192.168.61.11)) 意思是当用户的host字段包含*或者host包含该服务器的IP时才能登录
    ldap_backup_uri LDAP的备份服务器
    ldap_default_authtok 是ldap_read的用户密码(明文)

    创建或替换 /etc/sssd/sssd.conf 内容如下:

[domain/LDAP]
enumerate=False
entry_cache_timeout = 3600
refresh_expired_interval = 1800
cache_credentials = TRUE
account_cache_expiration = 1
pwd_expiration_warning = 0

id_provider = ldap
auth_provider = ldap
sudo_provider = ldap
access_provider = ldap
chpass_provider = ldap
selinux_provider = none
subdomains_provider = none
autofs_provider = none
hostid_provider = none

lookup_family_order = ipv4_only
ldap_uri = ldaps://master.ldap.conf.top
ldap_backup_uri = ldaps://slave.ldap.conf.top
ldap_chpass_uri = ldaps://master.ldap.conf.top
ldap_default_bind_dn = uid=ldap_read,ou=ldap,dc=conf,dc=top
ldap_default_authtok = rm3cZklvmufI760O
ldap_search_base = dc=conf,dc=top
ldap_user_search_base = ou=People,dc=conf,dc=top
ldap_group_search_base = ou=Group,dc=conf,dc=top
ldap_sudo_search_base = ou=SUDOers,dc=conf,dc=top
ldap_user_search_filter = (active=1)(access=ssh)

ldap_access_order = filter
ldap_access_filter = (|(host=\*)(host=192.168.61.11))
ldap_pwd_policy = shadow
ldap_user_ssh_public_key = sshPublicKey
ldap_account_expire_policy = shadow
ldap_chpass_update_last_change = True

ldap_id_use_start_tls = True
ldap_tls_reqcert = hard
ldap_tls_cacertdir = /etc/openldap/certs
ldap_tls_cacert = /etc/openldap/certs/ca.crt
ldap_tls_cipher_suite = TLSv1.2+RSA:!EXPORT:!NULL
cache_credentials = True

[sssd]
domains = LDAP
services = nss, pam, ssh, sudo
config_file_version = 2

[pam]
domains = LDAP
offline_credentials_expiration = 1
offline_failed_login_attempts = 3
pam_account_expired_message = Account expired, please call help desk.

[ssh]
domains = LDAP
ssh_hash_known_hosts = false

[sudo]
domains = LDAP

[nss]
domains = LDAP
fd_limit = 65535
filter_groups = root,bin,daemon,sys,adm,tty,disk,lp,mem,kmem,wheel,mail,uucp,man,games,gopher,video,dip,ftp,lock,audio,nobody,users,dbus,utmp,utempter,floppy,vcsa,stapusr,stapsys,stapdev,abrt,cdrom,tape,dialout,haldaemon,ntp,cgred,saslauth,postdrop,postfix,sshd,oprofile,tcpdump,screen,slocate,www,tomcat,apache,nginx,zabbix,rpc,rpcuser,nfsnobody
filter_users = root,bin,daemon,adm,lp,sync,shutdown,halt,mail,uucp,operator,games,gopher,ftp,nobody,dbus,vcsa,abrt,haldaemon,ntp,saslauth,postfix,sshd,oprofile,tcpdump,www,tomcat,apache,nginx,zabbix,rpc,rpcuser,nfsnobody

    修改配置文件权限

chmod 600 /etc/sssd/sssd.conf

    启动sssd客户端服务

chkconfig sssd on
/etc/init.d/sssd start

4、修改 /etc/nsswitch.conf

/etc/nsswitch.conf直接替换为下面内容

passwd:     files sss
shadow:     files sss
group:      files sss
hosts:      files dns
bootparams: nisplus [NOTFOUND=return] files
ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files
netgroup:   files
publickey:  nisplus
automount:  files
aliases:    files nisplus
sudoers:    files sss

5、修改 /etc/ssh/sshd_config 加入以下内容

PubkeyAuthentication yes
AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys
AuthorizedKeysCommandRunAs nobody

6、重启ssh

/etc/init.d/sshd restart

7、另外通过LDAP Admin工具管理,给用户手动添加扩展属性

    通过LDAP Admin工具连接LDAP服务器,双击某个用户例如admin,打开用户属性,在账户扩展属性里勾选Shadow账户
    在目录树上找到对应用户uid=admin,右键编辑条目,在弹出编辑窗口中,左侧objectclass下拉选择并添加我们自定义的模板MyAccount和ssh公钥模块ldapPublickey,然后在右侧将黑色必填项填写后保存。备注: active=1(启用该用户),access=ssh(授权ssh登录), sshPublicKey(填写用户公钥)

参考: https://sgallagh.fedorapeople.org/sssd/1.7.0/man/sssd-ldap.5.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!