managing file system security

Upload: vishesh-kumar

Post on 09-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Managing File system security

    1/69

    Managing File system security

    chmod commands :- symbolic and relative

    method

    chmodcommandchmodcommandchmodcommandchmodcommandcanbeusetochangedifferentpermissionconfigurations.chmodtakestwolistsasitsarguments:permissionchangesandfilenames.

    Youcanspecifythelistofpermissionsintwodifferentways.Onewayusespermissionsymbolsandis referred toas the symbolicmethod. Theother useswhat is knownas a binarymaskand isreferredtoaseithertheabsoluteortherelativemethod.

    Symbolic Method

    The symbolicmethodofsettingpermissionsuses the characters r,w,and xr,w,andxr,w,andxr,w, and x for read, write, andexecute, respectively.Any of thesepermissionscan beaddedor removed.The symboltoaddapermissionistheplussign,+plussign,+plussign,+plussign,+.Thesymboltoremoveapermissionistheminussign,minussign,minussign,minussign,----....

    chmod:chmod:chmod:chmod:----FilePermissionsinSymbolicMethodFilePermissionsinSymbolicMethodFilePermissionsinSymbolicMethodFilePermissionsinSymbolicMethod

    Description

    r Read

    w Write

    x Execute (also gives permission to change into a directory)

    X Execute only if it is a directory or has execute permission for some user

    s Set user or group ID on execution

    t Sticky bit

    u Permissions granted to user who owns the file

    g Permissions granted to users in the file's group

    o Permissions granted to ownerof the group and users in the file's group

    r w x permissions

    Thefirstthree(r,w,x)areclear.Usethemtosetread,write,andexecutepermissions.

    s permission

    ThespermissionisusedondirectoriestokeeptheuserorgroupIDforafilecreatedinthedirectory.Tosettheuser IDforanynewfilescreatedin thedirectory totheownerof thedirectory,usethe

  • 8/7/2019 Managing File system security

    2/69

    chmodu+scommand.TosetthegroupIDforanynewfilescreatedinthedirectorytothedirectory'sgroup,usethechmodg+scommand.

    t permission

    t is a special permission which provides greater security on directories. Sticky bit is used fordirectoriestoprotectfileswithinthem.Filesinadirectorywiththestickybitsetcanonlybedeletedorrenamedbytherootuserortheownerofthedirectory.

    Sticky Bit Permission Using Symbols

    Thestickybitpermissionsymbolist.Thestickybitshowsupasatintheexecutepositionoftheother permissions. A program with read and execute permissions with the sticky bit has itspermissionsdisplayedasr-t.

    #chmod +t /home/vinita/account_detail

    #ls -l /home/vinita/account_detail

    -rwxr-xr-t 1 root root 4096 /home/vinita/account_detail

    u g o permission

    The last threepermissions (u, g,o) are onlyusedwith the =operator toset permissions for theowner,group,others,oreveryoneequaltotheexistingpermissionsfortheowner,group,others,oreveryone.Forexample,chmodg=u[filename]setsthegrouppermissionstothecurrentpermissionsfortheownerofthefile.

    ExamplesofsymbolicmethodExamplesofsymbolicmethodExamplesofsymbolicmethodExamplesofsymbolicmethod

    Absolute Permissions: Binary Masks

    Theabsolutemethodchangesallthepermissionsatonce,insteadofspecifyingoneortheother.Itusesabinarymaskthatreferencesallthepermissionsineachcategory.

  • 8/7/2019 Managing File system security

    3/69

  • 8/7/2019 Managing File system security

    4/69

    Defaults Permission : umask

    Wheneveryoucreateafileordirectory,itisgivendefaultpermissions.Youcandisplaythecurrentdefaults or change them with the umaskumaskumaskumask command. The permissions are displayed in binary orsymbolic format. The default permissions include anyexecute permissions that are applied toadirectory.Executepermissionfora fileisturnedoffbydefaultwhenyoucreateitbecausestandarddatafilesdonotusetheexecutablepermissions(tomakeafileexecutablelikeascript,youhavetomanually set its execute permission). Todisplay the current default permissions, use the umaskcommandwithnoarguments.

    The-Soptionusesthesymbolicformat.

    #umask -S

    u=rwx,g=rx,o=rx

    Thisdefaultumaskprovidesrw-r--r--permissionforstandardfilesandaddsexecutepermissionfordirectories,rwxr-xr-x.

    Youcansetanewdefaultbyspecifyingpermissionsineithersymbolicorbinaryformat.Tospecifythenewpermissions,usethe-Soption.Thefollowingexampledeniesothersreadpermission,whileallowinguserandgroupreadaccess,whichresultsinpermissionsofrwxr-x---:

  • 8/7/2019 Managing File system security

    5/69

    #umask -S u=rwx,g=rx,o=

    Whenyouusethebinaryformat,themaskistheinverseofthepermissionsyouwanttoset.Tosetboththereadandexecutepermissiononandthewritepermissionoff,youusetheoctalnumber2,abinary010.Tosetallpermissionson,youuseanoctal0,abinary000.

    Thefollowingexampleshowsthemaskforthepermissiondefaultsrwx,rx,andrx(rw,r,andrforfiles):

    #umask

    0022

    Tosetthedefaulttoonlydenyallpermissionsforothers,youuse0027,usingthebinarymask0111fortheotherpermissions.

    #umask 0027

    Linux chmod commands example and implementations

    Inourlasttwoarticlesyoulearntabout permission.Permissioncanbesetbychmodcommandintwodifferentwaysymbolicandbinarymasks.

    Inthisarticlewewillpracticallyimplementswhateveryouhavelearntsofarinfile permissions.Thisarticle isa sequential of last two articles if you havemissed last two articleswesuggest you toreviewthembeforegoingthroughthisfirst.

    Create3userabcwithoutpassword.Useforloopdespiteofcreatingthemseparately.Youhavelearntaboutthisinouradvanceusermanagementsassignments.

    #for user in a b c>do

    >useradd $USER>passwd d $USER

    >done

  • 8/7/2019 Managing File system security

    6/69

    Nowcreateagroupexampleandadduseraandbtoin.

    #groupadd example#usermod G example a

    #usermod G example b

    nowcreateatestdirectoryonrootpartitionandchangeownershiptouseraandgrouptoexample.

    Nowlogon3separateterminalsformtheseusers.

    FromrootsetpermissiontoFromrootsetpermissiontoFromrootsetpermissiontoFromrootsetpermissionto

    #chmod 700 /test

    Thiswillsetpermissionsto

    owner a full

    group example ( a ,b ) noneother c none

  • 8/7/2019 Managing File system security

    7/69

    toverifythesepermissiongoontheterminalswhereuseraisloggedonand

    $cd /test

    $cat > a_fileThis is a file of user a

    $lsa_file

    userawillabletodoallthreetaskreadwriteexecuteasownerhaveallthreepermissionNowtryto

    change/testdirectoryformuserb.Itwilldeny.Becauseuserbremaininexamplegroup.andgrouphavenopermissions.

    Now try to change /test directory form user c. it will alsodeny.Because user c is other for thisdirectoryandotherhavenopermissions.

    NowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromrootto

    #chmod 710 /test

    Thiswillgivefullpermissiontoownera.Andexecutetob(bisinthegroupofawhichisexample)Userc(other)stillhavenopermissions.

    Toverify try changedirectoyformuserbto /test is shouldsuccessbuthewillnotableto listthecontainofdirectory.

  • 8/7/2019 Managing File system security

    8/69

    $cd /test$ls

    Alsoverifythepermissionofc(other)bychangingthedirectoryto/test

    $cd /test

    NowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromrootto

    #chmod 751 /test

    Thiswill give full permissiontoownera. executeand read to b (b is in thegroup of awhich is

    example)Userc(other)nowhaveexecutepermissions.

    Toverifytrytolistformuserbto/testisshouldsuccessbuthewillnotabletowriteindirectory.

    $ls

    $cat > b_file

    Alsoverifythepermissionofc(other)bychangingthedirectoryto/test

    $cd /test$ls

  • 8/7/2019 Managing File system security

    9/69

    NowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromrootto

    #chmod 775 /test

    Thiswillgivefullpermissiontoownerab(bisinthegroupofawhichisexample)Userc(other)nowhavereadandexecutepermissions.

    Toverifytrymakenewfileformuserbto/testisshouldsuccess.

    $cd /test

    $ls$ cat > b_file

    This file is created by b

    Alsoverifythepermissionofc(other)bylistingthedirectoryto/test

    $cd /test$ls

    NowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromroottoNowchangepermissionfromrootto

    #chmod 777 /test

  • 8/7/2019 Managing File system security

    10/69

    Thiswillgivefullpermissiontoownerabandc.Userc(other)nowhavefullpermissions.

    Toverifymakefileformuserc

    $ cat > c_fileThis file is created by user c

    Linux chmod commands sticky bit example and

    implementations

    Inour perviousarticleswehave discussed about readwriteandexecute permission for file anddirectory.NowIwillshowyousomespecialpermissionwhichyoucansetforfilesanddirectories.

    Ownership issue

    Insomecaseyouwanttograntpermissiontootheruserwhilekeepingownershiptoself.

    s permissions permissions permissions permissionisusedtodealwiththissituations.soptionsisusedtoaddboth userIDandgroupIDpermissiontoafile.

    Thefollowingexampleadd'suserIDpermissiontothepppdprogram,whichisownedbytherootuser.Whenanordinaryuserrunspppd,therootuserretainsownership,allowingthepppdprogramtochangeroot-ownedfiles.

    # chmod +s /usr/sbin/pppd

    TheSetUserIDandSetGroupIDpermissionsshowupasansintheexecutepositionoftheownerandgroupsegments.SetUserIDandGroupIDareessentiallyvariationsoftheexecutepermission,x.Read,write,andUserIDpermissionarerwsinsteadofjustrwx.

  • 8/7/2019 Managing File system security

    11/69

    # ls -l /usr/sbin/pppd-rwsr-sr-x 1 root root 18666 Jan 12 12:48 /usr/sbin/pppd

    Sticky Bit Permissions

    StickyBitisusedfordirectoriestoprotectfileswithinthem.Filesinadirectorywiththestickybitsetcanonlybedeletedorrenamedbytherootuserortheownerofthedirectory.

    Sticky Bit Permission Using Symbols

    Thestickybitpermissionsymbolistttt.Thestickybitshowsupasat intheexecutepositionoftheother permissions. A program with read and execute permissions with the sticky bit has itspermissionsdisplayedasr-t.

    # chmod +t /home/vinita/data

    # ls -l /home/vinita/data-rwxr-xr-t 1 root root 4096 /home/vinita/data

    Sticky Bit Permission Using the Binary MethodAswithownership,forstickybitpermissions,youaddanotheroctalnumbertothebeginningof theoctaldigits.Theoctaldigitforthestickybitis1(001).Thefollowingexamplesetsthestickybitforthedatadirectory:

    # chmod 1755 /home/vinita/data

    ThenextexamplesetsboththestickybitandtheUserIDpermissiononthenewprogsdirectory.

    # chmod 5755 /usr/bin/newprogs

    # ls -l /usr/bin/newprogsdrwsr-xr-t 1 root root 4096 /usr/bin/newprogs

    Sticky bit example of practically implementations

    USER ID and GROUP ID Permissions

    Tounderstandstickybitanduserpermissioninmoredepthlet'stakeanexample.Createtwousernamedvinitaandnikita.Andaexampledirectoryonrootpartitions.

    #useradd vinita

    #passwd d vinita#useradd nikita

    #passwd d nikita#mkdir /example

  • 8/7/2019 Managing File system security

    12/69

    Asexampledirectoryiscreatedbyrootsotheownerandgroupofthisdirectorywillroot.Bydefaultpermissionwillbeinheritedtoallotherobjectcreatedinthisdirectorytorootowner.Nowwewillusesymbolicmethodtochangetheownershipissuetothisdirectory.

    #chmod ugo+rwxs /example#ls ld /example

    Asyoucanseeinimagesbitissetinownerandgroupfiledwhichwillautomaticallysetownerandgrouptotheirrespectiveownerandgroup.Toverifyloginformusernikitaandchangedirectorytoexampleandcreatesafile.

    $cd /example

    $cat > nikita_file

    This is the file of nikita$ls l

    Asyoucanseeownerfiledischangedtousernikita.

    Nowcreateafileformuservinita.

    $cd /example$cat > vinita_file

    This is file of Vinita

  • 8/7/2019 Managing File system security

    13/69

    $ls ld

    Nowyoucanunderstandwhatsbitdoinchmodcommand.Thisisbestoptionswhenusersareworkingonsomesharedproject.Astheywillgetsownershipoftheirfilesautomatically.

    Implementation of sticky bit

    Butthiscouldcreateotherproblem.Usercanaccidentlyorintenselydeleteotherusersfilesandfolderas all user have full permission on this shared folder.Goon terminalwhereuser Vinita isloggedinanddeletethefileofnikita.

    Tocontrolthisbehaviorsswitchtorootuserandsetstickybiton/examplefolder.

    #chmod o+t /example

    #ls ld /example

    Stickybitisdefinedbytoptions.Asyoucanseeinoutputotherhavetbitsetintheirfiled.Nowonlyowneroffileandrootusercandeletefileinthisfolder.

    ToverifyswitchVinitauseragainandtrytodeletethefilesofnikita.Thistimeitwillnotsuccessthistime.

  • 8/7/2019 Managing File system security

    14/69

    Toremovestickybituseminussign.

    #chmod o-t /example

    nowVinitacandeletethefilesownedbynikitaverify

    Access control lists setfacl getfacl example and

    implementations

    Inourperviousarticlesyoulearntthathowtosetread,write,andexecutepermissionsforthe ownerofthefile,thegroupassociatedwiththefile,andforeveryoneelsewhohasaccesstothefilesystem.These files are visible with the lslslsls ----l command.l command.l command.l command. These standard file permissions are all that an

    administrator needs to grant file privileges to users and to prevent unauthorized users fromaccessingimportantfiles.

    However,whenthesebasicfilepermissionsarenotenough,accesscontrollists,orACLs,canbeusedonanext3filesystem.ACLsexpandthebasicread,write,andexecutepermissionstomorecategoriesofusersandgroups.

    Inadditiontopermissionsfortheownerandgroupforthefile,ACLsallowforpermissionstobesetforanyuser,anyusergroup,andthegroupofallusersnotinthegroupfortheuser.

    Considerasituationwhereyouwanttograntwritepermissiononlytotwousersfrom agroupoftenusers.Ifyousetpermissionfromchmodallotherusersfromgroupwillgetwriteaccess onfile.In

    suchasituationACLsworks.

    Categories of ACLs

    TherearefourcategoriesofACLsperfile:

    Foranindividualuser, Forausergroup,

  • 8/7/2019 Managing File system security

    15/69

    Viatheeffectiverightsmask Forusersnotintheusergroupassociatedwiththefile.

    ToviewtheexistingACLsforafile,executethefollowing:

    getfacl

    IfACLsareenabled,theoutputshouldlooksimilar

    # file: accounts

    # owner: Shweta# group: Shwetauser::rwx

    group::r-xmask::rwx

    other::---

    To understand acl more clearly lets take a simpleexample of acl.

    CreatethreeusersnamedShwetaVinitaandNiddhi

    #for USER in Shweta Vinita Niddhi

    > do>useradd $USER

    >passwd d $USER>done

  • 8/7/2019 Managing File system security

    16/69

    Nowmakethemthememberofgoswamigroups

    #groupadd goswami

    #usermod G goswami Shweta

    #usermod G goswami Vinita

    #usermod G goswami Niddhi

    Nowcreatea/exampledirectoryandchangetheownershiptoShweta

    #mkdir /example

    #chown Shweta /example

    NowlogonformShwetaonotherterminalsandcreateafolder

    $cd /example$mkdir /accounts

    NowShweta want to grantwritepermission only toVinita.Niddhi will also get writes access ondirectoryifShewtasetswritepermissionongroupsassheisalsothememberofgoswamigroup.SoShwetawilluseacltograntwriteaccesstoVinita.

  • 8/7/2019 Managing File system security

    17/69

    $setfacl m u:Shweta:rwx accounts$setfacl m u:Vinita:rwx accounts

    $setfacl m other:--- accounts$getfacl accounts

    Toverifyexecutegetfaclcommandsonaccountsfolder

    AsinoutputyoucanseethatuserShwetaandVinitahavefullpermissionoveraccountsfolder.AllotheruserexceptShwetaandVinitahavenopermissionoveraccountsfolder.ToverifythisaclloginformVinitaonotherterminalandchangedirectorytoexample.

    Now make a test directory in account folder it should be successful as Vinita user have fullpermissionoveraccountfolder.

    NowgootherterminalsandloginformuserNiddhiandchangedirectorytoexample

  • 8/7/2019 Managing File system security

    18/69

    Trytochangedirectorytoaccountshewilldeniedasshehavenopermissionoveraccounts

    Linux chattr commands example and implementations

    Inthisparton file permissionwewilldiscussaboutchattr commandschattrcommandschattr commandschattrcommands.For examprospectiveyoushould be aware about the basic function of chattr commands.chattr commands.chattr commands.chattr commands. chattr attribute is used to stopaccidentlydeletationoffilesandfolder.You cannotdeletethefilessecuredviachattrattributeeventhoughyou have full permission over files. This is very use full in system files like shadow andpasswdfileswhichcontainsalluserinformationandpasswords.

    SyntaxforchattrcommandsisSyntaxforchattrcommandsisSyntaxforchattrcommandsisSyntaxforchattrcommandsis

    #chattr [operator] [switch] [file name]

    Theoperator++++causestheselectedattributestobeaddedtotheexistingattributesofthefiles;----causesthemtoberemoved;and====causesthemtobetheonlyattributesthatthefileshave.

    -R

    Recursivelychangeattributesofdirectoriesandtheircontents.Symboliclinksencounteredduringrecursivedirectorytraversalsareignored.

    -a

    Afilewiththeaaaaattributesetcanonlybeopeninappendmodeforwriting.Onlythesuperusercansetorclearthisattribute.

    -i

    Afilewiththeiiiiattributecannotbemodified:itcannotbedeletedorrenamed,nolinkcanbecreatedtothisfileandnodatacanbewrittentothefile.Onlythesuperusercansetorclearthisattribute.

    Let'stakeasimpleexampleLet'stakeasimpleexampleLet'stakeasimpleexampleLet'stakeasimpleexample

    Createafilefromrootuserandsetfullpermissiononthisfileformchmodandverifyit

    #cat > test

    This test file#chmod 777 test

    #ls l

  • 8/7/2019 Managing File system security

    19/69

    nowsecurethisfilewith+i+i+i+ioptions

    #chattr +i test

    Nowyoucanonlyreadthisfile.Allotheractionsexceptsreadwillbedeniedincludingappend,edit,renameordelete.chattrpermissioncanberemovedwithiiiioptions.

    createanewfileagainThistimewewillsecurethisfilewith+a+a+a+aoptions

    #chattr +a test

    with aaaa options you can read and append this file but all other recitations will be as it is. Maindifferencebetweenaaaaandiiiiswitchisiniiiiyoucannotappendthefilewhileinaaaaswitchyoucanappendthefile.

  • 8/7/2019 Managing File system security

    20/69

    TosecureentiredirectoryuseRRRRswitch.Directory securedwith----RRRRoptioncanberesetonlywithRRRRswitch.

    RHCE Linux - nologin file in etc directory and securetty file

    RHCE Linux - How to

    secure terminal

    InthisarticlefromourseriesofRHCEexamguidewewilllearnhowcanwesecurelocal terminal.InthisexamplewewilluseanormalusercreatedinourperviousarticlenamedVinitatodenylocallylogin.Youshouldcreateanormaluserincaseyoudonothaveany.

    Example Questions:-

    Youaretheadministratorofexample.Youaretheadministratorofexample.Youaretheadministratorofexample.Youaretheadministratorofexample.comdomaincomdomaincomdomaincomdomain.Configuretodenylocallogintoallnormalusers.Configuretodenylocallogintoallnormalusers.Configuretodenylocallogintoallnormalusers.Configuretodenylocallogintoallnormalusersonyouronyouronyouronyourdomainserverdomainserverdomainserverdomainserver.As.As.As.AswellasallowtorootloginonlyonFirstTerminal.wellasallowtorootloginonlyonFirstTerminal.wellasallowtorootloginonlyonFirstTerminal.wellasallowtorootloginonlyonFirstTerminal.

  • 8/7/2019 Managing File system security

    21/69

    Toaccomplishthistaskfollowthisstepbystepguide

    LoginfromrootuserandrunthesecommandLoginfromrootuserandrunthesecommandLoginfromrootuserandrunthesecommandLoginfromrootuserandrunthesecommand

    #touch /etc/nologin

    #vi /etc/securetty

    CommentallavailableterminallthenfirstasshowinfigureCommentallavailableterminallthenfirstasshowinfigureCommentallavailableterminallthenfirstasshowinfigureCommentallavailableterminallthenfirstasshowinfigure

    If /etc/nologin/etc/nologin/etc/nologin/etc/nologin file is created, then pam modules pan_nologinpan_nologinpan_nologinpan_nologin deny toall non-root users to loginlocally.Asyoucanseeinthirdlineof/etc/pam.d/login/etc/pam.d/login/etc/pam.d/login/etc/pam.d/loginfile

  • 8/7/2019 Managing File system security

    22/69

    pam_securettypam_securettypam_securettypam_securettymoduleschecksthe/etc/securetty/etc/securetty/etc/securetty/etc/securettyfile,whichterminalareavailabletoroot.Ifterminalisnotavailableinthisfilethenpam_securettymodulepam_securettymodulepam_securettymodulepam_securettymoduledenytologinonunavailableterminaltorootuser.

    Wehavemadenecessarychangeinconfigurationfiles.Nowrootusercanloginlocally

    onlyfromterminal1.Allotherusersaredeniedfromloginlocallyexceptroot.rootuserinitselfcanuseonlyterminal1.Hewillbedeniedfromloginlocallysameasotheruserifhetrytologinlocallyfromotherterminalsexceptterminal1.

  • 8/7/2019 Managing File system security

    23/69

    YoucanverifyitbyloginnormaluseronanylocalYoucanverifyitbyloginnormaluseronanylocalYoucanverifyitbyloginnormaluseronanylocalYoucanverifyitbyloginnormaluseronanylocallyavailableterminallyavailableterminallyavailableterminallyavailableterminal

    Nowyouhavesuccessfullyaccomplishedthetaskgivenyouitsgoodhabittoremoveallthechange

    youhavemade.

    Firstremovethe/etc/nologinfileFirstremovethe/etc/nologinfileFirstremovethe/etc/nologinfileFirstremovethe/etc/nologinfile

  • 8/7/2019 Managing File system security

    24/69

    Removeallthecommentsyouplacedin/etc/securettyRemoveallthecommentsyouplacedin/etc/securettyRemoveallthecommentsyouplacedin/etc/securettyRemoveallthecommentsyouplacedin/etc/securetty

    System administrations

  • 8/7/2019 Managing File system security

    25/69

    Linux fstab file error and solution step by

    step guide example and implementation

    fstabfstabfstabfstabfiledefinethemountpointsforpartition.Beforeyoucanusethefilesinadirectory,youneedtomountthatdirectoryonapartitionformattedtosomereadablefilesystem.Linuxnormallyautomatesthisprocessusingthe /etc/fstab/etc/fstab/etc/fstab/etc/fstabconfigurationfile.Youmayencounterproblemsifconnectionsarelostormediaisremoved.ThiscauseerrorandtheseerrorarehighlytestedinRHCEexam.

    RHCE Exam Questions

    Youare givingRHCE exam.Examiner gave you the Boot relatedproblemand told toYouaregivingRHCE exam.Examiner gave you the Boot related problemand told toYouare givingRHCE exam.Examiner gave you the Boot relatedproblemand told toYouaregivingRHCE exam.Examiner gave you the Boot related problemand told toyou thatyou thatyou thatyou that makemakemakemakesuccessfullysuccessfullysuccessfullysuccessfully boot the Systemboot the Systemboot the Systemboot the System. When you started the system, System automatically asking the root. When you started the system, System automatically asking the root. When you started the system, System automatically asking the root. When you started the system, System automatically asking the rootpasswordformaintenance.Howpasswordformaintenance.Howpasswordformaintenance.Howpasswordformaintenance.Howwillyoufixthatproblem?willyoufixthatproblem?willyoufixthatproblem?willyoufixthatproblem?

    Troubleshooting of fstab

    Inthispracticalwewilldiscusshowafaultyfstabfilecaseerrorandhowcanyouremovethem.

    Take back up and Open /etc/fstab file from vi command

    default fstab file look like this

    DescriptioDescriptioDescriptioDescriptionof/etc/fstabbyColumn,LefttoRightnof/etc/fstabbyColumn,LefttoRightnof/etc/fstabbyColumn,LefttoRightnof/etc/fstabbyColumn,LefttoRight

  • 8/7/2019 Managing File system security

    26/69

    Label Liststhedevicetobemounted

    MountPoint

    Notesthedirectorywherethefilesystemwillbemounted

    FilesystemFormat

    Describesthe filesystem type.Valid filesystemtypes includeext,ext2, ext3,msdos,vfat,devpts,proc,tmpfs,udf,iso9660,nfs,smb,andswap.

    DumpValue

    DumpValueEither0or1.Avalueof1meansthatdataisautomaticallysavedtodiskbythedump(8)commandwhenyouexitLinux.

    FilesystemCheckOrder

    FilesystemCheckOrderDeterminestheorderthat filesystemsarecheckedbyfsck(8)duringthebootprocess.Therootdirectory(/)filesystemshouldbesetto1,andotherlocal filesystems should be set to 2. Removable filesystems such as /mnt/cdromshould be set to 0, which means that they are not checked during the Linux bootprocess.

    Now make some change in/etc/fstab file so it could be faulty as I did in this file

    Save the change andrestartthe system

    After restart System will automatically ask the root password for maintenance

    Give root password , andremount system for read, write and open/etc/fstab file

    Correct the fstab file and save the change [ change will not save if you did notmount the system for read and write]

  • 8/7/2019 Managing File system security

    27/69

    After saving the change reboot system

    This time system will boot without any error.

    How to increase virtual terminal inlinux Example and Implementations

    The /etc/inittab/etc/inittab/etc/inittab/etc/inittabfileholdsinstructionsforyoursystemonhowtomanageterminaldevices.Alineinthe/etc/inittab/etc/inittab/etc/inittab/etc/inittabfilehasfourbasiccomponents:anID,arunlevel,anaction,andaprocess.anID,arunlevel,anaction,andaprocess.anID,arunlevel,anaction,andaprocess.anID,arunlevel,anaction,andaprocess.

    Terminaldevicesare identifiedbyIDnumbers,beginningwith1forthefirstdevice.Therunlevelatwhich the terminaloperates isusually 1.The action isusually respawn,whichmeans to run theprocesscontinually.Theprocessisacalltothemingetty,mgetty,oragettywiththeterminal device

    name.

    Wrong editing in this file could be dangerous even it could crash Linux system.We suggest you to take back up first before editing in this file.

    #cp /etc/inittab /root

    With this file you can change default run level, increase virtual terminals and disableALT+CTRL+DELkeycombinationtorestartthesystem.

  • 8/7/2019 Managing File system security

    28/69

    After taking backup open/etc/inittab file

    Change Default Run Level

    Linux have seven run levels. Functions of all run level are

    DuringsystemstartupprocessLinuxcheckthisfiletodetermineswhichrunlevelitshouldbebootbylookingattheinitdefaultdirectivein/etc//etc//etc//etc/inittabinittabinittabinittab.Forexample,theentry

    id:5:initdefault:

    showsadefaultstartingpointinrunlevel5,whichisassociatedwiththeGUI

    To change this default runlevel locate this tag id:5:initdefault: Now replacethe value 5to 3 as show here to boot system in run level 3 Save the file andrestart the system it will boot now in run level 3.

    How to disable ALT+CTRL+DEL key combination

    By default ALT+CTRL+DEL key combination is used to restart the system. This

    default behavior is also controlled by this tag in /etc/inittab file.

    By some mean if you don't want to use ATL+CTRL+DEL key to restart thesystem. Put a hash # sign to this tag and save the file and restart the system.Now you cannot restart the by ATL+CTRL+DEL key.

  • 8/7/2019 Managing File system security

    29/69

    How to increase the number of virtual consoles

    Virtual consoles are configured in /etc/inittab. By default, RHEL is configured with six virtualconsoles.Youcanconfigureuptotwelvevirtualconsolesin/etc/inittab.

    Here are the default /etc/inittab entries for the first six virtual consoles:

    To increase the number of virtual console copy the configuration line of lastvirtual console and past just below the default line and change the number asshown in image. Save file and restart the system.

    After restart you can login in to increased terminals by pressingALT+Funcation key combinations.

    Other use full commands

    #init [run level]

  • 8/7/2019 Managing File system security

    30/69

    Withthiscommandyoucanswitchbetweenrunlevels.Forexampletogoonrunlevelonetype

    #init 1

    Thiswilltakeyouonrunlevelone.

    #telinit 1

    Sameasinit.Thiswillalsotakeyouonrunlevelone.

    #runlevel

    Toknowonwhichrunlevelareyouworkingnowuserunlevelrunlevelrunlevelrunlevelcommands

    Linux How to recover grub.conf password and removekernel panic error

    TheGGGGrandUnifiedBootloader(GRUB)randUnifiedBootloader(GRUB)randUnifiedBootloader(GRUB)randUnifiedBootloader(GRUB) isamultibootbootloaderusedforLinuxWithGRUB,userscanselectoperatingsystemsto runfromamenuinterfacedisplayedwhenasystembootsup.UsearrowkeystomovetoanentryandpressENTER.

    AssuggestedbytheRedHatexamrequirements,fortheRHCTexam,youneedtoknowhowtousetheGRUBmenutobootintodifferentrunlevels,anddiagnoseandcorrectbootfailuresarisingfrombootloadererrors.Wehavecoveredhowtobootsystemindifferentrunlevelalreadyinpervious

    articlecheckthatforrunlevelrelatedquestion.

    HowtobootsystemindifferentrunlevelHowtobootsystemindifferentrunlevelHowtobootsystemindifferentrunlevelHowtobootsystemindifferentrunlevel

    Inthisarticlewewillcovertwomostcommandbootingissue.kernelpanicerrorandgrubpassword

    RHCE Exam Questions

  • 8/7/2019 Managing File system security

    31/69

    Youare givingRHCE exam.Examiner gave you the Boot relatedproblemand told toyou thatmakeYouaregivingRHCE exam.Examiner gave you the Boot related problemand told to you thatmakeYouare givingRHCE exam.Examiner gave you the Boot relatedproblemand told toyou thatmakeYouaregivingRHCE exam.Examiner gave you the Boot related problemand told to you thatmakesuccessfullysuccessfullysuccessfullysuccessfullyboottheSystemboottheSystemboottheSystemboottheSystem.Whilebootingsystem,yousawsomeerrorandstopthebootprocessby.Whilebootingsystem,yousawsomeerrorandstopthebootprocessby.Whilebootingsystem,yousawsomeerrorandstopthebootprocessby.Whilebootingsystem,yousawsomeerrorandstopthebootprocessbydispdispdispdisplaying some error messages.laying some error messages.laying some error messages.laying some error messages.Kernel PanicKernel PanicKernel PanicKernel Panic - --- not syncing:not syncing:not syncing:not syncing: AttemptedAttemptedAttemptedAttempted to kill init! to kill init! to kill init! to kill init!Andnofurtherbootprocess.Whatyouwilldotobootthesystem.Andnofurtherbootprocess.Whatyouwilldotobootthesystem.Andnofurtherbootprocess.Whatyouwilldotobootthesystem.Andnofurtherbootprocess.Whatyouwilldotobootthesystem.

    IfyouaregettingtheKernelpanicerror,itmeansitisbootloaderrelatedproblem.RedhatEnterpriseLinuxusestheGRUBbootloaderGRUBbootloaderGRUBbootloaderGRUBbootloader.YoucanpassthekernelparameterfromthebootloaderaswellasyoucancorrectthekernelparameterpassingfrombootloaderfromGRUBscreenatboottime.

    RHEL Linux Kernel panic error

    Forthispracticalwewillmodifygrubgrubgrubgrub.conf.conf.conf.confSoyoucanunderstandwhatexactlycasethekernelpanicerror.

    alwaystakebackupbeforemodifyinggrub.confgrub.confgrub.confgrub.confparameter

    #cp /etc/grub.conf /root

    open /etc/grub.conf from vi command

    Default grub.conf file look like this We suggest you to cram up this file

    Now change kernel line as show below [ change forward slash/ to backward slash\ ]

  • 8/7/2019 Managing File system security

    32/69

    Save file with :wq and reboot the system

    On Restart you will get kernel panic error

    How to remove kernel panic error

    Reboot system and press space bar on boot menu and select kernel line

    Now press e for edit and you will see the wrong entry of kernel line in grub.conf

    Correct the kernel parameter replace backward slash \ to forward slash / and press enter to

    Thiswillcorrectthiserrortemporary.Youwillgetsameerrorafterrebootingthesystem.Aschangeherewillnotchangethedefaultfaultygrub.confsoafterbootingsystemdon'tforgettoCorrectthe

    kernelparameterreplacebackwardslash\toforwardslash/

    #vi /etc/grub.conf

  • 8/7/2019 Managing File system security

    33/69

    How remove grub.conf password

    Bybootingsysteminsinglemodesinglemodesinglemodesinglemodeonecaneasilyrecoveredrootpassword.Thiscouldcasegreatsecurityrisk.ForthiseveryLinuxsystemadministratorpasswordprotectthegrub.confgrub.confgrub.confgrub.confTwotypesofpasswordcanbesetongrub.confonetoedittheparameteringrub.confgrub.confgrub.confgrub.confduringbootprocessandanothertobootoperatingsystem.Butwhatifyoulostbothrootandgrub.confpassword.

    For this practical open grub.conf file

    #vi /etc/grub.conf

    Set password for editing just below the hidemenu option and Set password forbooting the OS just below the title menu

    Now save file with :wq and restart the system

  • 8/7/2019 Managing File system security

    34/69

  • 8/7/2019 Managing File system security

    35/69

    Select Keyboard layout to US

    Press enter on continue and it will search for linux on hard disk

  • 8/7/2019 Managing File system security

    36/69

    We don't need networking for this operation so select no

    Rescue mode will mount system image under the /mnt/sysimage folder press ok

  • 8/7/2019 Managing File system security

    37/69

    now change chroot to /mnt/sysimage and open /etc/grub.conf

    Remove both hidemenu and title password and save file

    Now reboot the system and remove Linux CD from CDROM

    After reboot there should be no password on OS selection screen

    And on boot

    WehaverecoveredbothbootloaderandOSselectionmenupasswordnowyoueasilyrecoveredrootpasswordrootpasswordrootpasswordrootpasswordbybootingsysteminsinglemode.Ifyoufeeldifficultiesin recoveringrootpasswordcheckourperviousarticle

    HowtorecoverrootpasswordHowtorecoverrootpasswordHowtorecoverrootpasswordHowtorecoverrootpassword

  • 8/7/2019 Managing File system security

    38/69

    Remove root password in Linux RHCE

    InthisarticlefromourseriesofRHCEexamguidewewilllearnhowtoremoverootpasswordremoverootpasswordremoverootpasswordremoverootpassword.

    Example Question :-

    You are new System Administrator and from now you are going to handle the system and

    your main task is Network monitoring, Backup and Restore. But you donot know the rootpassword. Change the root password to redhat.

    To remove root password in linux follow this guide

    WhenSystemSuccessfully boot, itwill ask for usernameand password. But you don'tknow theroot'spassword.Tochangetherootpasswordyouneedtobootthesystemintosingleusermode.Youcanpassthekernelargumentsfromthebootloader.

    Rebootsystemwithalt+ctrl+delkeycombinationsRebootsystemwithalt+ctrl+delkeycombinationsRebootsystemwithalt+ctrl+delkeycombinationsRebootsystemwithalt+ctrl+delkeycombinationsPressspacebaronbootloaderscreenPressspacebaronbootloaderscreenPressspacebaronbootloaderscreenPressspacebaronbootloaderscreen

    ThiswilldropyouinOSselectionscreenThiswilldropyouinOSselectionscreenThiswilldropyouinOSselectionscreenThiswilldropyouinOSselectionscreen

    Selectlinux(Ifyouhavemultibootingthenselectlinux)Selectlinux(Ifyouhavemultibootingthenselectlinux)Selectlinux(Ifyouhavemultibootingthenselectlinux)Selectlinux(Ifyouhavemultibootingthenselectlinux)

    FromgrubbootloaderscreenselectkFromgrubbootloaderscreenselectkFromgrubbootloaderscreenselectkFromgrubbootloaderscreenselectkernelparameterlineandpressernelparameterlineandpressernelparameterlineandpressernelparameterlineandpresseeee

    InkerneleditingmodepressInkerneleditingmodepressInkerneleditingmodepressInkerneleditingmodepressspacebarspacebarspacebarspacebarandwriteandwriteandwriteandwritessssintheendoflinejustintheendoflinejustintheendoflinejustintheendoflinejustaftertherhgbquietandpressaftertherhgbquietandpressaftertherhgbquietandpressaftertherhgbquietandpressenterkeyenterkeyenterkeyenterkeythatwillbringingrubbootloaderthatwillbringingrubbootloaderthatwillbringingrubbootloaderthatwillbringingrubbootloader

    screenscreenscreenscreen

  • 8/7/2019 Managing File system security

    39/69

    OngrubbootloaderscreenpressOngrubbootloaderscreenpressOngrubbootloaderscreenpressOngrubbootloaderscreenpressbbbb

    ThischangewilltellThischangewilltellThischangewilltellThischangewilltelltobootsysteminsingleusermode.tobootsysteminsingleusermode.tobootsysteminsingleusermode.tobootsysteminsingleusermode.AfterloadingessentialmodalkernelwilldropinrescuemodewithrootAfterloadingessentialmodalkernelwilldropinrescuemodewithrootAfterloadingessentialmodalkernelwilldropinrescuemodewithrootAfterloadingessentialmodalkernelwilldropinrescuemodewithroot

    promptpromptpromptprompt

    nowrunpasswdcommandtoresetrootpasswordnowrunpasswdcommandtoresetrootpasswordnowrunpasswdcommandtoresetrootpasswordnowrunpasswdcommandtoresetrootpassword

    andinit5commandtorunsystemingraphicmodeoryoucanjustrebootandinit5commandtorunsystemingraphicmodeoryoucanjustrebootandinit5commandtorunsystemingraphicmodeoryoucanjustrebootandinit5commandtorunsystemingraphicmodeoryoucanjustrebootsystemtosystemtosystemtosystemtoonitsdefaonitsdefaonitsdefaonitsdefaultrunlevelultrunlevelultrunlevelultrunlevel

    No root login problem solution Exampleand Implementation

    In our previous article we discuss a situation where you were delivered a system without root

    password.

    rootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguide

    Inthistutorialwewilldiscussaboutsomemorecriticalrootloginrelatedissue.Thereareseveralissuethosecanstoprootformlogin.Wewillcoverallpossibleissuethosecanstoprootfromlogininexam.

    Step 1 Try to change root password

  • 8/7/2019 Managing File system security

    40/69

    If you are lucky one then simply changing root password will complete the task.

    To change password

    Boot system in single mode run passwd commands change password reboot system If you wonder how all these will happen please read our pervious article.

    rootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguiderootpasswordrecoveryStepbyStepguide

    If problem stillexistthen go on Step2

    Step2 Check root account for expire

    Examiner can deliver you a root account which is expired. For testingpurpose you can also expire it. First login from root and setroot accountto

    expire

    Nowrebootthesystem.Oncesystemgetrestartedrootwillnotbeabletologin.Whenrootwilltrytologinaftergivingusernameandpassworditgetanerrormessage((((toofasttoofasttoofasttoofastthatyouhardlybeabletothatyouhardlybeabletothatyouhardlybeabletothatyouhardlybeabletoreadit)readit)readit)readit)anditwillputyoubackonloginscreen.Toresolvethisissuebootsysteminsinglemode.Ifyou don't know how to boot system in single mode then read our pervious article in which werecoveredrootpasswordfromsinglemode.

    Now boot system insingle mode and check whetherroot accountis expiredor not

    ifyouseedateinaccoifyouseedateinaccoifyouseedateinaccoifyouseedateinaccountexpirelinemeanrootpasswordisexpireduntexpirelinemeanrootpasswordisexpireduntexpirelinemeanrootpasswordisexpireduntexpirelinemeanrootpasswordisexpired

    set it to never expire from chage commands and verify that rootaccount is

    set to never expire

  • 8/7/2019 Managing File system security

    41/69

    Now reboot the system and login from root If problem still exist then go onStep3

    Step3 change in /etc/shadow

    shadow file contain information about all password store in Linux. Default

    root passwordshould look like this

    Check this file also fromsingle mode

    If you see any! sign in front the root line as shown in image below then

    remove ! sign Be very careful while making change in this file never remove

    any character from lastof the line or from middle of the line.

    savethisfilewithsavethisfilewithsavethisfilewithsavethisfilewithwq!wq!wq!wq!andcheckpasswordfileandcheckpasswordfileandcheckpasswordfileandcheckpasswordfile

    Now open /etc/passwdfile

    Entry ofroot accountshould be look like this

    If you see nologin word in the end of line then remove it

    There should be no ! sign in front of the line if any presentremove !sign form

    the beginning of line.

  • 8/7/2019 Managing File system security

    42/69

    Linux RPM Red Hat's Package Manager

    In this article from our series of RHCE exam guidewewill learn howwe can install or removepackageinlinux.

    RPMisapowerfulsoftwaremanager.Itcaninstall,remove,query,andverifythesoftwareonyoursystem.RpmismorethanaRedHatspecifictool.Manyothermoderndistributions,suchasCalderaandSuSe,userpmtoo.Inthisarticlewewillbynomeansprovide comprehensivecoverageofrpm.Instead,wewillhighlightthesubsetofoptionswehavefoundusefulintherealRHCEExam.

    Querying Your System

    The firstthing you should do islookand seeswhatsoftwareyou have installedonyour system.

    Hereisthecommandtouse:

    #rpm -qa | more

    Incaseyouareunfamiliarwiththecommandline,letmebreakthiscommanddown.

    rpmrpmrpmrpmisthecommandname.Ittellsthecomputeryouwanttoruntherpmprogram.

    ((((----))))Inlinux,thesetoflettersfollowingadash(-)iscalledanoptionorswitch.

    ----qqqqtellsrpmyouwantthequeryoperation.

    aaaa following a in the -qa isamodifierfor the query optionwhich tellsrpmyouwant to list all thepackages.

    | more| more| more| moreThe|morepartoftheabovecommandisnotafeatureofrpmatall.Itisastandardlinuxwaytoshowoutputonepageatatime.

    package info

    RpmissmartenoughtousethepackagenamewithouttheversionRpmissmartenoughtousethepackagenamewithouttheversionRpmissmartenoughtousethepackagenamewithouttheversionRpmissmartenoughtousethepackagenamewithouttheversioninfo.Forexampleseeinimageinfo.Forexampleseeinimageinfo.Forexampleseeinimageinfo.Forexampleseeinimage

  • 8/7/2019 Managing File system security

    43/69

    Thepackageinfoissplitintothreepieces.

    Thefirstpieceisthepackagename. Thesecondisthesoftwareversionnumber. Thethirdisthepackagebuildnumber.

    All three are separated by dashes. The package build number is important incase ifthere is a more recent rpm build of a program with the same version

    Installing New Software

    Youcaninstallrpmfromanylocationwhereyouhaveit.InourexamplewewillinstallitfromRHELdvd.

    CommandtoinstallpackageisCommandtoinstallpackageisCommandtoinstallpackageisCommandtoinstallpackageis

    #rpm -ivh

    ----iistheinstallswitch.iistheinstallswitch.iistheinstallswitch.iistheinstallswitch.vforvforvforvforverbosemessagesincaseiftheinstallationfails.verbosemessagesincaseiftheinstallationfails.verbosemessagesincaseiftheinstallationfails.verbosemessagesincaseiftheinstallationfails.

    hoptionshowsourprogresswithhashmarks.hoptionshowsourprogresswithhashmarks.hoptionshowsourprogresswithhashmarks.hoptionshowsourprogresswithhashmarks.

    Avariationonaninstallisanupgrade.Anupgradeisusedwhenyouwanttoputamorerecentpackageinplaceofsomethingthatiscurrentlyinstalled.Theupgradesyntaxisexactlythesameasaninstall,butyoureplacethe----iiiiwitha----U.U.U.U.(NoticeitisacapitalU)Ifanewversionoftelnettelnettelnettelnet----serverserverserverservercomesout,rpmwilltakecareofremovingalltheoldpieceswhenyouupgrade.

    Sometimesapackageisnotremovedcleanly.Hereisthesituation,youtrytoinstallsomethingandrpmsaysitsalreadyinstalled.Youthentrytoremoveit,andrpmsaysthatisnotinstalled.Whatcanyoudo?

    #rpm -ivh --force package-1.0-5.i386.rpm

    The--------forceforceforceforceoptionisyoursolution.Itwillinstallrpminanyconditions.

  • 8/7/2019 Managing File system security

    44/69

    Dependenciesaregenerallyregardedasagoodthing.Rpmhasthecapabilitytoknowifsoftwarehassuchprerequisites.Intherealworld,noteverythingonyoursystemcan alwaysbefromanrpm.Soifyouwanttoinstallrpmwithoutcheckingdependenciesyoucanuse--------nodepsnodepsnodepsnodepsoptions

    #rpm -ivh --nodeps package-1.0-5.i386.rpm

    Removing Unwanted Software

    A major advantage to a packaging system like rpm is its ease to erase software.Hereishowyoudoit:

    #rpm -e telnet-server

    Linux service managements tools chkconfig ntsysv Example

    Implementation

    becontrolledbythreeprogramsinlinux.

    onfig (command line only)sv(simple text-based application that doesn't require a graphical desktop)e Service Configuration Tool(graphical application).

    fastestwaytocontrolservicesatthecommandline.The chkconfigchkconfigchkconfigchkconfigcommandgivesyouasimplewayto maintaindc/rc.dc/rc.dc/rc.dc/rc.ddirectorystructure.Withchkconfig,youcanadd,remove,andchangeservices;liststartup information;andchevice.

    ggggcommandcanbeusedtoconfigurerunlevelsandlistthecurrentrunlevelconfiguration.Itmustberunasrootifmodmmandssuchaslistingwhetheraserviceisstartedatboottimecanberunasanon-rootuser.

  • 8/7/2019 Managing File system security

    45/69

  • 8/7/2019 Managing File system security

    46/69

    dd service use add switch ( Note rpm must be install

    t Console Service Configuration Tool

    agingalargenumberofservices,thecommandlinecanbelessefficient.Youdon'tneedaGUI,justthentsysvtoolntsysvtoolntsysvtoolntsysvtool,whmandofthesamename.However,itaffectsonlyservicesinthecurrentrunlevelunlessyouaddanappropriateswitch.

    ifyouwanttoactivateseveralservicesinrunlevels3and5,startntsysvwiththefollowingcommand:

    -level 35

    Linux job scheduling with at commands Example and Implementations

    lowsyoutorunthecommandofyourchoice,once,ataspecifiedtimeinthefuture.

    anatjobtoberunonce.The atatatatdaemonworkstotheprintprocess;jobsarespooledin the /var/spool/atdirector/var/spool/atdirector/var/spool/atdirector/var/spool/atdirectore.

    theatdaemonatdaemonatdaemonatdaemontorunthecommandorscriptofyourchoice.Forthepurposeofthisarticlewearecreatingasimplescriprrentdirectoryandsendthisoutputtoterminal2.

    mmandline,youcanruntheatatatattimecommandtostartajobtoberunataspecifiedtime.Thattimecanbenow;inaspe

    rs,ordays;oratthetimeofyourchoice.Wewilltakeseveralexampletoillustrateitmoredeeply.TheCTRLCTRLCTRLCTRL----DcommDcommDcommDcommellandreturnstoyouroriginalcommandlineinterface.

    from root and create a simplescript filetest.sh and grant it execute permission

  • 8/7/2019 Managing File system security

    47/69

    date before schedulingjob fromatcommands

    this script on 21 Feb 2010 after seven days you need to schedule at commandas shown here

    this script after ten minutes you need to schedule at commandas shown here

    this script now you need to schedule at commandas shown here

    this script on 10:15 AM you need to schedule at commandas shown here

    ck the status of your jobs, so you can see if itwill work, run the following job queue command:

  • 8/7/2019 Managing File system security

    48/69

    re's a problem with the job, you can remove it with the atrm command. In this example you wouler 4 with the following command:

    Securing At daemon

    wanteveryonetobeabletorunajobinthemiddleofthenight.Ifyoursystemhaveimportantsecuritydata,someonaorworse,anditcouldbedonebeforeyoudiscoverthesecurityviolations.

    Two files are used to control the behavior of at daemons

    /at.allow If present then only users those name are in this file can use at daemons

    /at.deny If present then only user those name are in this file will not be able to use at daemons ape user all other can use at daemons

    oth files are not present then only root can access at daemons

    ample create two user Vinita and nikita

    files are formatted as one line per user; add user vinita to at.allow

    t login on other terminal from user vinita and schedule job from at commands

  • 8/7/2019 Managing File system security

    49/69

    ogin on other terminal from nikita and schedule job form at commands

    Linux job scheduling with cron commands Example and Implementations

    temisbasicallyasmart alarmclock.Whenthealarmsounds,Linuxrunsthecommandsofyourchoiceautomatically.Yorunatallsortsofregulartimeintervals.

    thecrondaemoncrondaemoncrondaemoncrondaemon(crond)bydefault.It'sconfiguredtocheckthe /var/spool/crondirectory/var/spool/crondirectory/var/spool/crondirectory/var/spool/crondirectoryforjobsbyuser.Italsochecomputerunder/etc/crontab/etc/crontab/etc/crontab/etc/crontabandinthe/etc/cron.d/etc/cron.d/etc/cron.d/etc/cron.ddirectory.directory.directory.directory.

    form root and check system date, and run crontab command toschedule job

    oucanschedulejob.Thereare6fieldinthisfile5fortimeandoneforcommands.

    Field Value

    minute 059

    hour Based on a 24-hour clock; for example, 23 = 11 P.M.

    day of month 131

    month 112, or jan, feb, mar, etc.

    day of week 07; where 0 and 7 are both Sunday; or sun, mon, tue, etc.

    command The command you want to run

    asteriskinanycolumn,cronrunsthatcommandforallpossiblevaluesofthatcolumn.Forexample,an*intheminute

  • 8/7/2019 Managing File system security

    50/69

    disruneveryminuteduringthespecifiedhour(s).Consideranotherexample,asshownhere:

    5 * ls

    sthelscommandeveryMay3at5:11A.M.Theasteriskinthedayofweekcolumnsimplymeansthatitdoesnotmatteontabstillrunsthelscommandatthespecifiedtime.

    xample time in my system is 21:46 and date is 14 Feb Sunday. ( See image above). Now I wi

    y the output ofls commands on tty2 at 21:50

    #crontab#crontab#crontab#crontab----eeee

    savefilesavefilesavefilesavefileandquitandquitandquitandquit

    udonothavetorestartcroneverytimeyoumakeachangebecausecronalwayschecksforchanges,Butsofarexamsconudonothavetorestartcroneverytimeyoumakeachangebecausecronalwayschecksforchanges,Butsofarexamsconudonothavetorestartcroneverytimeyoumakeachangebecausecronalwayschecksforchanges,Butsofarexamsconudonothavetorestartcroneverytimeyoumakeachangebecausecronalwayschecksforchanges,Butsofarexamscon

    cronwheneveryoumadechange.cronwheneveryoumadechange.cronwheneveryoumadechange.cronwheneveryoumadechange.

    or four minute and on 21:50 you will get the output ofls command on tty2

    Up cron for Users

    anusethe crontabcrontabcrontabcrontab command tocreateandmanagecron jobs for theirownaccounts. Thereare fourswitchesassmand:

    ser Allows the root user to edit the crontab of another specific user.sts the current entries in the crontab file.

    emoves cron entries.dits an existing crontab entry. By default, crontab uses vi.

    osetupcronentriesonyourownaccount,startwiththecrontabcrontabcrontabcrontab----eeeecommand.

    Securing cron daemon

    wanteveryonetobeabletorunajobinthemiddleofthenight.Ifyoursystemhaveimportantsecuritydata,someon

  • 8/7/2019 Managing File system security

    51/69

    aorworse,anditcouldbedonebeforeyoudiscoverthesecurityviolations.

    Two files are used to control the behavior of crond daemons

    /cron.allow If present then only users those name are in this file can use crond daemons

    /cron.deny If present then only user those name are in this file will not be able to use crond daemm these user all other can use cron daemonsoth files are not present then only root can access cron daemons

    ample create two user Vinita and nikita

    files are formatted as one line per user; add user nikita to cron.allow

    t login on other terminal from user nikita and schedule job from cron commands

    ogin on other terminal from vinita and schedule job form cron commands

  • 8/7/2019 Managing File system security

    52/69

  • 8/7/2019 Managing File system security

    53/69

    #cat /etc/passwd |more#cat /etc/shadow |more

    #cat /etc/group |more

    Nowaddasimpleuser.

    #useradd vinita#passwd vinita

    Nowreadthesefilesagainwithcatcommandalternateyoucanuse|grepswitchtofiltertheoutput

    #cat /etc/passwd |grep vinita

    #cat /etc/shadow |grep vinita#cat /etc/group |grep vinita

    # cd /home#ls ld vinita

    User's entry in passwd

    AllthesefilesarechangedwhenauseriscreatedInpasswdfilesentriesareinfollowingformatsseparatedby:

    vinita users login namex password required to login

    503 unique user id504 unique group id/home/vinita users home directory

    /bin/bash user shell

  • 8/7/2019 Managing File system security

    54/69

    Inshadowfilesentryisstraightforwards.WhatevershowingbesidetheusernameisthepasswordofuservinitainMD5encryptformat.

    User's entry in group

    Wheneveryoucreateanormaluser,usersprimarygroupformsamenameisautomaticallycreated.Asyoucanverifybylookingin/etc/group.504istheuniquegroupid.

    User's home directory

    Sameasgroup,usershomedirectoryisalsocreatedin/homepartitionandusergettheownershipofthisdirectory.

    How to create a user without password.

    Tocreateauserwithoutpasswordusedswitch.

    #useradd nikki#passwd -d nikki

    How to create a group.

    To create groupusegroupadd commands. Groupcreated by this command is called secondary

    group.

    #groupadd test#cat /etc/group |grep test

    How to add user in groups

    Toadduserinthisgroupuseusermodcommands

    #usermod G test vinita

    Thiscommandwillmakevinitausertomemberoftestgroup.

    How to delete secondary group

    Youcandeleteagroupbygroupdelcommands

    #groupdel test

  • 8/7/2019 Managing File system security

    55/69

    #cat /etc/group |grep test

    Youcannotdeleteusersprimarygroupuntiluserexistforexample

    #groupdel nikki

    How to delete User

    userdel command is used to delete user. When a users is deleted users primary group willautomaticallybedeleted.

    #userdel nikki

    #groupdel nikkigroupdel: group nikki does not exist.

    Wheneveryoudeleteuserwithuserdelcommand.entryofuserwillberemovedfromthesefiles.Butusers home folder and mail folder will not be deleted. As you can see in image. If you wantcompletely remove user including his home folder and mail folder use r switch with userdelcommands.

    System administrations

    User managementsInourlastassignmentwediscussaboutuserandgroupmanagements.Youlearntaboutthefileswhichareresponsibleforcreatinguserandgroups.Yousawwhatexactlyhappenswhenweaddnewuserinthesefiles.

    Toaddanewuser,usetheuseraddcommand.Thebasicsyntaxis

  • 8/7/2019 Managing File system security

    56/69

    # useradd [username]

    Theusernameistheonlyinformationrequiredtoaddanewuser;however,forexamprospectiveyoushouldknowsomeadditionalcommand-line argumentsforuseradd.Theuseraddcommandcreatestheaccount,buttheaccountislocked.

    Tounlocktheaccountandcreateapasswordfortheuser,usethecommandpasswd[username].passwd[username].passwd[username].passwd[username].Bydefault,theuser'shomedirectoryiscreatedandthefilesfrom/etc/skel//etc/skel//etc/skel//etc/skel/arecopiedintoit.

    ThetwoexceptionsareiftheMoptionisusedorifthehomedirectoryalreadyexists.

    We have already discussed about these two basic commands in our last article. If you haven'tcompletedourlastassignmentswesuggestyoutoreviewitbeforegoingwiththisarticleasit'sthesequentialoflastassignments.

    SystemadministrationsUsermanagementsPart1SystemadministrationsUsermanagementsPart1SystemadministrationsUsermanagementsPart1SystemadministrationsUsermanagementsPart1

    Createauserwithadditionalcommand-linearguments.Inthisexampleyouaregoingtoassignhomedirectoryonotherlocationssofirstcreateitandsameascreatefirstdesireduser'ssecondarygroup.

    #mkdir /test

    #groupadd example

    #useradd u 700 d /test/user1 g example c testing user s /bin/sh m

    user1#passwd user1

    -c [fullname] Full name of the user (or a comment about the user).If more than one word is needed, place quotation marksaround the value.

    -d [directory] Home directory for the user. The default value is/home/[username]/.

    -g [group] Default group for the user specified as a group name or

    group ID number. The group name or GID must already exist. The default isto create a private user group. If a private user group is

    notcreated, the default is the users group.

    -m Create a home directory for the user if it doesn't exist.Files from

  • 8/7/2019 Managing File system security

    57/69

    /etc/skel/ are copied into the home directory.-s [shell] Specify the user login shell for the user. The default shell

    if notspecified is /bin/bash.

    -u [uid] Integer to use for the user ID. Must be unique unless -o isused.

    Values less than 500 are reserved for system users.

    -M Do not create a home directory for the user. By default, ahome

    directory is created unless this option is used or unlessthe

    directory already exists.

    Nowloginformthisuser.Andcheckwheredidthisuserloggedinandwhyitsshellpromptislookingdifferent.

    $pwd/test/user1

    Bydefaultusergetsbashsellprompts.Butwemodifiedthisbyssssswitchandgivenuserto/bin/sh/bin/sh/bin/sh/bin/shshell.Nowchangeusershellagain

    #usermod s /bin/bash user1

    Verifybyloginagainfromuser1

    How to manage bulk users

    Considerasituationwhereyouneedtocreatemorethenthousanduser.Itwillbereallytedioustaskifyouwilldoitbysimpleuseraddcommands.HereyouhavetoswitchtoLinuxshellscripts.

  • 8/7/2019 Managing File system security

    58/69

    loopforcreatinguserloopforcreatinguserloopforcreatinguserloopforcreatinguser

    # for USER in _ _ _ _ _ _ _ _ _ _ _

    > do>useradd $USER

    >echo _ _ _ _ |passwd --stdin $USER>done

    ExampleExampleExampleExample(replaceusersvinitanikkitaniddhisumitshwetavickeykaushalmanojjaivinitanikkitaniddhisumitshwetavickeykaushalmanojjaivinitanikkitaniddhisumitshwetavickeykaushalmanojjaivinitanikkitaniddhisumitshwetavickeykaushalmanojjaitoyourusers)

    # for USER in vinita nikkita niddhi sumit shewta vickey kaushal manoj jai> do

    >useradd $USER>echo friends |passwd --stdin $USER

    >done

    Thissimpleforloopforloopforloopforloopwillcreate9usersandsettheirdefaultspasswordstofriends.

    LoopforcreatinggroupsLoopforcreatinggroupsLoopforcreatinggroupsLoopforcreatinggroups

    Nowcreate3groupsnamedsalesmarketproductionsusingforloop

    #for GROUP in sales market productions

  • 8/7/2019 Managing File system security

    59/69

    > do>groupadd $GROUP

    >doneVerify by cat and grep commands

    ForloopfordeletingbulkusersForloopfordeletingbulkusersForloopfordeletingbulkusersForloopfordeletingbulkusers

    Nowremovealltheuserwhichwecreatedinperviousexample.

    #for USER in vinita nikkita niddhi sumit shweta vickey kaushal manoj jai>do

    >userdel -r $USER>done

    ForloopfordeletingbulkusersForloopfordeletingbulkusersForloopfordeletingbulkusersForloopfordeletingbulkusers

    Removegroupswhichwecreateinperviousexample

    #for GROUP in sales market productions

    > do

    >groupdel $GROUP>done

    Bytheendofthisassignmentsyouhavelearntthat

  • 8/7/2019 Managing File system security

    60/69

  • 8/7/2019 Managing File system security

    61/69

    Insuchasituationsyouneedtocopythesefilemanually.Thesefilearehiddenandcanbeseenbyaswitchwithlscommands.

    $ls a

    .bash_profile

  • 8/7/2019 Managing File system security

    62/69

    Thisscriptfileinstructsusersessiontocheck.bashrcfileforuseraliasesandfunctions.Furtheritssetusercommandpath.ifyouwantaddyourowndirectorytoyourcommandpath.Editthisfile.Forexampleuservinitawantsherhomedirectoryshouldbecheckwhileexcutingcommandsshecanaddthislineinher.bash_profilefiles.

    $vi .bash_profilePATH=$PATH:$HOME/BIN:/home/vinita

    .bashrc

    Thisfileisusedtocontrolsuservariableandotherprofileduringhisloginsession.Ifyouwanttoexecuteanycommandautomaticallyonuserlogonsetthatcommandinthisfile.Forexampleifuservinitawantstoclearscreenimmediatelyafterherlogin.Sheneedtoaddclearcommandatendofthisfile.

    $vi .bashrc

    # add your command only in the end of fileclear

    Withthisfileyoucanplayafunnytrickwithyourfriends.Createauserandsetexitcommandinhis.bashrcfiles.Nowaskyourfriendstologinwiththisuser.exitcommandwilllogouttheuserassoonasuserwillloginanduserwillneverwillbeabletologin.

    .bash_logout

    Thisfileisusedtocleartheterminalsaftertheexitofcurrentuser.

    Aliases

    The aliasaliasaliasalias command isused tocreate another name for a command.The aliasdoes not exactlyreplace the name of the command; it simply gives another name to that command. An alias

  • 8/7/2019 Managing File system security

    63/69

  • 8/7/2019 Managing File system security

    64/69

    Other importantshell operations areoverwriting.Howmanytimes youhaveoverwritten files.Forexample

    $cat > test

    Testing file

    $lstest

    nowrunthiscommandonceagain

    $cat > testOld matter will overwrite without any message$ls

    $cat testOld matter will overwrite without any message

    NoticehoweasilyLinuxcanoverwritefile.Toturnoffthisshellfeature

    $set o noclobber

    Nowwheneveryouwilltrytooverwriteitwillstopyouwitherrormessage.

    Whateveryousetwithooptioncanbecorrectwith+sign.

    $set +o ignoreeofNow again you can logout with CTRL+D.

    Changing shell prompt

    Bydefaultshellpromptshowusernamehostnameandcurrentworkingdirectory.Youcanchangethisprompttofollowingvariable.

  • 8/7/2019 Managing File system security

    65/69

    ThThThThefollowingtableliststhecodesforconfiguringyourprompt:efollowingtableliststhecodesforconfiguringyourprompt:efollowingtableliststhecodesforconfiguringyourprompt:efollowingtableliststhecodesforconfiguringyourprompt:

    Prompt Codes Description

    \! Current history number

    \$ Use $ as prompt for all users except

    the root user, which has the # as its prompt

    \d Current date

    \# History command number for just the current shell

    \h Hostname

    \s Shell type currently active

    \t Time of day in hours, minutes, and seconds

    \u Username

    \v Shell version

    \w Full pathname of the current working directory

    \W Name of the current working directory

    \\ Displays a backslash character

    \n Inserts a newline

    \[ \] Allows entry of terminal-specific display characters

    for features like color or bold font

    \nnn Character specified in octal format

    Granting root privilege to normal user

    GenerallyinLinux,asystemadministratordoeseverythingpossibleasanormaluser.It'sagoodpractice to use superuser privileges only when absolutely necessary. But one time when it'sappropriateisduringtheRedHatexams.Goodadministratorswillreturntobeingnormaluserswhenthey'redonewiththeirtasks.MistakesastherootusercandisableyourLinuxsystem.Therearetwobasicwaystomakethiswork:

    susususuThe superuser command, su, prompts you for the root passwordbefore logging you inwith rootprivileges.

  • 8/7/2019 Managing File system security

    66/69

    sucommandwithoutanyargumentswillaskforrootpassword.Bygivingrootpasswordyouwillgetrootprivilege.Toexecuteanycommandyoushouldknowtheexactpathofcommandotherwiseyouget command not found error. Because you will not get roots command path. To get rootsenvironmentsandcommandpathsandhomedirectoryusehyphensignwithsucommands

    Limiting Access to su

    First,youwillneedtoaddtheuserswhoyouwanttoallowaccesstothesucommand.Makethemapartofthewheelgroup.Bydefault,thislinein/etc/grouplookslike:

    wheel:x:10:root

    Youcanaddtheusersofyourchoicetotheendofthislinedirectly,withtheuseuseuseusermodrmodrmodrmod----GwheelGwheelGwheelGwheel[username][username][username][username]command,orwiththeRedHatUserManager.

    #usermod G wheel vinita

    Next,youwillneedtomakeyourPluggableAuthenticationModules(PAM)lookforthisgroup.Youcandosobyactivatingthefollowingcommandinyour/etc/pam.d//etc/pam.d//etc/pam.d//etc/pam.d/susususufile:

    # auth required pam_wheel.so use_uid

    sudosudosudosudoThesudocommandallows users listed in /etc/sudoers to runadministrative commands.You canconfigure/etc/sudoerstosetlimitsontherootprivilegesgrantedtoaspecificuser.

  • 8/7/2019 Managing File system security

    67/69

    Tousesudocommandsyoudon'tneedtogive rootpassword.Auserwithappropriate rightfrom/etc/sudoerscanexecuterootprivilegecommandformhisownpasswords.

    RedHatEnterpriseLinuxprovidessomefeaturesthatmakeworkingasrootsomewhatsafer.Forexample,loginsusingtheftpandtelnetcommandstoremotecomputersaredisabledbydefault.

    Limiting Access to sudo

    Youcanlimitaccesstothesudosudosudosudocommand.Regularuserswhoareauthorizedin/etc/sudoers/etc/sudoers/etc/sudoers/etc/sudoerscanaccess administrative commands with their own password. You don't need to give out theadministrativepassword to everyonewho thinks they know asmuch as you doaboutLinux.Toaccess/etc/sudoers/etc/sudoers/etc/sudoers/etc/sudoersinthevieditor,runthevisudovisudovisudovisudocommand.

    Fromthefollowingdirective,therootuserisallowedfullaccesstoadministrativecommands:

  • 8/7/2019 Managing File system security

    68/69

    Forexample,ifyouwanttoallowuservinitafulladministrativeaccess,addthefollowingdirectiveto/etc/sudoers:/etc/sudoers:/etc/sudoers:/etc/sudoers:

    root ALL=(ALL) ALLvinita ALL=(ALL) ALL

    Inthiscase,allvinitaneedstodotorunanadministrativecommandsuchasstartingthenetworkservicefromherregularaccountistorun thefollowingcommand,enteringherownuserpassword(notetheregularuserprompt,$):

    $ sudo /sbin/service network restart

    Password:

  • 8/7/2019 Managing File system security

    69/69

    Youcanevenallowspecialusersadministrativeaccesswithoutapassword.Assuggestedbythecomments, the following directive in/etc/sudoerswouldallowall users in thewheelgroup to runadministrativecommandswithoutapassword:

    %wheel ALL=(ALL) NOPASSWD: ALL

    Butyoudon'thavetoallowfulladministrativeaccess.Forexample,ifyouwanttoallowthoseinthe%usersgrouptoshutdownthelocalsystem,youcanactivatethefollowingdirective:

    %users localhost=/sbin/shutdown -h now