func (ls *LdapSource) SearchGroup(name string) (*models.Group, error) { l, err := ls.dial() if err != nil { return nil, err } err = l.Bind(ls.BindDN, ls.Passwd) if err != nil { log.Printf("ERROR: Cannot bind: %s\n", err.Error()) return nil, err } search := ldap.NewSearchRequest( fmt.Sprintf(groupDnFmt, name, ls.Base), ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, "(objectclass=groupOfNames)", []string{"member"}, nil) sr, err := l.Search(search) if err != nil { // log.Printf("LDAP search error: %s", err) return nil, err } vals := sr.Entries[0].GetAttributeValues("member") members := make([]string, len(vals)) for i, dn := range vals { members[i] = dn[strings.Index(dn, "=")+1 : strings.Index(dn, ",")] } return &models.Group{name, members}, nil }
func (ls *LdapSource) ListPaged(limit int) (staffs []*models.Staff) { err := ls.Bind(ls.BindDN, ls.Passwd, false) if err != nil { // log.Printf("ERROR: Cannot bind: %s\n", err.Error()) return nil } if limit < 1 { limit = 1 } search := ldap.NewSearchRequest( "ou=people,"+ls.Base, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.Filter, ls.Attributes, nil) sr, err := ls.c.SearchWithPaging(search, uint32(limit)) if err != nil { log.Printf("ERROR: %s for search %v\n", err, search) return } if len(sr.Entries) > 0 { staffs = make([]*models.Staff, len(sr.Entries)) for i, entry := range sr.Entries { staffs[i] = entryToUser(entry) } } return }
// Example User Authentication shows how a typical application can verify a login attempt func Example_userAuthentication() { // The username and password we want to check username := "******" password := "******" bindusername := "******" bindpassword := "******" l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() // Reconnect with TLS err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) if err != nil { log.Fatal(err) } // First bind with a read only user err = l.Bind(bindusername, bindpassword) if err != nil { log.Fatal(err) } // Search for the given username searchRequest := ldap.NewSearchRequest( "dc=example,dc=com", ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, fmt.Sprintf("(&(objectClass=organizationalPerson)&(uid=%s))", username), []string{"dn"}, nil, ) sr, err := l.Search(searchRequest) if err != nil { log.Fatal(err) } if len(sr.Entries) != 1 { log.Fatal("User does not exist or too many entries returned") } userdn := sr.Entries[0].DN // Bind as the user to verify their password err = l.Bind(userdn, password) if err != nil { log.Fatal(err) } // Rebind as the read only user for any futher queries err = l.Bind(bindusername, bindpassword) if err != nil { log.Fatal(err) } }
// NewSearchRequest creates a new search request for the LDAP query and optionally includes more attributes func (q *LDAPQuery) NewSearchRequest(additionalAttributes []string) *ldap.SearchRequest { return ldap.NewSearchRequest( q.BaseDN, int(q.Scope), int(q.DerefAliases), 0, // allowed return size - indicates no limit q.TimeLimit, false, // not types only q.Filter, additionalAttributes, nil, // no controls ) }
// buildDNQuery builds the query that finds an LDAP entry with the given DN // this is done by setting the DN to be the base DN for the search and setting the search scope // to only consider the base object found func (o *LDAPQueryOnAttribute) buildDNQuery(dn string, attributes []string) *ldap.SearchRequest { return ldap.NewSearchRequest( dn, ldap.ScopeBaseObject, // over-ride original int(o.DerefAliases), 0, // allowed return size - indicates no limit o.TimeLimit, false, // not types only "objectClass=*", // filter that returns all values attributes, nil, // no controls ) }
func (_s *LDAP) _getBaseDN(rLog SBMSystem.LogFile, search, basedn string) string { var uattr = []string{"dn"} lsearch := ldap.NewSearchRequest(basedn, 2, ldap.NeverDerefAliases, 0, 0, false, search, uattr, nil) sr, err := _s.D.Search(lsearch) if err != nil { rLog.LogDbg(0, "LDAP::Search() ", basedn, " error: ", err) } if len(sr.Entries) > 0 { for _, entry := range sr.Entries { return entry.DN } } return "" }
func (ls *LdapSource) getEntry(udn string) (*ldap.Entry, error) { search := ldap.NewSearchRequest( udn, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.Filter, ls.Attributes, nil) sr, err := ls.c.Search(search) if err != nil { log.Printf("LDAP Search '%s' Error: ", udn, err) return nil, err } if len(sr.Entries) > 0 { return sr.Entries[0], nil } return nil, ErrNotFound }
func inGroup(username, group string, config *Config, conn *ldap.Conn, attrs []string) (bool, map[string][]string, error) { groupDN, err := getDN(group, config, conn) if err != nil { if config.Debug { log.Printf("DEBUG: Error: %s\n", err) } return false, nil, err } search := ldap.NewSearchRequest( config.BaseDN, ldap.ScopeWholeSubtree, ldap.DerefAlways, 1, 0, false, fmt.Sprintf("(sAMAccountName=%s)", username), append(attrs, "memberOf"), nil, ) result, lErr := conn.Search(search) if lErr != nil { if config.Debug { log.Printf("DEBUG: LDAP Error %v\n", lErr) } return false, nil, lErr } if len(result.Entries) == 1 { entryAttrs := attrsToMap(result.Entries[0]) if groups, ok := entryAttrs["memberOf"]; ok { for _, g := range groups { if groupDN == g { for _, key := range attrs { if key == "memberOf" { return true, entryAttrs, nil } } delete(entryAttrs, "memberOf") return true, entryAttrs, nil } } } return false, entryAttrs, nil } return false, nil, LDAPError("Amount of Entries returned was not one") }
func (_s *LDAP) _checkGroupMember(rLog SBMSystem.LogFile, userDN, groupDN, baseDN string, recurse_count int) int { var ( uattr = []string{"memberOf"} result = int(-1) ) if userDN == "" || groupDN == "" { return -1 } if recurse_count <= 0 { return -1 } lsearch := ldap.NewSearchRequest(userDN, 0, ldap.NeverDerefAliases, 0, 0, false, "(objectclass=*)", uattr, nil) sr, err := _s.D.Search(lsearch) if err != nil { rLog.LogDbg(0, "LDAP::Search() ", userDN, " error: ", err) } if len(sr.Entries) > 0 { for _, entry := range sr.Entries { for _, attr := range entry.Attributes { if attr.Name == "memberOf" { for _, x := range attr.Values { if groupDN == x { return 0 } else { if x != userDN { result = _s._checkGroupMember(rLog, x, groupDN, baseDN, recurse_count-1) if result == 0 { return 0 } } } } } } } } return -1 }
// buildAttributeQuery builds the query containing a filter that conjoins the common filter given // in the configuration with the specific attribute filter for which the attribute value is given func (o *LDAPQueryOnAttribute) buildAttributeQuery(attributeValue string, attributes []string) *ldap.SearchRequest { specificFilter := fmt.Sprintf("%s=%s", ldap.EscapeFilter(o.QueryAttribute), ldap.EscapeFilter(attributeValue)) filter := fmt.Sprintf("(&(%s)(%s))", o.Filter, specificFilter) return ldap.NewSearchRequest( o.BaseDN, int(o.Scope), int(o.DerefAliases), 0, // allowed return size - indicates no limit o.TimeLimit, false, // not types only filter, attributes, nil, // no controls ) }
// Search LDAP by cn filter func searchByName(l *ldap.Conn, name string) (*ldap.SearchResult, error) { filter := fmt.Sprintf("(cn=%v)", ReplaceAccents(name)) search := ldap.NewSearchRequest( baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, filter, attributes, nil) sr, err := l.Search(search) if err != nil { return nil, err } switch { case len(sr.Entries) == 0: return sr, ErrNoResults case len(sr.Entries) > 1: return sr, ErrTooManyResults } return sr, nil }
func getDN(cn string, config *Config, conn *ldap.Conn) (string, error) { search := ldap.NewSearchRequest( config.BaseDN, ldap.ScopeWholeSubtree, ldap.DerefAlways, 1, 0, false, fmt.Sprintf("(cn=%s)", cn), nil, nil, ) result, err := conn.Search(search) if err != nil { if config.Debug { log.Printf("DEBUG: LDAP Error %v\n", err) } return "", err } if len(result.Entries) > 0 { return result.Entries[0].DN, nil } return "", ConfigError(fmt.Sprintf("No DN found for: %s", cn)) }
func getAttrs(username string, config *Config, conn *ldap.Conn, attrs []string) (map[string][]string, error) { search := ldap.NewSearchRequest( config.BaseDN, ldap.ScopeWholeSubtree, ldap.DerefAlways, 1, 0, false, fmt.Sprintf("(sAMAccountName=%s)", username), attrs, nil, ) result, lErr := conn.Search(search) if lErr != nil { if config.Debug { log.Printf("DEBUG: LDAP Error %v\n", lErr) } return nil, lErr } if len(result.Entries) == 1 { return attrsToMap(result.Entries[0]), nil } return nil, LDAPError("Amount of Entries returned was not one") }
// ExampleConn_Search demonstrates how to use the search interface func ExampleConn_Search() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() searchRequest := ldap.NewSearchRequest( "dc=example,dc=com", // The base dn to search ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, "(&(objectClass=organizationalPerson))", // The filter to apply []string{"dn", "cn"}, // A list attributes to retrieve nil, ) sr, err := l.Search(searchRequest) if err != nil { log.Fatal(err) } for _, entry := range sr.Entries { fmt.Printf("%s: %v\n", entry.DN, entry.GetAttributeValue("cn")) } }
//ldap search and return required attributes' value from searched entries //default return entry's DN value if you leave attrs array empty func (la *LDAPAuth) ldapSearch(l *ldap.Conn, baseDN *string, filter *string, attrs *[]string) (string, error) { if l == nil { return "", fmt.Errorf("No ldap connection!") } glog.V(2).Infof("Searching...basedDN:%s, filter:%s", *baseDN, *filter) searchRequest := ldap.NewSearchRequest( *baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, *filter, *attrs, nil) sr, err := l.Search(searchRequest) if err != nil { return "", err } if len(sr.Entries) != 1 { return "", fmt.Errorf("User does not exist or too many entries returned.") } var buffer bytes.Buffer for _, entry := range sr.Entries { if len(*attrs) == 0 { glog.V(2).Infof("Entry DN = %s", entry.DN) buffer.WriteString(entry.DN) } else { for _, attr := range *attrs { values := strings.Join(entry.GetAttributeValues(attr), " ") glog.V(2).Infof("Entry %s = %s", attr, values) buffer.WriteString(values) } } } return buffer.String(), nil }
func goNTUWork(conf SBMSystem.ReadJSONConfig, rLog SBMSystem.LogFile) { type usIDPartList struct { id int name string } var ( ldap_Attr []string ldap_VCard []string queryx string multiInsert = int(64) //idxUsers = int(1) idxCards = int(1) workMode = string("FULL") i int pg SBMConnect.PgSQL my SBMConnect.MySQL ld SBMConnect.LDAP err error pgrows1 *sql.Rows ) rLog.Log("--> WakeUP!") for i = 0; i < len(conf.Conf.WLB_LDAP_ATTR); i++ { ldap_Attr = append(ldap_Attr, conf.Conf.WLB_LDAP_ATTR[i][0]) ldap_VCard = append(ldap_VCard, conf.Conf.WLB_LDAP_ATTR[i][1]) } if pg.Init(conf, "") < 0 { log.Println("Init PgSQL Error!") return } defer pg.Close() if my.Init(conf, mySQL_InitDB) < 0 { log.Println("Init MySQL Error!") return } defer my.Close() if ld.Init(conf) < 0 { log.Println("Init LDAP Error!") return } defer ld.Close() time.Sleep(10 * time.Second) x := make(map[string]string, len(ldap_Attr)) multiCount := 0 rLog.Log("\tCreate cacheDB from LDAP...") time_now := time.Now().Unix() time_get := pg.QSimple("select updtime from aaa_dav_ntu where userid=0;") switch { case time_get < 0: log.Println("PgSQL: Error reading NTU table") return case time_get > 0: pgrows1, err = pg.D.Query("select x.id, x.login, x.password, x.cdavprefix from aaa_logins as x where x.id in (select userid from aaa_dns where userid=x.id) order by login;") if err != nil { log.Printf("PG::Query() 02 error: %v\n", err) return } workMode = "FULL" case time_get == 0: pgrows1, err = pg.D.Query("select x.id, x.login, x.password, x.cdavprefix from aaa_logins as x, aaa_dav_ntu as y where x.id=y.userid and x.id in (select userid from aaa_dns where userid=x.id) order by login;") if err != nil { log.Printf("PG::Query() 03 error: %v\n", err) return } workMode = "PART" } usID := 0 usName := "" usPass := "" usCDavPrefix := 0 //userIDGet := 0 usIDArray := make([]usIDPartList, 0) for pgrows1.Next() { usCDavPrefix = 0 pgrows1.Scan(&usID, &usName, &usPass, &usCDavPrefix) usIDArray = append(usIDArray, usIDPartList{id: usID, name: usName}) /* userIDGet = my.QSimple("select id from users where username='******';") switch { case userIDGet < 0: log.Println("Error get user ID") return case userIDGet > 0: idxUsers = userIDGet case userIDGet == 0: userIDGet = my.QSimple("select id from users order by id desc limit 1;") if userIDGet > 0 { userIDGet++ idxUsers = userIDGet } else { userIDGet = 0 userIDGet++ log.Println("Error get max user ID") //return } } */ queryx = fmt.Sprintf("INSERT INTO z_cache_users (id, username, digesta1)\n\tVALUES (%d, '%s', '%s');", usID, usName, usPass) queryx = fmt.Sprintf("%s\nINSERT INTO z_cache_principals (id, uri, email, displayname, vcardurl)\n\tVALUES (%d, 'principals/%s', NULL, NULL, NULL);", queryx, usID, usName) queryx = fmt.Sprintf("%s\nINSERT INTO z_cache_addressbooks (id, principaluri, uri, ctag)\n\tVALUES (%d, 'principals/%s', 'default', 1); select id from users order by id desc limit 1", queryx, usID, usName) //log.Printf("%s\n", queryx) _, err = my.D.Query(queryx) if err != nil { log.Printf("03 MySQL::Query() error: %v\n", err) log.Printf("%s\n", queryx) return } pgrows2, err := pg.D.Query(fmt.Sprintf("select dn from aaa_dns where userid=%d;", usID)) if err != nil { log.Printf("02 PG::Query() error: %v\n", err) return } usDN := "" for pgrows2.Next() { pgrows2.Scan(&usDN) log.Printf("\t\t\t%3d/%s - %s\n", usID, usName, usDN) search := ldap.NewSearchRequest(usDN, 2, ldap.NeverDerefAliases, 0, 0, false, conf.Conf.LDAP_URL[0][4], ldap_Attr, nil) sr, err := ld.D.Search(search) if err != nil { log.Printf("LDAP::Search() error: %v\n", err) return } queryx = "" if len(sr.Entries) > 0 { for _, entry := range sr.Entries { for k := 0; k < len(ldap_Attr); k++ { x[ldap_VCard[k]] = "" } for _, attr := range entry.Attributes { for k := 0; k < len(ldap_Attr); k++ { if attr.Name == ldap_Attr[k] { x[ldap_VCard[k]] = strings.Join(attr.Values, ",") x[ldap_VCard[k]] = strings.Replace(x[ldap_VCard[k]], ",", "\n"+ldap_VCard[k]+":", -1) } } } y := fmt.Sprintf("BEGIN:VCARD\n") for k := 0; k < len(ldap_Attr); k++ { if x[ldap_VCard[k]] != "" { if ldap_VCard[k] == "FN" { fn_split := strings.Split(x[ldap_VCard[k]], " ") fn_nofam := strings.Replace(x[ldap_VCard[k]], fn_split[0], "", -1) fn_nofam = strings.Trim(fn_nofam, " ") y = fmt.Sprintf("%s%s:%s %s\n", y, ldap_VCard[k], fn_nofam, fn_split[0]) } else { switch usCDavPrefix { case 2: if ldap_VCard[k] == conf.Conf.CardDAVIPSuffix[0] { y = fmt.Sprintf("%s%s:%s@%s\n", y, ldap_VCard[k], x[ldap_VCard[k]], conf.Conf.CardDAVIPSuffix[1]) } y = fmt.Sprintf("%s%s:%s\n", y, ldap_VCard[k], x[ldap_VCard[k]]) case 1: if ldap_VCard[k] == conf.Conf.CardDAVIPSuffix[0] { y = fmt.Sprintf("%s%s:%s@%s\n", y, ldap_VCard[k], x[ldap_VCard[k]], conf.Conf.CardDAVIPSuffix[1]) } else { y = fmt.Sprintf("%s%s:%s\n", y, ldap_VCard[k], x[ldap_VCard[k]]) } default: y = fmt.Sprintf("%s%s:%s\n", y, ldap_VCard[k], x[ldap_VCard[k]]) } } } } z := md5.New() z.Write([]byte(y)) uid := hex.EncodeToString(z.Sum(nil)) y = fmt.Sprintf("%sUID:%s\n", y, uid) y = fmt.Sprintf("%sEND:VCARD\n", y) queryx = fmt.Sprintf("%s\nINSERT INTO z_cache_cards (id, addressbookid, carddata, uri, lastmodified)\n\tVALUES (%d, %d, '%s', '%s.vcf', NULL);", queryx, idxCards, usID, y, uid) if multiCount > multiInsert { _, err = my.D.Query(queryx) if err != nil { log.Printf("MySQL::Query() error: %v\n", err) log.Printf("%s\n", queryx) return } queryx = "" multiCount = 0 } multiCount++ idxCards++ } } _, err = my.D.Query(queryx) if err != nil { log.Printf("MySQL::Query() error: %v\n", err) log.Printf("%s\n", queryx) return } queryx = "" multiCount = 0 } //idxUsers++ } rLog.Log("\t\tComplete!") if workMode == "PART" { rLog.Log("\tUpdate tables in PartialUpdate mode...") for j := 0; j < len(usIDArray); j++ { log.Printf("\t\t\tUpdate %d/%s...\n", usIDArray[j].id, usIDArray[j].name) for i := 0; i < len(mySQL_Update_part1); i++ { log.Printf("\t\t\tstep %d (%d of %d)...\n", j+1, i+1, len(mySQL_Update_part1)) if my.QSimple(strings.Replace(mySQL_Update_part1[i], "XYZIDXYZ", fmt.Sprintf("%d", usIDArray[j].id), -1)) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update1); i++ { log.Printf("\t\t\tstep %d (%d of %d)...\n", j+1, i+1, len(mySQL_Update1)) if my.QSimple(mySQL_Update1[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update_part2); i++ { log.Printf("\t\t\tstep %d (%d of %d)...\n", j+1, i+1, len(mySQL_Update_part2)) if my.QSimple(strings.Replace(mySQL_Update_part2[i], "XYZIDXYZ", fmt.Sprintf("%d", usIDArray[j].id), -1)) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update2); i++ { log.Printf("\t\t\tstep %d (%d of %d)...\n", j+1, i+1, len(mySQL_Update2)) if my.QSimple(mySQL_Update2[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } time.Sleep(2 * time.Second) } } else { rLog.Log("\tUpdate tables...") for i := 0; i < len(mySQL_Update_full1); i++ { log.Printf("\t\t\tstep %d of %d...\n", i+1, len(mySQL_Update_full1)) if my.QSimple(mySQL_Update_full1[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update1); i++ { log.Printf("\t\t\tstep %d of %d...\n", i+1, len(mySQL_Update1)) if my.QSimple(mySQL_Update1[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update_full2); i++ { log.Printf("\t\t\tstep %d of %d...\n", i+1, len(mySQL_Update_full2)) if my.QSimple(mySQL_Update_full2[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } for i := 0; i < len(mySQL_Update2); i++ { log.Printf("\t\t\tstep %d of %d...\n", i+1, len(mySQL_Update2)) if my.QSimple(mySQL_Update2[i]) < 0 { log.Println("MySQL: Update error") return } time.Sleep(2 * time.Second) } } rLog.Log("\t\tComplete!") rLog.Log("\tClean NeedToUpdate table...") if pg.QSimple("delete from aaa_dav_ntu where userid=0 or updtime<", time_now, ";") < 0 { log.Println("PgSQL: Clean NTU table error") return } rLog.Log("\tComplete!") rLog.Bye() }
func indexHandler(w http.ResponseWriter, r *http.Request) { var ( xSearchPplMode = int(0) xSearch string xMessage string dn string dn_back string dn_back_tmp []string go_home_button string ldap_Search string ldapSearchMode = int(1) ckl1 int ldap_Attr []string xGetDN [1000]string xGetCkl int l *ldap.Conn err error xFRColor = string("#FFFFFF") xBGColor = string("#FFFFFF") LUserName = string("") setAdminMode = string("") ) username, userperm := CheckUserSession(r, w) //fmt.Printf("%s / %d\n", username, userperm) switch userperm { case roleAdmin: xFRColor = "#FF0000" xBGColor = "#FFFFFF" LUserName = username setAdminMode = "Yes" case roleUser: xFRColor = "#0000FF" xBGColor = "#FFFFFF" LUserName = username default: xFRColor = "#FFFFFF" xBGColor = "#FFFFFF" LUserName = "" } ldap_Attr = make([]string, len(rconf.WLB_LDAP_ATTR)) for ckl1 := 0; ckl1 < len(rconf.WLB_LDAP_ATTR); ckl1++ { ldap_Attr[ckl1] = rconf.WLB_LDAP_ATTR[ckl1][0] } SABModules.Log_ON(&rconf) defer SABModules.Log_OFF() get_dn := r.FormValue("dn") get_cn := r.FormValue("cn") get_fn := r.FormValue("FirstName") get_ln := r.FormValue("LastName") searchMode := r.FormValue("SearchMode") remIPClient := getIPAddress(r) // log.Printf("DN: %s --- CN: %s", get_dn, get_cn) if get_dn == "" { dn = rconf.LDAP_URL[ldap_count][3] } else { dn = get_dn } if len(dn) < len(rconf.LDAP_URL[ldap_count][3]) { dn = rconf.LDAP_URL[ldap_count][3] } log.Printf("->") log.Printf("--> %s", pVersion) log.Printf("->") ucurl, _ := strconv.Unquote(r.RequestURI) log.Println(remIPClient + " --> http://" + r.Host + ucurl) log.Printf("%s ++> DN: %s / CN: %s / Mode: %d / Def.DN: %s", remIPClient, dn, ldap_Search, ldapSearchMode, rconf.LDAP_URL[ldap_count][3]) if get_cn == "" && get_ln == "" && get_fn == "" { ldap_Search = rconf.LDAP_URL[ldap_count][4] } else { log.Printf("%s ++> SQL Search: %s/%s/%s\n", remIPClient, get_cn, get_fn, get_ln) dbpg, err := sql.Open("postgres", rconf.PG_DSN) if err != nil { log.Fatalf("PG_INIT::Open() error: %v\n", err) } defer dbpg.Close() queryx := "select x.dn from ldap_entries as x, ldapx_persons as y where x.uid=y.uid" if len(get_cn) > 2 { queryx = fmt.Sprintf("%s and lower(fullname) like lower('%%%s%%')", queryx, strings.ToLower(get_cn)) } if len(get_ln) > 2 { queryx = fmt.Sprintf("%s and lower(surname) like lower('%s%%')", queryx, strings.ToLower(get_ln)) } if len(get_fn) > 2 { queryx = fmt.Sprintf("%s and lower(name) like lower('%s%%')", queryx, strings.ToLower(get_fn)) } if len(get_cn) <= 2 && len(get_ln) <= 2 && len(get_fn) <= 2 { queryx = fmt.Sprintf("%s and 2=3;", queryx) } else { queryx = fmt.Sprintf("%s;", queryx) } // log.Printf("Search QUERY: %s\n", queryx) rows, err := dbpg.Query(queryx) if err != nil { fmt.Printf("SQL Error: %s\n", queryx) log.Printf("PG::Query() Check LDAP tables error: %v\n", err) return } xGetCkl = 0 for rows.Next() { rows.Scan(&xGetDN[xGetCkl]) //fmt.Println("XXX:", xGetDN[xGetCkl], dn) if strings.Contains(strings.ToLower(xGetDN[xGetCkl]), strings.ToLower(dn)) || searchMode == "Full" { log.Printf("%s <-- SQL Found: %s\n", remIPClient, xGetDN[xGetCkl]) xGetCkl++ if xGetCkl > userLimit { xMessage = fmt.Sprintf("Количество персон по вашему запросу превысило %d! Пожалуйста, задайте критерии более конкретно!", userLimit) break } } } xSearchPplMode = 1 ldapSearchMode = 2 } if strings.ToLower(dn) != strings.ToLower(rconf.LDAP_URL[ldap_count][3]) || xSearchPplMode == 1 { go_home_button = "+" } if ldapSearchMode != 2 { xSearch = "+" } if strings.ToLower(dn) != strings.ToLower(rconf.LDAP_URL[ldap_count][3]) { if ldapSearchMode == 1 && xSearchPplMode == 0 { dn_back_tmp = strings.Split(dn, ",") for ckl1 = 1; ckl1 < len(dn_back_tmp); ckl1++ { if ckl1 == 1 { dn_back = dn_back_tmp[ckl1] } else { dn_back += fmt.Sprintf(",%s", dn_back_tmp[ckl1]) } } } } // log.Printf("%s ... Initialize LDAP connector...", remIPClient) if initLDAPConnector() == "error" { return } l, err = ldap.Dial("tcp", rconf.LDAP_URL[ldap_count][0]) if err != nil { fmt.Fprintf(w, err.Error()) log.Printf("LDAP::Initialize() error: %v\n", err) return } // l.Debug = true defer l.Close() log.Printf("%s =!= Connected to server %d of %d: %s", remIPClient, ldap_count+1, len(rconf.LDAP_URL), rconf.LDAP_URL[ldap_count][0]) err = l.Bind(rconf.LDAP_URL[ldap_count][1], rconf.LDAP_URL[ldap_count][2]) if err != nil { fmt.Fprintf(w, err.Error()) log.Printf("LDAP::Bind() error: %v\n", err) return } t, err := template.ParseFiles("templates/header.html") if err != nil { fmt.Fprintf(w, err.Error()) log.Println(err.Error()) return } t.ExecuteTemplate(w, "header", template.FuncMap{"Pagetitle": rconf.WLB_HTML_Title, "FRColor": xFRColor, "BGColor": xBGColor}) t, err = template.ParseFiles("templates/search.html") if err != nil { fmt.Fprintf(w, err.Error()) log.Println(err.Error()) return } t.ExecuteTemplate(w, "search", template.FuncMap{"GoHome": go_home_button, "PrevDN": dn_back, "DN": dn, "xSearch": xSearch, "xMessage": xMessage, "LineColor": "#EEEEEE", "LUserName": LUserName, "LoginShow": "Yes", "RedirectDN": r.RequestURI}) t, err = template.ParseFiles("templates/index.html") if err != nil { fmt.Fprintf(w, err.Error()) log.Println(err.Error()) return } if xSearchPplMode == 0 { search := ldap.NewSearchRequest(dn, ldapSearchMode, ldap.NeverDerefAliases, 0, 0, false, ldap_Search, ldap_Attr, nil) // log.Printf("Search: %v\n%v\n%v\n%v\n%v\n%v\n", search, dn, ldapSearchMode, ldap.NeverDerefAliases, ldap_Search, ldap_Attr) sr, err := l.Search(search) if err != nil { fmt.Fprintf(w, err.Error()) log.Printf("LDAP::Search() error: %v\n", err) return } // fmt.Printf("\n\nSearch: %v", search) log.Printf("%s ++> search: %s // found: %d\n", remIPClient, search.Filter, len(sr.Entries)) if len(sr.Entries) > 0 { dnList := make(map[string]tList, len(sr.Entries)) for _, entry := range sr.Entries { fType := "" fField := make(map[string]string, len(rconf.WLB_LDAP_ATTR)) for _, attr := range entry.Attributes { for ckl1 := 0; ckl1 < len(rconf.WLB_LDAP_ATTR); ckl1++ { if attr.Name == rconf.WLB_LDAP_ATTR[ckl1][0] { fField[rconf.WLB_LDAP_ATTR[ckl1][1]] = fmt.Sprintf("%s", strings.Join(attr.Values, ",")) // fmt.Printf("Name: %s==%s --> %s = %s\n", attr.Name, rconf.WLB_LDAP_ATTR[ckl1][0], rconf.WLB_LDAP_ATTR[ckl1][1], fField[rconf.WLB_LDAP_ATTR[ckl1][1]]) if rconf.WLB_LDAP_ATTR[ckl1][1] == "ORGName" { fType = "Org" } if rconf.WLB_LDAP_ATTR[ckl1][1] == "USERName" { fType = "User" } } } } getMore(remIPClient, fField, fType, l, dnList, setAdminMode) } t.ExecuteTemplate(w, "index", dnList) } } else { dnList := make(map[string]tList, xGetCkl) for ckl1 = 0; ckl1 < xGetCkl; ckl1++ { // fmt.Printf("GET: %s / %d\n", xGetDN[ckl1], ckl1) search := ldap.NewSearchRequest(xGetDN[ckl1], 0, ldap.NeverDerefAliases, 0, 0, false, "(objectClass=inetOrgPerson)", ldap_Attr, nil) // fmt.Printf("GET: %v\n", search) sr, err := l.Search(search) if err != nil { fmt.Printf(err.Error()) // fmt.Fprintf(w, err.Error()) log.Printf("LDAP::Search() error: %v %v\n", search, err) continue } fType := "User" fField := make(map[string]string, len(rconf.WLB_LDAP_ATTR)) fField["DN"] = xGetDN[ckl1] if len(sr.Entries) > 0 { for _, entry := range sr.Entries { for _, attr := range entry.Attributes { for ckl2 := 0; ckl2 < len(rconf.WLB_LDAP_ATTR); ckl2++ { if attr.Name == rconf.WLB_LDAP_ATTR[ckl2][0] { fField[rconf.WLB_LDAP_ATTR[ckl2][1]] = fmt.Sprintf("%s", strings.Join(attr.Values, ",")) // fmt.Printf("Name: %s==%s --> %s = %s\n", attr.Name, rconf.WLB_LDAP_ATTR[ckl1][0], rconf.WLB_LDAP_ATTR[ckl1][1], fField[rconf.WLB_LDAP_ATTR[ckl1][1]]) } } } } } getMore(remIPClient, fField, fType, l, dnList, setAdminMode) } t.ExecuteTemplate(w, "index", dnList) } t, err = template.ParseFiles("templates/footer.html") if err != nil { fmt.Fprintf(w, err.Error()) log.Println(err.Error()) return } t.ExecuteTemplate(w, "footer", template.FuncMap{"WebBookVersion": pVersion, "xMailBT": rconf.WLB_MailBT, "LineColor": "#EEEEEE"}) }
func main() { flag.Usage = func() { fmt.Println(`ldapr -term "TERM" [-attr NAME,...] -tmpl "TEMPLATE"`) os.Exit(2) } term := flag.String("term", "", "") attr := flag.String("attr", "", "") tmpl := flag.String("tmpl", "", "") flag.Parse() viper.SetConfigName("ldapr") viper.SetConfigType("toml") viper.AddConfigPath(".") viper.AddConfigPath("~") if err := viper.ReadInConfig(); err != nil { util.Error(err, 1) } conn, err := ldap.Dial("tcp", viper.GetString("server")) if err != nil { util.Error(err, 1) } if err := conn.Bind(viper.GetString("user"), viper.GetString("password")); err != nil { util.Error(err, 1) } var attrs []string if *attr != "" { attrs = strings.Split(*attr, ",") } if res, err := conn.SearchWithPaging(ldap.NewSearchRequest(viper.GetString("base"), ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, *term, attrs, []ldap.Control{}, ), 1000); err != nil { util.Error(err, 1) } else { if *tmpl != "" { for _, entry := range res.Entries { m := map[string]string{ "DN": entry.DN, } for _, attr := range entry.Attributes { m[attr.Name] = strings.Join(attr.Values, ",") } if *tmpl != "" { tmp, err := template.New("ldapr").Parse(strings.TrimSpace(*tmpl) + "\n") if err != nil { util.Error(err, 1) } if err := tmp.Execute(os.Stdout, m); err != nil { util.Error(err, 1) } } } } else { for _, entry := range res.Entries { entry.PrettyPrint(0) } } } }
// getIdentity looks up a username in an LDAP server, and attempts to bind to the user's DN using the provided password func (a *Authenticator) getIdentity(username, password string) (authapi.UserIdentityInfo, bool, error) { defer func() { if e := recover(); e != nil { util.HandleError(fmt.Errorf("Recovered panic: %v, %s", e, debug.Stack())) } }() if len(username) == 0 || len(password) == 0 { return nil, false, nil } // Make the connection l, err := a.connect() if err != nil { return nil, false, err } defer l.Close() // If specified, bind the username/password for search phase if len(a.options.BindDN) > 0 { if err := l.Bind(a.options.BindDN, a.options.BindPassword); err != nil { return nil, false, err } } // & together the filter specified in the LDAP options with the user-specific filter filter := fmt.Sprintf("(&%s(%s=%s))", a.options.URL.Filter, ldap.EscapeFilter(a.options.URL.QueryAttribute), ldap.EscapeFilter(username), ) // Build list of attributes to retrieve attrs := util.NewStringSet(a.options.URL.QueryAttribute) attrs.Insert(a.options.AttributeEmail...) attrs.Insert(a.options.AttributeName...) attrs.Insert(a.options.AttributePreferredUsername...) attrs.Insert(a.options.AttributeID...) // Search for LDAP record searchRequest := ldap.NewSearchRequest( a.options.URL.BaseDN, // base dn int(a.options.URL.Scope), // scope ldap.NeverDerefAliases, // deref 2, // size limit, we want to know if this is not unique, but don't want the entire tree 0, // no client-specified time limit, determined by LDAP server. TODO: make configurable? false, // not types only filter, // filter attrs.List(), // attributes to retrieve nil, // controls ) glog.V(4).Infof("searching for %s", filter) results, err := l.Search(searchRequest) if err != nil { return nil, false, err } if len(results.Entries) == 0 { // 0 results means a missing username, not an error glog.V(4).Infof("no entries matching %s", filter) return nil, false, nil } if len(results.Entries) > 1 { // More than 1 result means a misconfigured server filter or query parameter return nil, false, fmt.Errorf("multiple entries found matching %q", username) } entry := results.Entries[0] glog.V(4).Infof("found dn=%q for %s", entry.DN, filter) // Bind with given username and password to attempt to authenticate if err := l.Bind(entry.DN, password); err != nil { glog.V(4).Infof("error binding password for %q: %v", entry.DN, err) if err, ok := err.(*ldap.Error); ok { switch err.ResultCode { case ldap.LDAPResultInappropriateAuthentication: // inappropriateAuthentication (48) // Indicates the server requires the client that had attempted // to bind anonymously or without supplying credentials to // provide some form of credentials. fallthrough case ldap.LDAPResultInvalidCredentials: // invalidCredentials (49) // Indicates that the provided credentials (e.g., the user's name // and password) are invalid. // Authentication failed, return false, but no error return nil, false, nil } } return nil, false, err } // Build the identity uid := getAttributeValue(entry, a.options.AttributeID) if uid == "" { return nil, false, fmt.Errorf("Could not retrieve a non-empty value from %v attributes for dn=%q", a.options.AttributeID, entry.DN) } identity := authapi.NewDefaultUserIdentityInfo(a.providerName, uid) // Add optional extra attributes if present for k, attrs := range map[string][]string{ authapi.IdentityPreferredUsernameKey: a.options.AttributePreferredUsername, authapi.IdentityEmailKey: a.options.AttributeEmail, authapi.IdentityDisplayNameKey: a.options.AttributeName, } { if v := getAttributeValue(entry, attrs); len(v) != 0 { identity.Extra[k] = v } } return identity, true, nil }
func AD_to_PG(conf *SABModules.Config_STR, pg_minsert int) int { var ( ckl_servers int num_servers int ckl = int(0) queryx string pg_AD_Create = string(` CREATE TABLE IF NOT EXISTS XYZWorkTableZYX (domain character varying(255), server character varying(255), displayname character varying(255), cn character varying(255), dlogin character varying(255), login character varying(255), mail character varying(255), ph_int character varying(255), ph_mob character varying(255), ph_ip character varying(255), department character varying(255), title character varying(255), dn character varying(255), connected character varying(5) NOT NULL DEFAULT 'no'::character varying, primary key (dlogin)); `) pg_AD_Create_Status = string(` CREATE TABLE IF NOT EXISTS XYZWorkTableZYX (server character varying(255), status character varying(255), primary key (server)); `) return_result = int(0) ) log.Printf("AD Export to PG...") rusFindRegExp := regexp.MustCompile(`[А-Яа-я]`) num_servers = len(conf.AD_LDAP) // fmt.Printf("%d\n", num_servers) for ckl = 0; ckl < num_servers; ckl++ { conf.AD_LDAP[ckl][6] = "enabled" } db, err := sql.Open("postgres", conf.PG_DSN) if err != nil { log.Printf("PG::Open() error: %v\n", err) return 10 } defer db.Close() queryx = strings.Replace(pg_AD_Create, "XYZWorkTableZYX", SABDefine.PG_Table_AD, -1) _, err = db.Query(queryx) if err != nil { log.Printf("PG::Exec() error: %v\n", err) return 11 } queryx = strings.Replace(pg_AD_Create_Status, "XYZWorkTableZYX", SABDefine.PG_Table_AD_Status, -1) _, err = db.Query(queryx) if err != nil { log.Printf("PG::Exec() error: %v\n", err) return 12 } for ckl_servers = 0; ckl_servers < num_servers; ckl_servers++ { if conf.AD_LDAP[ckl_servers][6] != "enabled" { continue } log.Printf("\t\tServer %2d of %2d / Pass 1 of 1 / Domain: %s, Controller: %s\n", ckl_servers+1, num_servers, conf.AD_LDAP[ckl_servers][0], conf.AD_LDAP[ckl_servers][1]) l, err := ldap.Dial("tcp", conf.AD_LDAP[ckl_servers][1]) if err != nil { log.Printf("LDAP::Initialize() error: %v\n", err) continue } defer l.Close() // l.Debug = true err = l.Bind(conf.AD_LDAP[ckl_servers][2], conf.AD_LDAP[ckl_servers][3]) if err != nil { log.Printf("LDAP::Bind() error: %v\n", err) continue } search := ldap.NewSearchRequest(conf.AD_LDAP[ckl_servers][4], ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, conf.AD_LDAP[ckl_servers][5], SABDefine.AD_attr, nil) sr, err := l.Search(search) if err != nil { log.Printf("LDAP::Search() error: %v\n", err) continue } log.Printf("\t\t\t%s // %d\n", search.Filter, len(sr.Entries)) if len(sr.Entries) > 10 { timenow := time.Now().Format("2006.01.02 15:04:05") queryx = fmt.Sprintf("INSERT INTO %s (server, status) select '%s', '%s' where not exists (select server from %s where server='%s'); update %s set status='%s' where server='%s'; ", SABDefine.PG_Table_AD_Status, conf.AD_LDAP[ckl_servers][1], timenow, SABDefine.PG_Table_AD_Status, conf.AD_LDAP[ckl_servers][1], SABDefine.PG_Table_AD_Status, timenow, conf.AD_LDAP[ckl_servers][1]) // log.Printf("%s\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Insert error: %v\n", err) return 13 } _, err = db.Query(fmt.Sprintf("delete from %s where server='%s';", SABDefine.PG_Table_AD, conf.AD_LDAP[ckl_servers][1])) if err != nil { log.Printf("PG::Query() Clean table error: %v\n", err) return 14 } } ckl = 0 for _, entry := range sr.Entries { if ckl < 1 { queryx = "" } fName := "" fCN := "" fLogin := "" fMail := "" fDep := "" fTitle := "" fDN := "" fPhone := "" fMobile := "" fIPPhone := "" for _, attr := range entry.Attributes { if attr.Name == "displayName" { fName = strings.Join(attr.Values, ",") } if attr.Name == "cn" { fCN = strings.Join(attr.Values, ",") } if attr.Name == "sAMAccountName" { fLogin = strings.Join(attr.Values, ",") } if attr.Name == "mail" { fMail = strings.Join(attr.Values, ",") } if attr.Name == "department" { fDep = strings.Join(attr.Values, ",") } if attr.Name == "title" { fTitle = strings.Join(attr.Values, ",") } if attr.Name == "distinguishedName" { fDN = strings.Join(attr.Values, ",") } if attr.Name == "telephoneNumber" { fPhone = strings.Join(attr.Values, ",") } if attr.Name == "mobile" { fMobile = strings.Join(attr.Values, ",") } if attr.Name == "pager" { fIPPhone = strings.Join(attr.Values, ",") } } if len(fName) > 0 && len(fLogin) > 0 && rusFindRegExp.FindString(fName) != "" { return_result = 94 /* if ckl > 0 && state == 1 { queryx = fmt.Sprintf("%s , ", queryx) } fOU = "" for ckl1 := int(len(fOUa) - 2); ckl1 > 0; ckl1-- { fOU = fmt.Sprintf("%s/%s", fOU, fOUa[ckl1]) } fOU = strings.Trim(strings.Trim(strings.Replace(strings.Replace(fOU, "OU=", "", -1), "O=", "", -1), "/"), " ") if fOU == "" { fOU = conf.ROOT_OU } pfName = SABModules.TextMutation(strings.Replace(fName[int(len(fName)-1)], "'", "", -1)) pfCN = SABModules.TextMutation(strings.Replace(fCN[0], "'", "", -1)) pfMail = strings.Replace(strings.ToLower(fMail), " ", "", -1) queryx = fmt.Sprintf("%sINSERT INTO %s (server, namerus, trnamerus, namelat, ou, mail) select '%s','%s','%s','%s','%s','%s' where not exists (select mail from %s where mail='%s'); ", queryx, SABDefine.PG_Table_Domino, conf.AD_LDAP[ckl_servers][0], pfName, unidecode.Unidecode(pfName), pfCN, fOU, pfMail, SABDefine.PG_Table_Domino, pfMail) //log.Printf("%s", queryx) //state = 1 */ queryx = fmt.Sprintf("%s INSERT INTO %s (domain,server,displayname,cn,login,dlogin,mail,department,title,dn,ph_int,ph_mob,ph_ip) values ('%s','%s','%s','%s','%s','%s@%s','%s','%s','%s','%s','%s','%s','%s');", queryx, SABDefine.PG_Table_AD, conf.AD_LDAP[ckl_servers][0], conf.AD_LDAP[ckl_servers][1], SABModules.NameMutation(fName), SABModules.NameMutation(fCN), SABModules.NameMutation(fLogin), SABModules.NameMutation(fLogin), conf.AD_LDAP[ckl_servers][0], fMail, SABModules.NameMutation(fDep), SABModules.NameMutation(fTitle), fDN, fPhone, fMobile, fIPPhone) //log.Printf("----- %s\n", queryx) // fmt.Printf("%s/%s/%s/%s/%s/%s/%s/%s\n", conf.AD_LDAP[ckl_servers][0], conf.AD_LDAP[ckl_servers][1], fName, fCN, fLogin, fMail, fDep, fTitle) } if ckl >= pg_minsert-1 { _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() insert error: %v /// %s\n", err, queryx) } queryx = "" ckl = 0 } else { ckl++ } /* if ckl >= pg_minsert-1 { // log.Printf("%s\n\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() insert error: %v /// %s\n", err, queryx) } queryx = "" ckl = 0 // state=0 } else { ckl++ } } // log.Printf("%s\n\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Insert into table error: %v\n", err) */ } if len(sr.Entries) > 1 { for ckl = 0; ckl < num_servers; ckl++ { if conf.AD_LDAP[ckl][0] == conf.AD_LDAP[ckl_servers][0] { conf.AD_LDAP[ckl][6] = "ok" if ckl != ckl_servers { queryx = fmt.Sprintf("INSERT INTO %s (server, status) select '%s', '%s' where not exists (select server from %s where server='%s'); update %s set status='%s' where server='%s'; ", SABDefine.PG_Table_AD_Status, conf.AD_LDAP[ckl][1], "SKIP", SABDefine.PG_Table_AD_Status, conf.AD_LDAP[ckl][1], SABDefine.PG_Table_AD_Status, "SKIP", conf.AD_LDAP[ckl][1]) // log.Printf("%s\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Create table error: %v\n", err) return 19 } } } } } } log.Printf("\tComplete") return return_result }
// getIdentity looks up a username in an LDAP server, and attempts to bind to the user's DN using the provided password func (a *Authenticator) getIdentity(username, password string) (authapi.UserIdentityInfo, bool, error) { defer func() { if e := recover(); e != nil { util.HandleError(fmt.Errorf("Recovered panic: %v, %s", e, debug.Stack())) } }() if len(username) == 0 || len(password) == 0 { return nil, false, nil } // Make the connection and bind to it if a bind DN and password were given l, err := a.options.ClientConfig.Connect() if err != nil { return nil, false, err } defer l.Close() if _, err := a.options.ClientConfig.Bind(l); err != nil { return nil, false, err } // & together the filter specified in the LDAP options with the user-specific filter filter := fmt.Sprintf("(&%s(%s=%s))", a.options.URL.Filter, ldap.EscapeFilter(a.options.URL.QueryAttribute), ldap.EscapeFilter(username), ) // Build list of attributes to retrieve attrs := sets.NewString(a.options.URL.QueryAttribute) attrs.Insert(a.options.UserAttributeDefiner.AllAttributes().List()...) // Search for LDAP record searchRequest := ldap.NewSearchRequest( a.options.URL.BaseDN, // base dn int(a.options.URL.Scope), // scope ldap.NeverDerefAliases, // deref 2, // size limit, we want to know if this is not unique, but don't want the entire tree 0, // no client-specified time limit, determined by LDAP server. TODO: make configurable? false, // not types only filter, // filter attrs.List(), // attributes to retrieve nil, // controls ) glog.V(4).Infof("searching for %s", filter) results, err := l.Search(searchRequest) if err != nil { return nil, false, err } if len(results.Entries) == 0 { // 0 results means a missing username, not an error glog.V(4).Infof("no entries matching %s", filter) return nil, false, nil } if len(results.Entries) > 1 { // More than 1 result means a misconfigured server filter or query parameter return nil, false, fmt.Errorf("multiple entries found matching %q", username) } entry := results.Entries[0] glog.V(4).Infof("found dn=%q for %s", entry.DN, filter) // Bind with given username and password to attempt to authenticate if err := l.Bind(entry.DN, password); err != nil { glog.V(4).Infof("error binding password for %q: %v", entry.DN, err) if err, ok := err.(*ldap.Error); ok { switch err.ResultCode { case ldap.LDAPResultInappropriateAuthentication: // inappropriateAuthentication (48) // Indicates the server requires the client that had attempted // to bind anonymously or without supplying credentials to // provide some form of credentials. fallthrough case ldap.LDAPResultInvalidCredentials: // invalidCredentials (49) // Indicates that the provided credentials (e.g., the user's name // and password) are invalid. // Authentication failed, return false, but no error return nil, false, nil } } return nil, false, err } // Build the identity identity, err := a.identityFactory.IdentityFor(entry) if err != nil { return nil, false, err } return identity, true, nil }
func LDAP_to_PG(conf *SABModules.Config_STR, pg_minsert int) int { var ( ckl_servers int num_servers int fName []string fCN []string fOUa []string fOU string fMail string pfName string pfCN string pfMail string ckl = int(0) state = int(0) queryx string pg_Domino_Create = string(` CREATE TABLE IF NOT EXISTS XYZWorkTableZYX (server character varying(255), namerus character varying(255), trnamerus character varying(255), namelat character varying(255), ou character varying(255), mail character varying(255), primary key (mail)); `) pg_Query_Create_Status = string(` CREATE TABLE IF NOT EXISTS XYZWorkTableZYX (server character varying(255), status character varying(255), primary key (server)); `) return_result = int(0) ) log.Printf("LDAP Export to PG...") num_servers = len(conf.LDAP_URL) db, err := sql.Open("postgres", conf.PG_DSN) if err != nil { log.Printf("PG::Open() error: %v\n", err) return 10 } defer db.Close() queryx = strings.Replace(pg_Domino_Create, "XYZWorkTableZYX", SABDefine.PG_Table_Domino, -1) _, err = db.Query(queryx) if err != nil { log.Printf("PG::Query() Create table error: %v\n", err) return 11 } queryx = strings.Replace(pg_Query_Create_Status, "XYZWorkTableZYX", SABDefine.PG_Table_Domino_Status, -1) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Create table error: %v\n", err) return 12 } for ckl_servers = 0; ckl_servers < num_servers; ckl_servers++ { log.Printf("\t\tServer %2d of %2d / Pass 1 of 1 / Server name: %s\n", ckl_servers+1, num_servers, conf.LDAP_URL[ckl_servers][0]) l, err := ldap.Dial("tcp", conf.LDAP_URL[ckl_servers][0]) if err != nil { log.Printf("LDAP::Initialize() error: %v\n", err) continue } defer l.Close() // l.Debug = true err = l.Bind(conf.LDAP_URL[ckl_servers][1], conf.LDAP_URL[ckl_servers][2]) if err != nil { log.Printf("LDAP::Bind() error: %v\n", err) continue } search := ldap.NewSearchRequest(conf.LDAP_URL[ckl_servers][3], ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, conf.LDAP_URL[ckl_servers][4], SABDefine.LDAP_attr, nil) sr, err := l.Search(search) if err != nil { log.Printf("LDAP::Search() error: %v\n", err) continue } log.Printf("\t\t\t%s // %d\n", search.Filter, len(sr.Entries)) if len(sr.Entries) > 10 { timenow := time.Now().Format("2006.01.02 15:04:05") queryx = fmt.Sprintf("INSERT INTO %s (server, status) select '%s', '%s' where not exists (select server from %s where server='%s'); update %s set status='%s' where server='%s'; ", SABDefine.PG_Table_Domino_Status, conf.LDAP_URL[ckl_servers][0], timenow, SABDefine.PG_Table_Domino_Status, conf.LDAP_URL[ckl_servers][0], SABDefine.PG_Table_Domino_Status, timenow, conf.LDAP_URL[ckl_servers][0]) // log.Printf("%s\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Create table error: %v\n", err) return 14 } _, err = db.Query(fmt.Sprintf("delete from %s where server='%s';", SABDefine.PG_Table_Domino, conf.LDAP_URL[ckl_servers][0])) if err != nil { log.Printf("PG::Query() Clean table error: %v\n", err) return 14 } } ckl = 0 for _, entry := range sr.Entries { if ckl < 1 { queryx = "" } for _, attr := range entry.Attributes { if attr.Name == "altfullname" { x := strings.Join(attr.Values, ",") fOUa = strings.Split(x, ",") fName = strings.Split(fOUa[0], "=") } if attr.Name == "cn" { x := strings.Join(attr.Values, ",") fCN = strings.Split(x, ",") } if attr.Name == "mail" { fMail = strings.Join(attr.Values, ",") } } if len(fName) > 0 && len(fCN) > 0 { return_result = 94 if ckl > 0 && state == 1 { queryx = fmt.Sprintf("%s , ", queryx) } fOU = "" for ckl1 := int(len(fOUa) - 2); ckl1 > 0; ckl1-- { fOU = fmt.Sprintf("%s/%s", fOU, fOUa[ckl1]) } fOU = strings.Trim(strings.Trim(strings.Replace(strings.Replace(fOU, "OU=", "", -1), "O=", "", -1), "/"), " ") if fOU == "" { fOU = conf.ROOT_OU } pfName = SABModules.TextMutation(strings.Replace(fName[int(len(fName)-1)], "'", "", -1)) pfCN = SABModules.TextMutation(strings.Replace(fCN[0], "'", "", -1)) pfMail = strings.Replace(strings.ToLower(fMail), " ", "", -1) queryx = fmt.Sprintf("%sINSERT INTO %s (server, namerus, trnamerus, namelat, ou, mail) select '%s','%s','%s','%s','%s','%s' where not exists (select mail from %s where mail='%s'); ", queryx, SABDefine.PG_Table_Domino, conf.LDAP_URL[ckl_servers][0], pfName, unidecode.Unidecode(pfName), pfCN, fOU, pfMail, SABDefine.PG_Table_Domino, pfMail) // log.Printf("%s", queryx) // state = 1 } if ckl >= pg_minsert-1 { // log.Printf("%s\n\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() insert error: %v /// %s\n", err, queryx) } queryx = "" ckl = 0 // state=0 } else { ckl++ } } // log.Printf("%s\n\n", queryx) _, err = db.Query(queryx) if err != nil { log.Printf("%s\n", queryx) log.Printf("PG::Query() Insert into table error: %v\n", err) } } log.Printf("\tComplete") return return_result }
func getMore(remIPClient string, fField map[string]string, fType string, l *ldap.Conn, dnList map[string]tList, setAdminMode string) { var ( fPath string fURL string fURLName string ckl1, ckl2, ckl3 int ldap_Attr []string aaa_login = string("") aaa_password = string("") aaa_fullname = string("") aaa_role = string("") aaa_cdavmode = int(0) newSABLogin string get_davdn = string("") err error ) dbpg, err := sql.Open("postgres", rconf.PG_DSN) if err != nil { log.Fatalf("PG_INIT::Open() error: %v\n", err) } defer dbpg.Close() if fField["DN"] != "" && (fField["USERName"] != "" || fField["ORGName"] != "") { fPath = fField["DN"] fPath = strings.Replace(strings.ToLower(fPath), ","+strings.ToLower(rconf.LDAP_URL[ldap_count][3]), "", -1) fPath_Split := strings.Split(fPath, ",") fURLName = "" for ckl1 = 0; ckl1 < len(fPath_Split)-1; ckl1++ { fPath_Strip := "" for ckl2 = ckl1 + 1; ckl2 < len(fPath_Split); ckl2++ { fPath_Strip = fmt.Sprintf("%s%s,", fPath_Strip, fPath_Split[ckl2]) } if fType == "User" { fPath_Strip = fmt.Sprintf("%s%s", fPath_Strip, rconf.LDAP_URL[ldap_count][3]) if ckl1 == 0 { fURL = fPath_Strip } // log.Printf("X1: %s", fPath_Strip) subsearch := ldap.NewSearchRequest(fPath_Strip, 0, ldap.NeverDerefAliases, 0, 0, false, rconf.LDAP_URL[ldap_count][4], ldap_Attr, nil) subsr, err := l.Search(subsearch) if err != nil { // fmt.Fprintf(w, err.Error()) log.Printf("LDAP::Search() error: %v\n", err) } // log.Printf("Y1: %s / %s / %d\n", fPath_Strip, rconf.LDAP_URL[ldap_count][4], len(subsr.Entries)) if len(subsr.Entries) > 0 { for _, subentry := range subsr.Entries { for _, subattr := range subentry.Attributes { for ckl3 = 0; ckl3 < len(rconf.WLB_LDAP_ATTR); ckl3++ { if subattr.Name == rconf.WLB_LDAP_ATTR[ckl3][0] { if rconf.WLB_LDAP_ATTR[ckl3][1] == "ORGName" { if ckl1 == 0 { fURLName = fmt.Sprintf("%s", strings.Join(subattr.Values, ",")) } else { fURLName = fmt.Sprintf("%s / %s", strings.Join(subattr.Values, ","), fURLName) } // log.Printf("Z1: %s", fURLName) } } } } } } } } fField["DN"] = strings.Replace(strings.ToLower(fField["DN"]), "/", ",", -1) fmt.Sprintf("/Go%s?dn=%s", fType, fField["DN"]) fField["DN"] = fmt.Sprintf("/Go%s?dn=%s", fType, fField["DN"]) fURL = fmt.Sprintf("/Go%s?dn=%s", fType, fURL) log.Printf("%s <-- %s", remIPClient, fField["DN"]) davDN := "LIST:\n" if setAdminMode == "Yes" { queryx := fmt.Sprintf("select x.dn from aaa_dns as x, aaa_logins as y where y.uid='%s' and y.id=x.userid;", fField["UID"]) //fmt.Printf("%s\n", queryx) rows, err := dbpg.Query(queryx) if err != nil { log.Printf("PG::Query() Select info from aaa_logins: %v\n", err) return } for rows.Next() { rows.Scan(&get_davdn) davDN = fmt.Sprintf("%s%s\n", davDN, get_davdn) } queryx = fmt.Sprintf("select login,password,fullname,role,cdavprefix from aaa_logins where uid='%s';", fField["UID"]) //fmt.Printf("%s\n", queryx) rows, err = dbpg.Query(queryx) if err != nil { log.Printf("PG::Query() Select info from aaa_logins: %v\n", err) return } rows.Next() rows.Scan(&aaa_login, &aaa_password, &aaa_fullname, &aaa_role, &aaa_cdavmode) if len(aaa_password) > 0 { aaa_password = "******" } else { aaa_password = "******" } xt, _ := strconv.Atoi(aaa_role) switch xt { case roleAdmin: aaa_role = "Administrator" case roleUser: aaa_role = "User" default: aaa_role = "Guest" } if len(fField["ADLogin"]) < 2 || len(fField["ADDomain"]) < 2 { newSABLogin = fField["Mail"] } else { newSABLogin = fmt.Sprintf("%s@%s", fField["ADLogin"], fField["ADDomain"]) } } dnList[fField["DN"]] = tList{URL: fURL, URLName: fURLName, ORGName: fField["ORGName"], USERName: fField["USERName"], FullName: fField["FullName"], Position: fField["Position"], PhoneInt: fField["PhoneInt"], Mobile: fField["Mobile"], PhoneExt: fField["PhoneExt"], Mail: fField["Mail"], ADLogin: fField["ADLogin"], ADDomain: fField["ADDomain"], AdminMode: setAdminMode, UID: fField["UID"], AAALogin: aaa_login, AAAPassword: aaa_password, AAAFullName: aaa_fullname, AAARole: aaa_role, NewSABLogin: newSABLogin, DavDN: davDN, AAACDMode: cDavMode[aaa_cdavmode], AAACDModeI: aaa_cdavmode} //fmt.Printf("%v\n", dnList) } }