Flask-LDAP3-Login Filter issue - User cannot login - flask

Using flask-ldap3-login to query AD for my web app logins. Works for everyone; but, for users who have "()" in their First name in AD. Here's the Debug log.
UN-SUCCESSFULL LOGIN
DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'mybinduser#mydomain.com'
DEBUG:flask_ldap3_login:Successfully bound to LDAP as 'mybinduser#mydomain.com' for search_bind method
DEBUG:flask_ldap3_login:Performing an LDAP Search using filter '(&(objectclass=person)(sAMAccountName=ebadu))', base 'DC=mydomain,DC=com', and scope 'SUBTREE'
DEBUG:flask_ldap3_login:Opening connection with bind user 'CN=Badu\, Ericka (EB),OU=HELPDESK,DC=mydomain,DC=com'
DEBUG:flask_ldap3_login:Directly binding a connection to a server with user:'CN=Badu\, ericka (EB),OU=HELPDESK,DC=mydomain,DC=com'
DEBUG:flask_ldap3_login:Authentication was successful for user 'ebadu'
DEBUG:flask_ldap3_login:Searching for groups for specific user with filter '(&(objectclass=group)(uniqueMember=CN=Badu\, Ericka (EB),OU=HELPDESK,DC=mydomain,DC=com))' , base 'DC=mydomain,DC=com' and scope 'LEVEL'
ERROR:flask_ldap3_login:malformed filter
DEBUG:flask_ldap3_login:Destroying connection at <0x7f8629604c50>
DEBUG:flask_ldap3_login:Destroying connection at <0x7f8628eabf98>
SUCCESFULL LOGIN
DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'mybinduser#mydomain.com'
DEBUG:flask_ldap3_login:Successfully bound to LDAP as 'mybinduser#mydomain.com' for search_bind method
DEBUG:flask_ldap3_login:Performing an LDAP Search using filter '(&(objectclass=person)(sAMAccountName=mpeters))', base 'DC=mydomain,DC=com', and scope 'SUBTREE'
DEBUG:flask_ldap3_login:Opening connection with bind user 'CN=Peters\, Mike,OU=HELPDESK,DC=mydomain,DC=com'
DEBUG:flask_ldap3_login:Directly binding a connection to a server with user:'CN=Peters\, Mike,OU=HELPDESK,DC=mydomain,DC=com'
DEBUG:flask_ldap3_login:Authentication was successful for user 'mpeters'
DEBUG:flask_ldap3_login:Searching for groups for specific user with filter '(&(objectclass=group)(uniqueMember=CN=Peters\, Mike,OU=HELPDESK,DC=mydomain,DC=com))' , base 'DC=mydomain,DC=com' and scope 'LEVEL'
DEBUG:flask_ldap3_login:Destroying connection at <0x7f8629683828>
DEBUG:flask_ldap3_login:Destroying connection at <0x7f8628e91048>
The AD logs says "An account was successfully logged on"; however, the user does not log in to the app. The user has no issues login in with the AD credentials anywhere else.
What might be the issue?
This is the flask-ldap3-login code:
LDAP_USER_RDN_ATTR = 'cn'
LDAP_USER_LOGIN_ATTR = 'sAMAccountName'
LDAP_BASE_DN = 'DC=mydomain,DC=com'
LDAP_REQUIRED_GROUP = 'ou=helpdesk,dc=mydomain,dc=com'
LDAP_USER_SEARCH_SCOPE = 'SUBTREE'

But "malformed filter" usually means that the LDAP query sent to AD isn't valid somehow. I asked about odd characters on the account, since if some special characters are not encoded properly, they can be misinterpreted as special characters used in LDAP queries.
It could be a bug in your code, or a bug in flask-ldap3-login. If you show your code, I might be able to give you some pointers.
Also, see if you can enable debug logging. It may tell you what the actual filter is that made it bomb. I'm not familiar with flask-ldap3-login, but, looking at the documentation, this might do it?:
app.config['DEBUG'] = True

SOLVED! Seems to be solved in the latest version of flask-ldap3-login. I did not upgrade but modified existing code:
Replaced this:
`search_filter = '(&{group_filter}({members_attr}={user_dn}))'.format('`
`group_filter=self.config.get('LDAP_GROUP_OBJECT_FILTER'),`
`members_attr=self.config.get('LDAP_GROUP_MEMBERS_ATTR'),`
`user_dn=dn`
with this:
`safe_dn = ldap3.utils.conv.escape_filter_chars(dn)`
`search_filter = '(&{group_filter}({members_attr}={user_dn}))'.format(`
`group_filter=self.config.get('LDAP_GROUP_OBJECT_FILTER'),`
`members_attr=self.config.get('LDAP_GROUP_MEMBERS_ATTR'),`
`user_dn=safe_dn`

Related

Odoo website, Creating a signup page for external users

How can I create a signup page in odoo website. The auth_signup module seems to do the job (according to their description). I don't know how to utilize it.
In the signup page there shouldn't be database selector
Where should I store the user data(including password); res.users or res.partner
you can turn off db listing w/ some params in in odoo.cfg conf
db_name = mydb
list_db = False
dbfilter = mydb
auth_signup takes care of the registration, you don't need to do anything. A res.user will be created as well as a partner related to it.
The pwd is stored in the user.
User Signup is a standard feature provided by Odoo, and it seems that you already found it.
The database selector shows because you have several PostgresSSQL databases.
The easiest way is to set a filter that limits it to the one you want:
start the server with the option --dbfilter=^MYDB$, where MYDBis the database name.
User data is stored both in res.userand res.partner: the user specific data, such as login and password, are stored in res.user. Other data, such as the Name is stored in a related res.partner record.

Using SitecoreUser.Profile with Forms Authentication

We use sitecore to manage our registered users (extranet domain) and when creating new virtual users we give it an email using the Profile.Email property and then call the Profile.Save() method.
Another property somewhere else reads the userProfile.Email, everything is fine at the beginning.
Plus we use Forms authentication with the remember me feature.
The problem is when we close the browser and reopen it Sitecore.Context.User contains info about the actual user who clicked remember me but the User.Profile always has the Email null.
I tried Reload() and initialize() they don't work. I also tried getting the user again via the username (User.FromName()) but the returned user object also doesn't have the Profile Email.
What is being done wrong?
There is one very important remark in Security API Cookbook. It is related to Sitecore 6 but as far as I know it should work with Sitecore 8 as there was no important changes in Security model. It worked for Sitecore 7.
Important You must log in a virtual user only after you assign Roles and Profile properties to them. The Roles and Profile properties that are assigned after logging in are lost upon subsequent request.
Sitecore.Security.Accounts.User user =
Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser(#"domain\user"
, true);
if (user != null)
{
string domainRole = #"domain\role";
if (Sitecore.Security.Accounts.Role.Exists(domainRole))
{
user.Roles.Add(Role.FromName(domainRole));
}
user.Profile.Email = "user#domain.com";
user.Profile[“Custom Property”] = “Custom Value”;
user.Profile.Save();
Sitecore.Security.Authentication.AuthenticationManager.LoginVirtualUser(user);
}

ADFS 3 - Username change and signout issue

We have a website integrated with ADFS 3 for authentication. Website allows users to change their usernames, which in turn changes their usernames in AD. If users changes their usernames we log them out using WSFederationAuthenticationModule.FederatedSignOut. However the page redirects to adfs url and throws an error. The event log shows that "either username or password is wrong".
MSIS7066: Authentication failed for the request. ---> System.Security.SecurityException: The user name or password is incorrect.
I wonder it is because of user name change. I tried with both lsalookupcachemaxsize set to 0 in registry and without the key. By the way does ADFS 3 even consider this registry key?
The code used is below -
FormsAuthentication.SignOut();
FederatedAuthentication.SessionAuthenticationModule.SignOut();
FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
Response.Expires = 0;
Session.Abandon();
var authenticationModule = FederatedAuthentication.WSFederationAuthenticationModule;
WSFederationAuthenticationModule.FederatedSignOut(new Uri(authenticationModule.Issuer), new Uri(authenticationModule.Realm));

Sending email not working on heroku

I have this function in forms.py. There is currently no email specifications in my settings.py.
def send_email(FROM_NAME,FROM,TO,SUB,MSG,EXISTING_EMAIL,EXISTING_PASSWORD):
FROMADDR = "%s <%s>" % (FROM_NAME, FROM)
LOGIN = EXISTING_EMAIL
PASSWORD = EXISTING_PASSWORD
TOADDRS = [TO]
SUBJECT = SUB
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += MSG+"\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I call it my views.py like so
send_email('my_name','from_me#gmail.com','to_som1#gmail.com','my subject','mymessage','my_existing_email#gmail.com','password_to_existing_email')
This works locally. I have tested it with yahoomail and gmail. But when I upload to heroku it gives the error "(535, '5.7.1 Please log in with your web browser and then try again. Learn more at\n5.7.1 support.google.com/mail/bin/answer.py?answer=78754 et6sm2577249qab.8')"
Can anyone help?
You want to use this:
FROMADDR = "%s <%s>" % (your_name, your_email)
You shouldn't be building emails with string interpolation, that's a good way to get your site used to send spam via header injections. See my answer here for details on how to construct emails securely.
Generally speaking, when formatting from addresses, you should use the format Display Name <email#example.com>. See RFC 5322 for details.
Have you read the page linked to in the error message?
If you're repeatedly prompted for your username and password, or if
you're getting an 'invalid credentials' or 'web login required' error,
make sure your password is correct. Keep in mind that password are
case-sensitive.
If you’re sure your password is correct, sign in to your account from
the web version of Gmail instead at http://mail.google.com
In most cases signing in from the web should resolve the issue
Here is what worked for me. After getting the error Please log in with your web browser and then try again. Learn more etc. when trying to send email from my web application, I logged in to the email via browser from my local computer.
After I logged in, there was a yellow notification bar on top which asking me if I want to allow external application access my mail. I confirmed this and Google asked me to log in to the account from the application within the next 10 mins. This will white-list the application.

Flash + pyAMF + Django session cookie security

First off, if there is a true, official way of having flash/flex's NetConnections usurp the session/cookie state of the surrounding web page, so that if the user has already logged in, they don't need to provide credentials again just to set up an AMF connection, please stop me now and post the official answer.
Barring that, I'm assuming there is not, as I have searched and it seems to not exist. I've concocted a means of doing this, but want some feedback as to whether it is secure.
Accessing a wrapper-page for a flash object will always go to secure https due to django middleware
When the page view is loaded in Django, it creates a "session alias" object with a unique key that points to the current session in play (in which someone ostensibly logged in)
That session alias model is saved, and that key is placed into a cookie whose key is another random string, call it randomcookie
That randomcookie key name is passed as a context variable and written into the html as a flashvar to the swf
The swf is also loaded only via https
The flash application uses ExternalInterface to call java to grab the value at that randomcookie location, and also deletes the cookie
It then creates a NetConnection to a secure server https location, passing that randomcookie as an argument (data, not in the url) to a login-using-cookie rpc
At the gateway side, pyamf looks up the session alias and gets the session it points to, and logs in the user based on that (and deletes the alias, so it can't be reused)
(And the gateway request could also set the session cookie and session.session_key to the known session ID, but I could let it make a whole new session key... I'm assuming that doing so should affect the response properly so that it contains the correct session key)
At this point, the returned cookie values on the flash side should stick to the NetConnection so that further calls are authenticated (if a connection is authenticated using username and password the normal way, this definitely works, so I think this is a safe bet, testing will soon prove or disprove this)
So, is this unsafe, or will this work properly? As far as I know, since the html page is guaranteed to be over ssl, the key and cookie data should be encrypted and not steal-able. Then, the info therein should be safe to use one-time as basically a temporary password, sent again over ssl because the gateway is also https. After that, it's using the normal pyAMF system over https and not doing anything out of the ordinary.
No responses on this so far, so the best I can do is confirm that it does in fact physically work. For details on how to set up Flex Builder to write html-wrappers that communicate with Django pages templates, see my other post. The above was accomplished using a combination of the aforementioned, plus:
Made a SessionAlias model:
class SessionAlias(models.Model):
alias = models.CharField( max_length=40, primary_key=True )
session = models.ForeignKey( Session )
created = models.DateTimeField( auto_now_add=True )
Flex points to a Django page that loads via a view containing:
s = SessionAlias()
s.alias = SessionStore().session_key // generates new 40-char random
s.session = Session.objects.get( session_key=request.session.session_key )
s.save();
randomcookie = SessionStore().session_key // generates new 40-char random
kwargs['extra_context']['randomcookie'] = randomcookie
response = direct_to_template( request, **kwargs )
response.set_cookie( randomcookie, value=alias )
In the flex html-wrapper, where randomcookie is the location to look for the alias:
<param name="flashVars" value="randomcookie={{randomcookie}}" />
In applicationComplete, where we get randomcookie and find the alias, and log on using that:
var randomcookie:String = this.parameters["randomcookie"];
// randomcookie is something like "abc123"
var js:String = "function get_cookie(){return document.cookie;}";
var cookies:String = ExternalInterface.call(js).toString();
// cookies looks like "abc123=def456; sessionid=ghi789; ..."
var alias:String = // strip out the "def456"
mynetconnection.call( "loginByAlias", alias, successFunc, failureFunc );
Which in turn access this pyamf gateway rpc:
from django.contrib.auth import SESSION_KEY, load_backend
from django.contrib.auth.models import User
from django.contrib import auth
from django.conf import settings
def loginByAlias( request, alias ):
a = SessionAlias.objects.get( alias=alias )
session_engine = __import__( settings.SESSION_ENGINE, {}, {}, [''] )
session_wrapper = session_engine.SessionStore( a.session.session_key )
user_id = session_wrapper.get( SESSION_KEY )
user = User.objects.get( id=user_id )
user.backend='django.contrib.auth.backends.ModelBackend'
auth.login( request, user )
a.delete()
return whateverToFlash
And at that point, on the flash/flex side, that particular mynetconnection retains the session cookie state that can make future calls such that, inside the gateway, request.user is the properly-authenticated user that logged onto the webpage in the first place.
Note again that the run/debug settings for flex must use https, as well as the gateway settings for NetConnection. And when releasing this, I have to make sure that authenticated users stay on https.
Any further info from people would be appreciated, especially if there's real feedback on the security aspects of this...
IE doesn't give access to cookies in local development but if you publish the SWF and put on a domain, it should pickup the session just like ever other browser. Use Firefox 3.6 to build your flex apps locally.
Tested in IE8, Firefox using a pyamf gateway on Flex 3 with NetConnection. The gateway function was decorated with #login_required