Advanced Hardening

WrongunWrongun && DCDC JuneJune 20052005

ssh://root:[email protected] Lab Challenge

JoinJoin thethe wifiwifi netnet andand sshssh intointo thethe boxbox usingusing thethe accountaccount specifiedspecified inin thethe footerfooter

TryTry toto pwnpwn thethe boxbox byby addingadding anan accountaccount forfor yourselfyourself oror backdooringbackdooring sshdsshd

ssh://root:[email protected] “Only one remote hole in the default install, in more than 8 years! “

ssh://root:[email protected] So OpenBSD is uber secure, right?

Actually,Actually, nono …… TheThe defaultdefault installinstall hashas nothingnothing enabledenabled (except(except ssh)ssh)

““NoNo wonderwonder itit’’ss secure,secure, itit’’ss poweredpowered off!off!””

SourceSource --onlyonly patchingpatching strategystrategy makesmakes itit difficultdifficult toto rollroll outout fixesfixes toto platformsplatforms w/ow/o compilerscompilers (i.e.(i.e. disklessdiskless firewalls,firewalls, etc.)etc.)

ssh://root:[email protected] Brief History of OpenBSD Vulnerabilities

30 March 05: Bugs in the cp(4) stack can lead to memory exhaustion or processing of TCP segments with invalid SACK optio ns and cause a system crash.

14 Dec 04: On systems running sakmpd(8) it is possible for a local user to cause kernel memory corruption and system panic by setti ng psec(4) credentials on a socket

20 Sept 04: radius authentication, as implemented by ogin_radius(8) , was not checking the shared secret used for replies sent by the radius server. This could allow an attacker to spoof a reply granting access to the attacker. Note that OpenBSD does no t ship with radius authentication enabled

ssh://root:[email protected] Brief History of OpenBSD Vulnerabilities

JunJun 2002:2002: ApacheApache chunkedchunked encodingencoding vulnerabilityvulnerability (remote(remote uid=nobody)uid=nobody) (Apache(Apache -- nosejob.c)nosejob.c)

** YourYour highhigh pricedpriced securitysecurity consultant'sconsultant's planeplane ticket:ticket: $1500$1500 ** YourYour highhigh pricedpriced securitysecurity consultant'sconsultant's time:time: $200/hour$200/hour ** RealSecureRealSecure nodesnodes allall overover youryour company:company: $200,000$200,000 ** GettingGetting ownedowned byby 0day:0day: PricelessPriceless Gobbles June ‘02

ssh://root:[email protected] Proactive Approach to Security

Source Code Audits strlcpy() and strlcat() Privilege separation size -bounded string copying and Privilege revocation concatenation Chroot jailing Memory protection New uids New uids W^X ProPolice .rodata segment Guard pages Randomized malloc() Randomized mmap() atexit() and stdio protection

ssh://root:[email protected] ProPolice

ModifiesModifies GCCGCC toto catchcatch manymany stackstack overflowoverflow issuesissues atat compilationcompilation timetime ReRe --ordersorders objectsobjects onon stackstack forfor safetysafety BetterBetter thanthan StackGuardStackGuard WorksWorks onon moremore thanthan justjust i386i386

ssh://root:[email protected] W ^ X

MemoryMemory pagespages shouldnshouldn ’’tt bebe bothboth writablewritable andand executableexecutable w/ow/o hardwarehardware supportsupport (i.e.(i.e. 64bit64bit IntelsIntels oror variousvarious SPARC/RiSC)SPARC/RiSC) thisthis maymay havehave seriousserious performanceperformance considerationsconsiderations

ssh://root:[email protected] Randomized Memory Management

Malloc() When you need to allocate less than a page Mmap() A page or greater

Result: each time you perform a memory allocation, you get a different address.

Note: this breaks A LOT of apps, and the Obsd team blames app developers for writing rubbish code

ssh://root:[email protected] Randomized Memory Management

StackGapStackGap RandomRandom 88 bytebyte alignmentalignment forfor toptop ofof stackstack RandomizeRandomize sharedshared librarylibrary orderorder MayMay breakbreak stuffstuff ifif loadingloading lotslots ofof librarieslibraries

NotNot insurmountableinsurmountable forfor attacker,attacker, butbut makesmakes itit difficultdifficult enoughenough thatthat manymany wonwon ’’tt botherbother

ssh://root:[email protected] Privilege Revocation

ManyMany progsprogs runrun w/w/ ‘‘revokedrevoked ’’ privs:privs: Ping,Ping, portmap,portmap, traceroute,traceroute, rwalld,rwalld, pppd,pppd, ,spamd, httpd,httpd, named,named, authpf,authpf, etc.etc. OnceOnce processprocess kickskicks off,off, itit runsruns asas unprivilegedunprivileged user.user. AttacksAttacks againstagainst setuidsetuid binariesbinaries runningrunning w/w/ privilegeprivilege revocationrevocation wonwon ’’tt succeedsucceed (unless(unless theythey dodo priorprior toto revocation!)revocation!)

ssh://root:[email protected] Privilege Separation

ManyMany progsprogs runrun w/w/ ‘‘separatedseparated ’’ privs:privs: Ftpd, Sshd, syslogd, pflogd, isakmpd, bgpd, tcpdump, etc. Once process kicks off, it forks. Most work is done by larger unprivileged process. Priv ’d work is done by smaller process that retains privileges. Inter -process communication accomplished by socketpair() Non -trivial to code, however even has adopted this (for sshd, and maybe some other tasks)

ssh://root:[email protected] Hardening Basics

KillKill ftpftp --proxyproxy KillKill identdidentd KillKill daytime,daytime, timetime

Hell,Hell, justjust killkill inetdinetd

ssh://root:[email protected] Hardening Basics (cont)

DisableDisable rootroot loginlogin viavia sshssh DisableDisable SSHSSH protprot verver 11 pfpf (makes(makes iptablesiptables looklook likelike aa kludge)kludge) EgressEgress filteringfiltering isis aa pain,pain, butbut willwill stopstop 99%99% ofof remoteremote shellsshells PFPF AUTHAUTH cancan grantgrant outboundoutbound permsperms toto specificspecific usersusers SetupSetup offoff --boxbox logginglogging w/w/ syslogsyslog --ngng

ssh://root:[email protected] Hardening Advanced Topics (chflags)

sappnd set the system append -only flag (superuser only) schg set the system immutable flag (superuser only) uappnd set the user append -only flag (owner or superuser only) uchg set the user immutable flag (owner or superuser only)

Best practices: Flag binaries immutable w/ Schg Flag log files append only w/ sappend Note this breaks newsyslog … deal w/ it ☺

Note system must be in single user mode to unset these flags

ssh://root:[email protected] Hardening Advanced Topics (Stephanie)

EnableEnable TrustedTrusted PathPath ExecutionExecution (TPE)(TPE) based on code Mike Schiffman wrote for OpenBSD 2.4) Only files owned by root are executable Only users in trusted group can execute arbitrary non -root 0wned binaries kern.security.trust_gid=666 Root can turn function on/off via kern.security.tpe=1 NoteNote daemondaemon usersusers needsneeds toto bebe addedadded toto trustedtrusted groupgroup ifif theirtheir binariesbinaries areare ownedowned byby !root!root

ssh://root:[email protected] Hardening Advanced Topics (Stephanie)

Enable VEXEC Integrity verification of executed programs, memory mapped objec ts, and opened files. Uses hash tables. Supports MD5, SHA1, SHA256, SHA384, SHA512, and RMD160.

Creates the Vexec pseudo -device Creates a fingerprint list of binaries listed in /etc/vexec.conf (using desired hash) Turn on via sysctl kern.security.vexec.op=1 kern.security.vexec.verbose=1 kern.security.vexec.strict=0 (set this to 1 for extra fun!)

ssh://root:[email protected] Hardening Advanced Topics (Stephanie)

VEXEC is essentially *realtime* TRIPWIRE

ssh://root:[email protected] Hardening Advanced Topics (Stephanie)

EnablesEnables userlanduserland privacyprivacy FingerFinger LastLast NetstatNetstat WW WhoWho

LastLast versionversion (for(for 3.6)3.6) atat http://www.innu.org/~brian/Stephanie/http://www.innu.org/~brian/Stephanie/

ssh://root:[email protected] Hardening Advanced Topics (Securelevel)

TheThe OpenBSDOpenBSD kernelkernel providesprovides fourfour levelslevels ofof systemsystem security:security:

--1:1: PermanentlyPermanently insecureinsecure modemode init(8)init(8) willwill notnot attemptattempt toto raiseraise thethe securelevelsecurelevel maymay onlyonly bebe setset withwith sysctl(8)sysctl(8) whilewhile thethe systemsystem isis insecureinsecure

ssh://root:[email protected] Hardening Advanced Topics (Securelevel)

0:0: InsecureInsecure modemode usedused duringduring bootstrappingbootstrapping andand whilewhile thethe systemsystem isis singlesingle --useruser allall devicesdevices maymay bebe readread oror writtenwritten subjectsubject toto theirtheir permissionspermissions systemsystem filefile flagsflags maymay bebe clearedcleared

ssh://root:[email protected] Hardening Advanced Topics (Securelevel)

1: Secure mode default mode when system is multi -user securelevel may no longer be lowered except by init /dev/mem and /dev/kmem may not be written to raw disk devices of mounted file systems are read -only system immutable and append -only file flags may not be removed kernel modules may not be loaded or unloaded the fs.posix.setuid sysctl variable may not be raised the net.inet.ip.sourceroute sysctl variable may not be raised

ssh://root:[email protected] Hardening Advanced Topics (Securelevel)

2:2: HighlyHighly securesecure modemode all effects of securelevel 1 raw disk devices are always read -only whether mounted or not settimeofday and clock_settime may not set the time backwards or close to overflow pfctl may no longer alter filter or nat rules the ddb.console and ddb.panic sysctl variables may not be raised

ssh://root:[email protected] Breaking Out of Securelevels

NonNon trivial,trivial, butbut wewe ’’veve foundfound 33 waysways IfIf /etc//etc/ (dir)(dir) isis schgschg ,, 22 methodsmethods IfIf /boot/boot (file)(file) isis schgschg ,, butbut /etc/etc isis not...not...

ssh://root:[email protected] Breaking Out of Securelevels [/etc not SCHG’d] : Method 1

LazymanLazyman ’’ss wayway (no(no stylestyle pointspoints thotho )) SimplySimply mvmv /etc//etc/ // etc.offetc.off mkdirmkdir /etc/etc &&&& cdcd //etc.offetc.off ;; tartar cfcf -- .. \\ || (( cdcd /etc;/etc; tartar xpfxpf -- ))

ssh://root:[email protected] Breaking Out of Securelevels [/etc not SCHG’d] Method 2 :: Stylepointz++

IfIf /etc//etc/ boot.confboot.conf doesn'tdoesn't exist...exist... (and(and itit doesn'tdoesn't byby defaultdefault !)!) CreateCreate /etc//etc/ boot.confboot.conf ,, andand ““rebootreboot ”” fromfrom youryour ownown ““customisedcustomised ”” kernelkernel ;; --)) Set option INSECURE in the kernel config Remove stephanie/vexec/etc Remove securelevel code Add in an rootkit backdoor Hell,Hell, it'sit's youryour kernel,kernel, andand hencehence youryour box!box! ssh://root:[email protected] Breaking Out of Securelevels [/etc *is* SCHG’d, but /boot is writable]

usr/mdec/biosbootusr/mdec/biosboot firstfirst stagestage bootstrapbootstrap /boot/boot systemsystem bootstrapbootstrap /etc//etc/ boot.confboot.conf systemsystem bootstrapsbootstraps startupstartup filefile If we can write to the bootloader , we can install our own bootloader which looks for the boot.conf wherever we want to put it. And we would have gotten away with it too if it wasn't for those pesky kernels...

ssh://root:[email protected] Quick and Dirty PPTP VPN

Quick PPTPD setup using poptop & userland GRE, mppe & mschapv2 Echo “net.inet.gre.allow=1 ” >> /etc/sysctl.conf Echo “net.inet.ip.forwarding=1 ” >> /etc/sysctl.conf Cd /usr/ports/net/poptop; Make && make install Echo “pptp: ” >> /etc/ppp/ppp.conf Echo “enable MSChapV2 ” >> /etc/ppp/ppp.conf Echo “set ifaddr 10.0.0.254 10.0.1.69 -10.0.1.79 ” >> /etc/ppp/ppp.conf Echo “dc password * * ” >> /etc/ppp/ppp.secret /usr/local/sbin/pptpd; Configure PF to taste

ssh://root:[email protected] Quick and Dirty PPTP VPN

This will give you a quick and effective PPTP (mschapv2) VPN server, compatible w/ WinXP native clients Good for l -users that need to publish web - content or pop/imap mail Not strong enough for proper system administration

ssh://root:[email protected] Quick and Dirty PPTP VPN

X.509 based IPSEC VPN is still the “real ” way to do VPN See Schneier and Mudge on how well M$ cleaned up mschap to create MSChapV2 and decide for yourself http://www.schneier.com /paper -pptpv2.html

ssh://root:[email protected] Strong Authentication for Remote Administration

SSH with private key on smartcard OpenSSH client and server has support Userspace program ‘sectok ’ to read/write to Cyberflex smartcards (and possibly others)

If we want to use X.509 based auth we ’ll either need to patch sshd, or run a commercial sshd. Popular win32 ssh clients already support X.509 cert on smartcard (i.e. SecureCRT) Passwords are going away – even latest Debian installer disables ssh -pw -auth by default!

ssh://root:[email protected] IPSEC

OpenBSDOpenBSD hashas toutedtouted ““nativenative ”” IPSECIPSEC sincesince 2.x.2.x. WeWe cancan createcreate sitesite toto sitesite IPSECIPSEC tunnelstunnels withwith kernelkernel IPSECIPSEC supportsupport andand userspaceuserspace isakmpd.isakmpd. NoNo needneed forfor freeswan/openswanfreeswan/openswan oror kernelkernel hackinghacking likelike onon LinuxLinux SeeSee manman vpnvpn forfor detailsdetails

ssh://root:[email protected] VMWare Detection

OnOn IntelIntel architectures,architectures, itit ’’ss possiblepossible toto telltell withwith somesome degreedegree ofof certaintycertainty ifif anan OpenBSDOpenBSD systemsystem wewe ’’rere usingusing isis ““realreal ”” oror ““memorexmemorex ”” ThisThis cancan bebe donedone byby attemptingattempting toto writewrite toto SensitiveSensitive RegisterRegister Instructions:Instructions: SGDT,SGDT, SLDTSLDT andand SIDTSIDT VMWareVMWare systemssystems writewrite predictablepredictable valuesvalues toto thethe IDTR,IDTR, LDTR,LDTR, andand GDTRGDTR (interrupt(interrupt descriptor,descriptor, locallocal descriptordescriptor andand globalglobal descriptordescriptor registers)registers)

ssh://root:[email protected] VMWare Detection

SeeSee ttp://www.trapkit.de/research/vmmttp://www.trapkit.de/research/vmm forfor moremore infoinfo

ssh://root:[email protected] Questions?

SoSo isis aa lockedlocked downdown OpenBSDOpenBSD boxbox actuallyactually usable?usable? DoDo II sleepsleep betterbetter atat nightnight knowingknowing II runrun OpenBSD?OpenBSD?

????????????

ssh://root:[email protected] References

Theo de Raadt, CansecWest ’03 http://www.openbsd.org/papers/csw03/index.html Stephanie http:// www.innu.org/~brian/Stephanie / Mudge & Bruce on M$PPTP (mschapv1&v2) http://www.schneier.com/pptp -faq.html (pre sellout) http:// www.schneier.com/pptp.html (post -sellout !) VMware detection http:// invisiblethings.org/papers/redpill.html Joanna you rock!!! http://www.trapkit.de/#research

ssh://root:[email protected]