Error while trying to authenticate user grafana

LDAP authentication doesn’t work with userPrincipalName as username #3431 Comments LDAP authentication doesn’t seem to work properly in my environment when using userPrincipalName as the value of username. That is, with the following values set in ldap.toml: [servers.attributes] . username = «userPrincipalName» email = «mail» . It works the first time a particular user […]

Содержание

  1. LDAP authentication doesn’t work with userPrincipalName as username #3431
  2. Comments
  3. [Bug] LDAPS — Error authenticating to Active Directory with Grafana ONLY when using TLS #7194
  4. Comments
  5. Issue with getting ldap working, conflicting info in ldap verbose output #2611
  6. Comments
  7. Map LDAP groups to Grafana org roles
  8. Map LDAP groups to Grafana org roles

LDAP authentication doesn’t work with userPrincipalName as username #3431

LDAP authentication doesn’t seem to work properly in my environment when using userPrincipalName as the value of username. That is, with the following values set in ldap.toml:

[servers.attributes]
.
username = «userPrincipalName»
email = «mail»
.

It works the first time a particular user tries to log in, but then on a subsequent login attempts you see an error like this in grafana.log:
[login.go:101 LoginPost()] [E] Error while trying to authenticate user: UNIQUE constraint failed: user.email

It seems Grafana is trying to create a new user every time, instead of realising that the user trying to login already exists. Thus, the unique constraint on the email field is failing.

When, eg, sAMAccountName is used as the value of username, everything works fine — both on login attempt 1, and on subsequent login attempts.

The values of these two attributes for me are:

userPrincipalName: Kenneth.MacArthur@company.com
sAMAccountName: Kenneth.MacArthur

Could the issue be the at sign in userPrincipalName?

It is slightly unclear exactly how the matching of existing users takes place — it seems like a little bit of black magic. 😉 Otherwise, I would be happy to help debug this further.

I’m running Grafana v2.5.0.

The text was updated successfully, but these errors were encountered:

matching is done on email and username

you can enable logging and see what ldap attributes are fetched. I guess the email property is not being matched correctly. Check that your ldap email property is correct or set it to userPrincipalName

When you say matching is done on email and username, do you mean that the values of both have to match for an LDAP user to be considered an existing user (ie, it’s an AND condition)?

If so, why have a unique constraint on email by itself?

I have verbose LDAP logging enabled. I am setting Grafana’s «email» property to the value of the «mail» attribute from our LDAP server, and the value of this attribute looks fine. As mentioned, everything works fine in any case when the «username» property is set to «sAMAccountName» from LDAP (without changing anything relating to the «email» property), so this doesn’t actually look like it has anything to do with «email».

whats ldap logging output? (showing the ldap attributes fetched during login)

Got the same issue:

using this config:
bind_dn = «cn=%s,cn=Users,dc=foo,dc=com»
search_filter = «(cn=%s)»
search_base_dns = [«cn=Users,dc=foo,dc=com»]
[servers.attributes]
name = «givenName»
surname = «sn»
username = «cn»
member_of = «memberOf»
email = «mail»
=> it’s works but it’s not the real username ldap used by users for authentification, they are entering the sAMAccountName

if using sAMAccountName
bind_dn = «sAMAccountName=%s,cn=Users,dc=foo,dc=com»
search_filter = «(sAMAccountName=%s)»
search_base_dns = [«cn=Users,dc=foo,dc=com»]
[servers.attributes]
name = «givenName»
surname = «sn»
username = «sAMAccountName»
member_of = «memberOf»
email = «mail»

=> dont work and got error :
[I] LDAP initial bind failed, LDAP Result Code 49 «Invalid Credentials»: 80090308: LdapErr: DSID-0C0903CF, comment: AcceptSecurityContext error, data 52e, v2580
[login.go:98 LoginPost()] [E] Invalid username or password: Invalid Username or Password

no 🙁 your ldap server does not like binding on sAMAccountName

if you have ldap admin/anonymous user can set bind_password or bind_dn to blank. Then the search (user lookup) will take place and the user authentication bind will be done on the search hit

@torkelo you’re right sAMAccountName not supported for direct bind_dn so i was trying an other way over userPrincipalName.

This command ldapsearch works using julien@foo.com (which is the userPrincipalName of course i entered manually the pwd) :
ldapsearch -x -h ldap.foo.com -D «julien@foo.com» -W -b «cn=users,dc=foo,dc=com» -s sub «(cn=*)» cn mail sn
Enter LDAP Password:

Meaning userPrincipalName is supported by our ldap (active directory).

How can i setup ldap.toml for use userPrincipalName for the bind_dn ?

i tried:
bind_dn = «userPrincipalName=%s,cn=Users,dc=pws,dc=com»
search_filter = «(userPrincipalName=%s)»
search_base_dns = [«cn=Users,dc=pws,dc=com»]

still having :
[I] LDAP initial bind failed, LDAP Result Code 49 «Invalid Credentials»: 80090308: LdapErr: DSID-0C0903CF, comment: AcceptSecurityContext error, data 52e, v2580
[login.go:98 LoginPost()] [E] Invalid username or password: Invalid Username or Password

if it’s working over ldapserach grafana should be able to connect over it also.

Hope you could provide me your help on it.

@kennethmac2000 which config you had in your ldap.toml, can you paste it here ?

set bind_dn= and bind_password= to blank (empty) to make grafana search for the user and bind on the dn after search (the dn will be full dn for the found user)

@torkelo i have tried setup like you mentionned :

bind_dn = »
bind_password = »
search_filter = «(userPrincipalName=%s)»
search_base_dns = [«cn=Users,dc=foo,dc=com»]
[servers.attributes]
name = «givenName»
surname = «sn»
username = «userPrincipalName»
member_of = «memberOf»
email = «mail»

or
#bind_dn = »
#bind_password = »
search_filter = «(userPrincipalName=%s)»
search_base_dns = [«cn=Users,dc=foo,dc=com»]
[servers.attributes]
name = «givenName»
surname = «sn»
username = «userPrincipalName»
member_of = «memberOf»
email = «mail»

Both dont work and getting this error :
[E] Error while trying to authenticate user: LDAP Result Code 1 «Operations Error»: 000004DC: LdapErr: DSID-0C090748, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580

if you cannot leave them blank (meaning anonymous access is not allowed), specify a bind_dn for user and bind_dn password to use for search

that is do not use «%s» in the bind_dn, specify a user that can be used for the initial bind,

i would avoid to put a user/password in clear text in a config which really not secure. I would have a dynamic bind_dn using the login/password entered by user.
Could be a bug inside the ldap.go connector ?

no, you need to specify a user in order to search ldap (since you do not have anonymous access to search), there is no bug, as your ldap does support binding on sAMAccountName you need to search for the user first (using sAMAccountName, then do the bind)

i can’t do based on userPrincipalName ? instead of sAMAccountName.
With userPrincipalName, my ldap support as exposed to you over ldapsearch

@JulienChampseix I am not sure I understand what your saying.

I though you tried but your ldap does not allow you to bind on the property you want to bind on? I am confused. Anyway you should be able to search on any property, then grafana will bind on the ldap dn entry for the found user.

In fact originally i tried to use sAMAccountName (instead of cn which is the default) using this config:

but my ldap (windows active directory) dont support it (confirmed using ldapsearch).

So second step i wanted try to use userPrincipalName:

but here i got the grafana error :

Note for this second step the command line ldapsearch works meaning the ldap support bind_dn using userPrincipalName but not over grafana.
Command ldapsearch for test with userPrincipalName which worked :

So i would be able to configure grafana (ldap.toml) using userPrincipalName with bind_dn but dont success for the moment. That’s why i would your help for fix it or detect if it’s hidden bug.

Hope it’s more clear 😉

@torkelo
any waiting your feedback on my previous comment, i had an other one question. When enabling verbose in ldap, is it possible to expose also the bindPath used ? which is used there https://github.com/grafana/grafana/blob/master/pkg/login/ldap.go#L256

@torkelo how to reopen this issue ? as atm we can’t use LDAP authentication with userPrincipalName

where do you specify userPrincipalName here?

Did you try to specify search user, and search on userPrincipalName? (static search user used for search only)

-D «julien@foo.com» here is the bind DN which is userPrincipalName field
-b «cn=users,dc=foo,dc=com» is the base dn for search which the ldap tree

As it’s working from command line, it should work over grafana(ldap.toml) also with the right config. But config posted previously i tested dont works.

@torkelo possible to add more information into the verbose mode of the ldap (like bind_dn used during connection, search used, ..) That will be very usefull and could easily for you to add those additionnal log in the 2.6 version which is in beta.

how can «julien@foo.com» be a bind dn, does not look like a dn path.

if no bind password or bind_dn is specified a second bind is done on the DN of the search hit. OR if bind_dn does not contain %s , meaning its a static dn for a user used only to be able search ldap.

The DN used for the second bind (it it needed), is the canonical dn path for the search hit, meaning the dn path the ldap server returns as the full path for search hit.

I’m not sure if this conversation is still about the original issue any more, but to clarify the setup in my environment:

  • There is a bind DN (and password) for the search user, which is a service account that we created specifically for this purpose
  • The search filter used in the first bind is «(userPrincipalName=%s)»
  • userPrincipalName is mapped to the username attribute in [servers.attributes]

To emphasise again, if I was happy to use sAMAccountName as the search filter/username value, this would already be working. But for some reason, things don’t work when I use userPrincipalName.

In my environment, sAMAccountName is kenneth.macarthur whereas userPrincipalName is kenneth.macarthur@company.com. It couldn’t be something as simple as the at sign in userPrincipalName could it?

what do you mean by «It couldn’t be something as simple as the at sign in userPrincipalName could it?»

The %s in the search filter will be replaced with the username you specify on the login page.

When your search filter is using userPrincipalName is there a search hit? If you have verbose logging enabled it should report ldap attributes for the search hit. It just the second bind that is failing?

I took quite some time to write the original issue, and I don’t think I can explain things again any better.

Logging in with userPrincipalName set to be the username works the first time (ie, before the user exists in Grafana’s database), but not on subsequent login attempts.

Logging in with sAMAccountName set to be the username works both the first time and on subsequent login attempts.

Logging in with an incorrect userPrincipalName or sAMAccountName value (or an incorrect password) does not work, at any time.

To be absolutely clear, it’s not the second bind that’s failing, it’s the second login attempt — but only when the username is set to userPrincipalName.

There is nothing output to the log, even with verbose LDAP logging on, which tells you specifically what is going on on that second login attempt.

The log does tell you that you’re trying to create a user with the same e-mail address as an existing user — which would makes sense if we were indeed trying to create a new user here. But we’re not.

A user record was already created on the first login attempt, and on login attempt 2, with the same login credentials, I would assume Grafana should be determining that the user logging in already has a record in the Grafana user database and not be trying to create another user record.

And indeed it does this correctly when we use sAMAccountName as the username.

The only two key differences between sAMAccountName and userPrincipalName in my environment is that userPrincipalName is longer, and it contains an at sign.

Grafana obviously has to do some matching to determine whether the user logging in is a new user or an existing user. Could the reason this matching logic appears to not be working correctly with userPrincipalName values be that the value is either too long or that it contains an at sign?

Источник

[Bug] LDAPS — Error authenticating to Active Directory with Grafana ONLY when using TLS #7194

AUTHENTICATION WORKS WITHOUT TLS/SSL

only change to configuration is:

change to enable ssl: «use_ssl=true»
change to the TCP port: «port = 636»

Please include this information:

  • What Grafana version are you using?
    grafana-4.0.1
  • What datasource are you using?
    grafana-zabbix
  • What OS are you running grafana on?
    Red Hat Enterprise Linux Server release 7.3 (Maipo)
  • What did you do?
    setup LDAP for LDAPS to Active Directory
  • What was the expected result?
    I can authenticate with Active Directory users/groups
  • What happened instead?
    Error Message:

The text was updated successfully, but these errors were encountered:

Also, I can connect using LDAPS test connection using the certificate in question and JXplorer on Mac OS X and I can test the certificate with OpenSSL using the same root CA — the result with OpenSSL is «Verify return code: 0 (ok)» (openssl s_client -connect host.organization.com:636 -CAfile /etc/pki/tls/root.pem)

I thought I could work around this by using start_tls on the default port, apparently start_tls is being ignored by Grafana. The user authentication was sent over the wire in clear text to the Active Directory server. I will open up a separate bug regarding the issue with start_tls.

update: This may be a misunderstanding on my part — the configuration for grafana may require both «enable_ssl» and «start_tls» to be toggled in order for TLS to be enabled with STARTTLS?

Regardless, I am getting the following error when attempting to start with STARTTLS.

Источник

Issue with getting ldap working, conflicting info in ldap verbose output #2611

Hello,
I’m trying to get ldap working and I’m seeing conflicting info being reported and am unsure if this is a bug or something else config wise and looking for some assistance to resolve this.

Config file has —
verbose_logging = true
search_filter = «(uid=%s)»
search_base_dns = [«dc=MYCOMPANY,dc=com»]

[servers.attributes]
name = «givenName»
surname = «sn»
username = «uid»
member_of = «memberOf»
email = «mail»

Map LDAP groups to Grafana org roles

[[servers.group_mappings]]
group_dn = ‘systems’
org_role = «Admin»
org_id = 1

[[servers.group_mappings]]
group_dn = «cn=compliance»
org_role = «Editor»

[[servers.group_mappings]]
group_dn = «hr»
org_role = «Viewer»

Console log shows —

2015/08/27 15:45:21 [I] Ldap User Info: (*login.ldapUserInfo)(0xc20825dd50)( <
DN: (string) (len=48) «uid=jdoe,ou=People,dc=MYCOMPANY,dc=com»,
FirstName: (string) (len=9) «John»,
LastName: (string) (len=8) «Doe»,
Username: (string) (len=9) «jdoe»,
Email: (string) (len=28) «jdoe@MYCOMPANY.com»,
MemberOf: ([]string) (len=5 cap=8) <
(string) (len=46) «cn=mycomp,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=50) «cn=systems2,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=48) «cn=systems,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=63) «cn=IM,ou=MyMisc,dc=MYCOMPANY,dc=com»,
(string) (len=60) «cn=mycomp,ou=IM Rosters,ou=MyMisc,dc=MYCOMPANY,dc=com»
>
>)

2015/08/27 15:45:21 [I] Ldap Auth: user jdoe does not belong in any of the specified ldap groups, ldapUser groups: [cn=mycomp,ou=Group,dc=MYCOMPANY,dc=com
cn=systems2,ou=Group,dc=MYCOMPANY,dc=com
cn=systems,ou=Group,dc=MYCOMPANY,dc=com
cn=IM,ou=MyMisc,dc=MYCOMPANY,dc=com
cn=mycomp,ou=IM Rosters,ou=MyMisc,dc=MYCOMPANY,dc=com]

2015/08/27 15:45:21 [login.go:98 LoginPost()] [E] Invalid username or password: Invalid Username or Password
2015/08/27 15:45:21 [I] Completed /login 401 Unauthorized in 11.731058ms
2015/08/27 15:45:21 [I] Completed /api/login/ping 401 Unauthorized in 1.74992ms

I can confirm that jdoe does belong in each of the listed ldap groups.
It is picking up the proper ldap groups for the passed in user but is then reporting that the user is not found in any of those ldap groups and erroring out.
How do I correct this issue?
I’ve tried both grafana 2.1.3 and the grafana 2.2.0-pre1 release.

The text was updated successfully, but these errors were encountered:

Try and change your group_dn config to include the full thing and not just the cn. (e.g. group_dn = «cn=mycomp,ou=Group,dc=MYCOMPANY,dc=com» )

in the [[servers.group_mappings]] section `group_dn’ must match the full DN exactly as ldap returns it.

You only specified a string on 2 cases and a cn path in one 🙂

Hi, thanks for the replies. The typo was a cut/paste error as I removed my corp info. I did have cn= proper syntax in the actual toml file. Also, I did try with the full DN and without before as well with no success.

Essentially here’s what’s happening —

(1) with the full DN —

Map LDAP groups to Grafana org roles

[[servers.group_mappings]]
group_dn = ‘cn=systems,ou=Group,dc=MYCOMPANY,dc=com’
org_role = «Admin»
org_id = 1

and no other servers.group_mappings, I’m getting —

2015/08/28 09:47:31 [I] Ldap User Info: (*login.ldapUserInfo)(0xc20825dd50)( <
DN: (string) (len=48) «uid=jdoe,ou=People,dc=MYCOMPANY,dc=com»,
FirstName: (string) (len=9) «John»,
LastName: (string) (len=8) «Doe»,
Username: (string) (len=9) «jdoe»,
Email: (string) (len=28) «jdoe@MYCOMPANY.com»,
MemberOf: ([]string) (len=5 cap=8) <
(string) (len=46) «cn=mycomp,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=50) «cn=systems2,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=48) «cn=systems,ou=Group,dc=MYCOMPANY,dc=com»,
(string) (len=63) «cn=IM,ou=MyMisc,dc=MYCOMPANY,dc=com»,
(string) (len=60) «cn=mycomp,ou=IM Rosters,ou=MyMisc,dc=MYCOMPANY,dc=com»
>
>)

2015/08/28 09:47:31 [login.go:101 LoginPost()] [E] Error while trying to authenticate user: UNIQUE constraint failed: org.name
2015/08/28 09:47:31 [I] Completed /login 500 Internal Server Error in 16.212318ms

(2) without the full DN —
[[servers.group_mappings]]
group_dn = ‘cn=systems’
org_role = «Admin»
org_id = 1

2015/08/28 09:48:03 [I] Ldap Auth: user jdoe does not belong in any of the specified ldap groups, ldapUser groups: [cn=mycomp,ou=Group,dc=MYCOMPANY,dc=com cn=systems2,ou=Group,dc=MYCOMPANY,dc=com cn=systems,ou=Group,dc=MYCOMPANY,dc=com cn=IM,ou=MyMisc,dc=MYCOMPANY,dc=com
cn=mycomp,ou=IM Rosters,ou=MyMisc,dc=MYCOMPANY,dc=com]
2015/08/28 09:48:03 [login.go:98 LoginPost()] [E] Invalid username or password: Invalid Username or Password
2015/08/28 09:48:03 [I] Completed /login 401 Unauthorized in 11.784752ms
2015/08/28 09:48:03 [I] Completed /api/login/ping 401 Unauthorized in 1.405854ms

Is there a way to make grafana report even more verbose output.
Again, thanks for all your help. The product is fantastic.

Hi torkelo, after checking some more, I think the issue is that the code is checking for MemberOf whereas my ldap is returning values only when queried for «UniqueMember».

How would I make the edit to get it to search on UniqueMember instead or in addition to MemberOf?

I attempted to edit ldap.go and settings.go and ldap_user.go but I’m in completely unfamiliar territory here.
I added «a.server.Attr.UniqueMember,» in the searchForUser function and tried returning that in &ldapUserInfo and edited ldap_user.go to be thus

type ldapUserInfo struct <
DN string
FirstName string
LastName string
Username string
Email string
MemberOf []string
UniqueMember []string
>

func (u ldapUserInfo) isMemberOf(group string) bool <
if group == «
» <
return true
>

But not having any luck. Can you pls assist?

Источник

Hello,

TL;DR : I’ve spent many hours trying to get Grafana to authenticate users via LDAPS to Active Directory. If anyone has the required magic to get it to work, I’d be quite happy.

I’m having issues with Grafana. I figured this might be a good place to ask. I’m trying to use LDAPS auth for user authentication and failing at it.

So far, the LDAP bind works in cleartext, I can login to the web UI just fine with any user who is part of the right groups. I’m trying to convert my install to use TLS to encrypt the communications.

Grafana : 10.222.0.166 (CentOS 7)
DC : 10.222.0.11 (WS2012R2)

Here’s the relevant part of my ldap configuration file :

[[servers]]
# Ldap server host (specify multiple hosts space separated)
host = "10.222.0.11"
port = 636
use_ssl = true
start_tls = false

Using ldapsearch, I can see what the normal seq is supposed to look like in wireshark.

Side note : Since LDAPsearch and PFsense are working using port 636 with SSL and are able to get whatever they need for auth, I was treating my AD config as working.

  1. When attempting to communicate using straight LDAPS (port=636, use_ssl=true, start_tls=false) :

    Grafana.log :

     lvl=eror msg="Error while trying to authenticate user" logger=context userId=0 orgId=0 uname= error="LDAP Result Code 200 "": read tcp 10.222.0.166:55622->10.222.0.11:636: read: connection reset by peer"
    

    Wireshark (running on the DC) : connection starts, then the DC sends a reset packet as soon as the client sends a «Hello».

  2. When attempting to communicate with the server with Start_TLS (port=389, ssl=true, start_tls=true), I get this :

    Grafana.log :

     lvl=eror msg="Error while trying to authenticate user" logger=context userId=0 orgId=0 uname= error="LDAP Result Code 200 "": TLS handshake failed (read tcp 10.222.0.166:48240->10.222.0.11:389: read: connection reset by peer)"
    

    Wireshark : connection starts, Start_TLS is asked and allowed then the client sends a Hello and the DC sends a connection reset packet.

At this point, I figure that Grafana’s ldap module is using some kind of voodoo magic that doesn’t properly do SSL/TLS.

Any help is welcome!

Какую версию Grafana вы используете?

графана-5.3.0

Какой источник данных вы используете?

Не имеющий отношения

На какой ОС вы используете Grafana?

Red Hat Enterprise Linux Server версии 7.5 (Maipo)

Что ты сделал?

Обновление IPA с 4.5.4 -> 4.6.4

Каков был ожидаемый результат?

Аутентификация LDAP будет продолжаться как обычно

Что произошло вместо этого?

Попытка аутентифицироваться через LDAP:

lvl=eror msg="Error while trying to authenticate user" logger=context userId=0 orgId=0 uname= error="LDAP Result Code 2 "Protocol Error": "

Поисковый запрос с IPA:

[05/Dec/2018:10:50:10.160459643 +0200] conn=84119 fd=338 slot=338 SSL connection from XXX.XX.X.XXX to XXX.XX.X.XXX
[05/Dec/2018:10:50:10.165958341 +0200] conn=84119 TLS1.2 256-bit AES-GCM
[05/Dec/2018:10:50:10.167109254 +0200] conn=84119 op=0 BIND dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd" method=128 version=3
[05/Dec/2018:10:50:10.167750466 +0200] conn=84119 op=0 RESULT err=0 tag=97 nentries=0 etime=0.0007013470 dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"
[05/Dec/2018:10:50:10.168907397 +0200] conn=84119 op=1 SRCH base="(null)" scope=2 asdlter="(uid=asdf)", invalid attribute request
[05/Dec/2018:10:50:10.168943337 +0200] conn=84119 op=1 RESULT err=2 tag=101 nentries=0 etime=0.0000119809
[05/Dec/2018:10:50:10.170213905 +0200] conn=84119 op=-1 fd=338 closed - B1

Как видите, база SRCH нулевая. Отладка tcpdump и проверка аутентификации ldap. Привязка работает нормально, но поиск выдает ноль

графана:

30 76 02 01 02 63 71 04

go-ldap (исходный код 5.3.0) / perl (Net :: LDAP) / python (ldap), они работают:

30 78 02 01 02 63 73 04

Как видите, 2-й и 7-й байты из гекса отличаются от других запросов. Может быть, реализация Grafana LDAP что-то добавляет / модифицирует в запрос?

Из go-ldap кажется, что этот блок отвечает за поисковые запросы, которые, похоже, не работают в grafana:

searchRequest := NewSearchRequest(
"dc=example,dc=com", // The base dn to search
ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
"(&(objectClass=organizationalPerson))", // The filter to apply
[]string{"dn", "cn"}, // A list attributes to retrieve
nil,
)

Графана:

func (a *ldapAuther) searchForUser(username string) (*LdapUserInfo, error) {
var searchResult *ldap.SearchResult
var err error

for _, searchBase := range a.server.SearchBaseDNs {
searchReq := ldap.SearchRequest{
BaseDN: searchBase,
Scope: ldap.ScopeWholeSubtree,
DerefAliases: ldap.NeverDerefAliases,
Attributes: []string{
a.server.Attr.Username,
a.server.Attr.Surname,
a.server.Attr.Email,
a.server.Attr.Name,
a.server.Attr.MemberOf,
},
Filter: strings.Replace(a.server.SearchFilter, "%s", ldap.EscapeFilter(username), -1),
}

Из кодов ошибок LDAP:

==============================
‣2
‣ LDAP_PROTOCOL_ERROR
‣ Указывает, что сервер получил недействительный или неверный запрос от клиента.
==============================

ldap.toml:

verbose_logging = true

[[servers]]
host = "foobar.asd.asd.asd"
port = 389
use_ssl = false
ssl_skip_verify = true

# Search user bind dn
bind_dn = "uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"
bind_password = 'asd'

search_filter = "(uid=%s)"
search_base_dns = ["cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"]

[servers.attributes]
name = "displayName"
username = "uid"
member_of = "memberOf"

[[servers.group_mappings]]
group_dn = "cn=sw_perfdb_grafana_admins_asd,cn=groups,cn=accounts,dc=asd,dc=asd,dc=asd"
org_role = "Admin"

[[servers.group_mappings]]
group_dn = "*"
org_role = "Viewer"

arebackenautldap
efforsmall
typbug

Эта конфигурация LDAP работала с IPA v4.5.4, а затем сломалась после обновления IPA? Или проблема была вызвана обновлением Grafana?

Я мало что знаю об IPA / FreeIPA, поэтому выясняю, есть ли какие-либо различия в синтаксисе или это то, что мы делаем с go-ldap, вот в чем проблема.

Да, эта конфигурация работала с IPA 4.5.4 (и все еще работает, у нас есть другой кластер, использующий более раннюю версию) и сломалась после обновления IPA, это не проблема конфигурации ldap.toml.

Тестирование ldap с базовым go-ldap и различными другими языками работает, поэтому проблема не должна быть связана с IPA.

Мы подозреваем, что какая-то переменная / класс искажает кодировку (asn1) сообщения в двоичном формате и, таким образом, искажает поисковый запрос.

Это правильный вариант:

Extended Response Protocol Op
01111000     0x78
Search Result Reference Protocol Op
01110011     0x73

Графана отправляет это:

Extended Response Protocol Op
01110110    0x76
Search Result Reference Protocol Op
01110001    0x71

Проверяя примечания к выпуску IPA v4.6.4, мы обнаружили по крайней мере один элемент, который мог вызвать это, который был связан, в основном, чтобы отклонить искаженный запрос или приказ защитить IPA от атаки DOS.

https://pagure.io/389-ds-base/issue/49969

@jarttori спасибо. Рассмотрим, как мы вызываем go-ldap и отправляем ли мы неверные параметры.

Интересно, может ли это быть так, я думаю, мы всегда отправляем пустой массив Controls:

https://github.com/go-ldap/ldap/issues/162#issuecomment -389100477

Это исправлено в v3 go-ldap, который был выпущен совсем недавно (чего мы ждали). Если мы обновим go-ldap до v3, это может решить вашу проблему (сейчас мы находимся на версии 2.5.1).

@jarttori, можете ли вы протестировать ночную сборку Grafana (иначе вам придется подождать до следующего основного выпуска Grafana)? Не на 100% уверен, что это решит вашу проблему, но надеюсь.

@daniellee Протестировано против

[root<strong i="7">@perffev01t</strong> gtenauja]# grafana-server -v
Version 5.5.0-pre1 (commit: b798a54, branch: master)

Все еще дает ту же ошибку

Dec 27 16:35:42 perffev01t grafana-server: t=2018-12-27T16:35:42+0200 lvl=eror msg="Error while trying to authenticate user" logger=context userId=0 orgId=0 uname= error="LDAP Result Code 2 "Protocol Error": "

IPA

[27/Dec/2018:16:38:15.727533829 +0200] conn=2177713 fd=279 slot=279 connection from asd.asd.asd.asd to asd.asd.asd.asd
[27/Dec/2018:16:38:15.728143523 +0200] conn=2177713 op=0 BIND dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd" method=128 version=3
[27/Dec/2018:16:38:15.728821418 +0200] conn=2177713 op=0 RESULT err=0 tag=97 nentries=0 etime=0.0000994572 dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"
[27/Dec/2018:16:38:15.730196410 +0200] conn=2177713 op=1 SRCH base="(null)" scope=2 filter="(uid=gtenauja)", invalid attribute request
[27/Dec/2018:16:38:15.730223666 +0200] conn=2177713 op=1 RESULT err=2 tag=101 nentries=0 etime=0.0000101198
[27/Dec/2018:16:38:15.733942535 +0200] conn=2177713 op=-1 fd=279 closed - B1

tcpdump:

0x0040:  bb11 3076 0201 0263 7104 2d63 6e3d 7573  ..0v...cq.-cn=us

Все еще отправляет тот же неверный запрос

30 76 02 01 02 63 71 04

@jarttori Я застрял на этом. Для меня это не очевидная ошибка, поскольку, похоже, она отлично работает с openldap.

Я не понимаю, как SRCH base="(null)" scope=2 filter="(uid=gtenauja)" может иметь нулевую базу. Базовая переменная должна быть получена из параметра search_base_dns в вашем файле toml.

Единственная проблема, которая кажется мне похожей, — это то, что может дать подсказку: https://github.com/nextcloud/server/issues/12086

Вполне возможно, что Grafana отправляет пустые атрибуты .

Я добавил оператор отладки для поискового запроса ldap: ce50e9331ab50d2a1946e3f4a95287c7a1989621

Можете ли вы протестировать еще раз с последней ночной сборкой Grafana с уровнем журнала, установленным на ldap:debug в вашем ini-файле:

[log]
mode = console
filters = ldap:debug

@daniellee Извините за задержку, я был в отпуске.

Вот отладка с той же ошибкой:

Jan  7 10:31:19 perffev01t grafana-server: t=2019-01-07T10:31:19+0200 lvl=dbug msg="Ldap Search For User Request" logger=ldap info="(ldap.SearchRequest) {n BaseDN: (string) (len=45) "cn=users,cn=accounts,dc=asd,dc=asd,dc=asd",n Scope: (int) 2,n DerefAliases: (int) 0,n SizeLimit: (int) 0,n TimeLimit: (int) 0,n TypesOnly: (bool) false,n Filter: (string) (len=14) "(uid=gtenauja)",n Attributes: ([]string) (len=5 cap=5) {n  (string) (len=3) "uid",n  (string) "",n  (string) "",n  (string) (len=11) "displayName",n  (string) (len=8) "memberOf"n },n Controls: ([]ldap.Control) <nil>n}n"

Что-то напуганное, после того, как я возился с запросами, я получил работу с:

func ExampleConn_Bind() {
        l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "asdasd", 389))
        if err != nil {
                log.Fatal(err)
        }
        defer l.Close()

        err = l.Bind("uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd", "asdasd")
        if err != nil {
                log.Fatal(err)
        }
                //      searchRequest := ldap.NewSearchRequest(
                // "cn=users,cn=accounts,dc=asd,dc=asd,dc=asd",
                // ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
                // "(uid=gtenauja)",
                // []string{"uid", " ", " ", "displayName", "memberOf"},
                // nil,
                searchBase := "cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"
                username := "gtenauja"
                Username := "uid"
                //Surname := ""
                Email := ""
                Name := "displayName"
                MemberOf := "memberOf"
                SearchFilter := "(uid=username)"
                searchReq := ldap.SearchRequest{
                        BaseDN:       searchBase,
                        Scope:        ldap.ScopeWholeSubtree,
                        DerefAliases: ldap.NeverDerefAliases,
                        Attributes: []string{
                                Username,
                //              Surname,
                                Email,
                                Name,
                                MemberOf,
                        },
                        Filter: strings.Replace(SearchFilter, "%s", ldap.EscapeFilter(username), -1),
                }
         fmt.Println(searchReq)

        sr, err := l.Search(&searchReq)
        if err != nil {
                log.Fatal(err)
        }

Как видите, я удалил только Фамилию из поля атрибута:

[root<strong i="9">@dnsv02t</strong> ~]# go run testildap.go 
{cn=users,cn=accounts,dc=asd,dc=asd,dc=asd 2 0 0 0 false (uid=gtenauja) [uid  displayName memberOf] []}
uid: gtenauja
cn=admins,cn=groups,cn=accounts,dc=asd,dc=asd,dc=asd

Из IPA:

[07/Jan/2019:18:28:01.445831394 +0200] conn=3212186 fd=227 slot=227 connection from asdasd to asdasd
[07/Jan/2019:18:28:01.446317430 +0200] conn=3212186 op=0 BIND dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd" method=128 version=3
[07/Jan/2019:18:28:01.447018125 +0200] conn=3212186 op=0 RESULT err=0 tag=97 nentries=0 etime=0.0000958548 dn="uid=readgroup,cn=users,cn=accounts,dc=asd,dc=asd,dc=asd"
[07/Jan/2019:18:28:01.448601446 +0200] conn=3212186 op=1 SRCH base="cn=users,cn=accounts,dc=asd,dc=asd,dc=asd" scope=2 filter="(uid=gtenauja)" attrs="uid  displayName memberOf"
[07/Jan/2019:18:28:01.449629158 +0200] conn=3212186 op=1 RESULT err=0 tag=101 nentries=1 etime=0.0001091756
[07/Jan/2019:18:28:01.457722444 +0200] conn=3212186 op=-1 fd=227 closed - B1

На самом деле не имело значения, какое поле атрибута я удалил, оно все равно работало. Однако шестнадцатеричный код по-прежнему неверен:

0x0040:  e0ba 3074 0201 0263 6f04 2d63 6e3d 7573

3074 0201 0263 6f04

Наконец-то удалось воспроизвести это (потребовалось время, чтобы FreeIPA заработал). Для меня ошибка возникает, когда у меня меньше 4 атрибутов.

Итак, этот toml работает:

[servers.attributes]
name = "givenName"
username = "uid"
member_of = "memberOf"
email =  "mail"

но после удаления атрибутов sn и email я получаю ту же ошибку, что и вы:

[servers.attributes]
name = "givenName"
username = "uid"
member_of = "memberOf"

Но это прекрасно работает с OpenLDAP. Таким образом, проблема заключается в отправке пустых атрибутов. Обходной путь — добавить еще один атрибут (либо email или sn или оба), пока исправление не будет выполнено и выпущено.

Ха, только что видел ваш комментарий. Не уверен, почему можно отправлять один пустой атрибут, а не два. Но я думаю, что это связано с тем исправлением безопасности IPA, на которое вы ссылались ранее.

Я могу подтвердить, что после добавления «email» в server.attributes аутентификация ldap работает.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги


Matthew Kruse <mkruse@…>

I’ll try and describe the odd behavior I’m seeing on 2.1.  I’ve got ldap enabled and that is working.  Where it goes wrong is if I create a new organization.  Once I create a new organization and logout, the current user is unable to every login again and I get this error: [login.go:101 LoginPost()] [E] Error while trying to authenticate user: Cannot remove last organization admin

Any ideas?

2015/08/06 12:02:43 [I] Starting Grafana

2015/08/06 12:02:43 [I] Version: 2.1.0, Commit: v2.1.0, Build date: 2015-08-04 07:19:48 -0700 PDT

2015/08/06 12:02:43 [I] Configuration Info

Config files:

  [0]: /home/httpd/dev/grafana-2.1/conf/defaults.ini

Paths:

  home: /home/httpd/dev/grafana-2.1

  data: /home/httpd/dev/grafana-2.1/data

  logs: /home/httpd/dev/grafana-2.1/log

2015/08/06 12:02:43 [I] Database: sqlite3, ConnectionString: file:/home/httpd/dev/grafana-2.1/data/data/grafana.db?cache=shared&mode=rwc&_loc=Local

2015/08/06 12:02:43 [I] Migrator: Starting DB migration

2015/08/06 12:02:43 [I] Migrator: exec migration id: create migration_log table


2015/08/06 12:02:59 [I] Migrator: exec migration id: alter dashboard_snapshot to mediumtext v2

2015/08/06 12:02:59 [I] Created default admin user: admin

2015/08/06 12:02:59 [I] Login: Ldap enabled, reading config file: /home/httpd/dev/grafana-2.1/conf/ldap.toml

2015/08/06 12:02:59 [I] Listen: http://0.0.0.0:3000

2015/08/06 12:06:28 [I] Completed /logout 302 Found in 3.437049ms

2015/08/06 12:07:14 [login.go:101 LoginPost()] [E] Error while trying to authenticate user: Cannot remove last organization admin

2015/08/06 12:07:14 [I] Completed /login 500 Internal Server Error in 166.608113ms

I’m guessing it has something to do with ldap config.  I just want to use ldap to auth the user.  Once a user is authed I’d want to allow them to create/edit/destroy and dashboard they want.

# Specify names of the ldap attributes your ldap uses

[servers.attributes]

name = «givenName»

surname = «sn»

username = «cn»

member_of = «memberOf»

email = «mail»

# Map ldap groups to grafana org roles

[[servers.group_mappings]]

group_dn = «*»

org_role = «Admin»

org_id = 1

[[servers.ldap_group_to_org_role_mappings]]

group_dn = «*»

org_role = «Editor»

[[servers.group_mappings]]

# If you want to match all (or no ldap groups) then you can use wildcard

group_dn = «*»

org_role = «Viewer»


Matthew Kruse <mkruse@…>

When I had the ‘admin’ user create a group and manually add my ldap user as the admin for the group, the next time my ldap user logs in the admin record gets deleted from the org_user table.

1|1|1|Admin|2015-08-06 19:53:13|2015-08-06 19:53:13

2|1|2|Admin|2015-08-06 19:54:17|2015-08-06 19:54:17

3|2|1|Admin|2015-08-06 19:54:48|2015-08-06 19:54:48

When my ldap user created the group, I got this in the the org_user table

1|1|1|Admin|2015-08-06 19:59:22|2015-08-06 19:59:22

2|1|2|Admin|2015-08-06 19:59:31|2015-08-06 19:59:31

3|2|2|Admin|2015-08-06 19:59:36|2015-08-06 19:59:36


Hi Matthew, I ran into the same problem; seems grafana will sync org roles to the LDAP mappings, including removing roles that don’t match any mappings. Since all the mappings you have are for org_id=1, none match for the new organization. Try adding the following entry to the ldap config:

[[servers.group_mappings]]
group_dn = "*"
org_role = "Admin"
org_id = 2

Kevin


Matthew Kruse <mkruse@…>

Thanks that was helpful.  I’ve got things working well enough at this point.  

Is there a better way to handle new organization creates short of manual config file updates?  It would be nice to lock out users in the Editor or Viewer roles from creating new organizations.

Понравилась статья? Поделить с друзьями:
  • Error with lpdd createsurface
  • Error with ipdd set display mode gens
  • Error with dll loading 101 aion
  • Error with command gdb version cannot run program gdb launching failed
  • Error with camera could not start video source