41
Computer Security: Computer Security: Principles and Practice Principles and Practice First Edition First Edition by William Stallings and Lawrie Brown by William Stallings and Lawrie Brown Lecture slides by Lawrie Brown Lecture slides by Lawrie Brown Chapter 23 Chapter 23 Linux Security Linux Security

Computer Security: Principles and Practice, 1/e - People Eecs Ku

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Computer Security: Computer Security: Principles and PracticePrinciples and Practice

First EditionFirst Editionby William Stallings and Lawrie Brownby William Stallings and Lawrie Brown

Lecture slides by Lawrie BrownLecture slides by Lawrie Brown

Chapter 23 Chapter 23 –– Linux SecurityLinux Security

Linux SecurityLinux Security

Linux has evolved into one of the most Linux has evolved into one of the most popular and versatile operating systemspopular and versatile operating systemsmany features mean broad attack surfacemany features mean broad attack surfacecan create highly secure Linux systemscan create highly secure Linux systemswill review:will review:

Discretionary Access ControlsDiscretionary Access Controlstypical vulnerabilities and exploits in Linuxtypical vulnerabilities and exploits in Linuxbest practices for mitigating those threatsbest practices for mitigating those threatsnew improvements to Linux security modelnew improvements to Linux security model

Linux Security ModelLinux Security Model

LinuxLinux’’ss traditional security model is:traditional security model is:people or people or procesesproceses with with ““rootroot”” privileges can privileges can do anythingdo anythingother accounts can do much lessother accounts can do much less

hence attackerhence attacker’’s want to get root privilegess want to get root privilegescan run robust, secure Linux systemscan run robust, secure Linux systemscrux of problem is use of crux of problem is use of Discretionary Discretionary Access ControlsAccess Controls (DAC)(DAC)

Linux Security TransactionsLinux Security Transactions

File System SecurityFile System Security

in Linux in Linux everythingeverything as a fileas a filee.g. memory, devicee.g. memory, device--drivers, named pipes, drivers, named pipes, and other system resourcesand other system resourceshence why hence why filesystemfilesystem security is so importantsecurity is so important

I/O to devices is via a I/O to devices is via a ““specialspecial”” filefilee.g. e.g. /dev//dev/cdromcdrom

have other special files like named pipeshave other special files like named pipesa conduit between processes / programsa conduit between processes / programs

Users and GroupsUsers and Groups

a usera user--account (user)account (user)represents someone capable of using filesrepresents someone capable of using filesassociated both with humans and processesassociated both with humans and processes

a groupa group--account (group)account (group)is a list of useris a list of user--accountsaccountsusers have a main group users have a main group may also belong to other groupsmay also belong to other groups

users & groups are users & groups are notnot filesfiles

Users and GroupsUsers and Groups

user's details are kept in user's details are kept in /etc/password/etc/passwordmaestro:x:200:100:Maestro Edward maestro:x:200:100:Maestro Edward HizzersandsHizzersands:/home/maestro:/bin/bash:/home/maestro:/bin/bash

additional group details in additional group details in /etc/group/etc/groupconductors:x:100:conductors:x:100:

pianists:x:102:maestro,volodyapianists:x:102:maestro,volodya

use use useradduseradd, , usermodusermod, , userdeluserdel to alterto alter

File PermissionsFile Permissions

files have two owners: a user & a groupfiles have two owners: a user & a groupeach with its own set of permissionseach with its own set of permissionswith a third set of permissions for otherwith a third set of permissions for otherpermissions are to read/write/execute in permissions are to read/write/execute in order user/group/other, cf.order user/group/other, cf.--rwrw--rwrw--rr---- 1 maestro user 35414 Mar 25 01:38 1 maestro user 35414 Mar 25 01:38 baton.txtbaton.txt

set using set using chmodchmod commandcommand

Directory PermissionsDirectory Permissions

read = list contentsread = list contentswrite = create or delete files in directorywrite = create or delete files in directoryexecute = use anything in or change execute = use anything in or change working directory to this directoryworking directory to this directorye.g.e.g.$ $ chmodchmod g+rxg+rx extreme_casserolesextreme_casseroles$ $ lsls --l extreme_casserolesl extreme_casserolesdrwxrdrwxr--xx------ 8 biff drummers 288 8 biff drummers 288 Mar 25 01:38 extreme_casserolesMar 25 01:38 extreme_casseroles

Sticky BitSticky Bit

originally used to lock file in memoryoriginally used to lock file in memorynow used on directories to limit deletenow used on directories to limit delete

if set must own file or dir to deleteif set must own file or dir to deleteother users cannot delete even if have writeother users cannot delete even if have write

set using set using chmodchmod command with +t flag, e.g.command with +t flag, e.g.chmodchmod +t extreme_casseroles+t extreme_casseroles

directory listing includes t or T flagdirectory listing includes t or T flagdrwxrwxdrwxrwx----T 8 biff drummers 288 Mar T 8 biff drummers 288 Mar 25 01:38 extreme_casseroles25 01:38 extreme_casseroles

only apply to specific directory not child only apply to specific directory not child dirsdirs

SetUIDSetUID and and SetGIDSetGID

setuidsetuid bit means program "runs as" ownerbit means program "runs as" ownerno matter who executes itno matter who executes it

setgidsetgid bit means run as a member of the bit means run as a member of the group which owns itgroup which owns it

again regardless of who executes itagain regardless of who executes it"run as" = "run with same privileges as"run as" = "run with same privileges as””are very dangerousare very dangerous if set on file owned by if set on file owned by root or other privileged account or grouproot or other privileged account or group

only used on executable files, not shell scriptsonly used on executable files, not shell scripts

SetGIDSetGID and Directoriesand Directories

setuidsetuid has no effect on directorieshas no effect on directoriessetgidsetgid does and causes any file created in does and causes any file created in a directory to inherit the directory's groupa directory to inherit the directory's groupuseful if users belong to other groups and useful if users belong to other groups and routinely create files to be shared with routinely create files to be shared with other members of those groupsother members of those groups

instead of manually changing its groupinstead of manually changing its group

Numeric File PermissionsNumeric File Permissions

Kernel Kernel vsvs User SpaceUser SpaceKernel spaceKernel space

refers to memory used by the Linux kernel refers to memory used by the Linux kernel and its loadable modules (e.g., device drivers)and its loadable modules (e.g., device drivers)

User spaceUser spacerefers to memory used by all other processesrefers to memory used by all other processes

since kernel enforces Linux DAC and since kernel enforces Linux DAC and security critical to isolate kernel from usersecurity critical to isolate kernel from user

so kernel space never swapped to diskso kernel space never swapped to diskonly root may load and unload kernel modulesonly root may load and unload kernel modules

setuidsetuid root Vulnerabilitiesroot Vulnerabilities

a a setuidsetuid rootroot program runs as rootprogram runs as rootno matter who executes itno matter who executes it

used to provide unprivileged users with access used to provide unprivileged users with access to privileged resourcesto privileged resourcesmust be very carefully programmedmust be very carefully programmed

if can be exploited due to a software bugif can be exploited due to a software bugmay allow otherwisemay allow otherwise--unprivileged users to use it to unprivileged users to use it to wield unauthorized root privilegeswield unauthorized root privileges

distributions now distributions now minimiseminimise setuidsetuid--root programsroot programssystem attackers still scan for them!system attackers still scan for them!

Web VulnerabilitiesWeb Vulnerabilitiesa very broad category of vulnerabilitiesa very broad category of vulnerabilities

because of ubiquity of world wide web have big and because of ubiquity of world wide web have big and visible attack surfacesvisible attack surfaces

when written in scripting languageswhen written in scripting languagesnot as prone to classic buffer overflowsnot as prone to classic buffer overflowscan suffer from poor inputcan suffer from poor input--handlinghandling

few few ““enabledenabled--byby--defaultdefault”” web applicationsweb applicationsbut users install vulnerable web applicationsbut users install vulnerable web applicationsor write custom web applications having easilyor write custom web applications having easily--identified and easilyidentified and easily--exploited flaws exploited flaws

RootkitsRootkits

allow attacker to cover their tracksallow attacker to cover their tracksif successfully installed before detection, all is if successfully installed before detection, all is very nearly lostvery nearly lostoriginally collections of hacked commandsoriginally collections of hacked commands

hiding attackerhiding attacker’’s files, directories, processess files, directories, processesnow use loadable kernel modulesnow use loadable kernel modules

intercepting system calls in kernelintercepting system calls in kernel--spacespacehiding attacker from standard commandshiding attacker from standard commands

may be able to detect with may be able to detect with chkrootkitchkrootkitgenerally have to wipe and rebuild systemgenerally have to wipe and rebuild system

Linux System HardeningLinux System Hardening

consider how to mitigate Linux security consider how to mitigate Linux security risks at system and application levelsrisks at system and application levelsfirst look at OSfirst look at OS--level security tools and level security tools and techniques that protect the entire systemtechniques that protect the entire system

OS InstallationOS Installationsecurity begins with O/S installationsecurity begins with O/S installationespecially what software is runespecially what software is run

since unused applications liable to be left in default, since unused applications liable to be left in default, unun--hardened and unhardened and un--patched statepatched state

generally should not run:generally should not run:X Window system, RPC services, RX Window system, RPC services, R--services, services, inetdinetd, , SMTP daemons, telnet etcSMTP daemons, telnet etc

also have some initial system s/w configuration:also have some initial system s/w configuration:setting root passwordsetting root passwordcreating a noncreating a non--root user accountroot user accountsetting an overall system security level setting an overall system security level enabling a simple hostenabling a simple host--based firewall policybased firewall policyenabling enabling SELinuxSELinux

Patch ManagementPatch Management

installed server applications must be:installed server applications must be:configured securelyconfigured securelykept up to date with security patcheskept up to date with security patches

patching can never win patching can never win ““patch ratpatch rat--racerace””have tools to automatically download and have tools to automatically download and install security updatesinstall security updates

e.g. up2date, e.g. up2date, YaSTYaST, apt, apt--getgetnote should not run automatic updates on note should not run automatic updates on changechange--controlled systems without testingcontrolled systems without testing

Network Access ControlsNetwork Access Controls

network a key attack vector to securenetwork a key attack vector to secureTCP wrappers a key tool to check accessTCP wrappers a key tool to check access

originally originally tcpdtcpd inetdinetd wrapper daemonwrapper daemonbefore allowing connection to service checksbefore allowing connection to service checks•• if requesting host explicitly in hosts.allow is okif requesting host explicitly in hosts.allow is ok•• if requesting host explicitly in hosts.deny is blockedif requesting host explicitly in hosts.deny is blocked•• if not in either is okif not in either is ok

checks on service, source IP, usernamechecks on service, source IP, usernamenow often part of app using now often part of app using libwrapperslibwrappers

Network Access ControlsNetwork Access Controlsalso have the very powerful also have the very powerful netfilternetfilter Linux Linux kernel native firewall mechanismkernel native firewall mechanism

and and iptablesiptables useruser--space front endspace front endas useful on firewalls, servers, desktopsas useful on firewalls, servers, desktopsdirect direct configconfig tricky, steep learning curvetricky, steep learning curvedo have automated rule generatorsdo have automated rule generatorstypically for typically for ““personnalpersonnal”” firewall use will:firewall use will:

allow incoming requests to specified servicesallow incoming requests to specified servicesblock all other inbound service requestsblock all other inbound service requestsallow all outbound (locallyallow all outbound (locally--originating) requestsoriginating) requests

if need greater security, manually if need greater security, manually configconfig

Antivirus SoftwareAntivirus Softwarehistorically Linux not as vulnerable to viruseshistorically Linux not as vulnerable to virusesmore to lesser popularity than securitymore to lesser popularity than securityprompt patching was effective for wormsprompt patching was effective for wormsbut viruses abuse users privilegesbut viruses abuse users privilegesnonnon--root users have less scope to exploitroot users have less scope to exploit

but can still consume resourcesbut can still consume resourcesgrowing Linux popularity mean exploitsgrowing Linux popularity mean exploitshence antivirus software will more importanthence antivirus software will more important

various commercial and free Linux A/Vvarious commercial and free Linux A/V

User ManagementUser Management

guiding principles in userguiding principles in user--account security:account security:need care setting file / directory permissionsneed care setting file / directory permissionsuse groups to differentiate between roles use groups to differentiate between roles use extreme care in granting / using root use extreme care in granting / using root privsprivs

commands: commands: chmodchmod, , useradduseradd/mod/del, /mod/del, groupaddgroupadd/mod/del, /mod/del, passwdpasswd, , chagechageinfo in files /etc/info in files /etc/passwdpasswd & /etc/group& /etc/groupmanage usermanage user’’s group membershipss group membershipsset appropriate password agesset appropriate password ages

Root DelegationRoot Delegationhave "root can to anything, users do littlehave "root can to anything, users do little”” issueissue““susu”” command allows users to run as rootcommand allows users to run as root

either root shell or single commandeither root shell or single commandmust supply root passwordmust supply root passwordmeans likely too many people know thismeans likely too many people know this

SELinuxSELinux RBAC can limit root authority, complexRBAC can limit root authority, complex““sudosudo”” allows users to run as rootallows users to run as root

but only need their password, not root passwordbut only need their password, not root password/etc//etc/sudoerssudoers file specifies what commands allowedfile specifies what commands allowed

or configure user/group perms to allow, trickyor configure user/group perms to allow, tricky

LoggingLoggingeffective logging a key resourceeffective logging a key resourceLinux logs using Linux logs using syslogdsyslogd or or SyslogSyslog--NGNG

receive log data from a variety of sourcesreceive log data from a variety of sourcessorts by sorts by facilityfacility (category) and (category) and severityseveritywrites log messages to local/remote log fileswrites log messages to local/remote log files

SyslogSyslog--NG preferable because it has:NG preferable because it has:variety of logvariety of log--data sources / destinationsdata sources / destinationsmuch more flexible much more flexible ““rules enginerules engine”” to configureto configurecan log via TCP which can be encryptedcan log via TCP which can be encrypted

should check and customized defaultsshould check and customized defaults

Log ManagementLog Management

balance number of log files usedbalance number of log files usedsize of few to finding info in manysize of few to finding info in many

manage size of log filesmanage size of log filesmust rotate log files and delete old copiesmust rotate log files and delete old copiestypically use typically use logrotatelogrotate utility run by utility run by croncronto manage both system and application logsto manage both system and application logs

must also configure application loggingmust also configure application logging

Application SecurityApplication Security

this is a large topicthis is a large topicmany security features are implemented in many security features are implemented in similar ways across different applicationssimilar ways across different applicationswill review issues such as:will review issues such as:

running as unprivileged user/grouprunning as unprivileged user/grouprunning in running in chrootchroot jailjailmodularitymodularityencryptionencryptionlogginglogging

Running As Unprivileged Running As Unprivileged User/GroupUser/Group

every process every process ““runs asruns as”” some usersome userextremely important this user is not rootextremely important this user is not root

since any bug can compromise entire systemsince any bug can compromise entire systemmay need root privileges, e.g. bind portmay need root privileges, e.g. bind port

have root parent perform privileged functionhave root parent perform privileged functionbut main service from unprivileged childbut main service from unprivileged child

user/group used should be dedicateduser/group used should be dedicatedeasier to identify source of log messageseasier to identify source of log messages

Running in Running in chrootchroot JailJailchrootchroot confines a process to a subset of /confines a process to a subset of /

maps a virtual maps a virtual ““//”” to some other directoryto some other directoryuseful if have a daemon that should only useful if have a daemon that should only access a portion of the file system, e.g. FTPaccess a portion of the file system, e.g. FTPdirectories outside the directories outside the chrootchroot jail arenjail aren’’t visible t visible or reachable at allor reachable at all

contains effects of compromised daemoncontains effects of compromised daemoncomplex to configure and troubleshootcomplex to configure and troubleshoot

must mirror portions of system in must mirror portions of system in chrootchroot jailjail

ModularityModularity

applications running as a single, large, applications running as a single, large, multipurpose process can be:multipurpose process can be:

more difficult to run as an unprivileged usermore difficult to run as an unprivileged userharder to locate / fix security bugs in source harder to locate / fix security bugs in source harder to disable unnecessary functionalityharder to disable unnecessary functionality

hence modularity a highly prized featurehence modularity a highly prized featureproviding a much smaller attack surfaceproviding a much smaller attack surface

cf. postfix cf. postfix vsvs sendmailsendmail, Apache modules, Apache modules

EncryptionEncryptionsending logins & passwords or application sending logins & passwords or application data over networks in clear text exposes data over networks in clear text exposes them to network eavesdropping attacksthem to network eavesdropping attackshence many network applications now hence many network applications now support encryption to protect such datasupport encryption to protect such data

often using often using OpenSSLOpenSSL librarylibrarymay need own X.509 certificates to usemay need own X.509 certificates to use

can generate/sign using can generate/sign using opensslopenssl commandcommandmay use commercial/own/free CAmay use commercial/own/free CA

LoggingLogging

applications can usually be configured to applications can usually be configured to log to any level of detail (debug to none)log to any level of detail (debug to none)need appropriate settingneed appropriate settingmust decide if use dedicated file or system must decide if use dedicated file or system logging facility (e.g. logging facility (e.g. syslogsyslog))

central facility useful for consistent usecentral facility useful for consistent usemust ensure any log files are rotatedmust ensure any log files are rotated

Mandatory Access ControlsMandatory Access Controls

Linux uses a DAC security modelLinux uses a DAC security modelbut Mandatory Access Controls (MAC) impose a but Mandatory Access Controls (MAC) impose a global security policy on all usersglobal security policy on all users

users may not set controls weaker than policyusers may not set controls weaker than policynormal admin done with accounts without authority to normal admin done with accounts without authority to change the global security policychange the global security policybut MAC systems have been hard to managebut MAC systems have been hard to manage

NovellNovell’’s s SuSESuSE Linux has Linux has AppArmorAppArmorRedHatRedHat Enterprise Linux has Enterprise Linux has SELinuxSELinuxpure pure SELinuxSELinux for highfor high--sensitivity, highsensitivity, high--securitysecurity

SELinuxSELinuxis is NSA'sNSA's powerful implementation of mandatory powerful implementation of mandatory access controls for Linuxaccess controls for LinuxLinux Linux DACsDACs still applies, but if it allows the action still applies, but if it allows the action SELinuxSELinux then evaluates it against its own then evaluates it against its own security policiessecurity policies"subjects" are processes (run user "subjects" are processes (run user cmdscmds))actions are "permissionsactions are "permissions””objects not just files & objects not just files & dirsdirsto manage complexity to manage complexity SELinuxSELinux has:has:

"that which is not expressly permitted, is denied"that which is not expressly permitted, is denied””groups of subjects, permissions, and objectsgroups of subjects, permissions, and objects

Security ContextsSecurity Contextseach individual subject & object in each individual subject & object in SELinuxSELinux is is governed by a governed by a security contextsecurity context being a:being a:

user user -- individual user (human or daemon)individual user (human or daemon)•• SELinuxSELinux maintains its own list of usersmaintains its own list of users•• user labels on subjects specify account's privileges user labels on subjects specify account's privileges •• user labels on objects specify its owneruser labels on objects specify its owner

role role -- like a group, assumed by userslike a group, assumed by users•• a user may only assume one role at a time, a user may only assume one role at a time, •• may only switch roles if and when authorized to do somay only switch roles if and when authorized to do so

domain (type) domain (type) -- a sandbox being a combination of a sandbox being a combination of subjects and objects that may interact with each othersubjects and objects that may interact with each other

this model is called this model is called Type EnforcementType Enforcement (TE)(TE)

Decision Making in Decision Making in SELinuxSELinux

two types of decisions: two types of decisions: accessaccess decisionsdecisions

when subjects do things to objects that already exist, when subjects do things to objects that already exist, or create new things in expected domainor create new things in expected domain

transitiontransition decisionsdecisionsinvocation of processes in different domains than the invocation of processes in different domains than the one in which the subjectone in which the subject--process is runningprocess is runningcreation of objects in different types (domains) than creation of objects in different types (domains) than their parent directoriestheir parent directoriestransitions must be authorized by transitions must be authorized by SELinuxSELinux policypolicy

RBAC and MLS ControlsRBAC and MLS Controls

havehave Role Based Access ControlRole Based Access Control (RBAC)(RBAC)rules specify rules specify roles roles a user may assumea user may assumeother rules specify circumstances when a user other rules specify circumstances when a user may may transitiontransition from one role to anotherfrom one role to another

and and Multi Level SecurityMulti Level Security (MLS)(MLS)concerns handling of classified dataconcerns handling of classified data•• ““no read up, no write downno read up, no write down””

MLS is enforced via file system labelingMLS is enforced via file system labeling

SELinuxSELinux Policy ManagementPolicy Managementcreating and maintainingcreating and maintaining SELinuxSELinux policies policies is complicated and timeis complicated and time--consumingconsuminga singlea single SELinuxSELinux policy may consist of policy may consist of hundreds of lines of texthundreds of lines of textRHEL has a default RHEL has a default ““targetedtargeted”” policypolicy

defines types for selected network appsdefines types for selected network appsallows everything else to use DAC controlsallows everything else to use DAC controls

have a range of have a range of SELinuxSELinux commandscommandssee additional references for detailssee additional references for details

Novell Novell AppArmorAppArmorNovellNovell’’s MAC fors MAC for SuSESuSE LinuxLinux

enforced at kernel levelenforced at kernel levelusing Linux Security Modulesusing Linux Security Modules

restricts behavior of selected applications restricts behavior of selected applications in a very granular but targeted wayin a very granular but targeted way

hence a compromised root application's hence a compromised root application's access will be containedaccess will be containedhas no controls addressing data classificationhas no controls addressing data classificationhence only a partial MAC implementationhence only a partial MAC implementation

nonnon--protected apps just use Linux DACprotected apps just use Linux DAC

SummarySummary

reviewed Linux security model and DACreviewed Linux security model and DACvulnerabilitiesvulnerabilitiesO/S and application hardeningO/S and application hardeningMAC, MAC, SELinuxSELinux and and AppArmorAppArmor