Skip to content

Commit

Permalink
Proof of concept for SASL GSSAPI changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Schlenker committed Feb 4, 2016
1 parent 42ce859 commit 56e9251
Show file tree
Hide file tree
Showing 6 changed files with 260 additions and 27 deletions.
58 changes: 44 additions & 14 deletions bin/ldaptor-search
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
#!/usr/bin/python

import sys
from ldaptor.protocols.ldap import ldapclient, ldif, ldapsyntax, ldapconnector
from ldaptor.protocols import pureber, pureldap
from ldaptor import usage, ldapfilter, config
from twisted.internet import protocol, reactor, defer
from ldaptor.protocols.ldap import ldapclient, ldapsyntax, ldapconnector
from ldaptor import usage, config
from twisted.internet import reactor

def printResults(o):
sys.stdout.write(str(o))

def search(client, baseDN, filter_text, attributes):
o=ldapsyntax.LDAPEntry(client=client, dn=baseDN)
d=o.search(filterText=filter_text,
attributes=attributes,
callback=printResults)

def do_anon_bind(client, bindDN):
o=ldapsyntax.LDAPEntryWithClient(client, bindDN)
d = o.bind(None)
d.addCallback(lambda x: client)
return d


def do_sasl_bind(client, bindDN):
from ldaptor import gssapi
o=ldapsyntax.LDAPEntryWithClient(client, bindDN)
service = 'ldap'
host = client.transport.addr[0]
ctx = gssapi.SASL_GSSAPIClientContext(service, host)
d = o.bind(None, sasl=True, sasl_ctx=ctx)
d.addCallback(lambda x: client)
return d


def do_search(client, baseDN, filter_text, attributes):
o=ldapsyntax.LDAPEntryWithClient(client, baseDN)
return o.search(filterText=filter_text, attributes=attributes, callback=printResults)


exitStatus=0

def error(fail):
print >>sys.stderr, 'fail:', fail.getErrorMessage()
print >>sys.stderr, fail.getTraceback()
global exitStatus
exitStatus=1

def main(cfg, filter_text, attributes):
def main(cfg, bindfunc, bindDN, filter_text, attributes):
try:
baseDN = cfg.getBaseDN()
except config.MissingBaseDNError, e:
Expand All @@ -32,16 +49,21 @@ def main(cfg, filter_text, attributes):

c = ldapconnector.LDAPClientCreator(reactor,
ldapclient.LDAPClient)
d = c.connectAnonymously(dn=baseDN,
overrides=cfg.getServiceLocationOverrides())
d.addCallback(search, baseDN, filter_text, attributes)
d = c.connect(dn=baseDN,
overrides=cfg.getServiceLocationOverrides())

if not bindDN:
bindDN = baseDN
d.addCallback(bindfunc, bindDN)
d.addCallback(do_search, baseDN, filter_text, attributes)
d.addErrback(error)
d.addBoth(lambda x: reactor.stop())

reactor.run()
sys.exit(exitStatus)

class MyOptions(usage.Options, usage.Options_service_location, usage.Options_base_optional):
class MyOptions(usage.Options, usage.Options_service_location,
usage.Options_base_optional, usage.Options_bind):
"""LDAPtor command line search utility"""

def parseArgs(self, filter, *attributes):
Expand All @@ -58,6 +80,14 @@ if __name__ == "__main__":

cfg = config.LDAPConfig(baseDN=opts['base'],
serviceLocationOverrides=opts['service-location'])

if opts['bind-sasl-mech'] == 'GSSAPI':
bindfunc = do_sasl_bind
else:
bindfunc = do_anon_bind

main(cfg,
bindfunc,
opts['binddn'],
opts['filter'],
opts['attributes'])
178 changes: 178 additions & 0 deletions ldaptor/gssapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# -*- python -*-
#
# GSSAPI SASL Code for LDAP Auth
#
# This implements the RFC 4752 SASL Mechanism GSSAPI for ldaptor
#
# (c) 2016 CONTACT SOFTWARE GmbH (www.contact-software.com)
#
# MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

import sys
import base64
import struct

if sys.platform == 'win32':
import kerberos_sspi as kerberos
else:
import kerberos

__all__ = [
'SASL_GSSAPIClientContext',
'SASL_GSSAPIServerContext',
]


# RFC 4752 Sect. 3
SASL_MECHANISM = 'GSSAPI'


class SASL_GSSAPIClientContext(object):

def __init__(self, service, host):
spn = "%s@%s" % (service, host)
self.client = None
self.response = ""
self.cres = kerberos.AUTH_GSS_CONTINUE
self.ctx = None

flags = (kerberos.GSS_C_CONF_FLAG
| kerberos.GSS_C_INTEG_FLAG
| kerberos.GSS_C_REPLAY_FLAG
| kerberos.GSS_C_SEQUENCE_FLAG)

errc, self.client = kerberos.authGSSClientInit(spn, gssflags=flags)

self._round = 0

def send(self, token_in):
if not self.ctx:
self.ctx = self._coro()
# Move to first waiting yield
self.ctx.send(None)
return self.ctx.send(token_in)

def __del__(self):
# TODO: Find a nicer way to trigger cleanup
self.ctx = None
client = self.client
self.client = None
if client:
kerberos.authGSSClientClean(client)

def start(self):
ctx = self._coro()
# Move to first waiting yield
ctx.send(None)
return ctx

def _handle_sasl_gssapi(self, token_in):
if sys.platform == "win32":
return self._handle_sasl_gssapi_win32(token_in)
else:
return self._handle_sasl_gssapi_unix(token_in)

def _handle_sasl_gssapi_win32(self, token_in):
# TODO: Simplify if kerberos_sspi gets fixed and authGSSClientUnwrap()
# works as it should.
# (https://github.com/may-day/kerberos-sspi/pull/3)
code = kerberos.authGSSClientUnwrap(
self.ctx, base64.encodestring(token_in))
if code == -1:
raise RuntimeError("SASL GSSAPI Auth failed")

data = kerberos.authGSSClientResponse(self.ctx)
data = self._process_security_options(data)
import sspicon
import win32security
ca = self.ctx['csa']
context = self.ctx
pkg_size_info = ca.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)
trailersize = pkg_size_info['SecurityTrailer']
blocksize = pkg_size_info['BlockSize']

encbuf = win32security.PySecBufferDescType()
encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN))
encbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA))
encbuf.append(win32security.PySecBufferType(blocksize, sspicon.SECBUFFER_PADDING))
encbuf[1].Buffer = data
ca.ctxt.EncryptMessage(0, encbuf, ca._get_next_seq_num())

context["response"] = encbuf[0].Buffer+encbuf[1].Buffer+encbuf[2].Buffer
self.response = kerberos.authGSSClientResponse(self.ctx)

def _handle_sasl_gssapi_unix(self, token_in):
# TODO: Probably needs a fix similar to kerberos_sspi
pass

def _process_security_options(self, data, user=None):
"""
Handle the security layer settings
"""
conf_and_size = data[:struct.calcsize("!L")] # network unsigned long
size = struct.unpack("!L", conf_and_size)[0] & 0x00ffffff
conf = struct.unpack("B", conf_and_size[0])[0] # B .. unsigned char

# FIXME: Debug prints...
print "N" if conf & kerberos.GSS_AUTH_P_NONE else "-"
print "I" if conf & kerberos.GSS_AUTH_P_INTEGRITY else "-"
print "P" if conf & kerberos.GSS_AUTH_P_PRIVACY else "-"
print "Maximum GSS token size is %d" % size

# Tell the truth, we do not handle any security layer
# (aka GSS_AUTH_P_NONE). RFC 4752 demands that the
# max client message size is zero in this case.
max_size_client_message = 0
security_layer = kerberos.GSS_AUTH_P_NONE
data = struct.pack("!L", security_layer << 24 +
(max_size_client_message & 0x00ffffff))
if user:
data = data + user.encode("utf-8")
return data

def _coro(self):
"""
Statemachine for the SASL progress
"""
token_in = yield
while self.cres == kerberos.AUTH_GSS_CONTINUE:
self.cres = kerberos.authGSSClientStep(
self.ctx,
base64.encodestring(token_in) if token_in is not None else None
)
if self.cres == -1:
break
self.response = kerberos.authGSSClientResponse(self.ctx)
self._round += 1
token_in = yield (SASL_MECHANISM, base64.decodestring(self.response))
if self.cres == kerberos.AUTH_GSS_COMPLETE:
token_in = yield (SASL_MECHANISM, base64.decodestring(self.response))
self._handle_sasl_gssapi(token_in)
yield (SASL_MECHANISM, base64.decodestring(self.response))
else:
raise RuntimeError("Unexpected extra token. Auth Failed")


class SASL_GSSAPIServerContext(object):
def __init__(self):
pass
2 changes: 1 addition & 1 deletion ldaptor/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def __len__(self):
def __nonzero__(self):
"""Always return True"""

def bind(self, password):
def bind(self, password, sasl=False, sasl_ctx=None):
"""
Try to authenticate with given secret.
Expand Down
21 changes: 18 additions & 3 deletions ldaptor/protocols/ldap/ldapsyntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,27 @@ def __len__(self):
def __nonzero__(self):
return True

def bind(self, password):
r=pureldap.LDAPBindRequest(dn=str(self.dn), auth=password)
def bind(self, password, sasl=False, sasl_ctx=None):
if sasl and sasl_ctx:
password = sasl_ctx.send(password)
r=pureldap.LDAPBindRequest(dn=str(self.dn), auth=password, sasl=sasl)
d = self.client.send(r)
d.addCallback(self._handle_bind_msg)
if sasl:
d.addCallback(self._handle_sasl_bind_msg, sasl_ctx)
else:
d.addCallback(self._handle_bind_msg)
return d

def _handle_sasl_bind_msg(self, msg, sasl_ctx):
assert isinstance(msg, pureldap.LDAPBindResponse)
assert msg.referral is None #TODO
if sasl_ctx and msg.resultCode == ldaperrors.LDAPSaslBindInProgress.resultCode:
token_in = msg.serverSaslCreds.value
return self.bind(token_in, sasl=True, sasl_ctx=sasl_ctx)
elif msg.resultCode!=ldaperrors.Success.resultCode:
raise ldaperrors.get(msg.resultCode, msg.errorMessage)
return self

def _handle_bind_msg(self, msg):
assert isinstance(msg, pureldap.LDAPBindResponse)
assert msg.referral is None #TODO
Expand Down
16 changes: 8 additions & 8 deletions ldaptor/protocols/pureldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,9 +587,9 @@ class LDAPMatchingRuleAssertion(BERSequence):
dnAttributes=None

def fromBER(klass, tag, content, berdecoder=None):
matchingRule = None
atype = None
matchValue = None
matchingRule = None
atype = None
matchValue = None
dnAttributes = None
l = berDecodeMultiple(content, LDAPBERDecoderContext_MatchingRuleAssertion(fallback=berdecoder, inherit=berdecoder))
assert 1 <= len(l) <= 4
Expand Down Expand Up @@ -1362,13 +1362,13 @@ def __init__(self, resultCode=None, matchedDN=None, errorMessage=None,
referral=None, serverSaslCreds=None,
responseName=None, response=None,
tag=None):
LDAPExtendedResponse.__init__(self,
resultCode=resultCode,
matchedDN=matchedDN,
LDAPExtendedResponse.__init__(self,
resultCode=resultCode,
matchedDN=matchedDN,
errorMessage=errorMessage,
referral=referral,
referral=referral,
serverSaslCreds=serverSaslCreds,
responseName=responseName,
responseName=responseName,
response=response,
tag=tag)

Expand Down
12 changes: 11 additions & 1 deletion ldaptor/usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ class Options_bind:
"use Distinguished Name to bind to the directory"),
('bind-auth-fd', None, None,
"read bind password from filedescriptor"),
)
('bind-sasl-mech', None, None,
"SASL Mechanism to use for binding to the directory"),
)

def postOptions_bind_auth_fd_numeric(self):
val=self.opts['bind-auth-fd']
Expand All @@ -106,6 +108,14 @@ def postOptions_bind_auth_fd_numeric(self):
raise usage.UsageError, "%s value must be numeric" % 'bind-auth-fd'
self.opts['bind-auth-fd'] = val

def postOptions_bind_sasl_mech(self):
val = self.opts['bind-sasl-mech']
MECHANISM = ('GSSAPI',)
if val is not None:
if val.upper() not in ('GSSAPI',):
raise usage.UsageError, "%s : unknown SASL mechanism" % 'bind-sasl-mech'


class Options_bind_mandatory(Options_bind):
def postOptions_bind_mandatory(self):
if not self.opts['binddn']:
Expand Down

0 comments on commit 56e9251

Please sign in to comment.