本文整理汇总了Python中puresasl.client.SASLClient.unwrap方法的典型用法代码示例。如果您正苦于以下问题:Python SASLClient.unwrap方法的具体用法?Python SASLClient.unwrap怎么用?Python SASLClient.unwrap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类puresasl.client.SASLClient
的用法示例。
在下文中一共展示了SASLClient.unwrap方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TSaslClientTransport
# 需要导入模块: from puresasl.client import SASLClient [as 别名]
# 或者: from puresasl.client.SASLClient import unwrap [as 别名]
class TSaslClientTransport(TTransportBase, CReadableTransport):
"""
SASL transport
"""
START = 1
OK = 2
BAD = 3
ERROR = 4
COMPLETE = 5
def __init__(self, transport, host, service, mechanism='GSSAPI',
**sasl_kwargs):
"""
transport: an underlying transport to use, typically just a TSocket
host: the name of the server, from a SASL perspective
service: the name of the server's service, from a SASL perspective
mechanism: the name of the preferred mechanism to use
All other kwargs will be passed to the puresasl.client.SASLClient
constructor.
"""
from puresasl.client import SASLClient
self.transport = transport
self.sasl = SASLClient(host, service, mechanism, **sasl_kwargs)
self.__wbuf = StringIO()
self.__rbuf = StringIO()
def open(self):
if not self.transport.isOpen():
self.transport.open()
self.send_sasl_msg(self.START, self.sasl.mechanism)
self.send_sasl_msg(self.OK, self.sasl.process())
while True:
status, challenge = self.recv_sasl_msg()
if status == self.OK:
self.send_sasl_msg(self.OK, self.sasl.process(challenge))
elif status == self.COMPLETE:
if not self.sasl.complete:
raise TTransportException("The server erroneously indicated "
"that SASL negotiation was complete")
else:
break
else:
raise TTransportException("Bad SASL negotiation status: %d (%s)"
% (status, challenge))
def send_sasl_msg(self, status, body):
header = pack(">BI", status, len(body))
self.transport.write(header + body)
self.transport.flush()
def recv_sasl_msg(self):
header = self.transport.readAll(5)
status, length = unpack(">BI", header)
if length > 0:
payload = self.transport.readAll(length)
else:
payload = ""
return status, payload
def write(self, data):
self.__wbuf.write(data)
def flush(self):
data = self.__wbuf.getvalue()
encoded = self.sasl.wrap(data)
self.transport.write(''.join((pack("!i", len(encoded)), encoded)))
self.transport.flush()
self.__wbuf = StringIO()
def read(self, sz):
ret = self.__rbuf.read(sz)
if len(ret) != 0:
return ret
self._read_frame()
return self.__rbuf.read(sz)
def _read_frame(self):
header = self.transport.readAll(4)
length, = unpack('!i', header)
encoded = self.transport.readAll(length)
self.__rbuf = StringIO(self.sasl.unwrap(encoded))
def close(self):
self.sasl.dispose()
self.transport.close()
# based on TFramedTransport
@property
def cstringio_buf(self):
return self.__rbuf
def cstringio_refill(self, prefix, reqlen):
#.........这里部分代码省略.........
示例2: TSaslClientTransport
# 需要导入模块: from puresasl.client import SASLClient [as 别名]
# 或者: from puresasl.client.SASLClient import unwrap [as 别名]
class TSaslClientTransport(TTransportBase, CReadableTransport):
START = 1
OK = 2
BAD = 3
ERROR = 4
COMPLETE = 5
def __init__(self, transport, host, service,
mechanism='GSSAPI', **sasl_kwargs):
from puresasl.client import SASLClient
self.transport = transport
self.sasl = SASLClient(host, service, mechanism, **sasl_kwargs)
self.__wbuf = StringIO()
self.__rbuf = StringIO()
def open(self):
if not self.transport.isOpen():
self.transport.open()
self.send_sasl_msg(self.START, self.sasl.mechanism)
self.send_sasl_msg(self.OK, self.sasl.process())
while True:
status, challenge = self.recv_sasl_msg()
if status == self.OK:
self.send_sasl_msg(self.OK, self.sasl.process(challenge))
elif status == self.COMPLETE:
if not self.sasl.complete:
raise TTransportException("The server erroneously indicated "
"that SASL negotiation was complete")
else:
break
else:
raise TTransportException("Bad SASL negotiation status: %d (%s)"
% (status, challenge))
def send_sasl_msg(self, status, body):
header = struct.pack(">BI", status, len(body))
self.transport.write(header + body)
self.transport.flush()
def recv_sasl_msg(self):
header = self.transport.readAll(5)
status, length = struct.unpack(">BI", header)
if length > 0:
payload = self.transport.readAll(length)
else:
payload = ""
return status, payload
def write(self, data):
self.__wbuf.write(data)
def flush(self):
data = self.__wbuf.getvalue()
encoded = self.sasl.wrap(data)
# Note stolen from TFramedTransport:
# N.B.: Doing this string concatenation is WAY cheaper than making
# two separate calls to the underlying socket object. Socket writes in
# Python turn out to be REALLY expensive, but it seems to do a pretty
# good job of managing string buffer operations without excessive copies
self.transport.write(''.join((struct.pack("!i", len(encoded)), encoded)))
self.transport.flush()
self.__wbuf = StringIO()
def read(self, sz):
ret = self.__rbuf.read(sz)
if len(ret) != 0:
return ret
self._read_frame()
return self.__rbuf.read(sz)
def _read_frame(self):
header = self.transport.readAll(4)
length, = struct.unpack('!i', header)
encoded = self.transport.readAll(length)
self.__rbuf = StringIO(self.sasl.unwrap(encoded))
def close(self):
self.sasl.dispose()
self.transport.close()
# Implement the CReadableTransport interface.
# Stolen shamelessly from TFramedTransport
@property
def cstringio_buf(self):
return self.__rbuf
def cstringio_refill(self, prefix, reqlen):
# self.__rbuf will already be empty here because fastbinary doesn't
# ask for a refill until the previous buffer is empty. Therefore,
# we can start reading new frames immediately.
while len(prefix) < reqlen:
self._read_frame()
prefix += self.__rbuf.getvalue()
#.........这里部分代码省略.........
示例3: TSaslClientTransport
# 需要导入模块: from puresasl.client import SASLClient [as 别名]
# 或者: from puresasl.client.SASLClient import unwrap [as 别名]
class TSaslClientTransport(TTransportBase, CReadableTransport):
"""
A SASL transport based on the pure-sasl library:
https://github.com/thobbs/pure-sasl
"""
START = 1
OK = 2
BAD = 3
ERROR = 4
COMPLETE = 5
def __init__(self, transport, host, service, mechanism="GSSAPI", **sasl_kwargs):
"""
transport: an underlying transport to use, typically just a TSocket
host: the name of the server, from a SASL perspective
service: the name of the server's service, from a SASL perspective
mechanism: the name of the preferred mechanism to use
All other kwargs will be passed to the puresasl.client.SASLClient
constructor.
"""
self.transport = transport
self.sasl = SASLClient(host, service, mechanism, **sasl_kwargs)
self.__wbuf = StringIO()
self.__rbuf = StringIO()
# extremely awful hack, but you've got to do what you've got to do.
# essentially "wrap" and "unwrap" are defined for the base Mechanism class and raise a NotImplementedError by
# default, and PlainMechanism doesn't implement its own versions (lol).
# self.sasl._chosen_mech.wrap = lambda x: x
# self.sasl._chosen_mech.unwrap = lambda x: x
def open(self):
if not self.transport.isOpen():
self.transport.open()
self.send_sasl_msg(self.START, self.sasl.mechanism)
self.send_sasl_msg(self.OK, self.sasl.process() or "")
while True:
status, challenge = self.recv_sasl_msg()
if status == self.OK:
self.send_sasl_msg(self.OK, self.sasl.process(challenge) or "")
elif status == self.COMPLETE:
# self.sasl.complete is not set for PLAIN authentication (trollface.jpg) so we have to skip this check
# break
if not self.sasl.complete:
raise TTransportException("The server erroneously indicated " "that SASL negotiation was complete")
else:
break
else:
raise TTransportException("Bad SASL negotiation status: %d (%s)" % (status, challenge))
def send_sasl_msg(self, status, body):
if body is None:
body = ""
header = pack(">BI", status, len(body))
body = body if isinstance(body, bytes) else body.encode("utf-8")
self.transport.write(header + body)
self.transport.flush()
def recv_sasl_msg(self):
header = self.transport.readAll(5)
status, length = unpack(">BI", header)
if length > 0:
payload = self.transport.readAll(length)
else:
payload = ""
return status, payload
def write(self, data):
self.__wbuf.write(data)
def flush(self):
data = self.__wbuf.getvalue()
encoded = self.sasl.wrap(data)
self.transport.write("".join((pack("!i", len(encoded)), encoded)))
self.transport.flush()
self.__wbuf = StringIO()
def read(self, sz):
ret = self.__rbuf.read(sz)
if len(ret) != 0:
return ret
self._read_frame()
return self.__rbuf.read(sz)
def _read_frame(self):
header = self.transport.readAll(4)
length, = unpack("!i", header)
encoded = self.transport.readAll(length)
self.__rbuf = StringIO(self.sasl.unwrap(encoded))
def close(self):
self.sasl.dispose()
self.transport.close()
#.........这里部分代码省略.........
示例4: ThriftSASLClientProtocol
# 需要导入模块: from puresasl.client import SASLClient [as 别名]
# 或者: from puresasl.client.SASLClient import unwrap [as 别名]
class ThriftSASLClientProtocol(ThriftClientProtocol):
START = 1
OK = 2
BAD = 3
ERROR = 4
COMPLETE = 5
MAX_LENGTH = 2 ** 31 - 1
def __init__(self, client_class, iprot_factory, oprot_factory=None,
host=None, service=None, mechanism='GSSAPI', **sasl_kwargs):
ThriftClientProtocol.__init__(self, client_class, iprot_factory, oprot_factory)
self._sasl_negotiation_deferred = None
self._sasl_negotiation_status = None
self.client = None
if host is not None:
self.createSASLClient(host, service, mechanism, **sasl_kwargs)
def createSASLClient(self, host, service, mechanism, **kwargs):
self.sasl = SASLClient(host, service, mechanism, **kwargs)
def dispatch(self, msg):
encoded = self.sasl.wrap(msg)
len_and_encoded = ''.join((struct.pack('!i', len(encoded)), encoded))
ThriftClientProtocol.dispatch(self, len_and_encoded)
@defer.inlineCallbacks
def connectionMade(self):
self._sendSASLMessage(self.START, self.sasl.mechanism)
initial_message = yield deferToThread(self.sasl.process)
self._sendSASLMessage(self.OK, initial_message)
while True:
status, challenge = yield self._receiveSASLMessage()
if status == self.OK:
response = yield deferToThread(self.sasl.process, challenge)
self._sendSASLMessage(self.OK, response)
elif status == self.COMPLETE:
if not self.sasl.complete:
msg = "The server erroneously indicated that SASL " \
"negotiation was complete"
raise TTransportException(msg, message=msg)
else:
break
else:
msg = "Bad SASL negotiation status: %d (%s)" % (status, challenge)
raise TTransportException(msg, message=msg)
self._sasl_negotiation_deferred = None
ThriftClientProtocol.connectionMade(self)
def _sendSASLMessage(self, status, body):
if body is None:
body = ""
header = struct.pack(">BI", status, len(body))
self.transport.write(header + body)
def _receiveSASLMessage(self):
self._sasl_negotiation_deferred = defer.Deferred()
self._sasl_negotiation_status = None
return self._sasl_negotiation_deferred
def connectionLost(self, reason=connectionDone):
if self.client:
ThriftClientProtocol.connectionLost(self, reason)
def dataReceived(self, data):
if self._sasl_negotiation_deferred:
# we got a sasl challenge in the format (status, length, challenge)
# save the status, let IntNStringReceiver piece the challenge data together
self._sasl_negotiation_status, = struct.unpack("B", data[0])
ThriftClientProtocol.dataReceived(self, data[1:])
else:
# normal frame, let IntNStringReceiver piece it together
ThriftClientProtocol.dataReceived(self, data)
def stringReceived(self, frame):
if self._sasl_negotiation_deferred:
# the frame is just a SASL challenge
response = (self._sasl_negotiation_status, frame)
self._sasl_negotiation_deferred.callback(response)
else:
# there's a second 4 byte length prefix inside the frame
decoded_frame = self.sasl.unwrap(frame[4:])
ThriftClientProtocol.stringReceived(self, decoded_frame)
示例5: LDAPSocket
# 需要导入模块: from puresasl.client import SASLClient [as 别名]
# 或者: from puresasl.client.SASLClient import unwrap [as 别名]
#.........这里部分代码省略.........
self._next_message_id += 1
lm = pack(mid, op, obj, controls)
raw = ber_encode(lm)
if self._has_sasl_client():
raw = self._sasl_client.wrap(raw)
return mid, raw
def send_message(self, op, obj, controls=None):
"""Create and send an LDAPMessage given an operation name and a corresponding object.
Operation names must be defined as component names in laurelin.ldap.rfc4511.ProtocolOp and
the object must be of the corresponding type.
:param str op: The protocol operation name
:param object obj: The associated protocol object (see :class:`.rfc4511.ProtocolOp` for mapping.
:param controls: Any request controls for the message
:type controls: rfc4511.Controls or None
:return: The message ID for this message
:rtype: int
"""
mid, raw = self._prep_message(op, obj, controls)
self._sock.sendall(raw)
return mid
def recv_one(self, want_message_id):
"""Get the next message with ``want_message_id`` being sent by the server
:param int want_message_id: The desired message ID.
:return: The LDAP message
:rtype: rfc4511.LDAPMessage
"""
return next(self.recv_messages(want_message_id))
def recv_messages(self, want_message_id):
"""Iterate all messages with ``want_message_id`` being sent by the server.
:param int want_message_id: The desired message ID.
:return: An iterator over :class:`.rfc4511.LDAPMessage`.
"""
flush_queue = True
raw = b''
while True:
if flush_queue:
if want_message_id in self._message_queues:
q = self._message_queues[want_message_id]
while True:
if len(q) == 0:
break
obj = q.popleft()
if len(q) == 0:
del self._message_queues[want_message_id]
yield obj
else:
flush_queue = True
if want_message_id in self.abandoned_mids:
return
try:
newraw = self._sock.recv(LDAPSocket.RECV_BUFFER)
if self._has_sasl_client():
newraw = self._sasl_client.unwrap(newraw)
raw += newraw
while len(raw) > 0:
response, raw = ber_decode(raw, asn1Spec=LDAPMessage())
have_message_id = response.getComponentByName('messageID')
if want_message_id == have_message_id:
yield response
elif have_message_id == 0:
msg = 'Received unsolicited message (default message - should never be seen)'
try:
mid, xr, ctrls = unpack('extendedResp', response)
res_code = xr.getComponentByName('resultCode')
xr_oid = six.text_type(xr.getComponentByName('responseName'))
if xr_oid == LDAPSocket.OID_DISCONNECTION_NOTICE:
mtype = 'Notice of Disconnection'
else:
mtype = 'Unhandled ({0})'.format(xr_oid)
diag = xr.getComponentByName('diagnosticMessage')
msg = 'Got unsolicited message: {0}: {1}: {2}'.format(mtype, res_code, diag)
if res_code == ResultCode('protocolError'):
msg += (' (This may indicate an incompatability between laurelin-ldap and your server '
'distribution)')
elif res_code == ResultCode('strongerAuthRequired'):
# this is a direct quote from RFC 4511 sec 4.4.1
msg += (' (The server has detected that an established security association between the'
' client and server has unexpectedly failed or been compromised)')
except UnexpectedResponseType:
msg = 'Unhandled unsolicited message from server'
finally:
raise LDAPUnsolicitedMessage(response, msg)
else:
if have_message_id not in self._message_queues:
self._message_queues[have_message_id] = deque()
self._message_queues[have_message_id].append(response)
except SubstrateUnderrunError:
flush_queue = False
continue
def close(self):
"""Close the low-level socket connection."""
return self._sock.close()