def passwd_generator(): """ This generator walks the /etc/passwd file and returns the next user and home directory. If XALT_USERS is set then it used that instead. It is a colon separated list. Super hack: if the colon separated list has a ";" in it then the first part is the user the second is the home directory. This is use in testing. """ xaltUserA = os.environ.get("XALT_USERS") if (xaltUserA): for user in xaltUserA.split(":"): idx = user.find(";") if (idx != -1): hdir = user[idx+1:] user = user[:idx] else: hdir = os.path.expanduser("~" + user) yield user, hdir else: for entry in getent.passwd(): yield entry.name, entry.dir
def update(self, newauth=None, length=None): '''Update credentials from the new authorization info we've been given. ''' if length is None or length < 1: length = Neo4jCreds.default_length if (not os.access(self.dirname, os.W_OK)): raise IOError('Directory %s not writable (are you root?)' % self.dirname) if newauth is None: newauth = Neo4jCreds.randpass(length) if DEBUG: print >> sys.stderr, 'Calling %s' % Neo4jCreds.passchange rc = subprocess.check_call( [Neo4jCreds.passchange, self.name, self.auth, newauth]) if rc != 0: raise IOError('Cannot update neo4j credentials.') self.auth = newauth if DEBUG: print >> sys.stderr, '%s "%s:%s" successful' % \ (Neo4jCreds.passchange, self.name, self.auth) userinfo = getent.passwd(CMAUSERID) if userinfo is None: raise OSError('CMA user id "%s" is unknown' % CMAUSERID) with open(self.filename, 'w') as f: self.auth = newauth os.chmod(self.filename, 0600) # pylint is confused about getent.passwd... # pylint: disable=E1101 os.chown(self.filename, userinfo.uid, userinfo.gid) f.write('%s\n%s\n' % (self.name, self.auth)) print >> sys.stderr, 'Updated Neo4j credentials cached in %s.' % self.filename
def update(self, newauth=None, length=None): '''Update credentials from the new authorization info we've been given. ''' if length is None or length < 1: length = Neo4jCreds.default_length if (not os.access(self.dirname, os.W_OK)): raise IOError('Directory %s not writable (are you root?)' % self.dirname) if newauth is None: newauth = Neo4jCreds.randpass(length) if DEBUG: print >> sys.stderr, 'Calling %s' % Neo4jCreds.passchange rc = subprocess.check_call([Neo4jCreds.passchange, self.name, self.auth, newauth]) if rc != 0: raise IOError('Cannot update neo4j credentials.') self.auth = newauth if DEBUG: print >> sys.stderr, '%s "%s:%s" successful' % \ (Neo4jCreds.passchange, self.name, self.auth) userinfo = getent.passwd(CMAUSERID) if userinfo is None: raise OSError('CMA user id "%s" is unknown' % CMAUSERID) with open(self.filename, 'w') as f: self.auth = newauth os.chmod(self.filename, 0600) # pylint is confused about getent.passwd... # pylint: disable=E1101 os.chown(self.filename, userinfo.uid, userinfo.gid) f.write('%s\n%s\n' % (self.name, self.auth)) print >> sys.stderr, 'Updated Neo4j credentials cached in %s.' % self.filename
def main(): if len(sys.argv)<2: print 'Usage: grade <filename.py>' getpass.getpass('press enter to continue...') return os.system('hg addremove .') os.system('hg commit -m "grading %s"' % sys.argv[1]) path = os.path.join(os.getcwd(),sys.argv[1]) if len(sys.argv)==4: classname, student_id = sys.argv[2], sys.argv[3] else: classname, student_id = path.split('/')[2].split('-') username = path.split('/')[2] name = getent.passwd(username).gecos.rstrip(',') print name grade = Test.run(classname, path) if grade!=None: key = username+': '+name grades = shopen('/tmp/grades') u = grades[classname] = grades.get(classname,{}) s = u[key] = u.get(key,{}) s[path.split('/')[-1]] = grade grades[classname] = u #print grades grades.close() getpass.getpass('press enter to continue...')
def passwd_generator(): """ This generator walks the /etc/passwd file and returns the next user and home directory. If XALT_USERS is set then it used that instead. It is a colon separated list. Super hack: if the colon separated list has a ";" in it then the first part is the user the second is the home directory. This is use in testing. """ xaltUserA = os.environ.get("XALT_USERS") if (xaltUserA): for user in xaltUserA.split(":"): idx = user.find(";") if (idx != -1): hdir = user[idx + 1:] user = user[:idx] else: hdir = os.path.expanduser("~" + user) yield user, hdir else: for entry in getent.passwd(): yield entry.name, entry.dir
def user_info(name): print("Getting User details for",name ) user = getent.passwd(name); if user: print(dict(user)) return dict(user) print("User not found") abort(404, "User not found.");
def passwd_generator(): xaltUserA = os.environ.get("XALT_USERS") if (xaltUserA): for user in xaltUserA.split(":"): yield user, os.path.expanduser("~" + user) else: for entry in getent.passwd(): yield entry.name, entry.dir
def make_key_dir(keydir, userid): 'Make a suitable directory for us to store our keys in ' if os.path.isdir(keydir): # Assume it's been set up suitably return os.mkdir(keydir, 0700) userinfo = getent.passwd(userid) if userinfo is None: raise(OSError('Userid "%s" is unknown.' % userid)) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(keydir, userinfo.uid, userinfo.gid)
def make_key_dir(keydir, userid): 'Make a suitable directory for us to store our keys in ' if os.path.isdir(keydir): # Assume it's been set up suitably return os.mkdir(keydir, 0700) userinfo = getent.passwd(userid) if userinfo is None: raise (OSError('Userid "%s" is unknown.' % userid)) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(keydir, userinfo.uid, userinfo.gid)
def make_pid_dir(pidfile, userid): 'Make a suitable directory for the pidfile' piddir = os.path.dirname(pidfile) if os.path.isdir(piddir): # Assume it's been set up suitably return os.mkdir(piddir, 0755) userinfo = getent.passwd(userid) if userinfo is None: raise (OSError('Userid "%s" is unknown.' % userid)) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(piddir, userinfo.uid, userinfo.gid)
def make_pid_dir(pidfile, userid): 'Make a suitable directory for the pidfile' piddir = os.path.dirname(pidfile) if os.path.isdir(piddir): # Assume it's been set up suitably return os.mkdir(piddir, 0755) userinfo = getent.passwd(userid) if userinfo is None: raise(OSError('Userid "%s" is unknown.' % userid)) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(piddir, userinfo.uid, userinfo.gid)
def execute(store, executor_context, otherargs, flagoptions): 'Generate the desired key-pairs' store = store executor_context = executor_context flagoptions = flagoptions if os.geteuid() != 0: return usage() if len(otherargs) > 0: return usage() cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() cmaidlist.sort() if len(cmaidlist) == 0: print('No CMA keys found. Generating two CMA key-pairs to start.') for sequence in (0, 1): print >> sys.stderr, "Generating key id", sequence cryptcurve25519_gen_persistent_keypair( '%s%05d' % (CMA_KEY_PREFIX, sequence)) cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() elif len(cmaidlist) == 1: lastkey = cmaidlist[0] lastseqno = int(lastkey[len(CMA_KEY_PREFIX):]) newkeyid = ('%s%05d' % (CMA_KEY_PREFIX, lastseqno + 1)) print('Generating an additional CMA key-pair.') cryptcurve25519_gen_persistent_keypair(newkeyid) cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() if len(cmaidlist) != 2: print('Unexpected number of CMA keys. Expecting 2, but got %d.' % len(cmaidlist)) extras = [] privatecount = 0 userinfo = getent.passwd(CMAUSERID) if userinfo is None: raise OSError('CMA user id "%s" is unknown' % CMAUSERID) for keyid in cmaidlist: privatename = pyCryptCurve25519.key_id_to_filename( keyid, pyCryptFrame.PRIVATEKEY) pubname = pyCryptCurve25519.key_id_to_filename( keyid, pyCryptFrame.PUBLICKEY) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(pubname, userinfo.uid, userinfo.gid) # pylint: disable=E1101 os.chown(privatename, userinfo.uid, userinfo.gid) privatecount += 1 if privatecount > 1: print('SECURELY HIDE *private* key %s' % privatename) extras.append(keyid)
def execute(store, executor_context, otherargs, flagoptions): 'Generate the desired key-pairs' store = store executor_context = executor_context flagoptions = flagoptions if os.geteuid() != 0: return usage() if len(otherargs) > 0: return usage() cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() cmaidlist.sort() if len(cmaidlist) == 0: print ('No CMA keys found. Generating two CMA key-pairs to start.') for sequence in (0, 1): print >> sys.stderr, "Generating key id", sequence cryptcurve25519_gen_persistent_keypair('%s%05d' % (CMA_KEY_PREFIX, sequence)) cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() elif len(cmaidlist) == 1: lastkey = cmaidlist[0] lastseqno = int(lastkey[len(CMA_KEY_PREFIX):]) newkeyid = ('%s%05d' % (CMA_KEY_PREFIX, lastseqno + 1)) print ('Generating an additional CMA key-pair.') cryptcurve25519_gen_persistent_keypair(newkeyid) cryptcurve25519_cache_all_keypairs() cmaidlist = pyCryptFrame.get_cma_key_ids() if len(cmaidlist) != 2: print ('Unexpected number of CMA keys. Expecting 2, but got %d.' % len(cmaidlist)) extras = [] privatecount = 0 userinfo = getent.passwd(CMAUSERID) if userinfo is None: raise OSError('CMA user id "%s" is unknown' % CMAUSERID) for keyid in cmaidlist: privatename = pyCryptCurve25519.key_id_to_filename(keyid, pyCryptFrame.PRIVATEKEY) pubname = pyCryptCurve25519.key_id_to_filename(keyid, pyCryptFrame.PUBLICKEY) # pylint doesn't understand about getent... # pylint: disable=E1101 os.chown(pubname, userinfo.uid, userinfo.gid) # pylint: disable=E1101 os.chown(privatename, userinfo.uid, userinfo.gid) privatecount += 1 if privatecount > 1: print ('SECURELY HIDE *private* key %s' % privatename) extras.append(keyid)
def drop_privileges_permanently(userid): ''' Drop our privileges permanently and run as the given user with the privileges to which they would be entitled if they logged in. That is, the uid, gid, and supplementary group list are all set correctly. We are careful to make sure we have exactly the permissions we need as 'userid'. Either we need to be started as root or as 'userid' or this function will fail and exit the program. ''' userinfo = getent.passwd(userid) if userinfo is None: raise (OSError('Userid "%s" is unknown.' % userid)) #pylint is confused about the getent.passwd object #pylint: disable=E1101 newuid = userinfo.uid #pylint: disable=E1101 newgid = userinfo.gid auxgroups = supplementary_groups_for_user(userid)[1] # Need to set supplementary groups, then group id then user id in that order. try: os.setgroups(auxgroups) os.setgid(newgid) os.setuid(newuid) except OSError: # We let this fail if it wants to and catch it below. # This allows this to work if we're already running as that user id... pass # Let's see if everything wound up as it should... if (os.getuid() != newuid or os.geteuid() != newuid or os.getgid() != newgid or os.getegid() != newgid): raise OSError( 'Could not set user/group ids to user "%s" [uid:%s, gid:%s].' % (userid, os.getuid(), os.getgid())) # Checking groups is a little more complicated - order is potentially not preserved... # This also allows for the case where there might be dups (which shouldn't happen?) curgroups = os.getgroups() for elem in auxgroups: if elem not in curgroups: raise OSError('Could not set auxiliary groups for user "%s"' % userid) for elem in curgroups: # I don't think the default gid is supposed to be in the current group list... # but it is in my tests... It should be harmless... if elem not in auxgroups and elem != newgid: raise OSError('Could not set auxiliary groups for user "%s"' % userid)
def Login(request): """登录界面""" error = '' if request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if request.method == 'GET': return render_to_response('login.html') else: username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) """如果从LDAP登录,没有创建过本地账号,添加之""" local_user = getent.passwd(username) if local_user is None: server_add_user(username=username) # c = {} # c.update(csrf(request)) # request.session['csrf_token'] = str(c.get('csrf_token')) # user_filter = User.objects.filter(username=username) # if user_filter: # user = user_filter[0] # if PyCrypt.md5_crypt(password) == user.password: # request.session['user_id'] = user.id # user_filter.update(last_login=datetime.datetime.now()) if user.role == 'SU': request.session['role_id'] = 2 elif user.role == 'GA': request.session['role_id'] = 1 else: request.session['role_id'] = 0 return HttpResponseRedirect( request.session.get('pre_url', '/')) # response.set_cookie('username', username, expires=604800) # response.set_cookie('seed', PyCrypt.md5_crypt(password), expires=604800) # return response else: error = '用户未激活' else: error = '用户名或密码错误' else: error = '用户名或密码错误' return render_to_response('login.html', {'error': error})
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) d = dict(getent.group('mhb-app')) groupmembers = d['members'] for username in groupmembers: user, created = User.objects.get_or_create( username=username ) if created: # no local password for such users user.set_unusable_password() # allow everybody access to admin: user.is_staff = True # we do not make anybody superuser here; # that should happen manually # user.save() try: # have to set a reasonable default group g = Group.objects.get(name="lehrender") user.groups.add(g) except: print "adding user to group did not work" pass # try to get the real-world user name : try: d = dict(getent.passwd(username)) gecos = d['gecos'] f, l = gecos.split(' ', 1) user.first_name = f user.last_name = l except: pass user.save() translation.deactivate()
def drop_privileges_permanently(userid): ''' Drop our privileges permanently and run as the given user with the privileges to which they would be entitled if they logged in. That is, the uid, gid, and supplementary group list are all set correctly. We are careful to make sure we have exactly the permissions we need as 'userid'. Either we need to be started as root or as 'userid' or this function will fail and exit the program. ''' userinfo = getent.passwd(userid) if userinfo is None: raise(OSError('Userid "%s" is unknown.' % userid)) #pylint is confused about the getent.passwd object #pylint: disable=E1101 newuid = userinfo.uid #pylint: disable=E1101 newgid = userinfo.gid auxgroups = supplementary_groups_for_user(userid)[1] # Need to set supplementary groups, then group id then user id in that order. try: os.setgroups(auxgroups) os.setgid(newgid) os.setuid(newuid) except OSError: # We let this fail if it wants to and catch it below. # This allows this to work if we're already running as that user id... pass # Let's see if everything wound up as it should... if (os.getuid() != newuid or os.geteuid() != newuid or os.getgid() != newgid or os.getegid() != newgid): raise OSError('Could not set user/group ids to user "%s" [uid:%s, gid:%s].' % (userid, os.getuid(), os.getgid())) # Checking groups is a little more complicated - order is potentially not preserved... # This also allows for the case where there might be dups (which shouldn't happen?) curgroups = os.getgroups() for elem in auxgroups: if elem not in curgroups: raise OSError('Could not set auxiliary groups for user "%s"' % userid) for elem in curgroups: # I don't think the default gid is supposed to be in the current group list... # but it is in my tests... It should be harmless... if elem not in auxgroups and elem != newgid: raise OSError('Could not set auxiliary groups for user "%s"' % userid)
def username(name): """ return getent info and snotsig """ try: passwd = dict(getent.passwd(name)) except TypeError: abort(400, "Invalid user") snotsig_path = '/home/{0}/solaris/.snotsig'.format(name) sig_path = '/home/{0}/solaris/.snotsig'.format(name) if os.path.isfile(snotsig_path): with open(snotsig_path) as f: snotsig = f.read() f.closed elif os.path.isfile(sig_path): with open(sig_path) as f: snotsig = f.read() f.closed #TODO check linux homedir as well else: snotsig = "" return jsonify({"passwd": passwd, "snotsig": snotsig})
def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) # print "trying to authenticate ", username, password try: kerberos.checkPassword(username, password, "", settings.KRB5_REALM) except kerberos.BasicAuthError: # print "Kerberos auth failed" return None # print "kerberos succeeded" # TODO: think how to better integrate this with the # django permission system. depending on group # membership, assign different permissions. # this requires a better understanding of the # way django permissions are expressed :-( if False and settings.RUN_ON_WEBAPP: webappgroup = dict(getent.group('mhb-app')) if username not in webappgroup['members']: return None user, created = User.objects.get_or_create( username=username ) # print "user, created: ", user, type(user), created if created: # no local password for such users user.set_unusable_password() # allow everybody access to admin: user.is_staff = True # we do not make anybody superuser here; # that should happen manually try: # have to set a reasonable default group g = Group.objects.get(name="lehrender") user.groups.add(g) except: # print "adding user to group did not work" pass # try to get the real-world user name : try: d = dict(getent.passwd(username)) gecos = d['gecos'] f, l = gecos.split(' ', 1) user.first_name = f user.last_name = l except: pass user.save() return user