2014-12-27 78 views
3

我在控制檯上玩python ldap,得到了我無法解釋的結果。希望有人能爲我澄清這一點。python ldap的全局選項

開放新的Python控制檯

import ldap 

certfile = '~/ad-server.test.loc.pem' 
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, certfile) 

who = 'CN=Administrator,CN=Users,dc=test,dc=loc' 
passwd = 'passwd' 
sslserver = 'ldaps://ad-server.test.loc:636' 

#let's say I would like to disable certificate verification for the next connection 
ldap.set_option(ldap.OPT_X_TLS_REQUIRECERT, ldap.OPT_X_TLS_ALLOW) 
conn = ldap.initialize(server) 
conn.simple_bind_s(who, passwd) 

(97, []) 

#connected successfully 

#Now I want to enable certificate verification and try to connect again (this time I should 
#fail because I use sef-signed certificate) 

#Unbind connection 

conn.unbind() 
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) 
conn = ldap.initialize(server) 

#Trying to connect 

conn.simple_bind_s(who, passwd) 

(97, []) 


# it is also connected succesfully. Why? 

這裏有一個問題, 我打開證書驗證,所以應該完成與錯誤連接嘗試,但它成功地做了連接(我使用自簽名的證書,這就是爲什麼嘗試連接應該失敗)?

另一個例子。做同樣的事情,但在不同的順序

開放新的Python控制檯

import ldap 

certfile = '~/ad-server.test.loc.pem' 
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, certfile) 
who = 'CN=Administrator,CN=Users,dc=test,dc=loc' 
passwd = 'passwd' 
sslserver = 'ldaps://ad-server.test.loc:636' 

#Trying to connect using selfsigned certificate 

ldap.set_option(ldap.OPT_X_TLS_REQUIRECERT, ldap.OPT_X_TLS_DEMAND) 
conn = ldap.initialize(server) 
conn.simple_bind_s(who, passwd) 
Traceback bla bla bla 
ldap.SERVER_DOWN: {'info': 'error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed', 'desc': "Can't contact LDAP server"} 

#Ok, let's disable verefication and try again 
conn.unbind() 
ldap.set_option(ldap.OPT_X_TLS_REQUIRECERT, ldap.OPT_X_TLS_ALLOW) 
conn = ldap.initialize(server) 
conn.simple_bind_s(who, passwd) 
Traceback bla bla bla 
ldap.SERVER_DOWN: {'info': 'error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed', 'desc': "Can't contact LDAP server"} 


# Even if I disabled verefication connection failed. Why? I expected a positive result. 

任何人能解釋一下嗎?

回答

4

我們剛碰到類似的問題。基本上,所有的TLS選項默認設置爲全局,並存儲在GNUTLS使用的上下文對象中。第一次創建連接時,該連接將成爲該進程中所有後續連接將使用的TLS上下文。

要改變這種行爲,最後TLS相關set_option叫你做應該是:

connection.set_option(ldap.OPT_X_TLS_NEWCTX, 0) 

這在python-ldap demos的一個實際完成的。

+1

感謝您的回覆。看起來它只適用於最新版本的openLDAP 2.4.x,我使用2.3.43 vesion :( – 2014-12-31 09:38:18

+1

我的同情心,現在我對4年前的版本感覺更好一些,至少它不會更老:) – 2015-01-05 23:19:02