Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
ManagingUsers&Groups,FilePermissions&Attributes
andEnablingsudoAccessonAccounts
LastAugust,theLinuxFoundationstartedtheLFCScertification(LinuxFoundationCertifiedSysadmin),a
brandnewprogramwhosepurposeistoallowindividualseverywhereandanywheretakeanexaminorderto
getcertifiedinbasictointermediateoperationalsupportforLinuxsystems,whichincludessupportingrunning
systemsandservices,alongwithoverallmonitoringandanalysis,plusintelligentdecisionmakingtobeableto
decidewhenitsnecessarytoescalateissuestohigherlevelsupportteams.
LinuxFoundationCertifiedSysadminPart8
PleasehaveaquicklookatthefollowingvideothatdescribesanintroductiontotheLinuxFoundation
CertificationProgram.
http://www.tecmint.com/manage-users-and-groups-in-linux/
1/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
ThisarticleisPart8ofa10tutoriallongseries,hereinthissection,wewillguideyouonhowtomanageusers
andgroupspermissionsinLinuxsystem,thatarerequiredfortheLFCScertificationexam.
SinceLinuxisamultiuseroperatingsystem(inthatitallowsmultipleusersondifferentcomputersorterminals
toaccessasinglesystem),youwillneedtoknowhowtoperformeffectiveusermanagement:howtoadd,edit,
suspend,ordeleteuseraccounts,alongwithgrantingthemthenecessarypermissionstodotheirassigned
tasks.
AddingUserAccounts
Toaddanewuseraccount,youcanruneitherofthefollowingtwocommandsasroot.
# adduser [new_account]
# useradd [new_account]
Whenanewuseraccountisaddedtothesystem,thefollowingoperationsareperformed.
1.His/herhomedirectoryiscreated(/home/usernamebydefault).
2.Thefollowinghiddenfilesarecopiedintotheusershomedirectory,andwillbeusedtoprovideenvironment
variablesforhis/herusersession.
.bash_logout
.bash_profile
.bashrc
3.Amailspooliscreatedfortheuserat/var/spool/mail/username.
4.Agroupiscreatedandgiventhesamenameasthenewuseraccount.
Understanding/etc/passwd
Thefullaccountinformationisstoredinthe/etc/passwdfile.Thisfilecontainsarecordpersystemuser
accountandhasthefollowingformat(fieldsaredelimitedbyacolon).
[username]:[x]:[UID]:[GID]:[Comment]:[Home directory]:[Default shell]
1.Fields[username]and[Comment]areselfexplanatory.
2.Thexinthesecondfieldindicatesthattheaccountisprotectedbyashadowedpassword(in/etc/shadow),
whichisneededtologonas[username].
3.The[UID]and[GID]fieldsareintegersthatrepresenttheUserIDentificationandtheprimaryGroup
IDentificationtowhich[username]belongs,respectively.
4.The[Homedirectory]indicatestheabsolutepathto[username]shomedirectory,and
5.The[Defaultshell]istheshellthatwillbemadeavailabletothisuserwhenheorsheloginsthesystem.
http://www.tecmint.com/manage-users-and-groups-in-linux/
2/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
Understanding/etc/group
Groupinformationisstoredinthe/etc/groupfile.Eachrecordhasthefollowingformat.
[Group name]:[Group password]:[GID]:[Group members]
1.[Groupname]isthenameofgroup.
2.Anxin[Grouppassword]indicatesgrouppasswordsarenotbeingused.
3.[GID]:sameasin/etc/passwd.
4.[Groupmembers]:acommaseparatedlistofuserswhoaremembersof[Groupname].
AddUserAccounts
Afteraddinganaccount,youcaneditthefollowinginformation(tonameafewfields)usingtheusermod
command,whosebasicsyntaxofusermodisasfollows.
# usermod [options] [username]
Settingtheexpirydateforanaccount
UsetheexpiredateflagfollowedbyadateinYYYYMMDDformat.
# usermod --expiredate 2014-10-30 tecmint
Addingtheusertosupplementarygroups
UsethecombinedaG,orappendgroupsoptions,followedbyacommaseparatedlistofgroups.
# usermod --append --groups root,users tecmint
Changingthedefaultlocationoftheusershomedirectory
Usethed,orhomeoptions,followedbytheabsolutepathtothenewhomedirectory.
# usermod --home /tmp tecmint
Changingtheshelltheuserwillusebydefault
Useshell,followedbythepathtothenewshell.
# usermod --shell /bin/sh tecmint
Displayingthegroupsanuserisamemberof
# groups tecmint
# id tecmint
http://www.tecmint.com/manage-users-and-groups-in-linux/
3/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
Nowletsexecutealltheabovecommandsinonego.
# usermod --expiredate 2014-10-30 --append --groups root,users --home /tmp -shell /bin/sh tecmint
usermodCommandExamples
Intheexampleabove,wewillsettheexpirydateofthetecmintuseraccounttoOctober30th,2014.Wewill
alsoaddtheaccounttotherootandusersgroup.Finally,wewillsetshasitsdefaultshellandchangethe
locationofthehomedirectoryto/tmp:
ReadAlso:
Forexistingaccounts,wecanalsodothefollowing.
Disablingaccountbylockingpassword
UsetheL(uppercaseL)orthelockoptiontolockauserspassword.
# usermod --lock tecmint
Unlockinguserpassword
Usetheuortheunlockoptiontounlockauserspasswordthatwaspreviouslyblocked.
# usermod --unlock tecmint
LockUserAccounts
Creatinganewgroupforreadandwriteaccesstofilesthatneedtobeaccessedbyseveralusers
Runthefollowingseriesofcommandstoachievethegoal.
http://www.tecmint.com/manage-users-and-groups-in-linux/
4/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
Youcandeleteagroupwiththefollowingcommand.
# groupdel [group_name]
Iftherearefilesownedbygroup_name,theywillnotbedeleted,butthegroupownerwillbesettotheGIDof
thegroupthatwasdeleted.
LinuxFilePermissions
Besidesthebasicread,write,andexecutepermissionsthatwediscussedinArchivingToolsandSettingFile
AttributesPart3ofthisseries,thereareotherlessused(butnotlessimportant)permissionsettings,
sometimesreferredtoasspecialpermissions.
Likethebasicpermissionsdiscussedearlier,theyaresetusinganoctalfileorthroughaletter(symbolic
notation)thatindicatesthetypeofpermission.
Deletinguseraccounts
Youcandeleteanaccount(alongwithitshomedirectory,ifitsownedbytheuser,andallthefilesresiding
therein,andalsothemailspool)usingtheuserdelcommandwiththeremoveoption.
# userdel --remove [username]
GroupManagement
Everytimeanewuseraccountisaddedtothesystem,agroupwiththesamenameiscreatedwiththe
usernameasitsonlymember.Otheruserscanbeaddedtothegrouplater.Oneofthepurposesofgroupsis
toimplementasimpleaccesscontroltofilesandothersystemresourcesbysettingtherightpermissionson
thoseresources.
Forexample,supposeyouhavethefollowingusers.
1.user1(primarygroup:user1)
2.user2(primarygroup:user2)
3.user3(primarygroup:user3)
Allofthemneedreadandwriteaccesstoafilecalledcommon.txtlocatedsomewhereonyourlocalsystem,
ormaybeonanetworksharethatuser1hascreated.Youmaybetemptedtodosomethinglike,
# chmod 660 common.txt
http://www.tecmint.com/manage-users-and-groups-in-linux/
5/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
OR
# chmod u=rw,g=rw,o= common.txt [notice the space between the last equal sign
and the file name]
However,thiswillonlyprovidereadandwriteaccesstotheownerofthefileandtothoseuserswhoare
membersofthegroupownerofthefile(user1inthiscase).Again,youmaybetemptedtoadduser2and
user3togroupuser1,butthatwillalsogivethemaccesstotherestofthefilesownedbyuseruser1and
groupuser1.
Thisiswheregroupscomeinhandy,andhereswhatyoushoulddoinacaselikethis.
UnderstandingSetuid
Whenthesetuidpermissionisappliedtoanexecutablefile,anuserrunningtheprograminheritstheeffective
privilegesoftheprogramsowner.Sincethisapproachcanreasonablyraisesecurityconcerns,thenumberof
fileswithsetuidpermissionmustbekepttoaminimum.Youwilllikelyfindprogramswiththispermissionset
whenasystemuserneedstoaccessafileownedbyroot.
Summingup,itisntjustthattheusercanexecutethebinaryfile,butalsothathecandosowithroots
privileges.Forexample,letscheckthepermissionsof/bin/passwd.Thisbinaryisusedtochangethe
passwordofanaccount,andmodifiesthe/etc/shadowfile.Thesuperusercanchangeanyonespassword,
butallotherusersshouldonlybeabletochangetheirown.
passwdCommandExamples
Thus,anyusershouldhavepermissiontorun/bin/passwd,butonlyrootwillbeabletospecifyanaccount.
Otheruserscanonlychangetheircorrespondingpasswords.
http://www.tecmint.com/manage-users-and-groups-in-linux/
6/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
ChangeUserPassword
UnderstandingSetgid
Whenthesetgidbitisset,theeffectiveGIDoftherealuserbecomesthatofthegroupowner.Thus,anyuser
canaccessafileundertheprivilegesgrantedtothegroupownerofsuchfile.Inaddition,whenthesetgidbitis
setonadirectory,newlycreatedfilesinheritthesamegroupasthedirectory,andnewlycreatedsubdirectories
willalsoinheritthesetgidbitoftheparentdirectory.Youwillmostlikelyusethisapproachwhenevermembers
ofacertaingroupneedaccesstoallthefilesinadirectory,regardlessofthefileownersprimarygroup.
# chmod g+s [filename]
Tosetthesetgidinoctalform,prependthenumber2tothecurrent(ordesired)basicpermissions.
# chmod 2755 [directory]
SettingtheSETGIDinadirectory
AddSetgidtoDirectory
http://www.tecmint.com/manage-users-and-groups-in-linux/
7/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
UnderstandingStickyBit
Whenthestickybitissetonfiles,Linuxjustignoresit,whereasfordirectoriesithastheeffectofpreventing
usersfromdeletingorevenrenamingthefilesitcontainsunlesstheuserownsthedirectory,thefile,orisroot.
# chmod o+t [directory]
Tosetthestickybitinoctalform,prependthenumber1tothecurrent(ordesired)basicpermissions.
# chmod 1755 [directory]
Withoutthestickybit,anyoneabletowritetothedirectorycandeleteorrenamefiles.Forthatreason,the
stickybitiscommonlyfoundondirectories,suchas/tmp,thatareworldwritable.
AddStickybittoDirectory
SpecialLinuxFileAttributes
Thereareotherattributesthatenablefurtherlimitsontheoperationsthatareallowedonfiles.Forexample,
preventthefilefrombeingrenamed,moved,deleted,orevenmodified.Theyaresetwiththechattrcommand
andcanbeviewedusingthelsattrtool,asfollows.
http://www.tecmint.com/manage-users-and-groups-in-linux/
8/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
# chattr +i file1
# chattr +a file2
Afterexecutingthosetwocommands,file1willbeimmutable(whichmeansitcannotbemoved,renamed,
modifiedordeleted)whereasfile2willenterappendonlymode(canonlybeopeninappendmodeforwriting).
ChattrCommandtoProtectFiles
AccessingtherootAccountandUsingsudo
Oneofthewaysuserscangainaccesstotherootaccountisbytyping.
$ su
andthenenteringrootspassword.
Ifauthenticationsucceeds,youwillbeloggedonasrootwiththecurrentworkingdirectoryasthesameasyou
werebefore.Ifyouwanttobeplacedinrootshomedirectoryinstead,run.
http://www.tecmint.com/manage-users-and-groups-in-linux/
9/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
$ su andthenenterrootspassword.
EnableSudoAccessonUsers
Theaboveprocedurerequiresthatanormaluserknowsrootspassword,whichposesaserioussecurityrisk.
Forthatreason,thesysadmincanconfigurethesudocommandtoallowanordinaryusertoexecute
commandsasadifferentuser(usuallythesuperuser)inaverycontrolledandlimitedway.Thus,restrictions
canbesetonausersoastoenablehimtorunoneormorespecificprivilegedcommandsandnoothers.
Toauthenticateusingsudo,theuseruseshis/herownpassword.Afterenteringthecommand,wewillbe
promptedforourpassword(notthesuperusers)andiftheauthenticationsucceeds(andiftheuserhasbeen
grantedprivilegestorunthecommand),thespecifiedcommandiscarriedout.
Tograntaccesstosudo,thesystemadministratormusteditthe/etc/sudoersfile.Itisrecommendedthatthis
fileiseditedusingthevisudocommandinsteadofopeningitdirectlywithatexteditor.
# visudo
Thisopensthe/etc/sudoersfileusingvim(youcanfollowtheinstructionsgiveninInstallandUsevimas
EditorPart2ofthisseriestoeditthefile).
Thesearethemostrelevantlines.
Defaults
secure_path="/usr/sbin:/usr/bin:/sbin"
root
ALL=(ALL) ALL
tecmint
ALL=/bin/yum update
http://www.tecmint.com/manage-users-and-groups-in-linux/
10/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
gacanepa
ALL=NOPASSWD:/bin/updatedb
%admin
ALL=(ALL) ALL
Letstakeacloserlookatthem.
Defaults
secure_path="/usr/sbin:/usr/bin:/sbin:/usr/local/bin"
Thislineletsyouspecifythedirectoriesthatwillbeusedforsudo,andisusedtopreventusinguserspecific
directories,whichcanharmthesystem.
Thenextlinesareusedtospecifypermissions.
root
ALL=(ALL) ALL
1.ThefirstALLkeywordindicatesthatthisruleappliestoallhosts.
2.ThesecondALLindicatesthattheuserinthefirstcolumncanruncommandswiththeprivilegesofany
user.
3.ThethirdALLmeansanycommandcanberun.
tecmint
ALL=/bin/yum update
Ifnouserisspecifiedafterthe=sign,sudoassumestherootuser.Inthiscase,usertecmintwillbeableto
runyumupdateasroot.
gacanepa
ALL=NOPASSWD:/bin/updatedb
TheNOPASSWDdirectiveallowsusergacanepatorun/bin/updatedbwithoutneedingtoenterhispassword.
%admin
ALL=(ALL) ALL
The%signindicatesthatthislineappliestoagroupcalledadmin.Themeaningoftherestofthelineis
identicaltothatofanregularuser.Thismeansthatmembersofthegroupadmincanrunallcommandsas
anyuseronallhosts.
Toseewhatprivilegesaregrantedtoyoubysudo,usetheloptiontolistthem.
http://www.tecmint.com/manage-users-and-groups-in-linux/
11/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
SudoAccessRules
PAM(PluggableAuthenticationModules)
PluggableAuthenticationModules(PAM)offertheflexibilityofsettingaspecificauthenticationschemeona
perapplicationand/orperservicebasisusingmodules.ThistoolpresentonallmodernLinuxdistributions
overcametheproblemoftenfacedbydevelopersintheearlydaysofLinux,wheneachprogramthatrequired
authenticationhadtobecompiledspeciallytoknowhowtogetthenecessaryinformation.
Forexample,withPAM,itdoesntmatterwhetheryourpasswordisstoredin/etc/shadoworonaseparate
serverinsideyournetwork.
Forexample,whentheloginprogramneedstoauthenticateauser,PAMprovidesdynamicallythelibrarythat
containsthefunctionsfortherightauthenticationscheme.Thus,changingtheauthenticationschemeforthe
loginapplication(oranyotherprogramusingPAM)iseasysinceitonlyinvolveseditingaconfigurationfile
(mostlikely,afilenamedaftertheapplication,locatedinside/etc/pam.d,andlesslikelyin
/etc/pam.conf).
Filesinside/etc/pam.dindicatewhichapplicationsareusingPAMnatively.Inaddition,wecantellwhether
acertainapplicationusesPAMbycheckingifitthePAMlibrary(libpam)hasbeenlinkedtoit:
# ldd $(which login) | grep libpam # login uses PAM
# ldd $(which top) | grep libpam # top does not use PAM
http://www.tecmint.com/manage-users-and-groups-in-linux/
12/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
CheckLinuxPAMLibrary
Intheaboveimagewecanseethatthelibpamhasbeenlinkedwiththeloginapplication.Thismakessense
sincethisapplicationisinvolvedintheoperationofsystemuserauthentication,whereastopdoesnot.
LetsexaminethePAMconfigurationfileforpasswdyes,thewellknownutilitytochangeuserspasswords.
Itislocatedat/etc/pam.d/passwd:
# cat /etc/passwd
http://www.tecmint.com/manage-users-and-groups-in-linux/
13/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
PAMConfigurationFileforLinuxPassword
Thefirstcolumnindicatesthetypeofauthenticationtobeusedwiththemodule-path(thirdcolumn).When
ahyphenappearsbeforethetype,PAMwillnotrecordtothesystemlogifthemodulecannotbeloaded
becauseitcouldnotbefoundinthesystem.
Thefollowingauthenticationtypesareavailable:
account:thismoduletypechecksiftheuserorservicehassuppliedvalidcredentialstoauthenticate.
auth:thismoduletypeverifiesthattheuseriswhohe/sheclaimstobeandgrantsanyneededprivileges.
password:thismoduletypeallowstheuserorservicetoupdatetheirpassword.
session:thismoduletypeindicateswhatshouldbedonebeforeand/oraftertheauthenticationsucceeds.
Thesecondcolumn(calledcontrol)indicateswhatshouldhappeniftheauthenticationwiththismodule
fails:
1.requisite:iftheauthenticationviathismodulefails,overallauthenticationwillbedeniedimmediately.
2.requiredissimilartorequisite,althoughallotherlistedmodulesforthisservicewillbecalledbefore
denyingauthentication.
3.sufficient:iftheauthenticationviathismodulefails,PAMwillstillgrantauthenticationevenifaprevious
markedasrequiredfailed.
4.optional:iftheauthenticationviathismodulefailsorsucceeds,nothinghappensunlessthisistheonly
moduleofitstypedefinedforthisservice.
5.includemeansthatthelinesofthegiventypeshouldbereadfromanotherfile.
6.substackissimilartoincludesbutauthenticationfailuresorsuccessesdonotcausetheexitofthe
http://www.tecmint.com/manage-users-and-groups-in-linux/
14/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
completemodule,butonlyofthesubstack.
Thefourthcolumn,ifitexists,showstheargumentstobepassedtothemodule.
Thefirstthreelinesin/etc/pam.d/passwd(shownabove),loadthesystemauthmoduletocheckthatthe
userhassuppliedvalidcredentials(account).Ifso,itallowshim/hertochangetheauthenticationtoken
(password)bygivingpermissiontousepasswd(auth).
Forexample,ifyouappend
remember=2
tothefollowingline
password
sufficient
use_authtok
in/etc/pam.d/systemauth:
password
sufficient
use_authtok remember=2
thelasttwohashedpasswordsofeachuseraresavedin/etc/security/opasswdsothattheycannotbe
reused:
http://www.tecmint.com/manage-users-and-groups-in-linux/
15/16
7/4/2016
Managing Users & Groups, File Permissions & Attributes and Enabling sudo Access on Accounts
LinuxPasswordFields
Summary
Effectiveuserandfilemanagementskillsareessentialtoolsforanysystemadministrator.Inthisarticlewe
havecoveredthebasicsandhopeyoucanuseitasagoodstartingtopointtobuildupon.Feelfreetoleave
yourcommentsorquestionsbelow,andwellrespondquickly.
http://www.tecmint.com/manage-users-and-groups-in-linux/
16/16