- 新增 ldap_ad.go,支持 AD 密码编码、字段映射与目录类型判断 - 重构 ldap/ldap_users/ldap_ou,兼容 OpenLDAP 与 AD 登录、导入、OU 浏览 - 前端系统设置增加目录类型选择与 AD 配置项 - Dockerfile 按 TARGETARCH 单架构编译 Agent,限制 Node 内存防 OOM - run.sh 新增 docker fast/upgrade,README 补充 LDAP/AD 与常见问题
411 lines
12 KiB
Go
411 lines
12 KiB
Go
package controller
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"ezops/model"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-ldap/ldap/v3"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// LDAPHandler LDAP处理器
|
|
type LDAPHandler struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewLDAPHandler 创建LDAP处理器
|
|
func NewLDAPHandler(db *gorm.DB) *LDAPHandler {
|
|
return &LDAPHandler{db: db}
|
|
}
|
|
|
|
// LDAPAuthInfo LDAP认证返回的用户信息
|
|
type LDAPAuthInfo struct {
|
|
Username string
|
|
DisplayName string
|
|
Email string
|
|
}
|
|
|
|
var ldapUserAttrs = []string{
|
|
"uid", "cn", "displayName", "mail", "userPrincipalName", "sAMAccountName",
|
|
"telephoneNumber", "mobile", "title", "department",
|
|
}
|
|
|
|
var ldapUserAttrSets = [][]string{
|
|
{"uid", "cn", "displayName", "mail", "telephoneNumber", "mobile", "title", "department"},
|
|
{"sAMAccountName", "userPrincipalName", "displayName", "cn", "mail", "telephoneNumber", "mobile", "title", "department"},
|
|
ldapUserAttrs,
|
|
}
|
|
|
|
// dialLDAP 连接LDAP服务器
|
|
func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) {
|
|
if cfg.LDAPHost == "" {
|
|
return nil, fmt.Errorf("LDAP not configured")
|
|
}
|
|
protocol := "ldap"
|
|
if cfg.UseLDAPS != nil && *cfg.UseLDAPS {
|
|
protocol = "ldaps"
|
|
}
|
|
port := 389
|
|
if cfg.LDAPPort != nil && *cfg.LDAPPort > 0 {
|
|
port = *cfg.LDAPPort
|
|
}
|
|
uri := fmt.Sprintf("%s://%s:%d", protocol, cfg.LDAPHost, port)
|
|
dialer := &net.Dialer{Timeout: 5 * time.Second}
|
|
return ldap.DialURL(uri, ldap.DialWithDialer(dialer))
|
|
}
|
|
|
|
// ldapUserFilter 构造兼容 OpenLDAP 与 AD 的用户搜索过滤器 // Logan.Li
|
|
func ldapUserFilter(cfg *model.LDAPConfig, username string) string {
|
|
escaped := ldap.EscapeFilter(username)
|
|
if cfg.SearchFilter != nil && strings.TrimSpace(*cfg.SearchFilter) != "" {
|
|
sf := strings.TrimSpace(*cfg.SearchFilter)
|
|
if strings.Contains(sf, "%s") {
|
|
return strings.ReplaceAll(sf, "%s", escaped)
|
|
}
|
|
return fmt.Sprintf("(&%s(|(uid=%s)(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s)))", sf, escaped, escaped, escaped, escaped)
|
|
}
|
|
return fmt.Sprintf("(|(&(objectClass=inetOrgPerson)(uid=%s))(&(objectClass=user)(|(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s))))", escaped, escaped, escaped, escaped)
|
|
}
|
|
|
|
// ldapADUserFilter 生成 AD 兜底过滤器,参考 opsx-monitor 的 sAMAccountName/userPrincipalName/cn 兼容策略 // Logan.Li
|
|
func ldapADUserFilter(username string) string {
|
|
escaped := ldap.EscapeFilter(username)
|
|
return fmt.Sprintf("(|(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s))", escaped, escaped, escaped)
|
|
}
|
|
|
|
// ldapUserListFilters 返回目录用户列表过滤器,先尊重配置,再补 OpenLDAP/AD 兜底 // Logan.Li
|
|
func ldapUserListFilters(cfg *model.LDAPConfig) []string {
|
|
filters := []string{}
|
|
if cfg.SearchFilter != nil && strings.TrimSpace(*cfg.SearchFilter) != "" {
|
|
sf := strings.TrimSpace(*cfg.SearchFilter)
|
|
if strings.Contains(sf, "%s") {
|
|
filters = append(filters, strings.ReplaceAll(sf, "%s", "*"))
|
|
} else {
|
|
filters = append(filters, sf)
|
|
}
|
|
}
|
|
filters = append(filters,
|
|
"(objectClass=inetOrgPerson)",
|
|
"(&(objectClass=user)(|(sAMAccountName=*)(userPrincipalName=*)))",
|
|
)
|
|
return filters
|
|
}
|
|
|
|
// ldapEntryAttr 按属性名回退读取,兼容 OpenLDAP 与 AD 常见字段 // Logan.Li
|
|
func ldapEntryAttr(entry *ldap.Entry, names ...string) string {
|
|
for _, name := range names {
|
|
if v := entry.GetAttributeValue(name); v != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// ldapUserMapping 读取用户字段映射,同时提供 AD/OpenLDAP 默认回退 // Logan.Li
|
|
func ldapUserMapping(cfg *model.LDAPConfig) map[string]string {
|
|
userMapping := ldapDefaultUserMapping(cfg)
|
|
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
|
_ = json.Unmarshal([]byte(*cfg.UserMapping), &userMapping)
|
|
}
|
|
return userMapping
|
|
}
|
|
|
|
// ldapIdentityFromEntry 将目录条目转换为平台统一用户信息 // Logan.Li
|
|
func ldapIdentityFromEntry(cfg *model.LDAPConfig, entry *ldap.Entry, fallbackUsername string) *LDAPAuthInfo {
|
|
mapping := ldapUserMapping(cfg)
|
|
mappedUsername := ldapEntryAttr(entry, mapping["username"])
|
|
mappedDisplay := ldapEntryAttr(entry, mapping["display_name"])
|
|
mappedEmail := ldapEntryAttr(entry, mapping["email"])
|
|
info := &LDAPAuthInfo{
|
|
Username: ldapFirstNonEmpty(mappedUsername, ldapEntryAttr(entry, "uid", "sAMAccountName", "userPrincipalName", "cn"), fallbackUsername),
|
|
DisplayName: ldapFirstNonEmpty(mappedDisplay, ldapEntryAttr(entry, "displayName", "cn"), fallbackUsername),
|
|
Email: ldapFirstNonEmpty(mappedEmail, ldapEntryAttr(entry, "mail", "userPrincipalName")),
|
|
}
|
|
return info
|
|
}
|
|
|
|
func ldapFirstNonEmpty(values ...string) string {
|
|
for _, v := range values {
|
|
if strings.TrimSpace(v) != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// ldapIsInvalidAttributeErr 判断目录不支持某些属性时的错误,用于 OpenLDAP/AD 属性集降级 // Logan.Li
|
|
func ldapIsInvalidAttributeErr(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
msg := strings.ToLower(err.Error())
|
|
return strings.Contains(msg, "undefined attribute") ||
|
|
strings.Contains(msg, "invalid attribute") ||
|
|
strings.Contains(msg, "attribute type undefined") ||
|
|
strings.Contains(msg, "no such attribute")
|
|
}
|
|
|
|
// ldapSearchUsers 使用多组属性搜索,避免 OpenLDAP 与 AD 互不支持属性时整体失败 // Logan.Li
|
|
func ldapSearchUsers(conn *ldap.Conn, baseDN, filter string, sizeLimit int) (*ldap.SearchResult, error) {
|
|
var lastErr error
|
|
for _, attrs := range ldapUserAttrSets {
|
|
searchReq := ldap.NewSearchRequest(
|
|
baseDN,
|
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
sizeLimit, 10, false,
|
|
filter,
|
|
attrs,
|
|
nil,
|
|
)
|
|
sr, err := conn.Search(searchReq)
|
|
if err == nil {
|
|
return sr, nil
|
|
}
|
|
lastErr = err
|
|
if ldapIsInvalidAttributeErr(err) {
|
|
continue
|
|
}
|
|
return nil, err
|
|
}
|
|
return nil, lastErr
|
|
}
|
|
|
|
// ldapSearchFirstUser 查找单个用户,过滤器兼容 OpenLDAP 与 Active Directory // Logan.Li
|
|
func ldapSearchFirstUser(conn *ldap.Conn, cfg *model.LDAPConfig, username string) (*ldap.Entry, error) {
|
|
for _, filter := range []string{ldapUserFilter(cfg, username), ldapADUserFilter(username)} {
|
|
sr, err := ldapSearchUsers(conn, cfg.BaseDN, filter, 1)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(sr.Entries) > 0 {
|
|
return sr.Entries[0], nil
|
|
}
|
|
}
|
|
return nil, fmt.Errorf("LDAP用户不存在")
|
|
}
|
|
|
|
// tryLDAPAuth 尝试LDAP认证,返回用户信息
|
|
func tryLDAPAuth(db *gorm.DB, username, password string) (*LDAPAuthInfo, error) {
|
|
var cfg model.LDAPConfig
|
|
if err := db.Order("id").First(&cfg).Error; err != nil {
|
|
return nil, fmt.Errorf("LDAP未配置")
|
|
}
|
|
if cfg.LDAPHost == "" {
|
|
return nil, fmt.Errorf("LDAP not configured")
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("LDAP连接失败: %w", err)
|
|
}
|
|
defer conn.Close()
|
|
|
|
// Admin bind
|
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
return nil, fmt.Errorf("LDAP管理员绑定失败: %w", err)
|
|
}
|
|
|
|
entry, err := ldapSearchFirstUser(conn, &cfg, username)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("LDAP用户不存在")
|
|
}
|
|
userDN := entry.DN
|
|
|
|
// 使用用户 DN 重新绑定以校验密码,兼容 OpenLDAP 与 AD // Logan.Li
|
|
if err := conn.Bind(userDN, password); err != nil {
|
|
return nil, fmt.Errorf("LDAP密码验证失败: %w", err)
|
|
}
|
|
|
|
return ldapIdentityFromEntry(&cfg, entry, username), nil
|
|
}
|
|
|
|
// GetLDAPConfig 获取LDAP配置
|
|
// GET /api/v1/admin/ldap-config
|
|
func (h *LDAPHandler) GetLDAPConfig(c *gin.Context) {
|
|
var configs []model.LDAPConfig
|
|
h.db.Order("id").Find(&configs)
|
|
if len(configs) == 0 {
|
|
c.JSON(http.StatusOK, gin.H{})
|
|
return
|
|
}
|
|
cfg := configs[0]
|
|
// mask password
|
|
cfg.AdminPassword = "******"
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Data: cfg})
|
|
}
|
|
|
|
// UpdateLDAPConfig 更新LDAP配置
|
|
// PUT /api/v1/admin/ldap-config
|
|
func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) {
|
|
var input map[string]interface{}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
|
|
return
|
|
}
|
|
|
|
var configs []model.LDAPConfig
|
|
h.db.Order("id").Find(&configs)
|
|
|
|
getStr := func(key string) string {
|
|
if v, ok := input[key].(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
getInt := func(key string) int {
|
|
if v, ok := input[key].(float64); ok {
|
|
return int(v)
|
|
}
|
|
return 0
|
|
}
|
|
getBool := func(key string) *bool {
|
|
if v, ok := input[key].(bool); ok {
|
|
return &v
|
|
}
|
|
return nil
|
|
}
|
|
hasKey := func(key string) bool {
|
|
_, ok := input[key]
|
|
return ok
|
|
}
|
|
|
|
userMappingStr := ""
|
|
if um, ok := input["user_mapping"]; ok {
|
|
if um == nil || um == "" {
|
|
userMappingStr = "{}"
|
|
} else if bytes, err := json.Marshal(um); err == nil {
|
|
userMappingStr = string(bytes)
|
|
}
|
|
}
|
|
|
|
serverType := getStr("server_type")
|
|
if serverType == "" {
|
|
serverType = ldapServerOpenLDAP
|
|
}
|
|
|
|
if len(configs) == 0 {
|
|
// Create
|
|
cfg := model.LDAPConfig{
|
|
ServerType: serverType,
|
|
LDAPHost: getStr("ldap_host"),
|
|
AdminDN: getStr("admin_dn"),
|
|
BaseDN: getStr("base_dn"),
|
|
AdminPassword: getStr("admin_password"),
|
|
}
|
|
if sf := getStr("search_filter"); sf != "" {
|
|
cfg.SearchFilter = &sf
|
|
}
|
|
if userMappingStr != "" {
|
|
cfg.UserMapping = &userMappingStr
|
|
}
|
|
if port := getInt("ldap_port"); port > 0 {
|
|
cfg.LDAPPort = &port
|
|
}
|
|
if b := getBool("use_ldaps"); b != nil {
|
|
cfg.UseLDAPS = b
|
|
}
|
|
h.db.Create(&cfg)
|
|
cfg.AdminPassword = "******"
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "LDAP配置已创建", Data: cfg})
|
|
} else {
|
|
// Update
|
|
cfg := configs[0]
|
|
updates := map[string]interface{}{}
|
|
if hasKey("server_type") {
|
|
st := getStr("server_type")
|
|
if st == "" {
|
|
st = ldapServerOpenLDAP
|
|
}
|
|
updates["server_type"] = st
|
|
}
|
|
if v := getStr("ldap_host"); v != "" {
|
|
updates["ldap_host"] = v
|
|
}
|
|
if v := getStr("base_dn"); v != "" {
|
|
updates["base_dn"] = v
|
|
}
|
|
if v := getStr("admin_dn"); v != "" {
|
|
updates["admin_dn"] = v
|
|
}
|
|
if hasKey("search_filter") {
|
|
v := strings.TrimSpace(getStr("search_filter"))
|
|
updates["search_filter"] = &v
|
|
}
|
|
if userMappingStr != "" {
|
|
updates["user_mapping"] = userMappingStr
|
|
}
|
|
if v := getStr("admin_password"); v != "" && v != "******" {
|
|
updates["admin_password"] = v
|
|
}
|
|
if port := getInt("ldap_port"); port > 0 {
|
|
updates["ldap_port"] = port
|
|
}
|
|
if b := getBool("use_ldaps"); b != nil {
|
|
updates["use_ldaps"] = *b
|
|
}
|
|
if len(updates) > 0 {
|
|
h.db.Model(&cfg).Updates(updates)
|
|
}
|
|
h.db.First(&cfg, cfg.ID)
|
|
cfg.AdminPassword = "******"
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "LDAP配置已更新", Data: cfg})
|
|
}
|
|
}
|
|
|
|
// TestLDAPConnection 测试LDAP连接
|
|
// POST /api/v1/admin/ldap-config/test
|
|
func (h *LDAPHandler) TestLDAPConnection(c *gin.Context) {
|
|
var req struct {
|
|
TestUser string `json:"test_user"`
|
|
TestPassword string `json:"test_password"`
|
|
}
|
|
c.ShouldBindJSON(&req)
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := h.db.Order("id").First(&cfg).Error; err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": "LDAP配置不存在,请先保存配置"})
|
|
return
|
|
}
|
|
if cfg.LDAPHost == "" {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": "LDAP未配置"})
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("连接失败: %s", err)})
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("管理员绑定失败: %s", err)})
|
|
return
|
|
}
|
|
|
|
// If test_user provided, search and verify
|
|
if req.TestUser != "" && req.TestPassword != "" {
|
|
entry, err := ldapSearchFirstUser(conn, &cfg, req.TestUser)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("用户 %s 不存在", req.TestUser)})
|
|
return
|
|
}
|
|
userDN := entry.DN
|
|
if err := conn.Bind(userDN, req.TestPassword); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("密码验证失败: %s", err)})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": fmt.Sprintf("认证成功!用户DN: %s", userDN), "user_info": ldapIdentityFromEntry(&cfg, entry, req.TestUser)}})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": "LDAP连接成功,管理员认证通过"}})
|
|
}
|