pyldap AD authentication bind_s vs simple_bind_s - python

I am using pyldap to connect to AD server
pyldap is providing two functions bind_s() and simple_bind_s()
can any one explain me when to use bind_s() and simple_bind_s() and which one is best.

simple_bind_s() can do simple LDAP authentication or Kerberos authentication. However, bind_s() can only do LDAP authentication to form connection with Active Directory server.
I mostly prefer simple_bind_s() because we need both authentication support for applications but if you're sure you will never need to implement/use kerberos authentication in your application then feel free to pick bind_s().
Following is the implementations of respective bind definitions (Reference):
simple_bind_s():
def simple_bind_s(self,who='',cred='',serverctrls=None,clientctrls=None):
"""
simple_bind_s([who='' [,cred='']]) -> 4-tuple
"""
msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all=1,timeout=self.timeout)
return resp_type, resp_data, resp_msgid, resp_ctrls
bind_s():
def bind_s(self,who,cred,method=ldap.AUTH_SIMPLE):
"""
bind_s(who, cred, method) -> None
"""
msgid = self.bind(who,cred,method)
return self.result(msgid,all=1,timeout=self.timeout)

Related

Openstack python api: How create a connection using Application Credentials?

Currently I am using (of course with more elaborate variables):
conn = openstack.connect(
load_yaml_config=False,
load_envvars=False,
auth_url=AL,
project_name=PN,
username=UN,
password=PW,
region_name=RN,
user_domain_name=UDN,
project_domain_name=PDN,
app_name=42,
app_version=42
)
to connect to projects. But in the future I would like to offer using application credentials, too. While there is plenty of documentation on how to authenticate with said credentials, I can't find anything about authenticating a connection with it. How is it done?
So what I am looking for is a way to create a connection without username and password, but credentials instead.
On connection: https://docs.openstack.org/openstacksdk/latest/user/connection.html
On application credentials: https://docs.openstack.org/keystone/queens/user/application_credentials.html
On rest-api calls https://docs.openstack.org/api-ref/identity/v3/index.html#application-credentials
Existing authenticated session
This might be an option:
From existing authenticated Session
-----------------------------------
For applications that already have an authenticated Session, simply passing
it to the :class:`~openstack.connection.Connection` constructor is all that
is needed:
.. code-block:: python
from openstack import connection
conn = connection.Connection(
session=session,
region_name='example-region',
compute_api_version='2',
identity_interface='internal')
but I have to investigate further.
I couldn't find any documentation, but apparently it is possible to create a connection like this:
openstack.connect(
load_yaml_config=False,
load_envvars=False,
auth_url=AU,
region_name=RN,
application_credential_id=ACI,
application_credential_secret=ACS,
auth_type=AT
)
and that will return a connection object just like before. auth_type has to be "v3applicationcredential" when using application credentials.

What is "principal" argument of kerbros-sspi?

I was trying to connect to remote machine via WinRM in Python (pywinrm) using domain account, following the instruction in
How to connect to remote machine via WinRM in Python (pywinrm) using domain account?
using
session = winrm.Session(server, auth=('user#DOMAIN', 'doesNotMatterBecauseYouAreUsingAKerbTicket'), transport='kerberos')
but I got this:
NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
I googled "principal argument" and I got its meaning in mathematics,which is in complex_analysis (https://en.m.wikipedia.org/wiki/Argument_(complex_analysis)) and definitely not the right meaning. I'm not a native English speaker and I got stuck here.
The original code is here:
https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py
def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
        # Flags used by kerberos module.
        gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
        if self.delegate:
            gssflags |= kerberos.GSS_C_DELEG_FLAG
        try:
            kerb_stage = "authGSSClientInit()"
            # contexts still need to be stored by host, but hostname_override
            # allows use of an arbitrary hostname for the kerberos exchange
            # (eg, in cases of aliased hosts, internal vs external, CNAMEs
            # w/ name-based HTTP hosting)
            kerb_host = self.hostname_override if self.hostname_override is not None else host
            kerb_spn = "{0}#{1}".format(self.service, kerb_host)
            
            kwargs = {}
            # kerberos-sspi: Never pass principal. Raise if user tries to specify one.
            if not self._using_kerberos_sspi:
                kwargs['principal'] = self.principal
            elif self.principal:
                raise NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
Any help will be greatly appreciated.

simple Authentication and ACL using cornice

I have a RESTful API written in pyramid/cornice. It provides an API for an Ember client.
I have followed the cornice tutorial and have a valid_token validator which I use on many views as methods of resource classes.
def valid_token(request):
header = 'Authorization'
token = request.headers.get(header)
if token is None:
request.errors.add('headers', header, "Missing token")
request.errors.status = 401
return
session = DBSession.query(Session).get(token)
if not session:
request.errors.add('headers', header, "invalid token")
request.errors.status = 401
request.validated['session'] = session
Now I want to start selectively protecting resources. The Pyramid way seems to be to register authentication/authorization policies. The ACLAuthorizationPolicy seems to provide access to the nice ACL tooling in pyramid. However, it seems that pyramid needs both authentication and authorization policies to function. Since I'm authenticating with my validator this is confusing me.
Can I use ACL to control authorization whilst authenticating using my cornice valid_token validator? Do I need to register pyramid authentication or authorization policies?
I'm a bit confused, having little experience of using ACL in pyramid.
It is not an easy question :)
Shortly:
What you implemented in your validator is already taken care of by Pyramid with an AuthenticationPolicy
Start setting up a SessionAuthenticationPolicy with your custom callback (see code)
Once this authn setup, you will have those 401 responses, and your session value in the request.authenticated_userid attribute. You can also custom stuff in the request.registry object.
The only reason to keep your validator is if you want to return the invalid token messages in the 401 response. But for that, you can define a custom 401 pyramid view (using #forbidden_view_config)
Once you have that, you can setup a custom authorization for your views. You can find a very simple example in Cliquet first versions here : authz code and view perm
Good luck!
You may wanna do something like:
from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from your_module import valid_token
authn_policy = SessionAuthenticationPolicy(debug=True, callback=valid_token)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(authentication_policy=authn_policy,authorization_policy=authz_policy)
And ofcourse in the Configuration will receive other arguments like settigns, locale_negociator, ...........
Hope this will help

How can I access Google App Engine endpoints API from Python application with use OAuth?

How can I access Google App Engine endpoints API for Python (not web, android, ios)?
I read this tutorial but it not explains it enough to understand this.
As I found on serve side I can use such code to identify user:
#endpoints.method(message_types.VoidMessage, Greeting,
path='hellogreeting/authed', http_method='POST',
name='greetings.authed')
def greeting_authed(self, request):
current_user = endpoints.get_current_user()
email = (current_user.email() if current_user is not None
else 'Anonymous')
return Greeting(message='hello %s' % (email,))
Full code of API example
How can I connect from Python client to this API and call 'hellogreeting/authed' with authentication current_user != None.
Can you share some code how to do it?
app_id = 'xxx'
user = 'xxx'
password = 'xxx'
callAPI(app_id, user, password, 'hellogreeting/authed')
You need to configure your App Engine instance to be able to serve your API. I would recommend you create a separate module dedicated to your API, like explained in these docs: https://developers.google.com/appengine/docs/python/endpoints/api_server.
Once everything is correctly set up on the server side, you can call your API using something like: http://your-module.your-app.appspot.com/_ah/spi/hellogreeting/authed.
If you're using the development server, things are a little bit different for accessing modules, but once you know which port number the App Engine development server has assigned to your API module, you can reach it locally using: http://localost:<api_module_port_#>/_ah/spi/hellogreeting/authed.
Hope this helped.

Looking for advice to secure a private REST API written in python-flask

I am currently writing a rest API in python with the microframework Flask. It's a private API and it deals with user data. I plan to use this API to build a web and an Android app.
For now I use digest auth to secure private user data. For example if you want to post data on my service with the user bob you make a post request at myapi/story/create and provide bob's credentials with the digest pattern.
I am aware this is not a good solution because :
-Digest auth is not secure
-The client is not authenticated (How to secure requests not related with current user, for example create a new user ?)
I read a lot of stuff about oAuth but the 3-legged authentication seems overkill because I don't plan to open my API to third party.
The 2-legged oAuth won't fit because it only provides authentification for clients and not for users.
Another problem with oAuth is that I haven't found a comprehensive guide for implementing it in Python. I found the python-oauth2 library, but I don't understand the server example and I can't find additional documentation. Plus it seems that many aspects of oAuth are not covered in this example.
So my questions are :
Is there alternative scheme (not oAuth) for authenticate both client and user with a reasonable level of security ?
If oAuth is the best solution :
How to skip the authorization process (because users won't have to authorize third party clients)?
Is there detailled documentation for python-oauth2 or for any other Python library?
Any help or advice will be appreciated.
The simple answer is to expose your API via HTTPS only, and then use HTTP Basic authentication. I don't think there's really any reason to bother with Digest. Basic authentication is insecure, but is submitted with every request so you never need to worry about your authentication going stale or whatever. By tunneling it over HTTPS, you have a secure connection.
If you want to authenticate the client, you could use SSL client certificates. That said, in general it's pretty tough to really lock down the client against malicious users, so I would consider making the sign-up functions openly accessible and protect yourself from DOS etc via out-of-band account verification.
Have you already considered to use the Basic Authentication?
I haven't used yet the framework you mentioned, but I used the basic auth to protect some urls in an app based on web.py and worked fine.
Basically, you can use a token in base64 which is actually a standard http heeader.
Maybe this example can help you:
class Login:
def GET(self):
auth = web.ctx.env.get('HTTP_AUTHORIZATION')
authreq = False
if auth is None:
authreq = True
else:
auth = re.sub('^Basic ','',auth)
username,password = base64.decodestring(auth).split(':')
if (username,password) in settings.allowed:
raise web.seeother('/eai')
else:
authreq = True
if authreq:
web.header('WWW-Authenticate','Basic realm="Auth example"')
web.ctx.status = '401 Unauthorized'
return
If you are interested in basic authentication, here is a quick attribute which you can use to decorate your handlers http://www.varunpant.com/posts/basic-authentication-in-web-py-via-attribute. This example is primarily written in web.py context, but I guess it can be easily tweaked.
def check_auth(username, password):
return username == 'username' and password == 'password'
def requires_auth(f):
#wraps(f)
def decorated(*args, **kwargs):
auth = web.ctx.env['HTTP_AUTHORIZATION'] if 'HTTP_AUTHORIZATION' in web.ctx.env else None
if auth:
auth = re.sub('^Basic ', '', auth)
username, password = base64.decodestring(auth).split(':')
if not auth or not check_auth(username, password):
web.header('WWW-Authenticate', 'Basic realm="admin"')
web.ctx.status = '401 Unauthorized'
return
return f(*args, **kwargs)
return decorated

Categories