Exemplo n.º 1
0
        def authenticate(username, password, elist=_elist):
            """ elist will be used to store an immutable dict (from the
			function's point of view, it won't be reset each time the function is
			called).
			"""
            global log

            # service:  PAM service to authenticate against, defaults to 'login'
            service = 'login'
            # login service seems to return faster,
            if username == 'root':
                service = 'passwd'

            log.debug("authenticate, authenticating: %s " % username)

            if not str(password).strip():  # password IS blank
                log.debug("password is blank!")
                if username in elist:
                    return False
                else:
                    elist.append(username)

                    if pam.authenticate(username, password):
                        return True
                    else:
                        return False  # didn't have this, and it authenticated a second time
                        # below, causing the first instance of a blank password to take
                        # twice as long to authenticate, duh!
            else:
                if pam.authenticate(username, password):
                    return True
                else:
                    return False
Exemplo n.º 2
0
def handle_client(sock):
    data = json.loads(sock.recv(4096))
    if data["request"] == "status":
        f = open("/etc/hostname")
        if os.path.exists("/var/run/genesis.pid"):
            status = "active"
        else:
            status = "inactive"
        sock.sendall(json.dumps({"response": "ok", "name": f.readline().strip("\n"), "status": status}))
        f.close()
    elif data["request"] == "reload":
        if pam.authenticate(data["user"], data["pass"], service="account"):
            sock.sendall(json.dumps({"response": "ok"}))
            reload()
        else:
            sock.sendall(json.dumps({"response": "fail"}))
    elif data["request"] == "shutdown":
        if pam.authenticate(data["user"], data["pass"], service="account"):
            sock.sendall(json.dumps({"response": "ok"}))
            shutdown()
        else:
            sock.sendall(json.dumps({"response": "fail"}))
    elif data["request"] == "reboot":
        if pam.authenticate(data["user"], data["pass"], service="account"):
            sock.sendall(json.dumps({"response": "ok"}))
            reboot()
        else:
            sock.sendall(json.dumps({"response": "fail"}))
    elif data["request"] == "ping":
        sock.sendall(json.dumps({"response": "ok"}))
Exemplo n.º 3
0
def pam_auth(username, password):
    ''' Accepts username and password and tried to use PAM for authentication.
    Works only with root privileges
  '''
    return pam.authenticate(username, password, service="system-auth")
    try:
        return pam.authenticate(username, password, service="system-auth")
    except:
        return False
def handle_auth(pam_user, pam_rhost):

    # Read parameters tunneled through password field

    authtok = sys.stdin.readline().rstrip()[:-1]

    auth_params = None
    try:
        auth_params = json.loads(authtok)
        session_id = auth_params['SessionId']
        password = auth_params['SshPassword']
    except (ValueError, KeyError) as e:

        # Backwards compatibility case
        # Client sends a session ID prepended to the SSH password.
        # Extract the sesssion ID, and then perform standard PAM
        # authentication with the username and remaining password.
        # Older backwards compatibility case: if the password length is
        # not correct, skip the session ID logic.

        # Two hex characters per byte
        expected_authtok_length = (2 * (psi_config.SESSION_ID_BYTE_LENGTH +
                                        psi_config.SSH_PASSWORD_BYTE_LENGTH))

        if len(authtok) == expected_authtok_length:
            session_id = authtok[0:psi_config.SESSION_ID_BYTE_LENGTH * 2]
            password = authtok[psi_config.SESSION_ID_BYTE_LENGTH * 2:]
            if 0 != len(
                    filter(lambda x: x not in psi_config.SESSION_ID_CHARACTERS,
                           session_id)):
                return False
        else:

            # Older backwards compatibility case
            session_id = None
            password = authtok

    # Authenticate user

    try:
        pam.authenticate(pam_user, password)
    except pam.PamException as e:
        return False

    # Call 'auth' plugins

    for plugin in plugins:
        if hasattr(plugin, 'auth') and not plugin.auth(auth_params):
            return False

    # Store session_id/region mapping for stats

    if session_id:
        set_session_region(pam_rhost, session_id)

    return True
Exemplo n.º 5
0
def handle_auth(pam_user, pam_rhost):

    # Read parameters tunneled through password field

    authtok = sys.stdin.readline().rstrip()[:-1]

    auth_params = None
    try:
        auth_params = json.loads(authtok)
        session_id = auth_params['SessionId']
        password = auth_params['SshPassword']
    except (ValueError, KeyError) as e:

        # Backwards compatibility case
        # Client sends a session ID prepended to the SSH password.
        # Extract the sesssion ID, and then perform standard PAM
        # authentication with the username and remaining password.
        # Older backwards compatibility case: if the password length is
        # not correct, skip the session ID logic.

        # Two hex characters per byte
        expected_authtok_length = (
            2*(psi_config.SESSION_ID_BYTE_LENGTH +
               psi_config.SSH_PASSWORD_BYTE_LENGTH))
            
        if len(authtok) == expected_authtok_length:
            session_id = authtok[0:psi_config.SESSION_ID_BYTE_LENGTH*2]
            password = authtok[psi_config.SESSION_ID_BYTE_LENGTH*2:]
            if 0 != len(filter(lambda x : x not in psi_config.SESSION_ID_CHARACTERS, session_id)):
                return False
        else:

            # Older backwards compatibility case
            session_id = None
            password = authtok

    # Authenticate user

    try:
        pam.authenticate(pam_user, password)
    except pam.PamException as e:
        return False

    # Call 'auth' plugins

    for plugin in plugins:
        if hasattr(plugin, 'auth') and not plugin.auth(auth_params):
            return False

    # Store session_id/region mapping for stats

    if session_id:
        set_session_region(pam_rhost, session_id)

    return True
Exemplo n.º 6
0
    def check_auth(self, username, password):
        if pam.authenticate(username, password,
                            desktop.conf.AUTH.PAM_SERVICE.get()):
            is_super = False
            if User.objects.count() == 0:
                is_super = True

            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = find_or_create_user(username, None)
                if user is not None and user.is_active:
                    profile = get_profile(user)
                    profile.creation_method = UserProfile.CreationMethod.EXTERNAL
                    profile.save()
                    user.is_superuser = is_super

                    default_group = get_default_user_group()
                    if default_group is not None:
                        user.groups.add(default_group)

                    user.save()

            user = rewrite_user(user)
            return user

        return None
Exemplo n.º 7
0
    def authenticate(self, username=None, password=None):
        if pam.authenticate(username, password, settings.PAM_SERVICE):
            try:
                user = User.objects.get(username=username)
                user.set_password(password)
                user.save()
            except User.DoesNotExist:
                user = User(username=username, password=password)
                user.save()

                if settings.USE_LDAP:
                    import ldap

                    l = ldap.initialize(settings.LDAP_HOST)
                    l.set_option(ldap.OPT_REFERRALS, 0)
                    l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
                    l.simple_bind_s(settings.LDAP_BIND_DN, settings.LDAP_BIND_PASS)
                    r = l.search(settings.LDAP_SEARCH_PATH, ldap.SCOPE_ONELEVEL, "(uid=%s)" % username,
                                 [settings.LDAP_FIRST_NAME, settings.LDAP_LAST_NAME, settings.LDAP_EMAIL,
                                  settings.LDAP_DATE_JOINED])
                    r = l.result(r)
                    user.first_name = r[1][0][1][settings.LDAP_FIRST_NAME][0]
                    user.last_name = r[1][0][1][settings.LDAP_LAST_NAME][0]
                    user.email = r[1][0][1][settings.LDAP_EMAIL][0]
                    date_joined = r[1][0][1][settings.LDAP_DATE_JOINED][0]
                    user.date_joined = datetime.strptime(date_joined[:-1], '%Y%m%d%H%M%S')
                    user.save()

            return user
        return None
Exemplo n.º 8
0
  def authenticate(self, request=None, username=None, password=None):
    username = force_username_case(username)

    if AUTH.PAM_USE_PWD_MODULE.get():
      LOG.debug('Setting username to %s using PAM pwd module for user %s' % (getpwnam(username).pw_name, username))
      username = getpwnam(username).pw_name

    if pam.authenticate(username, password, AUTH.PAM_SERVICE.get()):
      is_super = False
      if User.objects.exclude(id=install_sample_user().id).count() == 0:
        is_super = True

      try:
        if AUTH.IGNORE_USERNAME_CASE.get():
          user = User.objects.get(username__iexact=username)
        else:
          user = User.objects.get(username=username)
      except User.DoesNotExist:
        user = find_or_create_user(username, None)
        if user is not None and user.is_active:
          profile = get_profile(user)
          profile.creation_method = UserProfile.CreationMethod.EXTERNAL.name
          profile.save()
          user.is_superuser = is_super

          ensure_has_a_group(user)

          user.save()

      user = rewrite_user(user)
      return user

    return None
Exemplo n.º 9
0
 def handle_request(self, parameters):
     # fill in any missing userdn, etc.
     self.validate(parameters)
     is_root = (self.calleruid == 0) and parameters['asroot']
     mods = []
     # check if the the user passed the rootpwmoddn
     if parameters['asroot']:
         binddn = cfg.rootpwmoddn
         # check if rootpwmodpw should be used
         if not parameters['password'] and is_root and cfg.rootpwmodpw:
             password = cfg.rootpwmodpw
         else:
             password = parameters['password']
     else:
         binddn = parameters['userdn']
         password = parameters['password']
     # write response header
     self.fp.write_int32(constants.NSLCD_RESULT_BEGIN)
     # check home directory modification
     homedir = parameters['mods'].get(constants.NSLCD_USERMOD_HOMEDIR)
     if homedir:
         if is_root:
             mods.append((ldap.MOD_REPLACE, passwd.attmap['homeDirectory'], [homedir]))
         elif not os.path.isabs(homedir):
             self.write_result(constants.NSLCD_USERMOD_HOMEDIR,
                               'should be an absolute path')
         elif not os.path.isdir(homedir):
             self.write_result(constants.NSLCD_USERMOD_HOMEDIR,
                               'not a directory')
         else:
             mods.append((ldap.MOD_REPLACE, passwd.attmap['homeDirectory'], [homedir]))
     # check login shell modification
     shell = parameters['mods'].get(constants.NSLCD_USERMOD_SHELL)
     if shell:
         if is_root:
             mods.append((ldap.MOD_REPLACE, passwd.attmap['loginShell'], [shell]))
         elif shell not in list_shells():
             self.write_result(constants.NSLCD_USERMOD_SHELL,
                               'unlisted shell')
         elif not os.path.isfile(shell) or not os.access(shell, os.X_OK):
             self.write_result(constants.NSLCD_USERMOD_SHELL,
                               'not an executable')
         else:
             mods.append((ldap.MOD_REPLACE, passwd.attmap['loginShell'], [shell]))
     # get a connection and perform the modification
     if mods:
         try:
             conn, authz, msg = pam.authenticate(binddn, password)
             conn.modify_s(parameters['userdn'], mods)
             logging.info('changed information for %s', parameters['userdn'])
         except (ldap.INVALID_CREDENTIALS, ldap.INSUFFICIENT_ACCESS) as e:
             try:
                 msg = e[0]['desc']
             except Exception:
                 msg = str(e)
             logging.debug('modification failed: %s', msg)
             self.write_result(constants.NSLCD_USERMOD_RESULT, msg)
     # write closing statement
     self.fp.write_int32(constants.NSLCD_USERMOD_END)
     self.fp.write_int32(constants.NSLCD_RESULT_END)
Exemplo n.º 10
0
    def authenticate(self, request=None, username=None, password=None):
        username = force_username_case(username)

        if pam.authenticate(username, password, AUTH.PAM_SERVICE.get()):
            is_super = False
            if User.objects.count() == 0:
                is_super = True

            try:
                if AUTH.IGNORE_USERNAME_CASE.get():
                    user = User.objects.get(username__iexact=username)
                else:
                    user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = find_or_create_user(username, None)
                if user is not None and user.is_active:
                    profile = get_profile(user)
                    profile.creation_method = UserProfile.CreationMethod.EXTERNAL.name
                    profile.save()
                    user.is_superuser = is_super

                    ensure_has_a_group(user)

                    user.save()

            user = rewrite_user(user)
            return user

        return None
Exemplo n.º 11
0
    def post(self):
        import pam
        import pwd

        username = self.get_argument("username")
        password = self.get_argument("password")

        if pam.authenticate(username, password):
            db = self.settings['db_async']
            info = pwd.getpwnam(username)
            fms_token = str(uuid.uuid4())
            user = {
                u'_id': fms_token,
                u'username': username,
                u'uid': info.pw_uid,
                u'gid': info.pw_gid,
                u'home': info.pw_dir,
                u'created': datetime.datetime.now()
            }

            result = yield motor.Op(db.tokens.insert, user)
            self.set_secure_cookie("fms_auth", fms_token, expires_days=None)
            self.write("OK")
        else:
            self.clear_cookie("username")
            self.set_status(401)  #Unauthorized
Exemplo n.º 12
0
  def authenticate(self, username, password):
    username = force_username_case(username)

    if pam.authenticate(username, password, desktop.conf.AUTH.PAM_SERVICE.get()):
      is_super = False
      if User.objects.count() == 0:
        is_super = True

      try:
        if desktop.conf.AUTH.IGNORE_USERNAME_CASE.get():
          user = User.objects.get(username__iexact=username)
        else:
          user = User.objects.get(username=username)
      except User.DoesNotExist:
        user = find_or_create_user(username, None)
        if user is not None and user.is_active:
          profile = get_profile(user)
          profile.creation_method = UserProfile.CreationMethod.EXTERNAL
          profile.save()
          user.is_superuser = is_super

          ensure_has_a_group(user)

          user.save()

      user = rewrite_user(user)
      return user

    return None
Exemplo n.º 13
0
  def handle(self):
    logger.debug("Received connection.")
    while True:
      try:
        r = self.request.recv(1024)
        if len(r) == 0:
          logger.debug("Client quit")
          break
        data = json.loads(str(r, 'utf-8'))
      except ValueError:
        self.reply({}, status=400, message='JSON Parse error')

      if 'username' in data:
        if 'password' in data:
          username = data['username']
          password = data['password']
          service = data.get('service', 'login')
          if pam.authenticate(username, password, service=service):
            self.reply({}, status=200, message='Authentication successful.')
          else:
            self.reply({}, status=401, message='Authentication failed.')
        else:
          self.reply({}, status=400, message='Password is missing.')
      else:
        self.reply({}, status=400, message='Username is missing.')
Exemplo n.º 14
0
def chgPass(request):
    """修改登录系统的密码"""
    error = ""
    msg = ""
    if request.method == "POST":
        username = request.session.get("username")
        oldpass = request.POST.get("oldpass")
        password = request.POST.get("password")
        password_confirm = request.POST.get("password_confirm")
        if "" in [oldpass, password, password_confirm]:
            error = "带*内容不能为空"
        elif not pam.authenticate(username, oldpass):
            error = "密码不正确"
        elif password != password_confirm:
            error = "两次密码不匹配"

        if not error:
            ret = subprocess.call("%s %s %s" % (chgpass_shell, username, password), shell=True)
            if ret:
                error = "密码修改失败"
            else:
                msg = "修改密码成功"

    return render_to_response(
        "chgPass.html", {"msg": msg, "error": error, "pass_menu": "active"}, context_instance=RequestContext(request)
    )
Exemplo n.º 15
0
 def authenticate(self, username=None, password=None):
     # print("PAMBackend.authenticate was just called, like.. right now !!!!!")
     if (pam.authenticate(username, password)):
         print("pam.authenticate() returned True")
         try:
             user = User.objects.get(username=username)
             print("User found")
         except User.DoesNotExist:
             print("User *not* found")
             user = User(username=username)
             user.is_staff = False
             user.is_active = True
             try:
                 user.save()
                 print("user created")
             except:
                 print("user *not* created")
         try:
             a = Staff.objects.get( Q( user=user ) | Q( nethz_login=user.username ))
             if not a.user == user:
                 a.user = user
                 a.save()
             print( "advisor found: %s" % ( a ) )
         except Staff.DoesNotExist:
             a = Staff(user=user)
             try:
                 a.save()
             except Exception as e:
                 print( e )
             print( "created advisor: %s" % ( a ) )
         print(a)
         return user
     else:
         return
Exemplo n.º 16
0
  def post(self):
    import pam
    import pwd

    username = self.get_argument("username")
    password = self.get_argument("password")

    if pam.authenticate(username, password):
      db = self.settings['db_async']
      info = pwd.getpwnam(username)
      fms_token = str(uuid.uuid4())
      user = {
        u'_id' : fms_token,
        u'username' : username,
        u'uid' : info.pw_uid,
        u'gid' : info.pw_gid,
        u'home': info.pw_dir,
        u'created' : datetime.datetime.now()
      }

      result =  yield motor.Op(db.tokens.insert, user)
      self.set_secure_cookie("fms_auth", fms_token, expires_days=None)
      self.write("OK")
    else:
      self.clear_cookie("username")
      self.set_status(401) #Unauthorized
Exemplo n.º 17
0
 def GET(self):
     getInput = web.input(username="", password="")
     if pam.authenticate(getInput.username, getInput.password):
         session.loggedin = True
         return 'success'
     else:
         return 'fail'
Exemplo n.º 18
0
def chgPass(request):
    error = ''
    msg = ''
    if request.method == 'POST':
        username = request.session.get('username')
        oldpass = request.POST.get('oldpass')
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')
        if '' in [oldpass, password, password_confirm]:
            error = '带*内容不能为空'
        elif not pam.authenticate(username, oldpass):
            error = '密码不正确'
        elif password != password_confirm:
            error = '两次密码不匹配'

        if not error:
            ret = subprocess.call('%s %s %s' %
                                  (chgpass_shell, username, password),
                                  shell=True)
            if ret:
                error = '密码修改失败'
            else:
                msg = '修改密码成功'

    return render_to_response('chgPass.html', {
        'msg': msg,
        'error': error,
        'pass_menu': 'active'
    },
                              context_instance=RequestContext(request))
Exemplo n.º 19
0
  def check_auth(self, username, password):
    if pam.authenticate(username, password, desktop.conf.AUTH.PAM_SERVICE.get()):
      is_super = False
      if User.objects.count() == 0:
        is_super = True

      try:
        user = User.objects.get(username=username)
      except User.DoesNotExist:
        user = find_or_create_user(username, None)
        if user is not None and user.is_active:
          profile = get_profile(user)
          profile.creation_method = UserProfile.CreationMethod.EXTERNAL
          profile.save()
          user.is_superuser = is_super

          default_group = get_default_user_group()
          if default_group is not None:
            user.groups.add(default_group)

          user.save()

      user = rewrite_user(user)
      return user

    return None
Exemplo n.º 20
0
def pam_authenticate(username=None, password=None):
	if pam.authenticate(username, password, service="login"):
		try:
			user = User.objects.get(username=username)

			# Change user password in DB because PAM authenticated the new one.
			if user.check_password(password):
				return True

			user.set_password(password)
			user.save()

			return True

		except User.DoesNotExist:
			# New user that is not in the database.
			user = User.objects.create_user(username=username, password=password)
			
			# Checks if the user has sudo right for the server
			if username in grp.getgrnam("sudo")[3]:
				if not "sudo" in Group.objects.all():
					group = Group.objects.create(name="sudo")
				else:
					group = Group.objects.get(name="sudo")

				user.groups.add(group)
				user.save()
		
			return True

	return False
Exemplo n.º 21
0
    def check_password(self, password):
        if 'palco.backends.PAMBackend' in settings.AUTHENTICATION_BACKENDS:
            import pam

            return pam.authenticate(self.user.username, password, settings.PAM_SERVICE)
        else:
            return self.user.check_password(password)
Exemplo n.º 22
0
    def get_html(self, http_context):
        no_auth = ['.jpg', '.png', '.css', '.ico', '.htm']

        if http_context.module == 'static' and (http_context.url[-4:]
                                                in no_auth):
            return None

        sessionid = http_context.sessionid
        if 'num_logout' in http_context.http_get.keys():
            http_context.session.del_var(sessionid, 'CONNECTED')

        error = ''
        connected = False
        sessionvars = http_context.session.get_vars(sessionid)

        if 'CONNECTED' in sessionvars.keys():
            if not 'alphanum_json' in http_context.http_get.keys():
                return None
            else:
                connected = True
                error = 'No Error'

        http_post = http_context.http_post
        http_post_varlist = http_post.keys()
        allowedlogin = self._webconf['login_allowusers'].split(',')
        loginmodule = self._webconf['login_pammodule']
        if 'alphanum_login' in http_post_varlist and 'str_password' in http_post_varlist:
            if http_post['alphanum_login'] in allowedlogin and pam.authenticate(
                    http_post['alphanum_login'], http_post['str_password'],
                    loginmodule):
                http_context.session.add_var(sessionid, 'CONNECTED', True)
                http_context.session.add_var(sessionid, 'user',
                                             http_post['alphanum_login'])

                if not 'alphanum_json' in http_context.http_get.keys():
                    return None
                connected = True
                error = 'No Error'
            else:
                error = 'Wrong credentials'
        token = sessionvars['posttoken']

        content = {
            'page': http_context.url,
            'error': error,
            'token': token,
            'connected': connected
        }
        if 'alphanum_json' in http_context.http_get.keys():
            template = None
            content = json.dumps(content)
            http_context.session.add_var(sessionid, 'API', True)
        else:
            template = 'login.tpl'

        return WebStructure.HttpContext(statuscode=200,
                                        content=content,
                                        template=template,
                                        mimetype='text/html')
Exemplo n.º 23
0
 def doLogin(self, username=None, password=None):
     result = pam.authenticate(username=username, password=password, service='login')
     if result:
         global logined
         logined=1
         raise cherrypy.HTTPRedirect("Serverconfig")
     else:
         raise cherrypy.HTTPRedirect("index")
Exemplo n.º 24
0
def valid_auth(environ):
    auth = environ.get('HTTP_AUTHORIZATION', None)
    if auth:
        auth = b64decode(auth[6:])
        username, password = auth.split(':')
        return authenticate(username, password)
    else:
        return False
Exemplo n.º 25
0
 def _checkPAM(self, username, password):
     if '\\' in username:
         domain, user = username.split('\\')
         username = '******' % (user, domain.upper())
     elif '@' in username:
         user, domain = username.split('@')
         username = '******' % (user, domain.upper())
     return pam.authenticate(username, password, self.pamService)
Exemplo n.º 26
0
 def check(self, username, password, realm):
     """
     Checks if there is a user with the specified username and password for the specified realm
     @param string username
     @param string password in clear text
     @return boolean
     """
     return pam.authenticate(username, password)
Exemplo n.º 27
0
 def authenticate(self):
     if pam.authenticate(self.username, self.password):
         logging.debug("Auth success for user: %s" % self.username)
         self.password = None  # such security! :D
         self.authenticated = True
     else:
         logging.debug("Auth FAIL for user: %s" % self.username)
         self.authenticated = False
Exemplo n.º 28
0
    def delete_user(self, *args):
        import pam

        password_input = Gtk.Entry()
        password_input.set_visibility(False)
        password_input.set_alignment(0.5)

        confirm = KanoDialog(
            title_text = _('Are you sure you want to delete this account?'),
            description_text = _('Enter {}\'s password - A reboot will be required'.format(self.user)),
            widget=password_input,
            has_entry=True,
            button_dict = [
                {
                    'label': _('Cancel').upper(),
                    'color': 'red',
                    'return_value': False
                },
                {
                    'label': _('Ok').upper(),
                    'color': 'green',
                    'return_value': True
                }
            ])

        confirm.dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)

        # Kano Dialog will return False if cancel button is clicked, or text from the entry field if Ok
        response=confirm.run()
        if response == False:
            return
        elif type(response) == str and not len(response):
            error = KanoDialog(title_text = _('Please enter the password for user {}'.format(self.user)))
            error.dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
            error.run()
            return
        else:
            password=response

        # Authenticate user and schedule removal. Protect against unknown troubles.
        try:
            if pam.authenticate(self.user, password):
                info = KanoDialog(title_text = _('User {} scheduled for removal'.format(self.user)), \
                                  description_text = _('Press OK to reboot'))
                info.dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
                info.run()

                os.system('sudo kano-init schedule delete-user "{}"'.format(self.user))
                LightDM.restart()
            else:
                error = KanoDialog(title_text = _('Incorrect password for user {}'.format(self.user)))
                error.dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
                error.run()
        except Exception as e:
            logger.error('Error deleting account {} - {}'.format(self.user, str(e)))
            error = KanoDialog(title_text = _('Could not delete account {}'.format(self.user)))
            error.dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
            error.run()
Exemplo n.º 29
0
    def auth(self, userobj, username, password, settings, **kwargs):
        if username not in _auth_cache:
            # Need lock here, as PAM authentication is not thread safe
            _pam_lock.acquire()
            try:
                auth_result = pam.authenticate(username, password,
                                               settings["service"])
                # cache result only if we properly authenticated
                if auth_result:
                    _auth_cache[username] = time.time()
            finally:
                _pam_lock.release()

            if not auth_result:
                log.error("PAM was unable to authenticate user: %s" %
                          (username, ))
                return None
        else:
            log.debug("Using cached auth for user: %s" % (username, ))

        # old attrs fetched from Kallithea database
        admin = getattr(userobj, 'admin', False)
        active = getattr(userobj, 'active', True)
        email = getattr(userobj, 'email',
                        '') or "%s@%s" % (username, socket.gethostname())
        firstname = getattr(userobj, 'firstname', '')
        lastname = getattr(userobj, 'lastname', '')
        extern_type = getattr(userobj, 'extern_type', '')

        user_attrs = {
            'username': username,
            'firstname': firstname,
            'lastname': lastname,
            'groups':
            [g.gr_name for g in grp.getgrall() if username in g.gr_mem],
            'email': email,
            'admin': admin,
            'active': active,
            "active_from_extern": None,
            'extern_name': username,
            'extern_type': extern_type,
        }

        try:
            user_data = pwd.getpwnam(username)
            regex = settings["gecos"]
            match = re.search(regex, user_data.pw_gecos)
            if match:
                user_attrs["firstname"] = match.group('first_name')
                user_attrs["lastname"] = match.group('last_name')
        except Exception:
            log.warning("Cannot extract additional info for PAM user %s",
                        username)
            pass

        log.debug("pamuser: \n%s" % formatted_json(user_attrs))
        log.info('user %s authenticated correctly' % user_attrs['username'])
        return user_attrs
Exemplo n.º 30
0
    def is_authorized(self, username, password):
        """Returns true is a user is authorised via PAM.

        Note: We use the 'login' PAM stack rather than inventing
              our own.

        @rtype: boolean
        """
        return pam.authenticate(username, password, 'sshd')
Exemplo n.º 31
0
def authenticate(username, password):
    import pam
    # This will fetch tickets twice but...
    if not pam.authenticate(USER, password, "sshd"):
        raise AuthenticationRequired("Invalid credentials.")

    if not getTickets(username, password):
        raise AuthenticationRequired("Unable to get tickets.")

    return makeToken()
Exemplo n.º 32
0
    def authenticate(self, username, password, **kwargs):
        if pam.authenticate(username, password):
            metadata = {}
            if username == 'root':
                metadata['is_admin'] == True

            tenant = {'id': username, 'name': username}
            user = {'id': username, 'name': username}

            return (tenant, user, metadata)
Exemplo n.º 33
0
    def authenticate(self, username, password, **kwargs):
        if pam.authenticate(username, password):
            extras = {}
            if username == "root":
                extras["is_admin"] == True

            tenant = {"id": username, "name": username}
            user = {"id": username, "name": username}

            return (tenant, user, extras)
Exemplo n.º 34
0
    def auth(self, userobj, username, password, settings, **kwargs):
        if username not in _auth_cache:
            # Need lock here, as PAM authentication is not thread safe
            _pam_lock.acquire()
            try:
                auth_result = pam.authenticate(username, password,
                                               settings["service"])
                # cache result only if we properly authenticated
                if auth_result:
                    _auth_cache[username] = time.time()
            finally:
                _pam_lock.release()

            if not auth_result:
                log.error("PAM was unable to authenticate user: %s" % (username,))
                return None
        else:
            log.debug("Using cached auth for user: %s" % (username,))

        # old attrs fetched from Kallithea database
        admin = getattr(userobj, 'admin', False)
        active = getattr(userobj, 'active', True)
        email = getattr(userobj, 'email', '') or "%s@%s" % (username, socket.gethostname())
        firstname = getattr(userobj, 'firstname', '')
        lastname = getattr(userobj, 'lastname', '')
        extern_type = getattr(userobj, 'extern_type', '')

        user_attrs = {
            'username': username,
            'firstname': firstname,
            'lastname': lastname,
            'groups': [g.gr_name for g in grp.getgrall() if username in g.gr_mem],
            'email': email,
            'admin': admin,
            'active': active,
            "active_from_extern": None,
            'extern_name': username,
            'extern_type': extern_type,
        }

        try:
            user_data = pwd.getpwnam(username)
            regex = settings["gecos"]
            match = re.search(regex, user_data.pw_gecos)
            if match:
                user_attrs["firstname"] = match.group('first_name')
                user_attrs["lastname"] = match.group('last_name')
        except Exception:
            log.warning("Cannot extract additional info for PAM user %s", username)
            pass

        log.debug("pamuser: \n%s" % formatted_json(user_attrs))
        log.info('user %s authenticated correctly' % user_attrs['username'])
        return user_attrs
Exemplo n.º 35
0
    def authenticate(self, username, password, **kwargs):
        if pam.authenticate(username, password):
            metadata = {}
            if username == 'root':
                metadata['is_admin'] == True

            tenant = {'id': username,
                      'name': username}
            user = {'id': username,
                    'name': username}

            return (tenant, user, metadata)
Exemplo n.º 36
0
def get_sudo_password(heading, parent=None):
    entry = Gtk.Entry()
    entry.set_visibility(False)
    kdialog = KanoDialog(
        title_text=heading,
        description_text="Enter your system password - default is kano:",
        widget=entry,
        has_entry=True,
        global_style=True,
        parent_window=parent
    )

    pw = kdialog.run()
    del kdialog
    del entry

    while not pam.authenticate(getpass.getuser(), pw):
        fail = KanoDialog(
            title_text=heading,
            description_text="The password was incorrect. Try again?",
            button_dict={
                "YES": {
                    "return_value": 0
                },
                "CANCEL": {
                    "return_value": -1,
                    "color": "red"
                }
            },
            parent_window=parent
        )

        rv = fail.run()
        del fail
        if rv < 0:
            return

        entry = Gtk.Entry()
        entry.set_visibility(False)
        kdialog = KanoDialog(
            title_text=heading,
            description_text="Re-enter your system password - default is kano:",
            widget=entry,
            has_entry=True,
            global_style=True,
            parent_window=parent
        )

        pw = kdialog.run()
        del kdialog
        del entry

    return pw
Exemplo n.º 37
0
 def validate_password(self, field):
     """use Linux PAM for authenticate"""
     username = self.username.data
     if platform.system().lower() == 'linux':
         g.logger.debug('use pam for authenticate.')
         from pam import authenticate
         if authenticate(username, field.data):
             g.logger.info('session opened for user %s.' % username)
             return username
         else:
             raise ValueError('Authentication failure.')
     return username
Exemplo n.º 38
0
def authenticate_user(state, control_code):
    state.user_name = getpass.getuser()
    if control_code == 'new':
        state.control.send(str(state.user_name).encode('ascii'))
    user_name = state.control.recv(1024).decode('ascii')
    user_pass = state.control.recv(1024).decode('ascii')
    result = 'pass'
    if pam.authenticate(user_name, user_pass):
        state.control.send(str(result).encode('ascii'))
    else:
        result = 'fail'
        state.control.send(str(result).encode('ascii'))
Exemplo n.º 39
0
 def handle_request(self, parameters):
     # fill in any missing userdn, etc.
     self.validate(parameters)
     is_root = (self.calleruid == 0) and parameters["asroot"]
     mods = []
     # check if the the user passed the rootpwmoddn
     if parameters["asroot"]:
         binddn = cfg.rootpwmoddn
         # check if rootpwmodpw should be used
         if not parameters["password"] and is_root and cfg.rootpwmodpw:
             password = cfg.rootpwmodpw
         else:
             password = parameters["password"]
     else:
         binddn = parameters["userdn"]
         password = parameters["password"]
     # write response header
     self.fp.write_int32(constants.NSLCD_RESULT_BEGIN)
     # check home directory modification
     homedir = parameters["mods"].get(constants.NSLCD_USERMOD_HOMEDIR)
     if homedir:
         if is_root:
             mods.append((ldap.MOD_REPLACE, passwd.attmap["homeDirectory"], [homedir]))
         elif not os.path.isabs(homedir):
             self.write_result(constants.NSLCD_USERMOD_HOMEDIR, "should be an absolute path")
         elif not os.path.isdir(homedir):
             self.write_result(constants.NSLCD_USERMOD_HOMEDIR, "not a directory")
         else:
             mods.append((ldap.MOD_REPLACE, passwd.attmap["homeDirectory"], [homedir]))
     # check login shell modification
     shell = parameters["mods"].get(constants.NSLCD_USERMOD_SHELL)
     if shell:
         if is_root:
             mods.append((ldap.MOD_REPLACE, passwd.attmap["loginShell"], [shell]))
         elif shell not in list_shells():
             self.write_result(constants.NSLCD_USERMOD_SHELL, "unlisted shell")
         elif not os.path.isfile(shell) or not os.access(shell, os.X_OK):
             self.write_result(constants.NSLCD_USERMOD_SHELL, "not an executable")
         else:
             mods.append((ldap.MOD_REPLACE, passwd.attmap["loginShell"], [shell]))
     # get a connection and perform the modification
     if mods:
         try:
             conn, authz, msg = pam.authenticate(binddn, password)
             conn.modify_s(parameters["userdn"], mods)
             logging.info("changed information for %s", parameters["userdn"])
         except (ldap.INVALID_CREDENTIALS, ldap.INSUFFICIENT_ACCESS), e:
             try:
                 msg = e[0]["desc"]
             except:
                 msg = str(e)
             logging.debug("modification failed: %s", msg)
             self.write_result(constants.NSLCD_USERMOD_RESULT, msg)
Exemplo n.º 40
0
 def authenticate(self, username=None, password=None):
     if pam.authenticate(username, password, service='login'):
         try:
             return User.objects.get(username=username)
         except User.DoesNotExist:
             # Create new django user
             user = User(username=username)
             user.set_password(password)
             user.save()
             user.groups.add(Group.objects.get(name='Users'))
             return user
     return None
Exemplo n.º 41
0
def verify_current_password(password):
    # Verify the current password in the first text box
    # Get current username
    username, e, num = run_cmd("echo $SUDO_USER")

    # Remove trailing newline character
    username = username.rstrip()

    if not pam.authenticate(username, password):
        # Could not verify password
        return False

    return True
Exemplo n.º 42
0
 def requestAvatarId(self, credentials):
     if pam.authenticate(credentials.username, credentials.password):
         log.info('Successful login with PAM for %s' % credentials.username)
         auth = getUtility(IAuthentication)
         oms_user = User(credentials.username)
         oms_user.groups.extend(get_linux_groups_for_user(credentials.username))
         log.info(' Adding user groups: %s' % ', '.join(oms_user.groups))
         for g in get_linux_groups_for_user(credentials.username):
             auth.registerPrincipal(Group(g))
         auth.registerPrincipal(oms_user)
         return defer.succeed(credentials.username)
     log.warning(' Authentication failed with PAM for %s' % credentials.username)
     return defer.fail(UnauthorizedLogin('Invalid credentials'))
Exemplo n.º 43
0
def verify_current_password(password):
    # Verify the current password in the first text box
    # Get current username
    username, e, num = run_cmd("echo $SUDO_USER")

    # Remove trailing newline character
    username = username.rstrip()

    if not pam.authenticate(username, password):
        # Could not verify password
        return False

    return True
Exemplo n.º 44
0
 def verify(self):
     self.verifyTime += 1
     import pam
     password = self.ui.editPassword.text()
     status =  pam.authenticate(self.getUsername(), password)
     if not status:
         self.ui.labStatus.setText("Validate failed %d"%self.verifyTime)
         self.ui.editPassword.clear()
     else:
         self.ui.labStatus.setText("Validate passed")
         self.setWallpaper()
         notify.Notify(title='gwaller',content="set wallpaper successful").inotify()
         self.close()
Exemplo n.º 45
0
def is_authenticated(user, password):
    """Check if ``user``/``password`` couple is valid."""

    if user is None or password is None:
      return False

    # Check whether the user exists in the PAM system
    try:
        pwd.getpwnam(user).pw_uid
    except KeyError:
        log.LOGGER.debug("User %s not found" % user)
        return False
    else:
        log.LOGGER.debug("User %s found" % user)

    # Check whether the group exists
    try:
        # Obtain supplementary groups
        members = grp.getgrnam(GROUP_MEMBERSHIP).gr_mem
    except KeyError:
        log.LOGGER.debug(
            "The PAM membership required group (%s) doesn't exist" %
            GROUP_MEMBERSHIP)
        return False

    # Check whether the user exists
    try:
        # Get user primary group
        primary_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
    except KeyError:
        log.LOGGER.debug(
            "The PAM user (%s) doesn't exist" %
            user)
        return False

    # Check whether the user belongs to the required group (primary or supplementary)
    if primary_group == GROUP_MEMBERSHIP or user in members:
        log.LOGGER.debug(
            "The PAM user belongs to the required group (%s)" %
            GROUP_MEMBERSHIP)
        # Check the password
        if pam.authenticate(user, password):
            return True
        else:
            log.LOGGER.debug("Wrong PAM password")
    else:
        log.LOGGER.debug(
            "The PAM user doesn't belong to the required group (%s)" %
            GROUP_MEMBERSHIP)

    return False
Exemplo n.º 46
0
    def auth(self, userobj, username, password, settings, **kwargs):
        if not username or not password:
            log.debug('Empty username or password skipping...')
            return None

        auth_result = pam.authenticate(username, password, settings["service"])

        if not auth_result:
            log.error("PAM was unable to authenticate user: %s" % (username, ))
            return None

        log.debug('Got PAM response %s' % (auth_result, ))

        # old attrs fetched from RhodeCode database
        default_email = "%s@%s" % (username, socket.gethostname())
        admin = getattr(userobj, 'admin', False)
        active = getattr(userobj, 'active', True)
        email = getattr(userobj, 'email', '') or default_email
        username = getattr(userobj, 'username', username)
        firstname = getattr(userobj, 'firstname', '')
        lastname = getattr(userobj, 'lastname', '')
        extern_type = getattr(userobj, 'extern_type', '')

        user_attrs = {
            'username': username,
            'firstname': firstname,
            'lastname': lastname,
            'groups': [g.gr_name for g in grp.getgrall()
                       if username in g.gr_mem],
            'email': email,
            'admin': admin,
            'active': active,
            'active_from_extern': None,
            'extern_name': username,
            'extern_type': extern_type,
        }

        try:
            user_data = pwd.getpwnam(username)
            regex = settings["gecos"]
            match = re.search(regex, user_data.pw_gecos)
            if match:
                user_attrs["firstname"] = match.group('first_name')
                user_attrs["lastname"] = match.group('last_name')
        except Exception:
            log.warning("Cannot extract additional info for PAM user")
            pass

        log.debug("pamuser: %s", user_attrs)
        log.info('user %s authenticated correctly' % user_attrs['username'])
        return user_attrs
Exemplo n.º 47
0
def get_sudo_password(heading, parent=None):
    entry = Gtk.Entry()
    entry.set_visibility(False)
    kdialog = KanoDialog(
        title_text=heading,
        description_text=_("Enter your system password - default is kano:"),
        widget=entry,
        has_entry=True,
        global_style=True,
        parent_window=parent)

    pw = kdialog.run()
    del kdialog
    del entry

    while not pam.authenticate(getpass.getuser(), pw):
        fail = KanoDialog(
            title_text=heading,
            description_text=_("The password was incorrect. Try again?"),
            button_dict={
                _("YES"): {
                    "return_value": 0
                },
                _("CANCEL"): {
                    "return_value": -1,
                    "color": "red"
                }
            },
            parent_window=parent)

        rv = fail.run()
        del fail
        if rv < 0:
            return

        entry = Gtk.Entry()
        entry.set_visibility(False)
        kdialog = KanoDialog(
            title_text=heading,
            description_text=_(
                "Re-enter your system password - default is kano:"),
            widget=entry,
            has_entry=True,
            global_style=True,
            parent_window=parent)

        pw = kdialog.run()
        del kdialog
        del entry

    return pw
Exemplo n.º 48
0
def get_user(username, provider, password=None):
    if provider == "Local":
        u = User.query.filter_by(name=username, provider=provider).first()
        if u is not None and u.check_password(password):
            return u
    elif provider == "PAM":
        if pam.authenticate(username, password):
            u = User.query.filter_by(name=username, provider=provider).first()
            if u is None:
                u = User(name=username, provider=provider)
                db.session.add(u)
                db.session.commit()
            return u
    return None
Exemplo n.º 49
0
def get_user(username, provider, password=None):
    if provider == "Local":
        u = User.query.filter_by(name=username, provider=provider).first()
        if u is not None and u.check_password(password):
            return u
    elif provider == "PAM":
        if pam.authenticate(username, password):
            u = User.query.filter_by(name=username, provider=provider).first()
            if u is None:
                u = User(name=username, provider=provider)
                db.session.add(u)
                db.session.commit()
            return u
    return None
Exemplo n.º 50
0
def login():
    username = request.form["username"]
    password = request.form["password"]
    is_auth = pam.authenticate(username,password)
    if is_auth:
        session["logged_in"] = True
        session["username"] = username
        session["auth_message"] = None
        user_repo = '/mapr/' + MAPR_CLUSTER + NOTEBOOKS_FOLDER + '/' + username
        subprocess.call(['mkdir','-p',user_repo])
        subprocess.call(['chown',username,user_repo])
        subprocess.call(['chmod','777',user_repo])
    else:
        session["auth_message"]="authentication failed for {}".format(username)
    return home() 
Exemplo n.º 51
0
Arquivo: app_2.py Projeto: nbet/spad
def login_2():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            ret = pam.authenticate(form['username'].data, form['password'].data)
            if not ret:
                flash('Invalid credentials', 'error')
            else:
                connect_to_masters()
                session['username'] = form['username'].data
                return redirect(request.args.get("next") or url_for("index_2"))
        except Unauthorized:
            flash('Invalid credentials', 'error')

    return render_template("login_2.html", form=form)
 def requestAvatarId(self, credentials):
     if pam.authenticate(credentials.username, credentials.password):
         log.info('Successful login with PAM for %s' % credentials.username)
         auth = getUtility(IAuthentication)
         oms_user = User(credentials.username)
         oms_user.groups.extend(
             get_linux_groups_for_user(credentials.username))
         log.info(' Adding user groups: %s' % ', '.join(oms_user.groups))
         for g in get_linux_groups_for_user(credentials.username):
             auth.registerPrincipal(Group(g))
         auth.registerPrincipal(oms_user)
         return defer.succeed(credentials.username)
     log.warning(' Authentication failed with PAM for %s' %
                 credentials.username)
     return defer.fail(UnauthorizedLogin('Invalid credentials'))
Exemplo n.º 53
0
def is_authenticated(user, password):
    """Check if ``user``/``password`` couple is valid."""
    if user is None or password is None:
        return False

    # Check whether the user exists in the PAM system
    try:
        pwd.getpwnam(user).pw_uid
    except KeyError:
        log.LOGGER.debug("User %s not found" % user)
        return False
    else:
        log.LOGGER.debug("User %s found" % user)

    # Check whether the group exists
    try:
        # Obtain supplementary groups
        members = grp.getgrnam(GROUP_MEMBERSHIP).gr_mem
    except KeyError:
        log.LOGGER.debug(
            "The PAM membership required group (%s) doesn't exist" %
            GROUP_MEMBERSHIP)
        return False

    # Check whether the user exists
    try:
        # Get user primary group
        primary_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
    except KeyError:
        log.LOGGER.debug("The PAM user (%s) doesn't exist" % user)
        return False

    # Check whether the user belongs to the required group
    # (primary or supplementary)
    if primary_group == GROUP_MEMBERSHIP or user in members:
        log.LOGGER.debug("The PAM user belongs to the required group (%s)" %
                         GROUP_MEMBERSHIP)
        # Check the password
        if pam.authenticate(user, password):
            return True
        else:
            log.LOGGER.debug("Wrong PAM password")
    else:
        log.LOGGER.debug(
            "The PAM user doesn't belong to the required group (%s)" %
            GROUP_MEMBERSHIP)

    return False
Exemplo n.º 54
0
    def check(self, uid=None, passwd=None):
        """:func:`burpui.misc.auth.local.LocalLoader.check` verifies if the
        given password matches the given user settings.

        :param uid: User to authenticate
        :type uid: str

        :param passwd: Password
        :type passwd: str

        :returns: True if there is a match, otherwise False
        """
        if self.users is None or uid in self.users:
            return pam.authenticate(uid, passwd, 'other')

        return False
Exemplo n.º 55
0
    def post(self, request):
        print("POST REQ")
        username = request.data.get('username')
        password = request.data.get('password')
        print("post request: " + username + "\npassword: "******"PAM:  " + str(pa))
        if pa:
            print("User " + username + " authenticated succesfully.")
            return Response(status=status.HTTP_200_OK)
        else:
            print("User " + username + " authentication failed")
            return Response(status=status.HTTP_403_FORBIDDEN)
Exemplo n.º 56
0
    def authenticate(self, username=None, password=None):
        if pam.authenticate(username, password):
            try:
                user = User.objects.get(username=username)
            except:
                user = User(username=username, password='******')

                if getattr(settings, 'PAM_IS_SUPERUSER', False):
                    user.is_superuser = True

                if getattr(settings, 'PAM_IS_STAFF', user.is_superuser):
                    user.is_staff = True

                user.save()
            return user
        return None
Exemplo n.º 57
0
 def handle_read(self):
     data = self._buf + self.recv(1024)
     if not data:
         self.close()
         return
     reqs, data = data.rsplit('\r\n', 1)
     self._buf = data
     for req in reqs.split('\r\n'):
         try:
             user, passwd = req.split()
         except:
             self.send('bad\r\n')
         else:
             if pam.authenticate(user, passwd):
                 self.send('ok\r\n')
             else:
                 self.send('fail\r\n')
Exemplo n.º 58
0
 def on_cancel(self, evt):
     from pam import authenticate
     '''Cancel button has been pressed.  Clean up and exit without continuing.'''
     page = evt.GetPage()
     print "on_cancel: %s\n" % page.__class__, page.title
     dialog = wx.TextEntryDialog(None,
                                 "Enter Password to Log In",
                                 defaultValue='',
                                 style=wx.OK | wx.CANCEL | wx.TE_PASSWORD)
     if dialog.ShowModal() == wx.ID_OK:
         if authenticate('update', dialog.GetValue()) is False:
             wx.MessageBox("The update system will shut down now",
                           "Shutting Down")
             subprocess.Popen('sudo /sbin/shutdown -h now', shell=True)
     else:
         evt.Veto()
     dialog.Destroy()
Exemplo n.º 59
0
    def authenticate(self, request, username=None, password=None):
        if pam.authenticate(username, password):
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username)
                user.is_staff = False
                user.is_superuser = False
                gcos = pwd.getpwnam(username).pw_gecos.split(',')
                user.email = gcos[4]
                if len(gcos[0].split(' ')) == 2:
                    user.firstname = gcos[0].split(' ')[0]
                    user.lastname = gcos[0].split(' ')[1]

                user.save()
            return user
        else:
            return None
Exemplo n.º 60
0
    def basic_auth_user(self, realm, user_name, password, environ):
        pam = self.pam

        is_ok = pam.authenticate(
            user_name,
            password,
            service=self.pam_service,
            resetcreds=self.pam_resetcreds,
            encoding=self.pam_encoding,
        )
        if is_ok:
            _logger.debug("User '{}' logged on.".format(user_name))
            return True

        _logger.warning(
            "pam.authenticate('{}', '***', '{}') failed with code {}: {}".
            format(user_name, self.pam_service, pam.code, pam.reason))
        return False