Python sspi.ClientAuth() Examples

The following are 8 code examples of sspi.ClientAuth(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sspi , or try the search function .
Example #1
Source File: session.py    From smbprotocol with MIT License 6 votes vote down vote up
def __init__(self, username, password, server):
        log.info("Setting up SSPI Security Context for Windows auth")
        self._call_counter = 0

        flags = sspicon.ISC_REQ_INTEGRITY | \
            sspicon.ISC_REQ_CONFIDENTIALITY | \
            sspicon.ISC_REQ_REPLAY_DETECT | \
            sspicon.ISC_REQ_SEQUENCE_DETECT | \
            sspicon.ISC_REQ_MUTUAL_AUTH

        domain, username = _split_username_and_domain(username)
        # We could use the MECH to derive the package name but we are just
        # better off using Negotiate and lettings Windows do all the heavy
        # lifting.
        self._context = sspi.ClientAuth(
            pkg_name='Negotiate',
            auth_info=(username, domain, password),
            targetspn="cifs/%s" % server,
            scflags=flags
        ) 
Example #2
Source File: socket_server.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def sspi_client():
    c = httplib.HTTPConnection("localhost", options.port)
    c.connect()
    # Do the auth dance.
    ca = sspi.ClientAuth(options.package, targetspn=options.target_spn)
    data = None
    while 1:
        err, out_buf = ca.authorize(data)
        _send_msg(c.sock, out_buf[0].Buffer)
        if err==0:
            break
        data = _get_msg(c.sock)
    print "Auth dance complete - sending a few encryted messages"
    # Assume out data is sensitive - encrypt the message.
    for data in "Hello from the client".split():
        blob, key = ca.encrypt(data)
        _send_msg(c.sock, blob)
        _send_msg(c.sock, key)
    c.sock.close()
    print "Client completed." 
Example #3
Source File: validate_password.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def validate(username, password, domain = ""):
    auth_info = username, domain, password
    ca = ClientAuth("NTLM", auth_info = auth_info)
    sa = ServerAuth("NTLM")
      
    data = err = None
    while err != 0:
        err, data = ca.authorize(data)
        err, data = sa.authorize(data)
    # If we get here without exception, we worked! 
Example #4
Source File: test_sspi.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _doAuth(self, pkg_name):
        sspiclient=sspi.ClientAuth(pkg_name,targetspn=win32api.GetUserName())
        sspiserver=sspi.ServerAuth(pkg_name)

        sec_buffer=None
        err = 1
        while err != 0:
            err, sec_buffer = sspiclient.authorize(sec_buffer)
            err, sec_buffer = sspiserver.authorize(sec_buffer)
        return sspiclient, sspiserver 
Example #5
Source File: spnego.py    From pypsrp with MIT License 5 votes vote down vote up
def init_context(self):
        flags = sspicon.ISC_REQ_INTEGRITY | \
                sspicon.ISC_REQ_CONFIDENTIALITY | \
                sspicon.ISC_REQ_REPLAY_DETECT | \
                sspicon.ISC_REQ_SEQUENCE_DETECT | \
                sspicon.ISC_REQ_MUTUAL_AUTH

        if self._delegate:
            flags |= sspicon.ISC_REQ_DELEGATE

        self._context = sspi.ClientAuth(
            pkg_name=self.auth_provider,
            auth_info=(self.username, self.domain, self.password),
            targetspn=self._target_spn,
            scflags=flags
        ) 
Example #6
Source File: px.py    From px with MIT License 4 votes vote down vote up
def __init__(self, proxy_type, proxy_server_address):
        pwd = ""
        if State.username:
            key = State.username
            if State.domain != "":
                key = State.domain + "\\" + State.username
            pwd = keyring.get_password("Px", key)

        if proxy_type == "NTLM":
            if not pwd:
                self.ctx = sspi.ClientAuth("NTLM",
                  os.environ.get("USERNAME"), scflags=0)
                self.get_response = self.get_response_sspi
            else:
                self.ctx = ntlm_auth.ntlm.NtlmContext(
                    State.username, pwd, State.domain, "", ntlm_compatibility=3)
                self.get_response = self.get_response_ntlm
        elif proxy_type == "BASIC":
            if not State.username:
                dprint("No username configured for Basic authentication")
            elif not pwd:
                dprint("No password configured for Basic authentication")
            else:
                # Colons are forbidden in usernames and passwords for basic auth
                # but since this can happen very easily, we make a special check
                # just for colons so people immediately understand that and don't
                # have to look up other resources.
                if ":" in State.username or ":" in pwd:
                    dprint("Credentials contain invalid colon character")
                else:
                    # Additionally check for invalid control characters as per
                    # RFC5234 Appendix B.1 (section CTL)
                    illegal_control_characters = "".join(
                        chr(i) for i in range(0x20)) + "\u007F"

                    if any(char in State.username or char in pwd
                            for char in illegal_control_characters):
                        dprint("Credentials contain invalid characters: %s" % ", ".join("0x" + "%x" % ord(char) for char in illegal_control_characters))
                    else:
                        # Remove newline appended by base64 function
                        self.ctx = b64encode(
                            "%s:%s" % (State.username, pwd))[:-1].decode()
            self.get_response = self.get_response_basic
        else:
            principal = None
            if pwd:
                if State.domain:
                    principal = (urlparse.quote(State.username) + "@" +
                        urlparse.quote(State.domain) + ":" + urlparse.quote(pwd))
                else:
                    principal = (urlparse.quote(State.username) + ":" +
                        urlparse.quote(pwd))

            _, self.ctx = winkerberos.authGSSClientInit("HTTP@" +
                proxy_server_address, principal=principal, gssflags=0,
                mech_oid=winkerberos.GSS_MECH_OID_SPNEGO)
            self.get_response = self.get_response_wkb 
Example #7
Source File: checksums.py    From peach with Mozilla Public License 2.0 4 votes vote down vote up
def fixup(self):
            try:
                fullName = self.context.getFullname()
                xml = self.getXml()
                firstFullName = str(xml.xpath(self.firstSend)[0].get("fullName"))
                firstFullName = firstFullName[firstFullName.index('.') + 1:]
                if fullName.find(firstFullName) > -1 and SspiAuthenticationFixup._firstObj != self.context:
                    #scflags = sspicon.ISC_REQ_INTEGRITY|sspicon.ISC_REQ_SEQUENCE_DETECT|\
                    #	sspicon.ISC_REQ_REPLAY_DETECT|sspicon.ISC_REQ_CONFIDENTIALITY
                    scflags = sspicon.ISC_REQ_INTEGRITY | sspicon.ISC_REQ_SEQUENCE_DETECT | \
                              sspicon.ISC_REQ_REPLAY_DETECT
                    SspiAuthenticationFixup._firstObj = self.context
                    SspiAuthenticationFixup._sspi = sspi.ClientAuth(
                        "Negotiate",
                        "", # client_name
                        (self.username, self.workgroup, self.password), # auth_info
                        None, # targetsn (target security context provider)
                        scflags, #scflags	# None,	# security context flags
                    )
                    (done, data) = SspiAuthenticationFixup._sspi.authorize(None)
                    data = data[0].Buffer
                    SspiAuthenticationFixup._data = data
                    return data
                if fullName.find(firstFullName) > -1:
                    return SspiAuthenticationFixup._data
                secondFullName = str(xml.xpath(self.secondSend)[0].get("fullName"))
                secondFullName = secondFullName[secondFullName.index('.') + 1:]
                if fullName.find(secondFullName) > -1 and SspiAuthenticationFixup._secondObj != self.context:
                    inputData = self.context.getInternalValue()
                    if len(inputData) < 5:
                        return None
                    (done, data) = SspiAuthenticationFixup._sspi.authorize(inputData)
                    data = data[0].Buffer
                    SspiAuthenticationFixup._secondObj = self.context
                    SspiAuthenticationFixup._data = data
                    return data
                if fullName.find(secondFullName) > -1:
                    return SspiAuthenticationFixup._data
            except:
                print("!!! EXCEPTION !!!")
                print(repr(sys.exc_info()))
                pass 
Example #8
Source File: ssh_gss.py    From imoocc with GNU General Public License v2.0 4 votes vote down vote up
def ssh_init_sec_context(self, target, desired_mech=None,
                             username=None, recv_token=None):
        """
        Initialize a SSPI context.

        :param str username: The name of the user who attempts to login
        :param str target: The FQDN of the target to connect to
        :param str desired_mech: The negotiated SSPI mechanism
                                 ("pseudo negotiated" mechanism, because we
                                 support just the krb5 mechanism :-))
        :param recv_token: The SSPI token received from the Server
        :raise SSHException: Is raised if the desired mechanism of the client
                             is not supported
        :return: A ``String`` if the SSPI has returned a token or ``None`` if
                 no token was returned
        :rtype: String or None
        """
        self._username = username
        self._gss_host = target
        error = 0
        targ_name = "host/" + self._gss_host
        if desired_mech is not None:
            mech, __ = decoder.decode(desired_mech)
            if mech.__str__() != self._krb5_mech:
                raise SSHException("Unsupported mechanism OID.")
        try:
            if recv_token is None:
                self._gss_ctxt = sspi.ClientAuth("Kerberos",
                                                 scflags=self._gss_flags,
                                                 targetspn=targ_name)
            error, token = self._gss_ctxt.authorize(recv_token)
            token = token[0].Buffer
        except:
            raise Exception("{0}, Target: {1}".format(sys.exc_info()[1],
                                                      self._gss_host))
        if error == 0:
            """
            if the status is GSS_COMPLETE (error = 0) the context is fully
            established an we can set _gss_ctxt_status to True.
            """
            self._gss_ctxt_status = True
            token = None
            """
            You won't get another token if the context is fully established,
            so i set token to None instead of ""
            """
        return token