Exemplo n.º 1
0
func initLDAPConnector() string {
	var (
		ckl = int(0)
		err error
		l   *ldap.Conn
	)

	for {
		if ckl > 9 {
			log.Printf("LDAP Init SRV ***** Error connect to all LDAP servers...")
			return "error"
		}

		ldap_count++
		if ldap_count > len(rconf.LDAP_URL)-1 {
			ldap_count = 0
		}

		log.Printf("LDAP Init SRV ***** Trying connect to server %d of %d: %s", ldap_count+1, len(rconf.LDAP_URL), rconf.LDAP_URL[ldap_count][0])
		l, err = ldap.Dial("tcp", rconf.LDAP_URL[ldap_count][0])
		if err != nil {
			continue
		}

		defer l.Close()

		break

		ckl++
	}
	return rconf.LDAP_URL[ldap_count][0]
}
Exemplo n.º 2
0
func NewLDAPClient(ldapUri, bindDn, bindPass string, searchBase ...string) (ad *LDAPClient, err error) {
	protoHostPort := strings.Split(ldapUri, "://")
	if len(protoHostPort) != 2 {
		err = fmt.Errorf("Invalid LDAP URI: %s", ldapUri)
		return
	}

	ad = &LDAPClient{URI: ldapUri}

	if protoHostPort[0] == "ldaps" {
		ad.Conn, err = ldap.DialTLS("tcp", protoHostPort[1], &tls.Config{InsecureSkipVerify: true})
	} else {
		//no ssl port 389
		ad.Conn, err = ldap.Dial("tcp", protoHostPort[1])
	}
	if err != nil {
		return
	}

	if len(searchBase) > 0 {
		ad.DefaultSearchBase = searchBase[0]
	}
	err = ad.Bind(bindDn, bindPass)
	return
}
Exemplo n.º 3
0
func (_s *LDAP) InitS(rLog SBMSystem.LogFile, user, password, server string) int {
	var err error

	_s.CS = -1

	rLog.LogDbg(2, "LDAP Init SRV ***** Trying connect to server ", server, " with login ", user)

	_s.D, err = ldap.Dial("tcp", server)
	if err != nil {
		rLog.LogDbg(0, "LDAP::Dial() to server ", server, " error: ", err)
		return -1
	}

	//L.Debug()

	err = _s.D.Bind(user, password)
	if err != nil {
		rLog.LogDbg(1, "LDAP::Bind() to server ", server, " with login ", user, " error: ", err)
		return -1
	}

	rLog.LogDbg(2, "LDAP Init SRV ***** Success! Connected to server ", server, " with login ", user)

	_s.CS = 0
	return 0
}
Exemplo n.º 4
0
func (a *ldapAuther) Dial() error {
	var err error
	var certPool *x509.CertPool
	if a.server.RootCACert != "" {
		certPool := x509.NewCertPool()
		for _, caCertFile := range strings.Split(a.server.RootCACert, " ") {
			if pem, err := ioutil.ReadFile(caCertFile); err != nil {
				return err
			} else {
				if !certPool.AppendCertsFromPEM(pem) {
					return errors.New("Failed to append CA certificate " + caCertFile)
				}
			}
		}
	}
	for _, host := range strings.Split(a.server.Host, " ") {
		address := fmt.Sprintf("%s:%d", host, a.server.Port)
		if a.server.UseSSL {
			tlsCfg := &tls.Config{
				InsecureSkipVerify: a.server.SkipVerifySSL,
				ServerName:         host,
				RootCAs:            certPool,
			}
			a.conn, err = ldap.DialTLS("tcp", address, tlsCfg)
		} else {
			a.conn, err = ldap.Dial("tcp", address)
		}

		if err == nil {
			return nil
		}
	}
	return err
}
Exemplo n.º 5
0
//Connect returns an open connection to an Active Directory server specified by the given config
func (c *Config) Connect() (*ldap.Conn, error) {
	if c.TLSConfig == nil {
		c.TLSConfig = &tls.Config{
			ServerName: c.Server,
		}
	}

	switch c.Security {
	case SecurityNone:
		conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
		if err != nil {
			if c.Debug {
				log.Printf("DEBUG: LDAP Error %v\n", err)
			}
			return nil, err
		}
		return conn, nil
	case SecurityTLS:
		conn, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port), c.TLSConfig)
		if err != nil {
			if c.Debug {
				log.Printf("DEBUG: LDAP Error %v\n", err)
			}
			return nil, err
		}
		return conn, nil
	case SecurityStartTLS:
		conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
		if err != nil {
			if c.Debug {
				log.Printf("DEBUG: LDAP Error %v\n", err)
			}
			return nil, err
		}
		err = conn.StartTLS(c.TLSConfig)
		if err != nil {
			if c.Debug {
				log.Printf("DEBUG: LDAP Error %v\n", err)
			}
			return nil, err
		}
		return conn, nil
	default:
		return nil, ConfigError("Invalid Security setting")
	}
}
Exemplo n.º 6
0
// 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)
	}
}
Exemplo n.º 7
0
func (a *ldapAuther) Dial() error {
	address := fmt.Sprintf("%s:%d", a.server.Host, a.server.Port)
	var err error
	if a.server.UseSSL {
		a.conn, err = ldap.DialTLS("tcp", address, nil)
	} else {
		a.conn, err = ldap.Dial("tcp", address)
	}

	return err
}
Exemplo n.º 8
0
// ExampleConn_Bind demonstrats how to bind a connection to an ldap user
// allowing access to restricted attrabutes that user has access to
func ExampleConn_Bind() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	err = l.Bind("cn=read-only-admin,dc=example,dc=com", "password")
	if err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 9
0
func (lc *LDAPClient) ConnectAndBind() (err error) {
	if strings.HasPrefix(lc.URI, "ldaps") {
		lc.LdapConn, err = ldap.DialTLS("tcp", lc.hostPort, &tls.Config{InsecureSkipVerify: true})
	} else {
		//no ssl port 389
		lc.LdapConn, err = ldap.Dial("tcp", lc.hostPort)
	}
	if err != nil {
		return
	}
	err = lc.LdapConn.Bind(lc.UserBindDN, lc.UserBindPass)
	return
}
Exemplo n.º 10
0
func (c *ConfigEntry) DialLDAP() (*ldap.Conn, error) {

	u, err := url.Parse(c.Url)
	if err != nil {
		return nil, err
	}
	host, port, err := net.SplitHostPort(u.Host)
	if err != nil {
		host = u.Host
	}

	var conn *ldap.Conn
	var tlsConfig *tls.Config
	switch u.Scheme {
	case "ldap":
		if port == "" {
			port = "389"
		}
		conn, err = ldap.Dial("tcp", host+":"+port)
		if err != nil {
			break
		}
		if conn == nil {
			err = fmt.Errorf("empty connection after dialing")
			break
		}
		if c.StartTLS {
			tlsConfig, err = c.GetTLSConfig(host)
			if err != nil {
				break
			}
			err = conn.StartTLS(tlsConfig)
		}
	case "ldaps":
		if port == "" {
			port = "636"
		}
		tlsConfig, err = c.GetTLSConfig(host)
		if err != nil {
			break
		}
		conn, err = ldap.DialTLS("tcp", host+":"+port, tlsConfig)
	default:
		return nil, fmt.Errorf("invalid LDAP scheme")
	}
	if err != nil {
		return nil, fmt.Errorf("cannot connect to LDAP: %v", err)
	}

	return conn, nil
}
Exemplo n.º 11
0
// ExampleConn_Compare demonstrates how to comapre an attribute with a value
func ExampleConn_Compare() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	matched, err := l.Compare("cn=user,dc=example,dc=com", "uid", "someuserid")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(matched)
}
Exemplo n.º 12
0
// ExampleStartTLS demonstrates how to start a TLS connection
func ExampleConn_StartTLS() {
	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)
	}

	// Opertations via l are now encrypted
}
Exemplo n.º 13
0
func (a *ldapAuther) Dial() error {
	address := fmt.Sprintf("%s:%d", a.server.Host, a.server.Port)
	var err error
	if a.server.UseSSL {
		tlsCfg := &tls.Config{
			InsecureSkipVerify: a.server.SkipVerifySSL,
			ServerName:         a.server.Host,
		}
		a.conn, err = ldap.DialTLS("tcp", address, tlsCfg)
	} else {
		a.conn, err = ldap.Dial("tcp", address)
	}

	return err
}
Exemplo n.º 14
0
func (la *LDAPAuth) ldapConnection() (*ldap.Conn, error) {
	glog.V(2).Infof("Dial: starting...%s", la.config.Addr)
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s", la.config.Addr))
	if err != nil {
		return nil, err
	}
	if la.config.StartTLS {
		glog.V(2).Infof("StartTLS...")
		err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
		if err != nil {
			return nil, err
		}
	}
	return l, nil
}
Exemplo n.º 15
0
func login(user string, password string) (*ldap.Conn, error) {

	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort))
	if err != nil {
		return nil, err
	}
	l.Debug = debug

	bindRequest := ldap.NewSimpleBindRequest(user, password, nil)
	_, err = l.SimpleBind(bindRequest)
	if err != nil {
		return nil, err
	}
	return l, nil
}
Exemplo n.º 16
0
func (sua *LdapAuthConfig) connect() (*ldap.Conn, error) {
	if sua.Tls {
		tlsConfig := &tls.Config{
			ServerName: sua.Host,
		}
		if sua.Insecure {
			tlsConfig = &tls.Config{
				InsecureSkipVerify: true,
			}
		}
		l, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", sua.Host, sua.Port), tlsConfig)
		return l, err
	} else {
		l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", sua.Host, sua.Port))
		return l, err
	}
}
Exemplo n.º 17
0
func ExampleConn_Modify() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	// Add a description, and replace the mail attributes
	modify := ldap.NewModifyRequest("cn=user,dc=example,dc=com")
	modify.Add("description", []string{"An example user"})
	modify.Replace("mail", []string{"*****@*****.**"})

	err = l.Modify(modify)
	if err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 18
0
// Connect returns an established LDAP connection, or an error if the connection could not
// be made (or successfully upgraded to TLS). If no error is returned, the caller is responsible for
// closing the connection
func (l *LDAPClientConfig) Connect() (*ldap.Conn, error) {
	tlsConfig := l.TLSConfig

	// Ensure tlsConfig specifies the server we're connecting to
	if tlsConfig != nil && !tlsConfig.InsecureSkipVerify && len(tlsConfig.ServerName) == 0 {
		// Add to a copy of the tlsConfig to avoid mutating the original
		c := *tlsConfig
		if host, _, err := net.SplitHostPort(l.Host); err == nil {
			c.ServerName = host
		} else {
			c.ServerName = l.Host
		}
		tlsConfig = &c
	}

	switch l.Scheme {
	case SchemeLDAP:
		con, err := ldap.Dial("tcp", l.Host)
		if err != nil {
			return nil, err
		}

		// If an insecure connection is desired, we're done
		if l.Insecure {
			return con, nil
		}

		// Attempt to upgrade to TLS
		if err := con.StartTLS(tlsConfig); err != nil {
			// We're returning an error on a successfully opened connection
			// We are responsible for closing the open connection
			con.Close()
			return nil, err
		}

		return con, nil

	case SchemeLDAPS:
		return ldap.DialTLS("tcp", l.Host, tlsConfig)

	default:
		return nil, fmt.Errorf("unsupported scheme %q", l.Scheme)
	}
}
Exemplo n.º 19
0
func ExampleConn_PasswordModify_admin() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	err = l.Bind("cn=admin,dc=example,dc=com", "password")
	if err != nil {
		log.Fatal(err)
	}

	passwordModifyRequest := ldap.NewPasswordModifyRequest("cn=user,dc=example,dc=com", "", "NewPassword")
	_, err = l.PasswordModify(passwordModifyRequest)

	if err != nil {
		log.Fatalf("Password could not be changed: %s", err.Error())
	}
}
Exemplo n.º 20
0
func (_s *LDAP) Init(conf SBMSystem.ReadJSONConfig, rLog SBMSystem.LogFile) int {
	var (
		attemptCounter = int(0)
		err            error
	)

	_s.CS = -1

	for {
		if attemptCounter > len(conf.Conf.LDAP_URL)*2 {
			rLog.LogDbg(0, "LDAP Init SRV ***** Error connect to all LDAP servers !!!")
			return -1
		}

		if LDAPCounter > len(conf.Conf.LDAP_URL)-1 {
			LDAPCounter = 0
		}

		rLog.LogDbg(2, "LDAP Init SRV ***** Trying connect to server ", LDAPCounter+1, " of ", len(conf.Conf.LDAP_URL), ": ", conf.Conf.LDAP_URL[LDAPCounter][0])
		_s.D, err = ldap.Dial("tcp", conf.Conf.LDAP_URL[LDAPCounter][0])
		if err != nil {
			LDAPCounter++
			attemptCounter++
			continue
		}

		rLog.LogDbg(2, "LDAP Init SRV ***** Success! Connected to server ", LDAPCounter+1, " of ", len(conf.Conf.LDAP_URL), ": ", conf.Conf.LDAP_URL[LDAPCounter][0])
		LDAPCounter++
		break
	}

	//_s.D.Debug()

	err = _s.D.Bind(conf.Conf.LDAP_URL[0][1], conf.Conf.LDAP_URL[0][2])
	if err != nil {
		rLog.LogDbg(0, "LDAP::Bind() to server ", conf.Conf.LDAP_URL[LDAPCounter][0], " with login ", conf.Conf.LDAP_URL[0][1], " error: ", err)
		return -1
	}

	_s.CS = 0
	return 0
}
Exemplo n.º 21
0
func Example_vchuppolicy() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()
	l.Debug = true

	bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", nil)

	r, err := l.SimpleBind(bindRequest)

	passwordMustChangeControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordMustChange)
	var passwordMustChange *ldap.ControlVChuPasswordMustChange
	if passwordMustChangeControl != nil {
		passwordMustChange = passwordMustChangeControl.(*ldap.ControlVChuPasswordMustChange)
	}

	if passwordMustChange != nil && passwordMustChange.MustChange {
		log.Printf("Password Must be changed.\n")
	}

	passwordWarningControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordWarning)

	var passwordWarning *ldap.ControlVChuPasswordWarning
	if passwordWarningControl != nil {
		passwordWarning = passwordWarningControl.(*ldap.ControlVChuPasswordWarning)
	} else {
		log.Printf("ppolicyControl response not available.\n")
	}
	if err != nil {
		log.Print("ERROR: Cannot bind: " + err.Error())
	} else {
		logStr := "Login Ok"
		if passwordWarning != nil {
			if passwordWarning.Expire >= 0 {
				logStr += fmt.Sprintf(". Password expires in %d seconds\n", passwordWarning.Expire)
			}
		}
		log.Print(logStr)
	}
}
Exemplo n.º 22
0
func (la *LDAPAuth) ldapConnection() (*ldap.Conn, error) {
	var l *ldap.Conn
	var err error
	if la.config.TLS == "" || la.config.TLS == "none" || la.config.TLS == "starttls" {
		glog.V(2).Infof("Dial: starting...%s", la.config.Addr)
		l, err = ldap.Dial("tcp", fmt.Sprintf("%s", la.config.Addr))
		if err == nil && la.config.TLS == "starttls" {
			glog.V(2).Infof("StartTLS...")
			if tlserr := l.StartTLS(&tls.Config{InsecureSkipVerify: la.config.InsecureTLSSkipVerify}); tlserr != nil {
				return nil, tlserr
			}
		}
	} else if la.config.TLS == "always" {
		glog.V(2).Infof("DialTLS: starting...%s", la.config.Addr)
		l, err = ldap.DialTLS("tcp", fmt.Sprintf("%s", la.config.Addr), &tls.Config{InsecureSkipVerify: la.config.InsecureTLSSkipVerify})
	}
	if err != nil {
		return nil, err
	}
	return l, nil
}
Exemplo n.º 23
0
func ExampleConn_PasswordModify_generatedPassword() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	err = l.Bind("cn=user,dc=example,dc=com", "password")
	if err != nil {
		log.Fatal(err)
	}

	passwordModifyRequest := ldap.NewPasswordModifyRequest("", "OldPassword", "")
	passwordModifyResponse, err := l.PasswordModify(passwordModifyRequest)
	if err != nil {
		log.Fatalf("Password could not be changed: %s", err.Error())
	}

	generatedPassword := passwordModifyResponse.GeneratedPassword
	log.Printf("Generated password: %s\n", generatedPassword)
}
Exemplo n.º 24
0
func main() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort))
	if err != nil {
		log.Fatalf("ERROR: %s\n", err.Error())
	}
	defer l.Close()
	l.Debug = true

	controls := []ldap.Control{}
	controls = append(controls, ldap.NewControlBeheraPasswordPolicy())
	bindRequest := ldap.NewSimpleBindRequest(user, passwd, controls)

	r, err := l.SimpleBind(bindRequest)
	ppolicyControl := ldap.FindControl(r.Controls, ldap.ControlTypeBeheraPasswordPolicy)

	var ppolicy *ldap.ControlBeheraPasswordPolicy
	if ppolicyControl != nil {
		ppolicy = ppolicyControl.(*ldap.ControlBeheraPasswordPolicy)
	} else {
		log.Printf("ppolicyControl response not avaliable.\n")
	}
	if err != nil {
		errStr := "ERROR: Cannot bind: " + err.Error()
		if ppolicy != nil && ppolicy.Error >= 0 {
			errStr += ":" + ppolicy.ErrorString
		}
		log.Print(errStr)
	} else {
		logStr := "Login Ok"
		if ppolicy != nil {
			if ppolicy.Expire >= 0 {
				logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire)
			} else if ppolicy.Grace >= 0 {
				logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace)
			}
		}
		log.Print(logStr)
	}
}
Exemplo n.º 25
0
func (ls *LdapSource) dial() (*ldap.Conn, error) {
	if ls.c != nil {
		return ls.c, nil
	}

	var err error
	if ls.UseSSL {
		ls.c, err = ldap.DialTLS("tcp", ls.Addr, &tls.Config{InsecureSkipVerify: true})
	} else {
		ls.c, err = ldap.Dial("tcp", ls.Addr)
	}

	if err != nil {
		log.Printf("LDAP Connect error, %s:%v", ls.Addr, err)
		ls.Enabled = false
		return nil, err
	}

	// ls.c.Debug = ls.Debug

	return ls.c, nil
}
Exemplo n.º 26
0
func Example_beherappolicy() {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	controls := []ldap.Control{}
	controls = append(controls, ldap.NewControlBeheraPasswordPolicy())
	bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", controls)

	r, err := l.SimpleBind(bindRequest)
	ppolicyControl := ldap.FindControl(r.Controls, ldap.ControlTypeBeheraPasswordPolicy)

	var ppolicy *ldap.ControlBeheraPasswordPolicy
	if ppolicyControl != nil {
		ppolicy = ppolicyControl.(*ldap.ControlBeheraPasswordPolicy)
	} else {
		log.Printf("ppolicyControl response not avaliable.\n")
	}
	if err != nil {
		errStr := "ERROR: Cannot bind: " + err.Error()
		if ppolicy != nil && ppolicy.Error >= 0 {
			errStr += ":" + ppolicy.ErrorString
		}
		log.Print(errStr)
	} else {
		logStr := "Login Ok"
		if ppolicy != nil {
			if ppolicy.Expire >= 0 {
				logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire)
			} else if ppolicy.Grace >= 0 {
				logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace)
			}
		}
		log.Print(logStr)
	}
}
Exemplo n.º 27
0
Arquivo: main.go Projeto: patito/chpwd
func changeLdapPassword(user *userConfig) error {

	l := &ldapConfig{"base_dn", 389, "127.0.0.1"}

	conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", l.address, l.port))
	if err != nil {
		return err
	}
	defer conn.Close()

	err = conn.Bind(l.baseDN, user.password)
	if err != nil {
		return err
	}

	passwordModifyRequest := ldap.NewPasswordModifyRequest("", user.password, user.newPassword)
	_, err = conn.PasswordModify(passwordModifyRequest)
	if err != nil {
		return err
	}

	return nil
}
Exemplo n.º 28
0
// 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"))
	}
}
Exemplo n.º 29
0
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)
			}
		}

	}
}
Exemplo n.º 30
0
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

}