Как получить все атрибуты записи LDAP с помощью запроса golang?

#go #ldap

#Вперед #ldap

Вопрос:

Я использую gopkg.in/ldap.v2 api для запроса к серверу LDAP, но было интересно, как получить все атрибуты записи, как только она появится в результате запроса? Вот полная программа, которая у меня есть:

 
/*In order to use this program, the user needs to get the package by running the following command:
go get gopkg.in/ldap.v2*/
package main

import (
  "fmt"
  "strings"
  "gopkg.in/ldap.v2"
  "os"
)
//Gives constants to be used for binding to and searching the LDAP server.
const (
  ldapServer = "127.0.0.1:389"
  ldapBind = "cn=admin,dc=test123,dc=com"
  ldapPassword = "Password"

  filterDN = "(objectclass=*)"
  baseDN = "dc=test123,dc=com"

  loginUsername = "admin"
  loginPassword = "Password"
)

//Main function, which is executed.
func main() {
  conn, err := connect()

  //If there is an error connecting to server, prints this
  if err != nil {
    fmt.Printf("Failed to connect. %s", err)
    return
  }
  //Close the connection at a later time.
  defer conn.Close()
  //Declares err to be list(conn), and checks if any errors. It prints the error(s) if there are any.
  if err := list(conn); err != nil {
    fmt.Printf("%v", err)
    return
  }

  /*
  //Declares err to be auth(conn), and checks if any errors. It prints the error(s) if there are any.
  if err := auth(conn); err != nil {
    fmt.Printf("%v", err)
    return
  }*/
}

//This function is used to connect to the LDAP server.
func connect() (*ldap.Conn, error) {
  conn, err := ldap.Dial("tcp", ldapServer)

  if err != nil {
    return nil, fmt.Errorf("Failed to connect. %s", err)
  }

  if err := conn.Bind(ldapBind, ldapPassword); err != nil {
    return nil, fmt.Errorf("Failed to bind. %s", err)
  }

  return conn, nil
}

//This function is used to search the LDAP server as well as output the attributes of the entries.
func list(conn *ldap.Conn) error {
  //This gets the command line argument and saves it in the form "(argument=*)"
  arg := ""
  filter := ""
  if len(os.Args) > 1{
    arg = os.Args[1]
    fmt.Println(arg)

    filter = "("   arg   "=*)"
  } else{
    fmt.Println("You need to input an argument for an attribute to search. I.E. : "go run anonymous_query.go cn"")
  }

  result, err := conn.Search(ldap.NewSearchRequest(
    baseDN,
    ldap.ScopeWholeSubtree,
    ldap.NeverDerefAliases,
    0,
    0,
    false,
    fmt.Sprintf(filter),

    //To add anymore strings to the search, you need to add it here.
    []string{"dn", "o", "cn", "ou", "uidNumber", "objectClass",
    "uid", "uidNumber", "gidNumber", "homeDirectory", "loginShell", "gecos",
    "shadowMax", "shadowWarning", "shadowLastChange", "dc", "description", "entryCSN"},
    nil,
  ))

  if err != nil {
    return fmt.Errorf("Failed to search users. %s", err)
  }

  //Prints all the attributes per entry
  for _, entry := range result.Entries {
    entry.Print()
    fmt.Println()
  }

  return nil
}

//This function authorizes the user and binds to the LDAP server.
func auth(conn *ldap.Conn) error {
  result, err := conn.Search(ldap.NewSearchRequest(
    baseDN,
    ldap.ScopeWholeSubtree,
    ldap.NeverDerefAliases,
    0,
    0,
    false,
    filter(loginUsername),
    []string{"dn"},
    nil,
  ))

  if err != nil {
    return fmt.Errorf("Failed to find user. %s", err)
  }

  if len(result.Entries) < 1 {
    return fmt.Errorf("User does not exist")
  }

  if len(result.Entries) > 1 {
    return fmt.Errorf("")
  }

  if err := conn.Bind(result.Entries[0].DN, loginPassword); err != nil {
    fmt.Printf("Failed to auth. %s", err)
  } else {
    fmt.Printf("Authenticated successfuly!")
  }

  return nil
}

func filter(needle string) string {
  res := strings.Replace(
    filterDN,
    "{username}",
    needle,
    -1,
  )

  return res
}

  

Проблема, с которой я столкнулся, находится в этой строке:

     //To add anymore strings to the search, you need to add it here.
    []string{"dn", "o", "cn", "ou", "uidNumber", "objectClass",
    "uid", "uidNumber", "gidNumber", "homeDirectory", "loginShell", "gecos",
    "shadowMax", "shadowWarning", "shadowLastChange", "dc", "description", "entryCSN"}
  

Я хотел бы получить все атрибуты записи LDAP вместо того, чтобы вручную вводить все атрибуты, которые я хочу получить из результата запроса. Другая причина в том, что я не знаю, какие атрибуты может иметь запись.

Любая помощь будет с благодарностью принята. Спасибо!

Ответ №1:

В операции поиска LDAP, если вы не укажете атрибуты для поиска, он вернет записи со всеми их атрибутами, так что это сделает работу:

 result, err := conn.Search(ldap.NewSearchRequest(
    baseDN,
    ldap.ScopeWholeSubtree,
    ldap.NeverDerefAliases,
    0,
    0,
    false,
    fmt.Sprintf(filter),
    []string{},
    nil,
  ))